POJ 1236 Network of Schools(強連通 Tarjan+縮點)

來源:互聯網
上載者:User

標籤:acm

POJ 1236 Network of Schools(強連通 Tarjan+縮點)

ACM

題目地址:POJ 1236

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

分析: 
跟HDU 2767 Proving Equivalences(題解)一樣的題目,不過多了個問題,其實轉化成DAG後就不難考慮了,其實只要選擇入度為0的點就行了。

代碼:

/**  Author:      illuz <iilluzen[at]gmail.com>*  File:        1236.cpp*  Create Date: 2014-07-30 15:13:12*  Descripton:  Tarjan */#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>using namespace std;#include <vector>#include <stack>#define repf(i,a,b) for(int i=(a);i<=(b);i++)typedef long long ll;const int N = 105;vector<int> G[N];stack<int> S;int low[N], dfn[N], sccno[N], tclock, scccnt;int id[N], od[N];int n, rd;void tarjan(int u) {low[u] = dfn[u] = ++tclock;S.push(u);int sz = G[u].size();repf (i, 0, sz - 1) {int v = G[u][i];if (!dfn[v]) {tarjan(v);low[u] = min(low[u], low[v]);} else if (!sccno[v]) {low[u] = min(low[u], dfn[v]);}}if (low[u] == dfn[u]) {scccnt++;int v = -1;while (v != u) {v = S.top();S.pop();sccno[v] = scccnt;}}}void read() {repf (i, 1, n) {G[i].clear();while (scanf("%d", &rd) && rd) {G[i].push_back(rd);}}}void find_scc() {tclock = scccnt = 0;memset(dfn, 0, sizeof(dfn));memset(low, 0, sizeof(low));memset(sccno, 0, sizeof(sccno));repf (i, 1, n) {if (!dfn[i]) {tarjan(i);}}}void solve() {if (scccnt == 1) {printf("1\n0\n");return;}memset(id, 0, sizeof(id));memset(od, 0, sizeof(od));repf (u, 1, n) {int sz = G[u].size();repf (i, 0, sz - 1) {int v = G[u][i];if (sccno[u] != sccno[v]) {id[sccno[v]]++;od[sccno[u]]++;}}}int idnum = 0, odnum = 0;repf (i, 1, scccnt) {idnum += (id[i] == 0);odnum += (od[i] == 0);}printf("%d\n%d\n", idnum, max(idnum, odnum));}int main() {while (~scanf("%d", &n)) {read();find_scc();solve();}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.