UVa 11324 The Largest Clique / 強連通分量

來源:互聯網
上載者:User

有一張有向圖G 求一個節點數最大的節點集 其中任意2點 u和v  要麼u 可以到v 要麼v可以到u 要麼相互可達

首先縮點 每一個強連通分量都是可達的 求一條路徑 路徑上的每個點的權值是該強連通分量的節點數 求權最大的路徑 可以用記憶化搜尋寫

 

#include <cstdio>#include <cstring>#include <vector>#include <stack>using namespace std;const int maxn = 1010;vector <int> G[maxn];stack <int> s;int pre[maxn];int low[maxn];int cnt[maxn];int degree[maxn];int sccno[maxn];//每個點所在強聯通分量的scc_cntint dfs_clock;int scc_cnt;int n, m;vector <int> a[maxn];int d[maxn];void dfs(int u){pre[u] = low[u] = ++dfs_clock;s.push(u);for(int i = 0; i < G[u].size(); i++){int v = G[u][i];if(!pre[v]){dfs(v);low[u] = min(low[u], low[v]);}else if(!sccno[v]){low[u] = min(low[u], pre[v]);}}if(low[u] == pre[u]){scc_cnt++;while(1){int x = s.top();s.pop();sccno[x] = scc_cnt;cnt[scc_cnt]++;if(x == u)break;}}}void find_scc(){dfs_clock = scc_cnt = 0;memset(sccno, 0, sizeof(sccno));memset(pre, 0, sizeof(pre));for(int i = 1; i <= n; i++)if(!pre[i])dfs(i);}int dp(int u){if(d[u] != -1)return d[u];d[u] = cnt[u];int ans = 0;for(int i = 0; i < a[u].size(); i++){int v = a[u][i];int temp = dp(v);ans = max(ans, temp);}d[u] += ans;return d[u];}int main(){int T;scanf("%d", &T);while(T--){scanf("%d %d", &n, &m);for(int i = 1; i <= n; i++){G[i].clear();a[i].clear();}for(int i = 1; i <= m; i++){int u, v;scanf("%d %d", &u, &v);G[u].push_back(v);}memset(degree, 0, sizeof(degree));memset(cnt, 0, sizeof(cnt));memset(d, -1, sizeof(d));find_scc();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]){a[sccno[u]].push_back(sccno[v]);degree[sccno[v]]++;}}}int ans = 0;for(int i = 1; i <= scc_cnt; i++){if(!degree[i]){int temp = dp(i);ans = max(ans, temp);}}printf("%d\n", 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.