Local minimum cost flow problem of the project (disjoint-set)

Write out the first disjoint-set (kruskal) because there are existing side, so it is natural to think of to do with the investigation and collection. However, this condition is determined whether the required number of disjoint-set view which all elements, the array is provided a num. During the union's update. [the root] kruskal algorithm is set in the total number of nodes it num ~ (kruskal bit out of the original, the original is kruskal minimum spanning tree, only n-1 sides, so that the number of edges of the selected records like )
Another method is to use prim, the cost of existing side as 0

#include <bits/stdc++.h>
using namespace std;
//kruskal 设置一个量记录元素个数 
struct edge{
	int u,v;
	int cost;
	edge(int u,int v,int c):u(u),v(v),cost(c){
	} 
};int num[101]; vector<edge>e;
bool cmp(edge a,edge b){
	return a.cost<b.cost;
}bool visit[101];
int father[1001];
int findfather(int x){
	int a=x;
	while(x!=father[x])
	x=father [x];
	return x;
}
void unionn(int a,int b) {
	int fa=findfather(a);
	int fb=findfather(b);
	if(fa!=fb){father[fa]=fb;num[fb]+=num[fa];
	}
	
}int ans=0;
int main(int argc, char** argv) {
	fill(num,num+101,1);
	int n,m,a,b,s,co;
	cin>>n;int k=n*(n-1)/2;
	for(int i=0;i<n;i++)father[i]=i;
	for(int i=0;i<k;i++){
		scanf("%d %d %d %d",&a,&b,&co,&s);
		if(s==1){
			unionn(a,b);
		} 
		else //待选边 
		e.push_back(edge(a,b,co));
	}
	
	sort(e.begin(),e.end(),cmp);
	for(int i=0;i<e.size();i++)
	{
		int fa=findfather(e[i].u);
		int fb=findfather(e[i].v);
		if(fa!=fb){
			father[fa]=fb;
			num[fb]+=num[fa];
			ans+=e[i].cost;
			if(num[fb]==n)break; 
		}
		
	}
	cout<<ans;
		return 0;
	}

Published 17 original articles · won praise 5 · Views 2365

Guess you like

Origin blog.csdn.net/ilikecarrots/article/details/88311181