标签:
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 24058 | Accepted: 8546 |
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! 题解:
这个题看有的人还求了次小生成树,其实不必要的,中间判断下是否存在多个生成树就好了;
代码:
1 #include<stdio.h> 2 #include<string.h> 3 const int INF=0x3f3f3f3f; 4 const int MAXN=110; 5 int vis[MAXN],map[MAXN][MAXN],low[MAXN]; 6 int ans,N,answer; 7 void prime(){ 8 memset(vis,0,sizeof(vis)); 9 int flot=1,temp,k; 10 answer=0; 11 ans=1; 12 vis[1]=1; 13 for(int i=1;i<=N;i++)low[i]=map[1][i]; 14 for(int i=1;i<=N;i++){ 15 temp=INF; 16 for(int j=1;j<=N;j++) 17 if(!vis[j]&&temp>low[j])temp=low[k=j]; 18 if(temp==INF){ 19 if(flot!=N)ans=0;//因为这题本来就是联通的,所以这句话可以省略; 20 // printf("flot=%d,N=%d\n",flot,N); 21 break; 22 } 23 int x=0; 24 for(int j=1;j<=N;j++){ 25 if(vis[j]&&map[k][j]==temp)x++; 26 if(x>1)break; 27 }//这个for循环的作用就是,当前已经找到距离这个图最小的点了,然后判断到这个最小点的距离为temp也就是最小值的点有几个,如果点数大于一则有多个最小生成树; 28 if(x>1){ 29 ans=0; 30 break; 31 } 32 answer+=temp; 33 vis[k]=1; 34 flot++; 35 for(int j=1;j<=N;j++){ 36 if(!vis[j]&&low[j]>map[k][j])low[j]=map[k][j]; 37 } 38 } 39 } 40 int main(){ 41 int T,M,a,b,c; 42 scanf("%d",&T); 43 while(T--){ 44 memset(map,INF,sizeof(map)); 45 scanf("%d%d",&N,&M); 46 while(M--){ 47 scanf("%d%d%d",&a,&b,&c); 48 if(c<map[a][b])map[a][b]=map[b][a]=c; 49 } 50 prime(); 51 if(ans)printf("%d\n",answer); 52 else printf("Not Unique!\n"); 53 } 54 return 0; 55 }
The Unique MST (判断是否存在多个最小生成树)
标签:
原文地址:http://www.cnblogs.com/handsomecui/p/4726610.html