UVa 10462 Is There A Second Way Left? (Kruskal,次小產生樹)

來源:互聯網
上載者:User

這道題還是比較有考慮的價值的

求:判斷是否有最小產生樹,次小產生樹,如果有次小產生樹,則輸出次小產生樹的總權值

要注意的是,點和點之間是有重邊的,要求次小產生樹,就一定要保留所有重邊

考慮到即要判斷圖是不是連通的,又要儲存重邊,所以Kruskal是首選,prim演算法或許有解,但是本人實在是沒有想出來怎麼樣比Kruskal能更加簡單,如果大牛經過,求指點

次小產生樹一定是最小產生樹減一條邊,再加一條邊,枚舉掉最小產生樹中的邊,一次求少一條邊的圖的最小產生樹即可

代碼如下:

#include <cstdio>#include <cstring>#include <algorithm>using namespace std;const int N = 110;const int M = 220;const int INF = 1000000000;int n, m, T, ans1, ans2, ise[N], f[N];struct edge {    int u, v, cost;}e[M];bool cmp( edge a, edge b ) {    return a.cost < b.cost;}int find ( int x ) {    return f[x] == x ? x: f[x] = find(f[x]);}int Kru() {    int ans = 0, num = 0, id = 0;    for ( int i = 1; i <= n; ++i ) f[i] = i;    for ( int i = 0; i < m; ++i ) {        int x = e[i].u;        int y = e[i].v;        int a = find(x);        int b = find(y);        if ( a != b ) ise[id++] = i, f[a] = b, ans += e[i].cost;    }    for ( int i = 1; i <= n; ++i ) if ( i == find(i) ) num++;    if ( num > 1 ) return INF;    else return ans;}int Kru_1( int del ) {    int ans = 0, num = 0;    for ( int i = 1; i <= n; ++i ) f[i] = i;    for ( int i = 0; i < m; ++i ) {        if ( i == del ) continue;        int x = e[i].u;        int y = e[i].v;        int a = find(x);        int b = find(y);        if ( a != b ) f[a] = b, ans += e[i].cost;    }    for ( int i = 1; i <= n; ++i ) if ( i == find(i) ) num++;    if ( num > 1 ) return INF;    else return ans;}int main(){    int idx = 1;    scanf("%d", &T);    while ( T-- ) {        scanf("%d%d", &n, &m);        for ( int i = 0; i < m; ++i )             scanf("%d%d%d", &e[i].u, &e[i].v, &e[i].cost);        sort( e, e+m, cmp );        ans1 = Kru(), ans2 = INF;        printf("Case #%d : ", idx++);        if ( ans1 == INF ) {            printf("No way\n");            continue;        }        for ( int i = 0; i < n-1; ++i ) {            int x = ise[i];            ans2 = min( ans2, Kru_1(x) );        }        if ( ans2 == INF ) printf("No second way\n");        else printf("%d\n", ans2);    }}

聯繫我們

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