int n, m; int w[N]; int f[N]; vector<int> h[N], nh[N]; int dfn[N], low[N], tot; int stk[N], instk[N], top; int scc[N], sz[N], cnt;
voidtarjan(int u) { dfn[u] = low[u] = ++tot; stk[++top] = u, instk[u] = 1; for (int i = 0; i < h[u].size(); i++) { int v = h[u][i]; if (!dfn[v]) { tarjan(v); low[u] = min(low[u], low[v]); } elseif (instk[v]) low[u] = min(low[u], dfn[v]); }
if (dfn[u] == low[u]) { cnt++; int v; do { v = stk[top--]; instk[v] = 0; scc[v] = cnt; sz[cnt] += w[v]; } while (u != v); } }
voiddfs(int u) { for (int i = 0; i < nh[u].size(); i++) { int v = nh[u][i]; if (!f[v]) dfs(v); f[u] = max(f[u], f[v]); } f[u] += sz[u]; }
intmain() { cin >> n >> m; for (int i = 1; i <= n; i++) cin >> w[i]; for (int i = 0; i < m; i++) { int a, b; cin >> a >> b; h[a].push_back(b); }
for (int i = 1; i <= n; i++) if (!dfn[i]) tarjan(i); for (int i = 1; i <= n; i++) for (int j = 0; j < h[i].size(); j++) { int u = scc[i], v = scc[h[i][j]]; if (u != v) nh[u].push_back(v); }
int res = 0; for (int i = 1; i <= cnt; i++) if (!f[i]) { dfs(i); res = max(res, f[i]); }
int n; vector<int> h[N]; int dfn[N], low[N], tot; int stk[N], instk[N], top; int scc[N], sz[N], cnt; int in[N], out[N];
voidtarjan(int u) { dfn[u] = low[u] = ++tot; stk[++top] = u, instk[u] = 1; for (int i = 0; i < h[u].size(); i++) { int v = h[u][i]; if (!dfn[v]) { tarjan(v); low[u] = min(low[u], low[v]); } elseif (instk[v]) low[u] = min(low[u], dfn[v]); }
if (dfn[u] == low[u]) { cnt++; int v; do { v = stk[top--]; instk[v] = 0; scc[v] = cnt; sz[cnt]++; } while (u != v); } }
intmain() { cin >> n; for (int i = 1; i <= n; i++) { int x; while (cin >> x, x) h[i].push_back(x); }
for (int i = 1; i <= n; i++) if (!dfn[i]) tarjan(i); for (int i = 1; i <= n; i++) for (int j = 0; j < h[i].size(); j++) if (scc[h[i][j]] != scc[i]) in[scc[h[i][j]]]++, out[scc[i]]++; int r1 = 0, r2 = 0; for (int i = 1; i <= cnt; i++) { if (!in[i]) r1++; if (!out[i]) r2++; }