UVA 11324,uva11324

來源:互聯網
上載者:User

UVA 11324,uva11324
UVA 11324 - The Largest Clique

題目連結

題意:給定一個有向圖,要求找一個集合,使得集合內任意兩點(u, v)要麼u能到v,要麼v能到u,問最大能選幾個點

思路:強連通分量,構造出scc之後,縮點,每個點的權值是集合點個數,然後做一遍dag找出最大權值路徑即可

代碼:

#include <cstdio>#include <cstring>#include <vector>#include <stack>#include <algorithm>using namespace std;const int N = 20005;vector<int> g[N], scc[N];int pre[N], lowlink[N], sccno[N], dfs_clock, scc_cnt;stack<int> S;void dfs_scc(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]) {dfs_scc(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(int n) {dfs_clock = scc_cnt = 0;memset(sccno, 0, sizeof(sccno));memset(pre, 0, sizeof(pre));for (int i = 0; i < n; i++)if (!pre[i]) dfs_scc(i);}int t, n, m, val[N];vector<int> g2[N];void build() {memset(val, 0, sizeof(val));for (int i = 1; i <= scc_cnt; i++)g2[i].clear();for (int u = 0; u < n; u++) {val[sccno[u]]++;for (int j = 0; j < g[u].size(); j++) {int v = g[u][j];if (sccno[u] != sccno[v])g2[sccno[u]].push_back(sccno[v]);}}}int dp[N];int dfs(int u) {if (dp[u] != -1) return dp[u];dp[u] = val[u];for (int i = 0; i < g2[u].size(); i++) {int v = g2[u][i];dp[u] = max(dp[u], dfs(v) + val[u]);}return dp[u];}int main() {scanf("%d", &t);while (t--) {scanf("%d%d", &n, &m);for (int i = 0; i < n; i++)g[i].clear();int u, v;while (m--) {scanf("%d%d", &u, &v);u--; v--;g[u].push_back(v);}find_scc(n);build();memset(dp, -1, sizeof(dp));int ans = 0;for (int i = 0; i < n; i++)ans = max(ans, dfs(sccno[i]));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.