強聯通塊tarjan演算法

來源:互聯網
上載者:User

標籤:style   blog   http   io   ar   color   sp   for   on   


http://poj.org/problem?id=1236
第一問:需要幾個學校存在軟體,才能通過傳遞,使得所有的學校都有軟體
用tarjan演算法求出強聯通分量後,將每個聯通分量縮成一個點,那麼問題1的答案就是入度為0的點的個數
為什嗎?入度為0的點,肯定不能通過其他學校傳送軟體給他,所以他必須存在一份軟體
第二問:需要加幾條邊,才能使得圖強聯通
縮點後,a為所有入度為0的點的個數,b為所有出度為0的點的個數,那麼答案就是max(a,b)

 

 1 #include <stdio.h> 2 #include <string.h> 3 #include <vector> 4 #include <stack> 5 using namespace std; 6 const int N = 100 + 10; 7 vector<int> G[N]; 8 stack<int> st; 9 bool vis[N];10 int sccno[N],pre[N],lowlink[N],in[N],out[N],dfs_clock,scc_cnt;11 int min(const int &a, const int &b)12 {13     return a < b ? a : b;14 }15 void tarjan(int u)16 {17     pre[u] = lowlink[u] = ++dfs_clock;18     st.push(u);19     for(int i=0; i<G[u].size(); ++i)20     {21         int v = G[u][i];22         if(!pre[v])23         {24             tarjan(v);25             lowlink[u] = min(lowlink[u],lowlink[v]);26         }27         else if(!sccno[v])28             lowlink[u] = min(lowlink[u],pre[v]);29     }30     if(lowlink[u]==pre[u])31     {32         scc_cnt++;33         for(;;)34         {35             int x = st.top();st.pop();36             sccno[x] = scc_cnt;37             if(x==u) break;38         }39     }40 }41 void find_scc(int n)42 {43     for(int i=1; i<=n; ++i)44         if(!pre[i])45             tarjan(i);46 }47 int main()48 {49     int n,i,a,b;50     scanf("%d",&n);51     for(a=1; a<=n; ++a)52     {53         while(scanf("%d",&b),b)54         {55             G[a].push_back(b);56             vis[b] = true;57         }    58     }59     find_scc(n);60     for(i=1; i<=scc_cnt; ++i) in[i] = out[i] = 1;61     for(int u=1; u<=n; ++u)62         for(i=0; i<G[u].size();++i)63         {64             int v = G[u][i];65             if(sccno[u] != sccno[v]) in[sccno[v]] = out[sccno[u]] = 0;66         }67     a = b = 0;68     for(i=1; i<=scc_cnt; ++i)69     {70         if(in[i]) a++;71         if(out[i]) b++;72     }    73     int ans = a > b ? a : b;74     if(scc_cnt == 1) ans = 0;75     printf("%d\n%d\n",a,ans);76     return 0;77 }

 

強聯通塊tarjan演算法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.