import java.io.*; import java.nio.charset.StandardCharsets; import java.util.*; public class kon { static String in1 = "4 5\n1 2\n2 3\n3 1\n3 4\n4 2\n"; static String in2 = "3 2\n1 2\n2 3\n"; static InputStream stringToStream(String string) { return new ByteArrayInputStream(string.getBytes(StandardCharsets.UTF_8)); } public static void main(String[] args) { // InputReader in = new InputReader(stringToStream(in1)); // InputReader in = new InputReader(stringToStream(in2)); InputReader in = new InputReader(System.in); OutputWriter out = new OutputWriter(System.out); int n = in.readInt(); int m = in.readInt(); Map<Integer, Collection<Integer>> graph = new HashMap<>((int) 1.5 * n); Map<Integer, Integer> inDegrees = new HashMap<>((int) 1.5 * m); // Map<Integer, Collection<Integer>> ins = new HashMap<>((int) 1.5 * m); for (int i = 0; i < m; i++) { int from = in.readInt() - 1; int to = in.readInt() - 1; if (!graph.containsKey(from)) graph.put(from, new HashSet<>()); if (!graph.containsKey(to)) graph.put(to, new HashSet<>()); graph.get(from).add(to); if (!inDegrees.containsKey(to)) inDegrees.put(to, 1); else inDegrees.put(to, inDegrees.get(to)); // if (!ins.containsKey(to)) ins.put(to, new HashSet<>()); // ins.get(to).add(from); } // for (int k : graph.keySet()) { // if (!ins.containsKey(k)) ins.put(k, new HashSet<>()); // } for (int k : graph.keySet()) { if (!inDegrees.containsKey(k)) inDegrees.put(k, 0); } // System.out.println(graph); // System.out.println(inDegrees); SLSimpleCycles solution = new SLSimpleCycles<>(graph, inDegrees); Set<Integer> commonNodes = solution.findSimpleCycles(); boolean hasCycles = solution.hasCycles(); // Johnson<Integer> solution = new Johnson<>(); // List<Set<Integer>> cycles = solution.cycles(graph, ins); // Set<Integer> commonNodes = solution.getCommonNodes(); // boolean hasCycles = cycles.size() > 0; if (hasCycles) { out.printLine(commonNodes.size()); Object[] resultArray = commonNodes.stream().map(x -> x + 1).sorted().toArray(); for (Object i : resultArray) { out.print(i); out.print(' '); } } else { out.printLine("NIE"); } out.flush(); out.close(); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } class SLSimpleCycles<V> { private Map<V, Collection<V>> graph; private Map<V, Integer> inDegrees; private List<List<V>> cycles = null; private V[] iToV = null; private Map<V, Integer> vToI = null; private Map<V, Set<V>> bSets = null; private ArrayDeque<V> stack = null; private Set<V> marked = null; private Map<V, Set<V>> removed = null; private int[] position = null; private boolean[] reach = null; private List<V> startVertices = null; private Set<V> commonNodes = null; public SLSimpleCycles(Map<V, Collection<V>> graph, Map<V, Integer> inDegrees) { if (graph == null) { throw new IllegalArgumentException("Null graph argument."); } this.graph = graph; this.inDegrees = inDegrees; } // public List<List<V>> findSimpleCycles() { public Set<V> findSimpleCycles() { initState(); // Kosaraju<V> kosaraju = new Kosaraju<>(); // List<Set<V>> sccs = kosaraju.sccs(graph); SCCTarjan<V> tarjan = new SCCTarjan<>(); List<Set<V>> sccs = tarjan.scc(graph); // if (sccs.size() > 1) return Collections.emptySet(); for (Set<V> scc : sccs) { int maxInDegree = -1; V startVertex = null; for (V v : scc) { int inDegree = inDegrees.get(v); if (inDegree > maxInDegree) { maxInDegree = inDegree; startVertex = v; } } startVertices.add(startVertex); } for (V vertex : startVertices) { cycle(toI(vertex), 0); if (commonNodes.isEmpty()) break; } // List<List<V>> result = cycles; // return result; return commonNodes; } private boolean cycle(int v, int q) { boolean foundCycle = false; V vV = toV(v); marked.add(vV); stack.push(vV); int t = stack.size(); position[v] = t; if (!reach[v]) { q = t; } Set<V> avRemoved = getRemoved(vV); Iterator<V> avIt = graph.get(vV).iterator(); while (avIt.hasNext()) { V wV = avIt.next(); if (avRemoved.contains(wV)) { continue; } int w = toI(wV); if (!marked.contains(wV)) { boolean gotCycle = cycle(w, q); if (gotCycle) { foundCycle = gotCycle; } else { noCycle(v, w); } } else if (position[w] <= q) { foundCycle = true; List<V> cycle = new ArrayList<V>(); Iterator<V> it = stack.descendingIterator(); V current = null; while (it.hasNext()) { current = it.next(); if (wV.equals(current)) { break; } } cycle.add(wV); while (it.hasNext()) { current = it.next(); cycle.add(current); if (current.equals(vV)) { break; } } cycles.add(cycle); commonNodes.retainAll(cycle); if (commonNodes.isEmpty()) return true; } else { noCycle(v, w); } } stack.pop(); if (foundCycle) { unmark(v); } reach[v] = true; position[v] = graph.size(); return foundCycle; } public boolean hasCycles() { return !cycles.isEmpty(); } private void noCycle(int x, int y) { V xV = toV(x); V yV = toV(y); Set<V> by = getBSet(yV); Set<V> axRemoved = getRemoved(xV); by.add(xV); axRemoved.add(yV); } private void unmark(int x) { V xV = toV(x); marked.remove(xV); Set<V> bx = getBSet(xV); for (V yV : bx) { Set<V> ayRemoved = getRemoved(yV); ayRemoved.remove(xV); if (marked.contains(yV)) { unmark(toI(yV)); } } bx.clear(); } private void initState() { cycles = new ArrayList<List<V>>(); iToV = (V[]) graph.keySet().toArray(); vToI = new HashMap<V, Integer>(); bSets = new HashMap<V, Set<V>>(); stack = new ArrayDeque<V>(); marked = new HashSet<V>(); removed = new HashMap<V, Set<V>>(); int size = graph.size(); position = new int[size]; reach = new boolean[size]; startVertices = new ArrayList<V>(); for (int i = 0; i < iToV.length; i++) { vToI.put(iToV[i], i); } commonNodes = new HashSet(graph.keySet()); } private Integer toI(V v) { return vToI.get(v); } private V toV(int i) { return iToV[i]; } private Set<V> getBSet(V v) { Set<V> result = bSets.get(v); if (result == null) { result = new HashSet<V>(); bSets.put(v, result); } return result; } private Set<V> getRemoved(V v) { Set<V> result = removed.get(v); if (result == null) { result = new HashSet<V>(); removed.put(v, result); } return result; } } class SCCTarjan<V> { Map<V, Collection<V>> graph; Map<V, Boolean> visited; Stack<V> stack; int time; Map<V, Integer> lowlink; List<Set<V>> components; public List<Set<V>> scc(Map<V, Collection<V>> graph) { this.graph = graph; visited = new HashMap<>(); stack = new Stack<>(); time = 0; lowlink = new HashMap<>(); components = new ArrayList<>(); for (V u : graph.keySet()) { lowlink.put(u, 0); } for (V u : graph.keySet()) if (!visited.containsKey(u)) dfs(u); return components; } void dfsRec(V u) { lowlink.put(u, time++); visited.put(u, true); stack.add(u); boolean isComponentRoot = true; // System.out.println("A---"); // System.out.println(lowlink); // System.out.println(visited); // System.out.println(stack); // System.out.println(isComponentRoot); // System.out.println("---"); for (V v : graph.get(u)) { if (!visited.containsKey(v)) dfsRec(v); if (lowlink.get(u) > lowlink.get(v)) { lowlink.put(u, lowlink.get(v)); isComponentRoot = false; } } // System.out.println("---"); // System.out.println(lowlink); // System.out.println(visited); // System.out.println(stack); // System.out.println(isComponentRoot); // System.out.println("B---"); if (isComponentRoot) { Set<V> component = new HashSet<>(); while (true) { V x = stack.pop(); component.add(x); lowlink.put(x, Integer.MAX_VALUE); if (x == u) break; } components.add(component); } } void dfs(V u) { dfsRec(u); } void dfsIt(V u) { boolean isComponentRoot = true; Stack<V> search = new Stack<>(); search.push(u); while (!search.isEmpty()) { V u2 = search.pop(); lowlink.put(u2, time++); visited.put(u2, true); stack.add(u2); System.out.println("---"); System.out.println(lowlink); System.out.println(visited); System.out.println(stack); System.out.println(isComponentRoot); System.out.println("---"); boolean wentSomewhere = false; for (V v : graph.get(u2)) { if (!visited.containsKey(v)) { wentSomewhere = true; search.push(v); continue; } if (lowlink.get(u2) > lowlink.get(v)) { lowlink.put(u2, lowlink.get(v)); isComponentRoot = false; } } System.out.println("---"); System.out.println(lowlink); System.out.println(visited); System.out.println(stack); System.out.println(isComponentRoot); System.out.println("---"); if (!wentSomewhere) if (isComponentRoot) { Set<V> component = new HashSet<>(); while (true) { V x = stack.pop(); component.add(x); lowlink.put(x, Integer.MAX_VALUE); if (x == u2) break; } components.add(component); } } } } class Kosaraju<V> { public List<Set<V>> sccs(Map<V, Collection<V>> graph) { List<Set<V>> result = new ArrayList<>(); Set<V> visited = new HashSet<>(); Stack<V> s = new Stack<>(); for (V v : graph.keySet()) { dfs(graph, visited, v, s); } Map<V, Collection<V>> transposed = transpose(graph); // System.out.println("transposed: " + transposed); visited = new HashSet<>(); while (!s.isEmpty()) { V v = s.pop(); if (!visited.contains(v)) { Set<V> comp = new HashSet<>(); dfs(transposed, visited, v, comp); result.add(comp); } } return result; } void dfs(Map<V, Collection<V>> graph, Set<V> visited, V v, Stack<V> stack) { Stack<V> dfsStack = new Stack<>(); if (!visited.contains(v)) { dfsStack.push(v); stack.push(v); while (!dfsStack.isEmpty()) { V popped = dfsStack.pop(); visited.add(popped); for (V next : graph.get(popped)) { if (!visited.contains(next)) { dfsStack.push(next); stack.push(next); } } } } } void dfs(Map<V, Collection<V>> graph, Set<V> visited, V v, Set<V> stack) { Stack<V> dfsStack = new Stack<>(); if (!visited.contains(v)) { dfsStack.push(v); stack.add(v); while (!dfsStack.isEmpty()) { V popped = dfsStack.pop(); visited.add(popped); for (V next : graph.get(popped)) { if (!visited.contains(next)) { dfsStack.push(next); stack.add(next); } } } } } public Map<V, Collection<V>> transpose(Map<V, Collection<V>> graph) { Map<V, Collection<V>> transposed = new HashMap<>(); for (V from : graph.keySet()) { if (!transposed.containsKey(from)) transposed.put(from, new HashSet<>()); for (V to : graph.get(from)) { if (!transposed.containsKey(to)) transposed.put(to, new HashSet<>()); transposed.get(to).add(from); } } return transposed; } } class Johnson<V> { class NodeAndNeighbors<V> { V node; Collection<V> neighbors; NodeAndNeighbors(V node, Collection<V> neighbors) { this.node = node; this.neighbors = neighbors; } @Override public String toString() { return "[" + node + "," + neighbors + "]"; } } Set<V> commonNodes; public List<Set<V>> cycles(Map<V, Collection<V>> graph, Map<V, Collection<V>> ins) { commonNodes = new HashSet<>(graph.keySet()); Kosaraju<V> kosaraju = new Kosaraju<>(); LinkedList<Set<V>> sccs = new LinkedList<>(kosaraju.sccs(graph)); // System.out.println("sccs: " + sccs); List<Set<V>> cycles = new ArrayList<>(); while (!sccs.isEmpty()) { Set<V> scc = sccs.pop(); V start = scc.iterator().next(); LinkedList<V> path = new LinkedList<>(); path.add(start); Set<V> blocked = new HashSet<>(); Set<V> closed = new HashSet<>(); blocked.add(start); Map<V, Set<V>> B = new HashMap<>(); Stack<NodeAndNeighbors<V>> stack = new Stack<>(); stack.push(new NodeAndNeighbors<>(start, new HashSet(graph.get(start)))); while (!stack.isEmpty()) { NodeAndNeighbors<V> nodeAndNeighbors = stack.peek(); V thisNode = nodeAndNeighbors.node; Collection<V> neighbors = nodeAndNeighbors.neighbors; if (!neighbors.isEmpty()) { V next = neighbors.iterator().next(); neighbors.remove(next); if (next.equals(start)) { Set<V> cycle = new HashSet<>(path); cycles.add(cycle); commonNodes.retainAll(cycle); if (commonNodes.isEmpty()) return cycles; closed.addAll(path); } else if (!blocked.contains(next)) { path.add(next); stack.push(new NodeAndNeighbors<>(next, new HashSet(graph.get(next)))); closed.remove(next); blocked.add(next); continue; } } // System.out.println("cycles: " + cycles); // System.out.println("graph: " + graph); // System.out.println("ins: " + ins); // System.out.println("start: " + start); // System.out.println("path: " + path); // System.out.println("blocked: " + blocked); // System.out.println("closed: " + closed); // System.out.println("B: " + B); // System.out.println("stack: " + stack); // System.out.println("neighbors: " + neighbors); // System.out.println("thisNode: " + thisNode); if (neighbors.isEmpty()) { if (closed.contains(thisNode)) { // System.out.println("unblock: " + thisNode + " " + blocked + " " + B); unblock(thisNode, blocked, B); } else { for (V neighbor : graph.get(thisNode)) { if (!B.containsKey(neighbor)) B.put(neighbor, new HashSet<>()); if (!B.get(neighbor).contains(thisNode)) B.get(neighbor).add (thisNode); } } stack.pop(); path.pop(); } } removeNode(graph, ins, start); sccs.addAll(kosaraju.sccs(graph)); } return cycles; } Set<V> getCommonNodes() { return commonNodes; } void removeNode(Map<V, Collection<V>> graph, Map<V, Collection<V>> ins, V node) { // System.out.println("TOREMOVE " + node); // System.out.println("! " + graph); // System.out.println("! " + ins); Set<V> removedNodePointingTo = new HashSet<>(graph.get(node)); graph.remove(node); for (V v : ins.get(node)) { graph.get(v).remove(node); // if (graph.get(v).isEmpty()) graph.remove(v); } ins.remove(node); for (V pointingTo : removedNodePointingTo) { ins.get(pointingTo).remove(node); // if (ins.get(pointingTo).isEmpty()) ins.remove(pointingTo); } // System.out.println("! " + graph); // System.out.println("! " + ins); } Map<V, Collection<V>> subgraph(Map<V, Collection<V>> graph, Collection<V> nodesPersisted) { Map<V, Collection<V>> subgraph = new HashMap<>(); Set<V> nodesToRemove = new HashSet<>(graph.keySet()); nodesToRemove.removeAll(nodesPersisted); for (V node : nodesPersisted) { subgraph.put(node, new HashSet<>(graph.get(node))); } for (V node : subgraph.keySet()) { subgraph.get(node).removeAll(nodesToRemove); } return subgraph; } void unblock(V thisNode, Set<V> blocked, Map<V, Set<V>> B) { Set<V> stack = new HashSet<>(); stack.add(thisNode); while (!stack.isEmpty()) { V node = stack.iterator().next(); stack.remove(node); if (blocked.contains(node)) { blocked.remove(node); if (B.containsKey(node)) { stack.addAll(B.get(node)); B.get(node).clear(); } } } } }
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 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 | import java.io.*; import java.nio.charset.StandardCharsets; import java.util.*; public class kon { static String in1 = "4 5\n1 2\n2 3\n3 1\n3 4\n4 2\n"; static String in2 = "3 2\n1 2\n2 3\n"; static InputStream stringToStream(String string) { return new ByteArrayInputStream(string.getBytes(StandardCharsets.UTF_8)); } public static void main(String[] args) { // InputReader in = new InputReader(stringToStream(in1)); // InputReader in = new InputReader(stringToStream(in2)); InputReader in = new InputReader(System.in); OutputWriter out = new OutputWriter(System.out); int n = in.readInt(); int m = in.readInt(); Map<Integer, Collection<Integer>> graph = new HashMap<>((int) 1.5 * n); Map<Integer, Integer> inDegrees = new HashMap<>((int) 1.5 * m); // Map<Integer, Collection<Integer>> ins = new HashMap<>((int) 1.5 * m); for (int i = 0; i < m; i++) { int from = in.readInt() - 1; int to = in.readInt() - 1; if (!graph.containsKey(from)) graph.put(from, new HashSet<>()); if (!graph.containsKey(to)) graph.put(to, new HashSet<>()); graph.get(from).add(to); if (!inDegrees.containsKey(to)) inDegrees.put(to, 1); else inDegrees.put(to, inDegrees.get(to)); // if (!ins.containsKey(to)) ins.put(to, new HashSet<>()); // ins.get(to).add(from); } // for (int k : graph.keySet()) { // if (!ins.containsKey(k)) ins.put(k, new HashSet<>()); // } for (int k : graph.keySet()) { if (!inDegrees.containsKey(k)) inDegrees.put(k, 0); } // System.out.println(graph); // System.out.println(inDegrees); SLSimpleCycles solution = new SLSimpleCycles<>(graph, inDegrees); Set<Integer> commonNodes = solution.findSimpleCycles(); boolean hasCycles = solution.hasCycles(); // Johnson<Integer> solution = new Johnson<>(); // List<Set<Integer>> cycles = solution.cycles(graph, ins); // Set<Integer> commonNodes = solution.getCommonNodes(); // boolean hasCycles = cycles.size() > 0; if (hasCycles) { out.printLine(commonNodes.size()); Object[] resultArray = commonNodes.stream().map(x -> x + 1).sorted().toArray(); for (Object i : resultArray) { out.print(i); out.print(' '); } } else { out.printLine("NIE"); } out.flush(); out.close(); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } class SLSimpleCycles<V> { private Map<V, Collection<V>> graph; private Map<V, Integer> inDegrees; private List<List<V>> cycles = null; private V[] iToV = null; private Map<V, Integer> vToI = null; private Map<V, Set<V>> bSets = null; private ArrayDeque<V> stack = null; private Set<V> marked = null; private Map<V, Set<V>> removed = null; private int[] position = null; private boolean[] reach = null; private List<V> startVertices = null; private Set<V> commonNodes = null; public SLSimpleCycles(Map<V, Collection<V>> graph, Map<V, Integer> inDegrees) { if (graph == null) { throw new IllegalArgumentException("Null graph argument."); } this.graph = graph; this.inDegrees = inDegrees; } // public List<List<V>> findSimpleCycles() { public Set<V> findSimpleCycles() { initState(); // Kosaraju<V> kosaraju = new Kosaraju<>(); // List<Set<V>> sccs = kosaraju.sccs(graph); SCCTarjan<V> tarjan = new SCCTarjan<>(); List<Set<V>> sccs = tarjan.scc(graph); // if (sccs.size() > 1) return Collections.emptySet(); for (Set<V> scc : sccs) { int maxInDegree = -1; V startVertex = null; for (V v : scc) { int inDegree = inDegrees.get(v); if (inDegree > maxInDegree) { maxInDegree = inDegree; startVertex = v; } } startVertices.add(startVertex); } for (V vertex : startVertices) { cycle(toI(vertex), 0); if (commonNodes.isEmpty()) break; } // List<List<V>> result = cycles; // return result; return commonNodes; } private boolean cycle(int v, int q) { boolean foundCycle = false; V vV = toV(v); marked.add(vV); stack.push(vV); int t = stack.size(); position[v] = t; if (!reach[v]) { q = t; } Set<V> avRemoved = getRemoved(vV); Iterator<V> avIt = graph.get(vV).iterator(); while (avIt.hasNext()) { V wV = avIt.next(); if (avRemoved.contains(wV)) { continue; } int w = toI(wV); if (!marked.contains(wV)) { boolean gotCycle = cycle(w, q); if (gotCycle) { foundCycle = gotCycle; } else { noCycle(v, w); } } else if (position[w] <= q) { foundCycle = true; List<V> cycle = new ArrayList<V>(); Iterator<V> it = stack.descendingIterator(); V current = null; while (it.hasNext()) { current = it.next(); if (wV.equals(current)) { break; } } cycle.add(wV); while (it.hasNext()) { current = it.next(); cycle.add(current); if (current.equals(vV)) { break; } } cycles.add(cycle); commonNodes.retainAll(cycle); if (commonNodes.isEmpty()) return true; } else { noCycle(v, w); } } stack.pop(); if (foundCycle) { unmark(v); } reach[v] = true; position[v] = graph.size(); return foundCycle; } public boolean hasCycles() { return !cycles.isEmpty(); } private void noCycle(int x, int y) { V xV = toV(x); V yV = toV(y); Set<V> by = getBSet(yV); Set<V> axRemoved = getRemoved(xV); by.add(xV); axRemoved.add(yV); } private void unmark(int x) { V xV = toV(x); marked.remove(xV); Set<V> bx = getBSet(xV); for (V yV : bx) { Set<V> ayRemoved = getRemoved(yV); ayRemoved.remove(xV); if (marked.contains(yV)) { unmark(toI(yV)); } } bx.clear(); } private void initState() { cycles = new ArrayList<List<V>>(); iToV = (V[]) graph.keySet().toArray(); vToI = new HashMap<V, Integer>(); bSets = new HashMap<V, Set<V>>(); stack = new ArrayDeque<V>(); marked = new HashSet<V>(); removed = new HashMap<V, Set<V>>(); int size = graph.size(); position = new int[size]; reach = new boolean[size]; startVertices = new ArrayList<V>(); for (int i = 0; i < iToV.length; i++) { vToI.put(iToV[i], i); } commonNodes = new HashSet(graph.keySet()); } private Integer toI(V v) { return vToI.get(v); } private V toV(int i) { return iToV[i]; } private Set<V> getBSet(V v) { Set<V> result = bSets.get(v); if (result == null) { result = new HashSet<V>(); bSets.put(v, result); } return result; } private Set<V> getRemoved(V v) { Set<V> result = removed.get(v); if (result == null) { result = new HashSet<V>(); removed.put(v, result); } return result; } } class SCCTarjan<V> { Map<V, Collection<V>> graph; Map<V, Boolean> visited; Stack<V> stack; int time; Map<V, Integer> lowlink; List<Set<V>> components; public List<Set<V>> scc(Map<V, Collection<V>> graph) { this.graph = graph; visited = new HashMap<>(); stack = new Stack<>(); time = 0; lowlink = new HashMap<>(); components = new ArrayList<>(); for (V u : graph.keySet()) { lowlink.put(u, 0); } for (V u : graph.keySet()) if (!visited.containsKey(u)) dfs(u); return components; } void dfsRec(V u) { lowlink.put(u, time++); visited.put(u, true); stack.add(u); boolean isComponentRoot = true; // System.out.println("A---"); // System.out.println(lowlink); // System.out.println(visited); // System.out.println(stack); // System.out.println(isComponentRoot); // System.out.println("---"); for (V v : graph.get(u)) { if (!visited.containsKey(v)) dfsRec(v); if (lowlink.get(u) > lowlink.get(v)) { lowlink.put(u, lowlink.get(v)); isComponentRoot = false; } } // System.out.println("---"); // System.out.println(lowlink); // System.out.println(visited); // System.out.println(stack); // System.out.println(isComponentRoot); // System.out.println("B---"); if (isComponentRoot) { Set<V> component = new HashSet<>(); while (true) { V x = stack.pop(); component.add(x); lowlink.put(x, Integer.MAX_VALUE); if (x == u) break; } components.add(component); } } void dfs(V u) { dfsRec(u); } void dfsIt(V u) { boolean isComponentRoot = true; Stack<V> search = new Stack<>(); search.push(u); while (!search.isEmpty()) { V u2 = search.pop(); lowlink.put(u2, time++); visited.put(u2, true); stack.add(u2); System.out.println("---"); System.out.println(lowlink); System.out.println(visited); System.out.println(stack); System.out.println(isComponentRoot); System.out.println("---"); boolean wentSomewhere = false; for (V v : graph.get(u2)) { if (!visited.containsKey(v)) { wentSomewhere = true; search.push(v); continue; } if (lowlink.get(u2) > lowlink.get(v)) { lowlink.put(u2, lowlink.get(v)); isComponentRoot = false; } } System.out.println("---"); System.out.println(lowlink); System.out.println(visited); System.out.println(stack); System.out.println(isComponentRoot); System.out.println("---"); if (!wentSomewhere) if (isComponentRoot) { Set<V> component = new HashSet<>(); while (true) { V x = stack.pop(); component.add(x); lowlink.put(x, Integer.MAX_VALUE); if (x == u2) break; } components.add(component); } } } } class Kosaraju<V> { public List<Set<V>> sccs(Map<V, Collection<V>> graph) { List<Set<V>> result = new ArrayList<>(); Set<V> visited = new HashSet<>(); Stack<V> s = new Stack<>(); for (V v : graph.keySet()) { dfs(graph, visited, v, s); } Map<V, Collection<V>> transposed = transpose(graph); // System.out.println("transposed: " + transposed); visited = new HashSet<>(); while (!s.isEmpty()) { V v = s.pop(); if (!visited.contains(v)) { Set<V> comp = new HashSet<>(); dfs(transposed, visited, v, comp); result.add(comp); } } return result; } void dfs(Map<V, Collection<V>> graph, Set<V> visited, V v, Stack<V> stack) { Stack<V> dfsStack = new Stack<>(); if (!visited.contains(v)) { dfsStack.push(v); stack.push(v); while (!dfsStack.isEmpty()) { V popped = dfsStack.pop(); visited.add(popped); for (V next : graph.get(popped)) { if (!visited.contains(next)) { dfsStack.push(next); stack.push(next); } } } } } void dfs(Map<V, Collection<V>> graph, Set<V> visited, V v, Set<V> stack) { Stack<V> dfsStack = new Stack<>(); if (!visited.contains(v)) { dfsStack.push(v); stack.add(v); while (!dfsStack.isEmpty()) { V popped = dfsStack.pop(); visited.add(popped); for (V next : graph.get(popped)) { if (!visited.contains(next)) { dfsStack.push(next); stack.add(next); } } } } } public Map<V, Collection<V>> transpose(Map<V, Collection<V>> graph) { Map<V, Collection<V>> transposed = new HashMap<>(); for (V from : graph.keySet()) { if (!transposed.containsKey(from)) transposed.put(from, new HashSet<>()); for (V to : graph.get(from)) { if (!transposed.containsKey(to)) transposed.put(to, new HashSet<>()); transposed.get(to).add(from); } } return transposed; } } class Johnson<V> { class NodeAndNeighbors<V> { V node; Collection<V> neighbors; NodeAndNeighbors(V node, Collection<V> neighbors) { this.node = node; this.neighbors = neighbors; } @Override public String toString() { return "[" + node + "," + neighbors + "]"; } } Set<V> commonNodes; public List<Set<V>> cycles(Map<V, Collection<V>> graph, Map<V, Collection<V>> ins) { commonNodes = new HashSet<>(graph.keySet()); Kosaraju<V> kosaraju = new Kosaraju<>(); LinkedList<Set<V>> sccs = new LinkedList<>(kosaraju.sccs(graph)); // System.out.println("sccs: " + sccs); List<Set<V>> cycles = new ArrayList<>(); while (!sccs.isEmpty()) { Set<V> scc = sccs.pop(); V start = scc.iterator().next(); LinkedList<V> path = new LinkedList<>(); path.add(start); Set<V> blocked = new HashSet<>(); Set<V> closed = new HashSet<>(); blocked.add(start); Map<V, Set<V>> B = new HashMap<>(); Stack<NodeAndNeighbors<V>> stack = new Stack<>(); stack.push(new NodeAndNeighbors<>(start, new HashSet(graph.get(start)))); while (!stack.isEmpty()) { NodeAndNeighbors<V> nodeAndNeighbors = stack.peek(); V thisNode = nodeAndNeighbors.node; Collection<V> neighbors = nodeAndNeighbors.neighbors; if (!neighbors.isEmpty()) { V next = neighbors.iterator().next(); neighbors.remove(next); if (next.equals(start)) { Set<V> cycle = new HashSet<>(path); cycles.add(cycle); commonNodes.retainAll(cycle); if (commonNodes.isEmpty()) return cycles; closed.addAll(path); } else if (!blocked.contains(next)) { path.add(next); stack.push(new NodeAndNeighbors<>(next, new HashSet(graph.get(next)))); closed.remove(next); blocked.add(next); continue; } } // System.out.println("cycles: " + cycles); // System.out.println("graph: " + graph); // System.out.println("ins: " + ins); // System.out.println("start: " + start); // System.out.println("path: " + path); // System.out.println("blocked: " + blocked); // System.out.println("closed: " + closed); // System.out.println("B: " + B); // System.out.println("stack: " + stack); // System.out.println("neighbors: " + neighbors); // System.out.println("thisNode: " + thisNode); if (neighbors.isEmpty()) { if (closed.contains(thisNode)) { // System.out.println("unblock: " + thisNode + " " + blocked + " " + B); unblock(thisNode, blocked, B); } else { for (V neighbor : graph.get(thisNode)) { if (!B.containsKey(neighbor)) B.put(neighbor, new HashSet<>()); if (!B.get(neighbor).contains(thisNode)) B.get(neighbor).add (thisNode); } } stack.pop(); path.pop(); } } removeNode(graph, ins, start); sccs.addAll(kosaraju.sccs(graph)); } return cycles; } Set<V> getCommonNodes() { return commonNodes; } void removeNode(Map<V, Collection<V>> graph, Map<V, Collection<V>> ins, V node) { // System.out.println("TOREMOVE " + node); // System.out.println("! " + graph); // System.out.println("! " + ins); Set<V> removedNodePointingTo = new HashSet<>(graph.get(node)); graph.remove(node); for (V v : ins.get(node)) { graph.get(v).remove(node); // if (graph.get(v).isEmpty()) graph.remove(v); } ins.remove(node); for (V pointingTo : removedNodePointingTo) { ins.get(pointingTo).remove(node); // if (ins.get(pointingTo).isEmpty()) ins.remove(pointingTo); } // System.out.println("! " + graph); // System.out.println("! " + ins); } Map<V, Collection<V>> subgraph(Map<V, Collection<V>> graph, Collection<V> nodesPersisted) { Map<V, Collection<V>> subgraph = new HashMap<>(); Set<V> nodesToRemove = new HashSet<>(graph.keySet()); nodesToRemove.removeAll(nodesPersisted); for (V node : nodesPersisted) { subgraph.put(node, new HashSet<>(graph.get(node))); } for (V node : subgraph.keySet()) { subgraph.get(node).removeAll(nodesToRemove); } return subgraph; } void unblock(V thisNode, Set<V> blocked, Map<V, Set<V>> B) { Set<V> stack = new HashSet<>(); stack.add(thisNode); while (!stack.isEmpty()) { V node = stack.iterator().next(); stack.remove(node); if (blocked.contains(node)) { blocked.remove(node); if (B.containsKey(node)) { stack.addAll(B.get(node)); B.get(node).clear(); } } } } } |