【USACO】The Cow Prom

【题目链接】

          点击打开链接

【算法】

        tarjan求强连通分量

【代码】

        

#include
#define MAXN 20005

using namespace std; 

int i,N,M,u,v,id,cnt;
int dfn[MAXN],low[MAXN],vis[MAXN];
vector edge[MAXN];
stack stk;

void dfs(int u) {
		int i,to,sum;
		dfn[u] = low[u] = ++id;
		stk.push(u); vis[u] = 1;
		for (i = 0; i < edge[u].size(); i++) {
				to = edge[u][i];
				if (!dfn[to]) {
						dfs(to);
						low[u] = min(low[u],low[to]);
				}	
				else {
						if (vis[to])
								low[u] = min(low[u],dfn[to]);
				}
		}	
		if (dfn[u] == low[u]) {
				sum = 0;
				while (true) {
						sum++;
						vis[stk.top()] = 0;
						if (stk.top() == u) {
								stk.pop();
								break;
						}
						stk.pop();
				}
				cnt += (sum > 1);
		}
}

int main() {
    
		scanf("%d%d",&N,&M);
		for (i = 1; i <= M; i++) {
				scanf("%d%d",&u,&v);
				edge[u].push_back(v);		
		}
		
		for (i = 1; i <= N; i++) {
				if (!dfn[i])
						dfs(i);
		}
		
		printf("%d\n",cnt);
		
		return 0;
	
}

你可能感兴趣的:(图的联通性,tarjan算法)