原题传送门
又是可以用上强连通分量
使用tarjan缩点,缩好的点建新图
问1:就是求新图入度为0的点个数,没毛病吧
问2:任一点都能到达其他点,说明是形成了一个环。环中任意一点入度出度不为0,那么我们只要求出入度为0的点个数与出度为0的点个数的更大的那个就行了(yy一下)
有一个注意点就是,新图中只有一个点的情况要特判,答案是 1 1 1 0 0 0
Code:
#include <bits/stdc++.h>
#define maxn 10010
using namespace std;
struct Edge{
int to, next;
}edge[maxn << 1];
struct Line{
int x, y;
}line[maxn];
int num, head[maxn], dfn[maxn], low[maxn], Index, tot;
int top, cnt, sta[maxn], vis[maxn], n, color[maxn], in[maxn], out[maxn];
inline int read(){
int s = 0, w = 1;
char c = getchar();
for (; !isdigit(c); c = getchar()) if (c == '-') w = -1;
for (; isdigit(c); c = getchar()) s = (s << 1) + (s << 3) + (c ^ 48);
return s * w;
}
void addedge(int x, int y){ edge[++num] = (Edge) { y, head[x] }; head[x] = num; }
void tarjan(int u){
dfn[u] = low[u] = ++Index;
vis[u] = 1, sta[++top] = u;
for (int i = head[u]; i; i = edge[i].next){
int v = edge[i].to;
if (!dfn[v]) tarjan(v), low[u] = min(low[u], low[v]); else
if (vis[v]) low[u] = min(low[u], dfn[v]);
}
if (dfn[u] == low[u]){
++tot;
while (sta[top + 1] != u)
color[sta[top]] = tot, vis[sta[top--]] = 0;
}
}
int main(){
n = read();
for (int i = 1; i <= n; ++i){
int x = read();
while (x) line[++cnt] = (Line) { i, x }, addedge(i, x), x = read();
}
for (int i = 1; i <= n; ++i)
if (!dfn[i]) tarjan(i);
num = 0;
memset(head, 0, sizeof(head));
for (int i = 1; i <= cnt; ++i)
if (color[line[i].x] != color[line[i].y])
addedge(color[line[i].x], color[line[i].y]),
++in[color[line[i].y]], ++out[color[line[i].x]];
int ans1 = 0, ans2 = 0;
for (int i = 1; i <= tot; ++i){
if (!in[i]) ++ans1;
if (!out[i]) ++ans2;
}
if (tot == 1) printf("1\n0\n"); else
printf("%d\n%d\n", ans1, max(ans1, ans2));
return 0;
}