题解 | #继续畅通工程#

继续畅通工程

https://www.nowcoder.com/practice/16212f7d46e44174b5505997ea998538

令weight为0即可
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

struct Edge {
	int x;
	int y;
	int weight;
	bool finish;  //表示完成的状态
};

#define N 1000 //元素的上限个数
int father[N];
int height[N];

bool compare(Edge lhs, Edge rhs) {
	return lhs.weight < rhs.weight;
}


void Init(int n) {
	for (int i = 1; i <= n; i++) {
		father[i] = i;
		height[i] = 1;
	}
}

int Find(int x) {
	if (x != father[x]) {
		father[x] = Find(father[x]);
	}
	return father[x];

}

void Union(int x, int y,int weight,int & total) {
	x = Find(x); y = Find(y);
	if (x != y) {  //判断x与y是否属于同一集合
		total += weight;  
	}
	if (height[x] < height[y])
		father[x] = y;
	else if (height[x] > height[y])
		father[y] = x;
	else {
		father[y] = x;
		++height[x];
	}
}

int main() {
	int n;
	while (cin >> n) {
		if (n == 0) break;
		Init(n);
		vector<Edge>  vec;
		Edge temp;
		for (int i = 0; i < n * (n - 1)/2; i++) {
			cin >> temp.x >> temp.y >> temp.weight >> temp.finish;
			if (temp.finish == true) 
				temp.weight = 0;

			vec.push_back(temp);
		}
		sort(vec.begin(), vec.end(), compare);  //将集合进行排序
		int total = 0;
		for (int i = 0; i < n * (n - 1)/2; i++) {
			 Union(vec[i].x, vec[i].y, vec[i].weight, total);
		}
		cout << total << endl;

	}
}

全部评论

相关推荐

整顿职场的柯基很威猛:这种不可怕,最可怕的是夹在一帮名校里的二本选手,人家才是最稳的。
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务