使用并查集判断连通图
import java.util.Scanner;
public class Main {
static int[] f = new int[1005];
public static void init() {
for (int i = 0; i < f.length; i++) {
f[i] = i;
}
}
public static int find(int x) {
if (f[x] == x)
return x;
return f[x] = find(f[x]);
}
public static void union(int x, int y) {
int fx = find(x);
int fy = find(y);
if (fx != fy) {
f[fx] = fy;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
init();
int n = sc.nextInt();
int m = sc.nextInt();
for (int i = 0; i < m; i++) {
union(sc.nextInt(), sc.nextInt());
}
int cnt = 0;
for (int i = 1; i <= n; i++) {
if (f[i] == i) {
cnt++;
}
}
if (cnt == 1) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
}