zoukankan      html  css  js  c++  java
  • poj1679The Unique MST

    题目链接:http://poj.org/problem?id=1679

    判断最小生成树是否唯一。

    先求出最小生成树权值ans,用vector记录用的边。

    依次不用vector里记录的边求生成树,若权值等于ans,说明不唯一。

     1 #include<iostream>
     2 #include<cstring>
     3 #include<vector>
     4 #include<algorithm>
     5 using namespace std;
     6 
     7 int n,m;
     8 struct edge
     9 {
    10     int u,v,w;
    11     bool operator <(const edge &a) const {
    12     return w<a.w;
    13     }
    14 }e[10010];
    15 int f[110];
    16 int ans;
    17 vector<int>mst;
    18 
    19 void init()
    20 {
    21     for(int i=0;i<=n;i++)
    22         f[i]=i;
    23 }
    24 
    25 int gf(int x)
    26 {
    27     return x==f[x]?x:f[x]=gf(f[x]);
    28 }
    29 
    30 void unit(int x,int y)
    31 {
    32     int px=gf(x);
    33     int py=gf(y);
    34     f[px]=py;
    35 }
    36 
    37 void kru()
    38 {
    39      init();
    40     for(int i=0;i<m;i++)
    41     {
    42         if(gf(e[i].u)!= gf(e[i].v))
    43         {
    44             mst.push_back(i);
    45             ans+=e[i].w;
    46             unit(e[i].u,e[i].v);
    47         }
    48     }
    49 
    50 }
    51 bool yesno()
    52 {
    53     for(int i=0;i<mst.size();i++)
    54     {
    55         int cost=0;
    56           init();
    57           int k=0;
    58         for(int j=0;j<m;j++)
    59         {
    60             if(mst[i]==j) continue;
    61             if(gf(e[j].u)!=gf(e[j].v))
    62         {
    63             cost+=e[j].w;
    64             k++;
    65             unit(e[j].u,e[j].v);
    66         }
    67         }
    68         if(cost==ans&&k==n-1) return 1;
    69     }
    70     return 0;
    71 }
    72 int main()
    73 {
    74     int t;
    75     cin>>t;
    76     while(t--)
    77     {
    78         mst.clear();
    79         ans=0;
    80 
    81         cin>>n>>m;
    82 
    83         for(int i=0;i<m;i++)
    84                 cin>>e[i].u>>e[i].v>>e[i].w;
    85 
    86         sort(e,e+m);
    87         kru();
    88         if(yesno()) cout<<"Not Unique!
    ";
    89         else  cout<<ans<<endl;
    90 
    91     }
    92 }
  • 相关阅读:
    4组Alpha冲刺2/6
    4组Alpha冲刺1/6
    4组Alpha冲刺3/6
    4组Alpha冲刺3/6
    4组Alpha冲刺4/6
    原创视频作品汇总(更新至2012.8.04)
    PPT全转通2.0发布
    PPT全转通1.3
    [原创]WIN8系统的远程桌面漏洞 利用QQ拼音纯净版实现提权
    原创钢琴曲 《夏季来临之前的歌》
  • 原文地址:https://www.cnblogs.com/yijiull/p/6616183.html
Copyright © 2011-2022 走看看