行电1102 Constructing Roads

来源:互联网 发布:订房软件 编辑:程序博客网 时间:2024/05/21 06:40
Problem 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
30 990 692990 0 179692 179 011 2
 

Sample Output
179

这是个最小生成树的简单变形,可以将已经修建好的路的花费设置为0,这样就可以套用模板了,下面是代码


#include<iostream>
#include<math.h>
#include<algorithm>
#include<stdio.h>
using namespace std;
struct lnode{
double x,y;
};
struct line{
int st,ed;
double len;
};
double map[101][101];
lnode node[1001];
line _line[100001];
int p[10001];
double dis(lnode a,lnode b)
{
return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
}
bool cmp(line a ,line b)
{
if(a.len<b.len)return true;
return false;
}
int find(int x)
{
return x==p[x]?x:p[x]=find(p[x]);
}
int main()
{
int n,q;
while(cin>>n)
{
double ans=0;
int count=0,t;
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
cin>>map[i][j];
cin>>q;
for(int i=0;i<q;i++)
{
int a,b;
cin>>a>>b;
map[a-1][b-1]=0;
}
for(int i=0;i<n;i++)
for(int j=i+1;j<n;j++)
{
t=count++;
_line[t].st=i;
_line[t].ed=j;
_line[t].len=map[i][j];
}
sort(_line,_line+count,cmp);
// for(int i=0;i<count;i++)
//cout<<_line[i].st<<' '<<_line[i].ed<<' '<<_line[i].len<<endl;
for(int i=0;i<count;i++)
p[i]=i;
for(int i=0;i<count;i++)
{
int a=find(_line[i].st);
int b=find(_line[i].ed);
if(a!=b)
ans+=_line[i].len;
p[a]=b;
}
cout<<ans<<endl;
}
//system("pause");
return 0;
}
0 0