poj1679 The Unique MST

先推荐下次下生成树的相关概念问题的描述。

http://blog.csdn.net/jarily/article/details/8883858

这个懂了次小生成树的解法就是判断次小是否等于最小。。。。。。。就是模版!

/*****************************************
Author      :Crazy_AC(JamesQi)
Time        :2015
File Name   :
*****************************************/
// #pragma comment(linker, "/STACK:1024000000,1024000000")
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <sstream>
#include <string>
#include <stack>
#include <queue>
#include <deque>
#include <vector>
#include <map>
#include <set>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <climits>
using namespace std;
#define MEM(x,y) memset(x, y,sizeof x)
#define pk push_back
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int,int> ii;
typedef pair<ii,int> iii;
const double eps = 1e-10;
const int inf = 1 << 30;
const int INF = 0x3f3f3f3f;
const int MOD = 1e9 + 7;
const int N = 110;
int G[N][N];
int pre[N], mark[N], dis[N], path[N][N];
bool Used[N][N];
int n, m;
int Prim() {
    int ret = 0;
    memset(mark, 0,sizeof mark);
    memset(Used, false,sizeof Used);
    memset(path, 0,sizeof path);
    mark[1] = true;
    for (int i = 1;i <= n;++i) {
        dis[i] = G[1][i];
        pre[i] = 1;
    }
    for (int i = 1;i < n;++i) {
        int u = -1;
        for (int j = 1;j <= n;++j) {
            if (!mark[j]) {
                if (u == -1 || dis[j] < dis[u])
                    u = j;
            }
        }
        Used[u][pre[u]] = Used[pre[u]][u] = true;
        ret += G[pre[u]][u];
        mark[u] = true;
        for (int j = 1;j <= n;++j) {
            if (mark[j] && j != u) {
                path[j][u] = path[u][j] = max(dis[u], path[j][pre[u]]);
            }
            if (!mark[j] && dis[j] > G[u][j]) {
                dis[j] = G[u][j];
                pre[j] = u;
            }
        }
    }
    return ret;
}
int main()
{    
    // freopen("in.txt","r",stdin);
    // freopen("out.txt","w",stdout);
    int t;
    scanf("%d",&t);
    while(t--) {
        scanf("%d%d",&n,&m);
        memset(G, INF,sizeof G);
        int u, v, w;
        for (int i = 1;i <= m;++i) {
            scanf("%d%d%d",&u,&v,&w);
            G[u][v] = G[v][u] = w;
        }
        int ans = Prim();
        int res = INF;
        for (int i = 1;i <= n;++i) {
            for (int j = i + 1;j <= n;++j) {
                if (!Used[i][j])
                    res = min(res,ans + G[i][j] - path[i][j]);
            }
        }
        if (res == ans) puts("Not Unique!");
        else printf("%d\n", ans);
    }
    return 0;
}


你可能感兴趣的:(dp,poj,MST)