1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
| import java.util.*;
public class code { public static void main(String[] args) { Scanner in = new Scanner(System.in); boolean flag = true; boolean[] visited = new boolean[1]; int n = 0, e = 0, cnt = 0, minTime = Integer.MAX_VALUE; List<Integer> temp; Map<Integer, List<Integer>> map = new HashMap<Integer, List<Integer>>(); while (in.hasNextLine()) { String str = in.nextLine(); if (flag) { String[] split = str.split(" "); n = Integer.parseInt(split[0]); visited = new boolean[n]; e = Integer.parseInt(split[1]); flag = false; } else { String[] split = str.split(" "); int a = Integer.parseInt(split[0]); int b = Integer.parseInt(split[1]); minTime = Math.min(minTime, a); if (map.containsKey(a)) { temp = map.get(a); temp.add(b); } else { temp = new ArrayList(); temp.add(b); } map.put(a, temp); cnt++; if (cnt == e) { break; } } } if (n == 0 || e == 0) { System.out.println(0); }
cnt = minTime; List<Integer> res = new ArrayList(); Deque<Integer> q1 = new ArrayDeque(); Deque<Integer> q2 = new ArrayDeque();
int machineCnt = 0; while (machineCnt < n) { res = new ArrayList(); if (map.containsKey(cnt)) { temp = map.get(cnt); } else { temp = new ArrayList(); } cnt++;
for (int idx : temp) { if (!visited[idx]) { res.add(idx); machineCnt++; visited[idx] = true; addNext(visited, q2, n, idx); } }
while (!q1.isEmpty()) { int idx = q1.poll(); if (!visited[idx]) { res.add(idx); machineCnt++; visited[idx] = true; addNext(visited, q2, n, idx); } }
if (machineCnt == n) { break; } q1 = q2; q2 = new ArrayDeque(); }
System.out.println(res.size()); Collections.sort(res); for (int num : res) System.out.print(num + " "); }
private static void addNext(boolean[] visited, Deque<Integer> q2, int len, int idx) { if (idx == 0) { if (!visited[1]) q2.add(1); if (!visited[len - 1]) q2.add(len - 1); } else if (idx == len - 1) { if (!visited[0]) q2.add(0); if (!visited[len - 2]) q2.add(len - 2); } else { if (!visited[idx - 1]) q2.add(idx - 1); if (!visited[idx + 1]) q2.add(idx + 1); } } }
|