Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 22668 | Accepted: 8038 |
Description
Input
Output
Sample Input
2 3 3 1 2 1 2 3 2 3 1 3 4 4 1 2 2 2 3 2 3 4 2 4 1 2
Sample Output
3 Not Unique!
POJ的网站绝对有问题。昨天就有一题提交不了,换到HUD上就A了,今天这题同样没法提交,一提交就卡死,换到百炼上成功AC。
根据概念来做,如果在某一步合并的时候有多个可以选,那么就不唯一了。
1 #include <iostream> 2 #include <cstdio> 3 #include <string> 4 #include <queue> 5 #include <vector> 6 #include <map> 7 #include <algorithm> 8 #include <cstring> 9 #include <cctype> 10 #include <cstdlib> 11 #include <cmath> 12 #include <ctime> 13 using namespace std; 14 15 const int SIZE = 105; 16 int FATHER[SIZE],N,M,NUM; 17 int MAP[SIZE][SIZE]; 18 struct Node 19 { 20 int from,to,cost; 21 }G[SIZE * SIZE]; 22 23 void ini(void); 24 int find_father(int); 25 void unite(int,int); 26 bool same(int,int); 27 int kruskal(void); 28 bool comp(const Node &,const Node &); 29 int main(void) 30 { 31 int t; 32 scanf("%d",&t); 33 while(t --) 34 { 35 scanf("%d%d",&N,&M); 36 ini(); 37 for(int i = 0;i < M;i ++) 38 { 39 scanf("%d%d%d",&G[NUM].from,&G[NUM].to,&G[NUM].cost); 40 NUM ++; 41 }
sort(G,G+NUM,comp); 42 kruskal(); 43 } 44 45 return 0; 46 } 47 48 void ini(void) 49 { 50 NUM = 0; 51 for(int i = 1;i <= N;i ++) 52 FATHER[i] = i; 53 } 54 55 int find_father(int n) 56 { 57 if(FATHER[n] == n) 58 return n; 59 return FATHER[n] = find_father(FATHER[n]); 60 } 61 62 void unite(int x,int y) 63 { 64 x = find_father(x); 65 y = find_father(y); 66 67 if(x == y) 68 return ; 69 FATHER[x] = y; 70 } 71 72 bool same(int x,int y) 73 { 74 return find_father(x) == find_father(y); 75 } 76 77 bool comp(const Node & a,const Node & b) 78 { 79 return a.cost < b.cost; 80 } 81 82 int kruskal(void) 83 { 84 int count = 0,ans = 0; 85 bool flag = true; 86 87 for(int i = 0;i < NUM;i ++) 88 if(!same(G[i].from,G[i].to)) 89 { 90 if(i + 1 < NUM && G[i].cost == G[i + 1].cost && (G[i].from == G[i + 1].from || G[i].from == G[i + 1].to || 91 G[i].to == G[i + 1].to || G[i].to == G[i + 1].from) && !same(G[i + 1].from,G[i + 1].to)) 92 { 93 flag = false; 94 break; 95 } 96 unite(G[i].from,G[i].to); 97 count ++; 98 ans += G[i].cost; 99 if(count == N - 1) 100 break; 101 } 102 if(flag) 103 printf("%d\n",ans); 104 else 105 puts("Not Unique!"); 106 }