首页 > 代码库 > poj1679

poj1679

  1 //Accepted    200 KB    16 ms
  2 //kruskal 判断最小生成树是否唯一,找到一条边后判断该边是否可以被取代
  3 #include <cstdio>
  4 #include <cstring>
  5 #include <algorithm>
  6 using namespace std;
  7 const int MAXN = 105;
  8 const int MAXM =MAXN *MAXN;
  9 const int inf =1000000000;
 10 struct node
 11 {
 12     int u,v,c;
 13     node()
 14     {
 15 
 16     }
 17     node(int u,int v,int c):u(u),v(v),c(c)
 18     {
 19 
 20     }
 21 }p[MAXM];
 22 int e;
 23 int f[MAXN];
 24 int n,m;
 25 int ans;
 26 int cmp(node x,node y)
 27 {
 28     return x.c<y.c;
 29 }
 30 void addnode(int u,int v,int c)
 31 {
 32     p[e++]=node(u,v,c);
 33 }
 34 void build()
 35 {
 36     for (int i=0;i<=n;i++)
 37     f[i]=i;
 38 }
 39 int find(int x)
 40 {
 41     if (f[x]==x) return x;
 42     return f[x]=find(f[x]);
 43 }
 44 void union_set(int x,int y)
 45 {
 46     int fx=find(x),fy=find(y);
 47     if (fx!=fy)
 48     {
 49         f[fy]=fx;
 50     }
 51 }
 52 int kruskal()
 53 {
 54     int m=0;
 55     ans=0;
 56     sort(p,p+e,cmp);
 57     for (int i=0;i<e;i++)
 58     {
 59         int x=find(p[i].u);
 60         int y=find(p[i].v);
 61         if (x!=y)
 62         {
 63             ans+=p[i].c;
 64             for (int j=i+1;j<e;j++)
 65             {
 66                 if (p[j].c>p[i].c) break;
 67                 int tx=find(p[j].u);
 68                 int ty=find(p[j].v);
 69                 if ((tx==x && ty==y) || (tx==y && ty==x))
 70                 {
 71                     return -1;
 72                 }
 73             }
 74             union_set(x,y);
 75             m++;
 76             if (m==n-1) return ans;
 77         }
 78     }
 79     return ans;
 80 }
 81 int main()
 82 {
 83     int T;
 84     scanf("%d",&T);
 85     while (T--)
 86     {
 87         scanf("%d%d",&n,&m);
 88         build();
 89         e=0;
 90         for (int i=0;i<m;i++)
 91         {
 92             int u,v,c;
 93             scanf("%d%d%d",&u,&v,&c);
 94             addnode(u,v,c);
 95         }
 96         int ans=kruskal();
 97         if (ans==-1) printf("Not Unique!\n");
 98         else printf("%d\n",ans);
 99     }
100     return 0;
101 }