判断最小生成树是否唯一

来源:互联网 发布:淘宝联盟拍了却没订单 编辑:程序博客网 时间:2024/06/05 09:39

http://poj.org/problem?id=1679

The Unique MST
Time Limit: 1000MS Memory Limit: 10000KTotal Submissions: 20487 Accepted: 7207

Description

Given a connected undirected graph, tell if its minimum spanning tree is unique. 

Definition 1 (Spanning Tree): Consider a connected, undirected graph G = (V, E). A spanning tree of G is a subgraph of G, say T = (V', E'), with the following properties: 
1. V' = V. 
2. T is connected and acyclic. 

Definition 2 (Minimum Spanning Tree): Consider an edge-weighted, connected, undirected graph G = (V, E). The minimum spanning tree T = (V, E') of G is the spanning tree that has the smallest total cost. The total cost of T means the sum of the weights on all the edges in E'. 

Input

The first line contains a single integer t (1 <= t <= 20), the number of test cases. Each case represents a graph. It begins with a line containing two integers n and m (1 <= n <= 100), the number of nodes and edges. Each of the following m lines contains a triple (xi, yi, wi), indicating that xi and yi are connected by an edge with weight = wi. For any two nodes, there is at most one edge connecting them.

Output

For each input, if the MST is unique, print the total cost of it, or otherwise print the string 'Not Unique!'.

Sample Input

23 31 2 12 3 23 1 34 41 2 22 3 23 4 24 1 2

Sample Output

3Not Unique!
程序:

#include"stdio.h"#include"string.h"#include"stack"#include"math.h"#include"algorithm"#include"stdlib.h"#define M 222#define inf 100000000#define eps 1e-12using namespace std;struct node{    int u,v,w;}e[M*M];int cmp(node a,node b){    return a.w<b.w;}int f[M];int finde(int x){    if(x!=f[x])        f[x]=finde(f[x]);    return f[x];}int main(){    int T;    scanf("%d",&T);    while(T--)    {        int n,m,i,j;        scanf("%d%d",&n,&m);        for(i=0;i<m;i++)            scanf("%d%d%d",&e[i].u,&e[i].v,&e[i].w);        sort(e,e+m,cmp);        int num=0;        int fuck=0;        int sum=0;        for(i=1;i<=n;i++)            f[i]=i;        for(i=0;i<m;)        {            j=i;            while(e[i].w==e[j].w&&j<m)            {                int x=finde(e[j].u);                int y=finde(e[j].v);                if(x!=y)                    fuck++;                j++;            }            j=i;            while(e[i].w==e[j].w&&j<m)            {                int x=finde(e[j].u);                int y=finde(e[j].v);                if(x!=y)                {                    f[x]=y;                    sum+=e[i].w;                    num++;                }                j++;            }            i=j;            if(num==n-1)                break;        }        if(fuck>num)            printf("Not Unique!\n");        else            printf("%d\n",sum);        //printf("%d %d\n",fuck,num);    }}


0 0
原创粉丝点击