题目链接:
POJ 1751 Highways
题意:
有n个点需要修公路将这n个点连通,修公路里程越长,成本越高。已知有m条公路已经修好了的。
求出最少成本下,需要修哪些公路,将这些公路的起始点输出来。
分析:
最小生成树。将m条已经修好的公路用并查集合并下,再用Kruskal算法记录下修的公路起始点即可。
注意:
测试样例无需循环读入,直接scanf(“%d”,&n);即可,用while反而WA.
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
const int maxn=800;
int n,m,tot,u,v,fu,fv;
int pre[maxn];
struct Point{
int x,y;
}point[maxn];
struct Edge{
int u,v;
double w;
}edge[maxn*maxn];
struct Ans{
int u,v;
}ans[maxn];
bool cmp(struct Edge a,struct Edge b)
{
return a.w<b.w;
}
double Distance(struct Point a,struct Point b)
{
int xx=a.x-b.x;
int yy=a.y-b.y;
return sqrt(xx*xx+yy*yy);
}
int find(int x)
{
return pre[x]==x?x:pre[x]=find(pre[x]);
}
int main()
{
#ifdef LOCAL
freopen("in.txt","r",stdin);
#endif
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%d%d",&point[i].x,&point[i].y);
tot=0;
for(int i=1;i<=n;i++)
{
for(int j=i+1;j<=n;j++)
{
edge[tot].u=i;
edge[tot].v=j;
edge[tot].w=Distance(point[i],point[j]);
tot++;
}
}
sort(edge,edge+tot,cmp);
for(int i=0;i<maxn;i++)
pre[i]=i;
scanf("%d",&m);
for(int i=1;i<=m;i++)
{
scanf("%d%d",&u,&v);
fu=find(u);
fv=find(v);
if(fu!=fv) pre[fu]=fv;
}
int tmp=0;
for(int i=0;i<tot;i++)
{
u=edge[i].u;
v=edge[i].v;
fu=find(u);
fv=find(v);
if(fu!=fv)
{
pre[fu]=fv;
ans[tmp].u=u;
ans[tmp].v=v;
tmp++;
}
}
for(int i=0;i<tmp;i++)
printf("%d %d\n",ans[i].u,ans[i].v);
return 0;
}