某地区经过对城镇交通状况的调查,得到现有城镇间快速道路的统计数据,并提出“畅通工程”的目标:使整个地区任何两个城镇间都可以实现快速交通(但不一定有直接的快速道路相连,只要互相间接通过快速路可达即可)。现得到城镇道路统计表,表中列出了任意两城镇间修建快速路的费用,以及该道路是否已经修通的状态。现请你编写程序,计算出全地区畅通需要的最低成本。
输入格式:
输入的第一行给出村庄数目N (1≤N≤100);随后的N(N−1)/2行对应村庄间道路的成本及修建状态:每行给出4个正整数,分别是两个村庄的编号(从1编号到N),此两村庄间道路的成本,以及修建状态 — 1表示已建,0表示未建。
输出格式:
输出全省畅通需要的最低成本。
输入样例:
4
1 2 1 1
1 3 4 0
1 4 1 1
2 3 3 0
2 4 2 1
3 4 5 0
输出样例:
3
代码长度限制 16 KB
时间限制 400 ms
内存限制 64 MB
题目分析:这是一道查并集的简单应用题,主要考察查并集的使用和排序;
#include<iostream>
#include<algorithm>
using namespace std;
struct Node {
int u;
int v;
int w;
};
int father[10001] = { 0 };
int find(int x) {
if (father[x] == x) {
return x;
}
else {
return father[x] = find(father[x]);
}
}
void Merge(int x, int y) {
int fx, fy;
fx = find(x);
fy = find(y);
if (fx == fy) {
return;
}
else {
father[fx] = fy;
}
}
bool Merge2(int x, int y) {
int fx, fy;
fx = find(x);
fy = find(y);
if (fx == fy) {
return true;
}
else {
father[fx] = fy;
return false;
}
}
bool cmp(Node n1, Node n2) {
return n1.w < n2.w;
}
int main() {
int n, m, d;
cin >> n;
m = n * (n - 1) / 2;
Node tree[10001] = { 0 };
for (int i = 0; i < m; i++) {
father[i] = i;
}
for (int i = 0; i < m; i++) {
cin >> tree[i].u >> tree[i].v >>tree[i].w >> d;
if (d == 1) {
Merge(tree[i].u, tree[i].v);
}
}
sort(tree, tree + m,cmp);
int sum=0;
for (int i = 0; i < m; i++) {
if (Merge2(tree[i].u, tree[i].v)==false) {
sum = sum + tree[i].w;
}
}
cout << sum;
}