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
30 990 692990 0 179692 179 011 2
Sample Output
179 解题思路:
要修公路,输入一个n,表示n个村庄。接着输入n*n的矩阵,然后输入一个q 接下来的q行
每行包含两个数a,b,表示a、b这条边联通,就是已经有公路不用修了,要让所有村庄联通在一起问:修路最小代价?
最小生成树的变形,有的村庄已经连接了,就直接把他们的权值赋为0,一样的做最小生成树,Prim算法。
代码如下:
1 #include2 #include 3 #include 4 using namespace std; 5 6 int N; 7 int dis[1001][1001]; 8 bool vis[1001][1001]; 9 struct edge{10 int u;11 int v;12 int w;13 }e[10005];14 int pre[1001];15 int find(int x)16 {17 return (x==pre[x])?x:pre[x] = find(pre[x]);18 }19 bool cmp(edge a , edge b)20 {21 return a.w