码迷,mamicode.com
首页 > 其他好文 > 详细

POJ - 1679 - The Unique MST (次小生成树)

时间:2015-08-15 18:23:26      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:poj   次小生成树   

题目传送:The Unique MST

AC代码:

#include <map>
#include <set>
#include <list>
#include <cmath>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <cctype>
#include <cstdio>
#include <string>
#include <vector>
#include <complex>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <sstream>
#include <utility>
#include <iostream>
#include <algorithm>
#include <functional>
#define LL long long
#define INF 0xfffffff
using namespace std;

int n, m;

const int maxn = 105; 
int cost[maxn][maxn];
int Max[maxn][maxn];

int vis[maxn];//用来标记点是否访问过
int used[maxn][maxn];//用来标记边是否访问过
int pre[maxn];

int low[maxn];

int ans;

int prim() {
    int ret = 0;
    memset(vis, 0, sizeof(vis));
    memset(Max, 0, sizeof(Max));
    memset(used, 0, sizeof(used));
    vis[1] = 1;
    pre[1] = -1;
    for(int i = 2; i <= n; i ++) {
        low[i] = cost[1][i];
        pre[i] = 1;
    }
    low[1] = 0;

    for(int i = 2; i <= n; i ++) {
        int mi = INF;
        int pos = -1;
        for(int j = 1; j <= n; j ++) {
            if(!vis[j] && mi > low[j]) {
                mi = low[j];
                pos = j;
            }
        }
        if(mi == INF) return -1;
        ret += mi;
        vis[pos] = 1;
        used[pos][pre[pos]] = used[pre[pos]][pos] = 1;
        for(int j = 1; j <= n; j ++) {
            if(vis[j]) Max[j][pos] = Max[pos][j] = max(Max[j][pre[pos]], low[pos]);
            if(!vis[j] && low[j] > cost[pos][j]) {
                low[j] = cost[pos][j];
                pre[j] = pos;
            }
        }
    }
    return ret;
}

int ci_st() {
    int mi = INF;
    for(int i = 1; i <= n; i ++) {
        for(int j = i + 1; j <= n; j ++) {
            if(cost[i][j] != INF && !used[i][j]) {
                mi = min(mi, ans + cost[i][j] - Max[i][j]);
            }
        }
    }
    return mi;
}

int main() {
    int T;
    scanf("%d", &T);
    while(T --) {
        scanf("%d %d", &n, &m);
        for(int i = 1; i <= n; i ++) {
            for(int j = 1; j <= n; j ++) {
                if(i == j) {
                    cost[i][j] = 0;
                }
                else cost[i][j] = INF;
            }
        }

        int u, v, w;
        for(int i = 0; i < m; i ++) {
            scanf("%d %d %d", &u, &v, &w);
            cost[u][v] = cost[v][u] = w;
        }

        ans = prim();
        if(ans == -1) {
            printf("Not Unique!\n");
            continue;
        }
        //cout << ans << " " <<  ci_st() << endl;
        if(ans == ci_st()) printf("Not Unique!\n");
        else printf("%d\n", ans);
    }
    return 0;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

POJ - 1679 - The Unique MST (次小生成树)

标签:poj   次小生成树   

原文地址:http://blog.csdn.net/u014355480/article/details/47683467

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!