行电1102 Constructing Roads

2019-04-14 21:34发布

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 3 0 990 692 990 0 179 692 179 0 1 1 2  
Sample Output 179
这是个最小生成树的简单变形,可以将已经修建好的路的花费设置为0,这样就可以套用模板了,下面是代码

#include
#include
#include
#include
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.lenreturn 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;ifor(int j=0;jcin>>map[i][j];
cin>>q;
for(int i=0;i{
int a,b;
cin>>a>>b;
map[a-1][b-1]=0;
}
for(int i=0;ifor(int j=i+1;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//cout<<_line[i].st<<' '<<_line[i].ed<<' '<<_line[i].len<for(int i=0;ip[i]=i;
for(int i=0;i{
int a=find(_line[i].st);
int b=find(_line[i].ed);
if(a!=b)
ans+=_line[i].len;
p[a]=b;
}
cout<}
//system("pause");
return 0;
}