【CodeVS】2822 爱在心中 [2017年6月计划 强连通分量03]
2822 爱在心中
 时间限制: 1 s 
 空间限制: 128000 KB 
 题目等级 : 钻石 Diamond 
一个人不算天使,模板题稍微修改一下即可过
良心样例
#include <bits/stdc++.h>
inline int max(int a, int b){return a < b ? b : a;}
inline int min(int a, int b){return a < b ? a : b;}
inline void read(int &x){x = 0;char ch = getchar();char c = ch;while(ch > '9' || ch < '0')c = ch, ch = getchar();while(ch <= '9' && ch >= '0')x = x * 10 + ch - '0', ch = getchar();if(c == '-')x = -x;}
inline void read(long long &x){x = 0;char ch = getchar();char c = ch;while(ch > '9' || ch < '0')c = ch, ch = getchar();while(ch <= '9' && ch >= '0')x = x * 10 + ch - '0', ch = getchar();if(c == '-')x = -x;}
const int INF = 0x3f3f3f3f;
const int MAXN = 100000 + 10;
const int MAXM = 100000 + 10;
struct Edge
{
	int u,v,next;
}edge1[MAXM];
int head1[MAXM],cnt1;
inline void insert1(int a, int b){edge1[++cnt1] = Edge{a, b, head1[a]};head1[a] = cnt1;}
Edge edge2[MAXM];
int head2[MAXN],cnt2;
inline void insert2(int a, int b){edge2[++cnt2] = Edge{a, b, head2[a]};head2[a] = cnt2;}
int n,m;
int stack[MAXN],top,t,group,belong[MAXN],dfn[MAXN],low[MAXN],num[MAXN];
bool b[MAXN], bb[MAXN];
int tmp1, tmp2;
int ans, ansgroup;
void dfs(int u)
{
	dfn[u] = low[u] = ++t;
	b[u] = bb[u] = true;
	stack[++top] = u;
	for(int pos = head1[u];pos;pos = edge1[pos].next)
	{
		int v = edge1[pos].v;
		if(!b[v])
		{
			dfs(v);
			low[u] = min(low[v], low[u]);
		}
		else if(bb[v] && low[u] > dfn[v])
		{
			low[u] = dfn[v];
		}
	}
	
	if(low[u] == dfn[u])
	{
		group ++;
		int now = 0;
		while(now != u)
		{
			now = stack[top--];
			belong[now] = group;
			bb[now] = false;
			num[group] ++;
		}
		if(num[group] > 1)ansgroup ++;
	}
} 
inline void rebuild()
{
	for(int u = 1;u <= n;u ++)
	{
		for(int pos = head1[u];pos;pos = edge1[pos].next)
		{
			int v = edge1[pos].v;
			if(belong[u] != belong[v])
			{
				insert2(belong[u], belong[v]);
			}
		}
	}
}
inline void tarjan()
{
	for(int i = 1;i <= n;i ++)if(!b[i])dfs(i);
	rebuild();
}
int main()
{
	read(n);read(m);
	for(int i = 1;i <= m;i ++)
	{
		read(tmp1);read(tmp2);
		insert1(tmp1, tmp2);
	}
	tarjan();
	printf("%d\n", ansgroup);
	for(int i = 1;i <= group;i ++)
	{
		if(!head2[i])
		{
			if(ans)
			{
				ans = 0;break;
			}
			else if(num[i] != 1)
			{
				ans = i;
			}
		}
	}
	if(ans == 0)
	{
		printf("-1");
		return 0;
	}
	for(int i = 1;i <= n;i ++)
	{
		if(belong[i] == ans)
		{
			printf("%d ", i);
		}
	}
	return 0;
} 

                
            
        
浙公网安备 33010602011771号