fork download
  1. import java.util.*;
  2.  
  3. class Graph {
  4. public static void main(String[] args) {
  5. int n, m;
  6. Scanner scanner = new Scanner(System.in);
  7. n = scanner.nextInt();
  8. m = scanner.nextInt();
  9.  
  10. ArrayList<Integer> gr[] = new ArrayList[n];
  11. for (int i = 0; i < n; i++) {
  12. gr[i] = new ArrayList<>();
  13. }
  14.  
  15. int s = 0;
  16. for (int i = 0; i < m; i++) {
  17. int u, v;
  18. u = scanner.nextInt();
  19. v = scanner.nextInt();
  20. gr[u - 1].add(v - 1);
  21. gr[v - 1].add(u - 1);
  22. }
  23.  
  24. LinkedList<Integer> queue = new LinkedList<>();
  25. queue.push(s);
  26. boolean used[] = new boolean[n];
  27. used[s] = true;
  28.  
  29. while (!queue.isEmpty()) {
  30. int v = queue.peek();
  31. queue.pop();
  32. for (int i = 0; i < gr[v].size(); ++i) {
  33. int to = gr[v].get(i);
  34. if (!used[to]) {
  35. used[to] = true;
  36. queue.push(to);
  37. }
  38. }
  39. }
  40. String answer = "YES";
  41. for (int i = 0; i < used.length; i++) {
  42. if (used[i] == false) {
  43. answer = "NO";
  44. }
  45. }
  46. System.out.println(answer);
  47. }
  48. }
  49.  
Success #stdin #stdout 0.06s 321344KB
stdin
4 5
1 2
2 1
2 4
2 4
4 2
stdout
NO