先求一发 scc 然后缩点,然后根据入度出度为 (0) 的点的个数乱搞。
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
int T, n, m, hea[20005], cnt, uu, vv, bel[20005], scc, din, sta[20005], idx;
int dfn[20005], loo[20005], ind[20005], oud[20005], cnt1, cnt2;
bool ins[20005];
struct Edge{
int too, nxt;
}edge[100005];
void add_edge(int fro, int too){
edge[++cnt].nxt = hea[fro];
edge[cnt].too = too;
hea[fro] = cnt;
}
void tarjan(int x){
dfn[x] = loo[x] = ++idx;
ins[x] = true;
sta[++din] = x;
for(int i=hea[x]; i; i=edge[i].nxt){
int t=edge[i].too;
if(!dfn[t]){
tarjan(t);
loo[x] = min(loo[x], loo[t]);
}
else if(ins[t]) loo[x] = min(loo[x], dfn[t]);
}
if(dfn[x]==loo[x]){
scc++;
int j;
do{
j = sta[din--];
ins[j] = false;
bel[j] = scc;
}while(dfn[j]!=loo[j]);
}
}
int main(){
cin>>T;
while(T--){
memset(hea, 0, sizeof(hea));
memset(dfn, 0, sizeof(dfn));
memset(loo, 0, sizeof(loo));
memset(ind, 0, sizeof(ind));
memset(oud, 0, sizeof(oud));
cnt = scc = din = idx = cnt1 = cnt2 = 0;
scanf("%d %d", &n, &m);
for(int i=1; i<=m; i++){
scanf("%d %d", &uu, &vv);
add_edge(uu, vv);
}
for(int i=1; i<=n; i++)
if(!dfn[i])
tarjan(i);
for(int i=1; i<=n; i++)
for(int j=hea[i]; j; j=edge[j].nxt){
int t=edge[j].too;
if(bel[i]!=bel[t]){
ind[bel[t]]++;
oud[bel[i]]++;
}
}
for(int i=1; i<=scc; i++){
if(!ind[i]) cnt1++;
if(!oud[i]) cnt2++;
}
if(scc==1) printf("0
");
else
printf("%d
", max(cnt1, cnt2));
}
return 0;
}