POJ 2421 Constructing Roads(最小生成树,边已经存在的处理方法)

Constructing Roads
Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 22483   Accepted: 9606

Description

There are N villages, which are numbered from 1 to N, and you should build some roads such that every two villages can connect to each other. We say two village A and B are connected, if and only if there is a road between A and B, or there exists a village C such that there is a road between A and C, and C and B are connected. 

We know that there are already some roads between some villages and your job is the build some roads such that all the villages are connect and the length of all the roads built is minimum.

Input

The first line is an integer N (3 <= N <= 100), which is the number of villages. Then come N lines, the i-th of which contains N integers, and the j-th of these N integers is the distance (the distance should be an integer within [1, 1000]) between village i and village j. 

Then there is an integer Q (0 <= Q <= N * (N + 1) / 2). Then come Q lines, each line contains two integers a and b (1 <= a < b <= N), which means the road between village a and village b has been built.

Output

You should output a line contains an integer, which is the length of all the roads to be built such that all the villages are connected, and this value is minimum.

Sample Input

3
0 990 692
990 0 179
692 179 0
1
1 2

Sample Output

179

Source

PKU Monthly,kicc


题意:

简单的生成树吧,就是对数据的加工处理上需要动下脑袋。


键入数据:
村庄的数目 n
村庄 1 1的距离 ,村庄1 2 的距离 村庄 1 3的距离 ,......村庄 1 n 的距离
村庄 2 1的距离 ,村庄2 2 的距离 村庄 2 3的距离 ,......村庄 2 n 的距离
.................................
村庄 n 1的距离 ,村庄n 2 的距离 村庄 n 3的距离 ,......村庄 n n 的距离

已有的边的数目 m

1 节点 节点 

m 节点 节点 


思路:

之前想的是再用一个结构体变量标记是否有该节点的边,但是有 BUG 即边的权值大的时候一直是错误的。

为了优先使用已经存在的边,就把该边的权值赋值为 0 ,那样排序后就优先选择了。


代码:

#include
#include
#include
using namespace std;
const int MYDD=110300;

int set[MYDD];
void init(int x) {//并查集的初始化
	for(int j=1; j<=x; j++)
		set[j]=j;
}

int find(int x) {//并查集的查操作
	int t,child=x;
	while(x!=set[x])
		x=set[x];
	while(child!=x) {
		t=set[child];// t 记录当前父节点
		set[child]=x;
		child=t;
	}
	return x;
}

bool combine(int x,int y) {//并查集的并操作
	int fx=find(x);
	int fy=find(y);
	if(fx!=fy) {
		set[fx]=fy;
		return true;//不成环
	}
	return false;
}

struct EDGE {
	int u,v,w,vis;//vis 标记当前节点是否已经有边
} edge[MYDD*8];
bool cmp(EDGE x,EDGE y) {
	return x.w


后:

******************

POJ 2421 Constructing Roads(最小生成树,边已经存在的处理方法)_第1张图片

你可能感兴趣的:(POJ,最小,最大,次小生成树)