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
题意:
关于题意,我心头有一万句草泥马飘过…首先 意思我没看清楚,看错了;题意是第i行第j个数代表第i个村庄与第j个村庄的距离;
然后wawawa,题中说多组输入了么?????我**;
思路:
用用最小生成树Kruskal算法,然后对于两个村庄之间已经建设好的路,把两个村庄合并起来即可;
#include <bits/stdc++.h>
using namespace std;
const int maxx=1e5+7;
map<int,map<int,int> > mp;
int pre[maxx];
struct node
{
int x,y;
int s;
}bb[maxx];
bool cmp(node a,node b)
{
return a.s<b.s;
}
int find(int x)//路径压缩
{
if(x!=pre[x])
{
pre[x]=find(pre[x]);
}
return pre[x];
}
void join(int x,int y)
{
int fx=find(x),fy=find(y);
if(fx!=fy)
{
pre[fx]=fy;
}
}
int main()
{
int n;
while(cin>>n)
{
int x;
int ans=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cin >>x;
if(j==i) continue;
bb[ans].x=i+1,bb[ans].y=j+1,bb[ans++].s=x;
}
}
int q;
cin >>q;
int a,b;
for(int i=0;i<=maxx;i++) pre[i]=i;
for(int i=0;i<q;i++)//已经建好路的,把两个村庄的状态合并起来
{
cin >>a>>b;
join(a,b);
}
sort(bb,bb+ans,cmp);
int sum=0;
for(int i=0;i<ans;i++)
{
if(find(bb[i].x)!=find(bb[i].y))
{
sum+=bb[i].s;
join(bb[i].x,bb[i].y);
}
}
cout <<sum<<endl;
}
return 0;
}