Source code for submission s839

Main.java

  1. import java.io.*;
  2. import java.util.*;
  3.  
  4. class Main {
  5. static int N, E;
  6. static Node[] nodes;
  7. public static void main(String args[]) throws Exception {
  8. String line;
  9.  
  10. while((line = br.readLine()) != null) {
  11. int a[] = new int[2];
  12. parseIntArr(line.toCharArray(), a);
  13. N = a[0]; E = a[1];
  14. nodes = new Node[N+1];
  15. ArrayList<Node> d3 = new ArrayList<Node>();
  16. for(int i = 1; i <= N; i++) nodes[i] = new Node();
  17.  
  18. boolean found = false;
  19.  
  20. for(int i = 0; i < E; i++) {
  21. if(!found) parseIntArr(br.readLine().toCharArray(), a);
  22. else {
  23. br.readLine();
  24. continue;
  25. }
  26.  
  27. nodes[a[0]].edges.add(a[1]);
  28. nodes[a[1]].edges.add(a[0]);
  29.  
  30. if(nodes[a[0]].edges.size() == 4) found = true;
  31. else if(nodes[a[1]].edges.size() == 4) found = true;
  32. else if(nodes[a[0]].edges.size() == 3) d3.add(nodes[a[0]]);
  33. else if(nodes[a[1]].edges.size() == 3) d3.add(nodes[a[1]]);
  34. }
  35.  
  36. if(found) System.out.println("YES");
  37. else {
  38. for(Node n : d3) {
  39. if(walk(n, false)) {
  40. found = true;
  41. break;
  42. }
  43. }
  44. if(found) System.out.println("YES");
  45. else System.out.println("NO");
  46. }
  47. }
  48. }
  49.  
  50. static boolean walk(Node n, boolean foundFirst) {
  51. if(n.visited) return false;
  52. else {
  53. n.visited = true;
  54. if(n.edges.size() == 3) {
  55. if(foundFirst) return true;
  56. else foundFirst = true;
  57. }
  58.  
  59. for(Integer i : n.edges) {
  60. boolean result = walk(nodes[i], foundFirst);
  61. if(result) return true;
  62. }
  63. }
  64. return false;
  65. }
  66.  
  67. public static void parseIntArr(char[] arr, int[] target)
  68. {
  69. int i = 0;
  70. int acc = -1;
  71.  
  72. for(char ch :arr)
  73. {
  74. if(ch == ' ')
  75. {
  76. if(acc!= -1)
  77. {
  78. target[i++] = acc;
  79. acc = -1;
  80. }
  81. }
  82. else if(acc == -1)
  83. acc = ch - '0';
  84. else
  85. acc = acc * 10 + (ch - '0');
  86. }
  87. if(acc != -1)
  88. target[i] = acc;
  89. }
  90. }
  91.  
  92. class Node {
  93. boolean visited = false;
  94. ArrayList<Integer> edges = new ArrayList<Integer>(4);
  95. }