标签:
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 21931 | Accepted: 7784 |
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!
题目意思:
给一个图,判定最小生成树是否唯一。prime次小生成树模板判定。
代码:
1 #include <cstdio> 2 #include <cstring> 3 #include <algorithm> 4 #include <iostream> 5 #include <vector> 6 #include <queue> 7 #include <cmath> 8 using namespace std; 9 10 #define N 105 11 #define inf 999999999 12 13 int max(int x,int y){return x>y?x:y;} 14 int min(int x,int y){return x<y?x:y;} 15 int abs(int x,int y){return x<0?-x:x;} 16 17 int maxh[N][N]; 18 int map[N][N]; 19 int fa[N]; 20 bool in[N]; 21 int stack[N]; 22 int n, m; 23 int dis[N]; 24 25 int prime(){ 26 int sum=0; 27 int top=0; 28 int i, j, k; 29 for(i=2;i<=n;i++){ 30 dis[i]=map[1][i];fa[i]=1; 31 } 32 memset(in,false,sizeof(in)); 33 dis[1]=0; 34 35 in[1]=true; 36 stack[top++]=1; 37 for(i=1;i<=n;i++){ 38 int minh=-1; 39 for(j=1;j<=n;j++){ 40 if(!in[j]&&(minh==-1||minh>dis[j])){ 41 k=j;minh=dis[j]; 42 } 43 44 }//printf("%d %d\n",minh,sum); 45 if(minh==-1) return sum; 46 47 in[k]=true; 48 sum+=minh; 49 50 for(j=0;j<top;j++) maxh[stack[j]][k]=maxh[k][stack[j]]=max(maxh[stack[j]][fa[k]],minh); 51 stack[top++]=k; 52 for(j=1;j<=n;j++){ 53 if(!in[j]&&dis[j]>map[k][j]){ 54 dis[j]=map[k][j]; 55 fa[j]=k; 56 } 57 } 58 } 59 } 60 61 main() 62 { 63 int t, i, j, k; 64 cin>>t; 65 while(t--){ 66 scanf("%d %d",&n,&m); 67 for(i=1;i<=n;i++){ 68 for(j=1;j<=n;j++){ 69 map[i][j]=inf; 70 maxh[i][j]=0; 71 } 72 } 73 int x, y, z; 74 while(m--){ 75 scanf("%d %d %d",&x,&y,&z); 76 map[x][y]=map[y][x]=z; 77 } 78 int ans=prime(); 79 //printf("%d\n",ans); 80 int minh=inf; 81 for(i=1;i<=n;i++){ 82 for(j=1;j<=n;j++){ 83 if(i!=j&&fa[i]!=j&&fa[j]!=i) 84 minh=min(minh,map[i][j]-maxh[i][j]); 85 } 86 } 87 if(minh==0) printf("Not Unique!\n"); 88 else printf("%d\n",ans); 89 } 90 }
标签:
原文地址:http://www.cnblogs.com/qq1012662902/p/4343340.html