http://poj.org/problem?id=3180
题意:n个点,m条边,求节点数大于1的强连通分量数。
强连通分量的模板题,只需要计数每个强连通分量的点数,找出大于1的即可。
#include<iostream>
#include<cstdio>
#include<stack>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn=20010,maxm=200100;
int dfn[maxn],low[maxn],head[maxn],color[maxn],sum[maxn];
int n,m,k,cnt,deep,ans;
bool vis[maxn];
struct edge{
int v,next;
}e[maxm];
stack<int> s;
void addedge(int u,int v){e[k].v=v;e[k].next=head[u];head[u]=k++;}
void tarjan(int u)
{
deep++;
dfn[u]=deep;
low[u]=deep;
vis[u]=1;
s.push(u);
for(int i=head[u];~i;i=e[i].next)
{
int v=e[i].v;
if(!dfn[v])
{
tarjan(v);
low[u]=min(low[u],low[v]);
}
else
{
if(vis[v])
{
low[u]=min(low[u],low[v]);
}
}
}
if(dfn[u]==low[u])
{
cnt++;
color[u]=cnt;
vis[u]=0;
while(s.top()!=u)
{
color[s.top()]=cnt;
vis[s.top()]=0;
s.pop();
}
s.pop();
}
}
int main()
{
int x,y;
memset(head,-1,sizeof(head));
scanf("%d%d",&n,&m);
for(int i=1;i<=m;i++)
{
scanf("%d%d",&x,&y);
addedge(x,y);
}
for(int i=1;i<=n;i++)
{
if(!dfn[i])
tarjan(i);
}
for(int i=1;i<=n;i++)
sum[color[i]]++;
for(int i=1;i<=cnt;i++)
if(sum[i]>1)
ans++;
printf("%d\n",ans);
return 0;
}