#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cstdlib>
#include<stack>
using namespace std;
const int maxn =105;
int map[maxn][maxn];
int low[maxn];
int dfn[maxn];
int in[maxn];
int out[maxn];
int instack[maxn];
int t[maxn];
int n,order,res,ans;
stack<int>s;
void init()
{
memset(map,0,sizeof(map));
memset(low,0,sizeof(low));
memset(dfn,0,sizeof(dfn));
memset(in,0,sizeof(in));
memset(out,0,sizeof(out));
memset(instack,0,sizeof(instack));
memset(t,0,sizeof(t));
while(!s.empty())
s.pop();
res=0;
order=0;
}
int min(int x,int y)
{
return x<y?x:y;
}
void tr(int u)
{
int v;
dfn[u]=low[u]=++order;
instack[u]=1;
s.push(u);
for(int i=1;i<=n;i++)
{
if(map[u][i])
{
if(!dfn[i])
{
tr(i);
low[u]=min(low[u],low[i]);
}
else if(instack[i])
low[u]=min(low[u],dfn[i]);
}
}
if(dfn[u]==low[u])
{
++res;
do{
v=s.top();
s.pop();
instack[v]=0;
t[v]=res;
}while(v!=u);
}
}
void tarjan()
{
for(int i=1;i<=n;i++)
{
if(!dfn[i])
tr(i);
}
}
void solve()
{
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
if(map[i][j]&&t[i]!=t[j])
{
++in[t[j]];
++out[t[i]];
}
}
int xx,yy;
xx=yy=0;
for(int i=1;i<=res;i++)
{
if(in[i]==0)
xx++;
else if(out[i]==0)
yy++;
}
ans=xx>yy?xx:yy;
}
int main()
{
int T,x;
scanf("%d",&T);
while(T--)
{
init();
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
while(scanf("%d",&x),x)
map[i][x]=1;
}
tarjan();
solve();
if(res==1)
printf("0\n");
else
printf("%d\n",ans);
}
return 0;
}
强连通缩点
最新推荐文章于 2022-05-18 19:18:44 发布