POJ 2186 挑战 --牛红人 强连通分量——Tarjan
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                POJ  2186   挑战 --牛红人  强连通分量——Tarjan
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                題意:n頭奶牛,給出若干個歡迎關系a b,表示a歡迎b,歡迎關系是單向的,但是是可以傳遞的,如:a歡迎b,b歡迎c,那么a歡迎c 。另外每個奶牛都是歡迎他自己的。求出被所有的奶牛歡迎的奶牛的數目.#include <iostream>#include <cstdio>
#include <cstring> #include <cstdlib> #include <cmath> #include <vector> #include <queue> #include <stack> #include <map> #include <algorithm> #include <set> using namespace std; typedef long long ll; typedef unsigned long long Ull; #define MM(a,b) memset(a,b,sizeof(a)); const double eps = 1e-10; const int inf =0x7f7f7f7f; const double pi=acos(-1); const int maxn=10000;vector<int> G[maxn+10]; int n,m,deg[maxn+10],pre[maxn+10],dfs_clock,scc_cnt,sccno[maxn+10],lowlink[maxn+10]; stack<int> S;void tarjan(int u) {pre[u]=lowlink[u]=++dfs_clock;S.push(u);for(int i=0;i<G[u].size();i++){int v=G[u][i];if(!pre[v]){tarjan(v);lowlink[u]=min(lowlink[u],lowlink[v]);}else if(!sccno[v])lowlink[u]=min(lowlink[u],pre[v]);}if(lowlink[u]==pre[u]){scc_cnt++;while(1){int x=S.top();S.pop();sccno[x]=scc_cnt;if(x==u) break;//找到了當前強連通的起始節點就退出,//不然會破壞其他強連通分量}} }void find_scc() {MM(pre,0);MM(sccno,0);scc_cnt=dfs_clock=0;for(int i=1;i<=n;i++)if(!pre[i])tarjan(i); }int main() {while(~scanf("%d %d",&n,&m)){for(int i=1;i<=n;i++)G[i].clear();for(int i=1;i<=m;i++){int u,v;scanf("%d %d",&u,&v);G[u].push_back(v);}find_scc();MM(deg,0);for(int u=1;u<=n;u++)for(int j=0;j<G[u].size();j++){int v=G[u][j];if(sccno[u]!=sccno[v])deg[sccno[u]]=1;}int cnt=0,ans=0;for(int i=1;i<=scc_cnt;i++)if(!deg[i])cnt++;if(cnt==1){for(int i=1;i<=n;i++)if(!deg[sccno[i]])ans++;}printf("%d\n",ans);}return 0; }
分析:強連通分量裸題,縮點成DAG后,只要求出出度為0的強連通就好,若不止1個,則說明不存在
被所有牛都視為紅人的強連通存在;否則直接輸出出度為0的強連通的牛的個數
轉載于:https://www.cnblogs.com/smilesundream/p/5474662.html
總結
以上是生活随笔為你收集整理的POJ 2186 挑战 --牛红人 强连通分量——Tarjan的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: sass安装 使用
 - 下一篇: 009Linux密码故障排除