zoukankan      html  css  js  c++  java
  • 洛谷 P2863 [USACO06JAN]牛的舞会The Cow Prom

    牛的舞会(tarjan板子题)

    tarjan算法学习过程中必做的一道板子题。

    #include <iostream>
    #include <cstring>
    #include <cstdio>
    #include <stack>
    #include <queue>
    using namespace std;
    //Mystery_Sky
    //
    #define maxn 1000010
    #define INF 0x3f3f3f3f
    struct Edge{
    	int to;
    	int next;
    }edge[maxn];
    stack <int> st;
    int low[maxn], dfn[maxn], vis[maxn];
    int head[maxn], cnt;
    int scc, ans, tot, num[maxn];
    int n, m, u, v;
    inline void add_edge(int u, int v)
    {
    	edge[++cnt].to = v;
    	edge[cnt].next = head[u];
    	head[u] = cnt;
    }
    
    void tarjan(int u)
    {
    	dfn[u] = low[u] = ++tot;
    	st.push(u);
    	vis[u] = 1;
    	for(int i = head[u]; i; i = edge[i].next) {
    		int v = edge[i].to;
    		if(!dfn[v]) {
    			tarjan(v);
    			low[u] = min(low[u], low[v]);
    		}
    		else if(vis[v]) low[u] = min(low[u], dfn[v]);
    	}
    	if(dfn[u] == low[u]) {
    		int j;
    		scc++;
    		do {
    			j = st.top();
    			st.pop();
    			vis[j] = 0;
    			num[scc]++;	
    		} while(j != u);
    	} 
    }
    
    int main() {
    	scanf("%d%d", &n, &m);
    	for(int i = 1; i <= m; i++) {
    		scanf("%d%d", &u, &v);
    		add_edge(u, v);
    	}
    	for(int i = 1; i <= n; i++) 
    		if(!dfn[i]) tarjan(i);
    	for(int i = 1; i <= scc; i++) {
    		if(num[i] > 1) ans++;
    	}
    	printf("%d
    ", ans);
    	return 0;
    }
    
    
    唯愿,青春不辜负梦想,未来星辰闪耀
  • 相关阅读:
    【NOIP2017】奶酪
    【NOIP2017】时间复杂度
    【NOIP2005】过河
    【洛谷习题】垃圾陷阱
    dfs序
    bzoj2441 小W的问题
    彩色迷宫
    蛋糕与蛋挞
    树上倍增
    因数个数定理
  • 原文地址:https://www.cnblogs.com/Benjamin-cpp/p/10498114.html
Copyright © 2011-2022 走看看