/**
* @verified https://atcoder.jp/contests/practice2/tasks/practice2_g
*/
class SCC {
static class Edge {
int from, to;
public Edge(int from, int to) {
this.from = from; this.to = to;
}
}
final int n;
int m;
final java.util.ArrayList unorderedEdges;
final int[] start;
final int[] ids;
boolean hasBuilt = false;
public SCC(int n) {
this.n = n;
this.unorderedEdges = new java.util.ArrayList();
this.start = new int[n + 1];
this.ids = new int[n];
}
public void addEdge(int from, int to) {
rangeCheck(from);
rangeCheck(to);
unorderedEdges.add(new Edge(from, to));
start[from + 1]++;
this.m++;
}
public int id(int i) {
if (!hasBuilt) {
throw new UnsupportedOperationException(
"Graph hasn't been built."
);
}
rangeCheck(i);
return ids[i];
}
public int[][] build() {
for (int i = 1; i = 0) continue;
par[i] = -1;
// vertex i, 0th child.
stack[ptr++] = 0l 0) {
// last element
long p = stack[--ptr];
// vertex
int u = (int) (p & 0xffff_ffffl);
// jth child
int j = (int) (p >>> 32);
if (j == 0) { // first visit
low[u] = ord[u] = nowOrd++;
vis[k++] = u;
}
if (start[u] + j 0) {
int to = orderedEdges[start[u] + j].to;
// update lowlink
if (par[to] == u) low[u] = Math.min(low[u], low[to]);
}
if (low[u] == ord[u]) { // root of a component
while (true) { // gathering verticies
int v = vis[--k];
ord[v] = n;
ids[v] = groupNum;
if (v == u) break;
}
groupNum++; // incr the number of components
}
}
}
}
for (int i = 0; i = n) {
throw new IndexOutOfBoundsException(
String.format("Index %d out of bounds for length %d", i, n)
);
}
}
}