Constructing Roads
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.
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.
3 0 990 692 990 0 179 692 179 0 1 1 2
179
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int map[110][110],per[110],m,n;
struct node {
int x,y,dis;
}s[10000];
void init()
{
for(int i=0;i<=n;i++)
per[i]=i;
}
int find (int x)
{
while(x!=per[x])
x=per[x];
return x;
}
bool join(int x,int y)
{
int fx=find(x);
int fy=find(y);
if(fx!=fy)
{
per[fx]=fy;
return true;
}
return false;
}
bool cmp(node x,node y)
{
return x.dis<y.dis;
}
int main()
{
int a,b,i,j,k;
while(scanf("%d",&n)!=EOF)
{
init();
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&map[i][j]);
scanf("%d",&m);
for(i=0;i<m;i++)
{
scanf("%d%d",&a,&b);
map[a][b]=map[b][a]=0;
}
int t=0;
for(i=1;i<=n;i++)
{
for(j=i;j<=n;j++)
{
s[t].x=i;
s[t].y=j;
s[t++].dis=map[i][j];
}
}
sort(s,s+t,cmp);
int sum=0;
for(i=0;i<t;i++)
{
if(join(s[i].x,s[i].y))
sum+=s[i].dis;
}
printf("%d\n",sum);
}
return 0;
}
6241



被折叠的 条评论
为什么被折叠?



