HDU 3367 Pseudoforest 最大產生樹_最小產生樹

來源:互聯網
上載者:User

題目來源:HDU 3367 Pseudoforest

題意:每個連通塊最多可以有一個環 求最大的森林

思路:考慮最大產生樹 如果祖先一樣沒有環 那就合并 如果祖先不一樣 如果2棵樹都沒有環 合并 如果有1棵樹有環 合并 標記該棵樹有環

#include <cstdio>#include <cstring>#include <algorithm>using namespace std;const int maxn = 100010;struct edge{int u, v, w;}e[maxn];int f[10010];int vis[maxn];int ok[10010];int n, m;bool cmp(edge a, edge b){return a.w > b.w;}int find(int x){if(x != f[x])return f[x] = find(f[x]);return f[x];}int MST(){int sum = 0;memset(vis, 0, sizeof(vis));memset(ok, 0, sizeof(ok));for(int i = 0; i < m; i++){int x = find(e[i].u);int y = find(e[i].v);if(x != y){if(!ok[x] && !ok[y]){sum += e[i].w;f[x] = y;}else if(!ok[x] || !ok[y]){ok[x] = ok[y] = 1;f[x] = y;sum += e[i].w;}}else if(!ok[x]){ok[x] = 1;sum += e[i].w;}}return sum;}int main(){while(scanf("%d %d", &n, &m) && (n+m)){for(int i = 0; i < n; i++)f[i] = i;for(int i = 0; i < m; i++){scanf("%d %d %d", &e[i].u, &e[i].v, &e[i].w);}sort(e, e+m, cmp);printf("%d\n", MST());}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.