POJ1236-Network of Schools(Tarjan + 縮點),tarjan縮點

來源:互聯網
上載者:User

POJ1236-Network of Schools(Tarjan + 縮點),tarjan縮點

題目連結


題意:給定一張有向圖,問最少選擇幾個點能遍曆全圖,以及最少添加幾條邊使得有向圖成為一個強連通圖。

思路:對於有向圖而言,首先求出有幾個強連通分量,之後將每個強連通分量縮點,形成DAG,本題開頭第一句就說圖是連通的了。之後想要遍曆整張圖的話,只要找出入度為0的點有幾個,而添加邊的數量就取決於所有點的出入度大小。

代碼:

#include <iostream>#include <cstdio>#include <cstring>#include <vector>#include <stack>#include <algorithm>using namespace std;const int MAXN = 105;vector<int> g[MAXN];stack<int> s; int pre[MAXN], lowlink[MAXN], sccno[MAXN], dfs_clock, scc_cnt;int n, in[MAXN], out[MAXN];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++;         int x = -1;        while (x != u) {            x = s.top();             s.pop();            sccno[x] = scc_cnt;        }    }}void find_scc() {    memset(pre, 0, sizeof(pre));    memset(sccno, 0, sizeof(sccno));    memset(lowlink, 0, sizeof(lowlink));    dfs_clock = scc_cnt = 0;    for (int i = 1; i <= n; i++)        if (!pre[i])            tarjan(i);}int main() {    while (scanf("%d", &n) != EOF) {        int u;        for (int i = 1; i <= n; i++) {            g[i].clear();            while (scanf("%d", &u) && u)                 g[i].push_back(u);        }        find_scc();        if (scc_cnt == 1) {            printf("1\n0\n");             continue;        }        else {            memset(in, 0, sizeof(in));             memset(out, 0, sizeof(out));             for (int u = 1; u <= n; u++) {                for (int i = 0; i < g[u].size(); i++) {                    int v = g[u][i];                     if (sccno[u] != sccno[v]) {                        in[sccno[v]]++;                          out[sccno[u]]++;                    }                }              }             int a = 0, b = 0;            for (int i = 1; i <= scc_cnt; i++) {                if (in[i] == 0) a++;                 if (out[i]== 0) b++;              }            int ans = max(a, b);            printf("%d\n%d\n", a, ans);        }    }     return 0;}





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.