C
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100010
int n, m, color[MAXSIZE];
struct Edge {
int to;
struct Edge *nxt;
} *graph[MAXSIZE];
int addEdge(int from, int to) {
struct Edge *s = (struct Edge*) calloc(1, sizeof(struct Edge));
s->to = to;
s->nxt = graph[from];
graph[from] = s;
}
void init() {
scanf("%d%d", &n, &m);
int u, v;
while (m--) {
scanf("%d%d", &u, &v);
addEdge(u, v);
addEdge(v, u);
}
}
int dfs(int u, int c) {
color[u] = c;
struct Edge *p = graph[u];
while (p != NULL) {
int v = p->to;
p = p->nxt;
if (!color[v] && !dfs(v, 3-c)) {
return 0;
} else if (color[v] == c) {
return 0;
}
}
return 1;
}
int main() {
init();
int flag = 1;
for (int u = 1; u <= n; ++u) {
if (!color[u] && !dfs(u, 1)) {
flag = 0;
break;
}
}
if (flag) {
puts("Yes");
} else {
puts("No");
}
return 0;
}
C++
#include <iostream>
#include <vector>
using namespace std;
const int MAXSIZE = 100010;
int n, m;
vector<int> color(MAXSIZE, 0);
vector<vector<int> > graph(MAXSIZE);
void addEdge(int from, int to) {
graph[from].push_back(to);
}
void init() {
cin >> n >> m;
int u, v;
while (m--) {
cin >> u >> v;
addEdge(u, v);
addEdge(v, u);
}
}
bool dfs(int u, int c) {
color[u] = c;
for (int v : graph[u]) {
if (!color[v] && !dfs(v, 3-c)) {
return false;
} else if (color[v] == c) {
return false;
}
}
return true;
}
int main() {
init();
bool flag = true;
for (int u = 1; u <= n; ++u) {
if (!color[u] && !dfs(u, 1)) {
flag = false;
break;
}
}
if (flag) {
cout << "Yes" << endl;
} else {
cout << "No" << endl;
}
return 0;
}
Go
package main
import "fmt"
type Edge struct {
to int
next *Edge
}
var (
n, m int
color []int
graph []*Edge
)
func addEdge(from, to int) {
edge := &Edge{to: to, next: graph[from]}
graph[from] = edge
}
func init() {
fmt.Scan(&n, &m)
color, graph = make([]int, n+1), make([]*Edge, n+1)
var u, v int
for i := 0; i < m; i++ {
fmt.Scan(&u, &v)
addEdge(u, v)
addEdge(v, u)
}
}
func dfs(u, c int) bool {
color[u] = c
for p := graph[u]; p != nil; p = p.next {
v := p.to
if color[v] == 0 && !dfs(v, 3-c) {
return false
} else if color[v] == c {
return false
}
}
return true
}
func main() {
flag := true
for u := 1; u <= n; u++ {
if color[u] == 0 && !dfs(u, 1) {
flag = false
break
}
}
if flag {
fmt.Println("Yes")
} else {
fmt.Println("No")
}
}