思路:该题和HDU1287一样,不用计算最小的花费,蛋疼的是你必须动态分配内存,否则RE
就是找入度为0的连通分支的个数。
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<vector>
#include<stack>
#include<string.h>
#define max 100009
using namespace std;
int N,M;
int X,Y,SCC;
int tem;
int n;
struct node
{
int u,v,next;
}*Edge;
stack<int>sta;
int vis[max];
int dfn[max],low[max];
int belong[max];
int head[max];
int ind[max];
int k;
int MIN(int a,int b)
{
return a>b?b:a;
}
void add(int u,int v)
{
Edge[k].u=u;
Edge[k].v=v;
Edge[k].next=head[u];
head[u]=k++;
}
void tarjan(int x)
{
vis[x]=2;
dfn[x]=low[x]=++n;
sta.push(x);
for(int i=head[x]; i!=-1; i=Edge[i].next)
{
// printf("%d\n",i);
int t=Edge[i].v;
if(!dfn[t])
{
tarjan(t);
low[x]=MIN(low[x],low[t]);
}
else if(vis[t]==2)
{
low[x]=MIN(low[x],dfn[t]);
}
}
if(low[x]==dfn[x])
{
tem++;
while(!sta.empty())
{
int m=sta.top();
sta.pop();
vis[m]=1;
belong[m]=tem;
ind[m]=0;
if(x==m)
break;
}
}
}
int main()
{
int a,b;
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&N,&M);
Edge =new node[max+5];
SCC=k=tem=X=Y=n=0;
memset(vis,0,sizeof(vis));
memset(dfn,0,sizeof(dfn));
memset(low,0,sizeof(low));
memset(head,-1,sizeof(head));
while(!sta.empty())
sta.pop();
for(int i=0; i<M; i++)
{
scanf("%d%d",&a,&b);
add(a,b);
}
for(int i=1; i<=N; i++)
if(!dfn[i])
tarjan(i);
for(int j=0; j<k; j++)
{
int s=belong[Edge[j].u];
int e=belong[Edge[j].v];
if(s!=e)
ind[e]++;
}
for(int i=1; i<=tem; i++)
{
if(ind[i]==0)
SCC++;
}
printf("%d\n",SCC);
delete[] Edge;
}
return 0;
}