The Unique MST POJ - 1679 (non Strictly small Spanning Tree)

Topic Link

Effect: Q minimum spanning tree constructed by the village is unique (this code can only determine the minimum spanning tree is unique, but can not find Strictly small Spanning Tree)

Strictly small spanning the future to make up
#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
#define maxn 150

using namespace std;

struct node{
	int u,v,w;
	bool vis;//比最小生成树多了个vis标志 
}edge[maxn*maxn];

int n,m,ans,tot;
int s[maxn],maps[maxn][maxn]; //maps数组用来维护u到v的距离,在枚举边的时候会用到
vector<int> p[maxn];//扩展路径 

bool cmp(const node &a,const node &b){
	return a.w<b.w;
}

int find(int u){
	return s[u]==u?u:find(s[u]);
}

void Kruskal(){
	tot=0,ans=0;
	sort(edge,edge+m,cmp);
	for(int i=0;i<m;i++){
		int a=find(edge[i].u);
		int b=find(edge[i].v);
		if(a!=b){
			s[b]=a;
			edge[i].vis=true;//标记入树的集合 
			ans+=edge[i].w;
			tot++;
			for(int j=0;j<p[a].size();j++){
				for(int k=0;k<p[b].size();k++){
					maps[p[a][j]][p[b][k]]=maps[p[b][k]][p[a][j]]=edge[i].w;
				}
			}
			for(int j=0;j<p[b].size();j++){
				p[a].push_back(p[b][j]);//因为路径压缩了,所以要把点存进父节点 
			}
		}
		if(tot==n){
			break;
		}
	}
}

int main(){
	int t;
	scanf("%d",&t);
	while(t--){
		memset(maps,0,sizeof maps);
		scanf("%d%d",&n,&m);
		for(int i=0;i<=n;i++){
			s[i]=i;
			p[i].clear();
			p[i].push_back(i);
		}
		for(int i=0;i<m;i++){
			scanf("%d%d%d",&edge[i].u,&edge[i].v,&edge[i].w);
			edge[i].vis=false; 
		} 
		Kruskal();
		int dis=0x3f3f3f3f;
		for(int i=0;i<m;i++){
			if(!edge[i].vis){
				dis=min(dis,ans+edge[i].w-maps[edge[i].u][edge[i].v]);
			}
		}
		if(dis>ans){//判断次小生成树和最小生成树 
			printf("%d\n",ans);
		}else{
			printf("Not Unique!\n");
		}
	}
	return 0;
}
Published 10 original articles · won praise 0 · Views 113

Guess you like

Origin blog.csdn.net/qq_43697256/article/details/103994444