POJ 3180 The Cow Prom 强连通分量

题目链接:http://poj.org/problem?id=3180

一句话题面:求出图中元素个数≥2的强连通分量个数。

题解:

我们先强连通缩点,然后貌似找出元素个数大于2的就好了。

AC代码:

#include 
#include 
#include 
using namespace std;
stack  dl;
const int MAXN = 150000;
int head[MAXN],to[MAXN],nxt[MAXN],dfn[MAXN],low[MAXN],ins[MAXN],sg[MAXN];
int oud[MAXN],sum[MAXN];
int cnt,n,m,a,b,tot,nfg,tjs;
void ad_edg(int x,int y)
{
	nxt[++tjs] = head[x];
	head[x] = tjs;
	to[tjs] = y;
}
void sread()
{
	scanf("%d%d",&n,&m);
	for (int i = 1;i <= m;i++)
	{
		scanf("%d%d",&a,&b);
		if (a == b) continue;
		ad_edg(a,b);
	}
}
void tarjan(int x)
{
	dfn[x] = low[x] = ++cnt;
	dl.push(x),ins[x] = 1;
	for (int i = head[x];i;i = nxt[i])
	{
		if (!dfn[to[i]])
		{
			tarjan(to[i]);
			low[x] = min(low[x],low[to[i]]);
		}else if (ins[to[i]])
			low[x] = min(low[x],dfn[to[i]]);
		
	}
	if (low[x] == dfn[x])
		{
			sg[x] = ++tot,sum[tot]++;
			while (dl.top() != x) ins[dl.top()] = 0,sg[dl.top()] = tot,dl.pop(),sum[tot]++;
			ins[x] = 0,dl.pop();
		}
}
void swork()
{
	for (int i = 1;i <= n;i++)
		if (!dfn[i]) tarjan(i);
	a = 0;
	for (int i = 1;i <= n;i++)
		if (sum[i] >= 2) a++;
	printf("%d\n",a);
}
int main()
{
	sread();
	swork();
	return 0;
}


你可能感兴趣的:(强连通,POJ)