要加边使一个图成为一个强连通分量,只需加max(出度为0的点数,入度为0的点数)条边(可以不使用tarjan算法)。题目数据有点弱,网上一些人所谓 结果 = 出度为0的点的数量+入度为0的点的数量 是错的,代码尾提供一种可以hack的数据
#include<bits/stdc++.h> using namespace std; typedef long long LL; const int N=110; int n,T; int in[N],out[N]; void init() { memset(in,0,sizeof(in)); memset(out,0,sizeof(out)); } int main() { scanf("%d",&T); while(T--) { scanf("%d",&n); init(); int v; for(int i=1;i<=n;i++) while(scanf("%d",&v)&&v) in[i]++,out[v]++; int ans1=0,ans2=0; for(int i=1;i<=n;i++) { if(!in[i]) ans1++; if(!out[i]) ans2++; } cout<<max(ans1,ans2)<<endl; } } /* 1 3 2 3 0 0 0 */