问题描述:
Problem Description
Eddy begins to like painting pictures recently ,he is sure of himself to become a painter.Every day Eddy draws pictures in his small room, and he usually puts out his newest pictures to let his friends appreciate. but the result it can be imagined, the friends are not interested in his picture.Eddy feels very puzzled,in order to change all friends ‘s view to his technical of painting pictures ,so Eddy creates a problem for the his friends of you.
Problem descriptions as follows: Given you some coordinates pionts on a drawing paper, every point links with the ink with the straight line, causes all points finally to link in the same place. How many distants does your duty discover the shortest length which the ink draws?
Input
The first line contains 0 < n <= 100, the number of point. For each point, a line follows; each following line contains two real numbers indicating the (x,y) coordinates of the point.
Input contains multiple test cases. Process to the end of file.
Output
Your program prints a single real number to two decimal places: the minimum total length of ink lines that can connect all the points.
Sample Input
3
1.0 1.0
2.0 2.0
2.0 4.0
Sample Output
3.41
大致题意:
在二维坐标系中给出n个点。求让所有点连通的最小花费。
思路分析:
基本的最短路。
prim或Kruskal算法都能解决。
ac代码:
#include<bits/stdc++.h>
using namespace std;
const long MAXN=10000;
long father[MAXN];
long m,n;//点数 边数
//m标号从1开始
typedef struct
{
long from;
long to;
double cost;
}Edge;
bool operator <(const Edge &a, const Edge &b)
{
return a.cost>b.cost;
}
priority_queue<Edge> q;
Edge e[100005];
void MakeSet()
{
long i;
for (i=0;i<=m;++i)
{
father[i]=i;
}
}
long Find(long i)
{
long r=i;
while (father[r]!=r)
{
r=father[r];
}
while (father[i]!=r)
{
long j=father[i];
father[i]=r;
i=j;
}
return r;
}
void Unition(long x,long y)
{
long fx=Find(x);
long fy=Find(y);
if (fx!=fy)
{
father[fx]=fy;
}
}
void Init()
{
while (!q.empty())
{
q.pop();
}
MakeSet();
Edge a;
double x[105],y[105];
int i,j,k;
for(i=0;i<m;i++)
{
cin>>x[i]>>y[i];
}
for(i=0;i<m;i++)
{
for(j=0;j<m;j++)
{
if(i==j)
continue;
a.from=i,a.to=j;
a.cost=sqrt((x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j]));
q.push(a);
}
}
}
void print(double cost)
{
printf("%.2f\n",cost);
}
void Kruskal()
{
Init();
long t=0;//表示合并次数
double cost=0;
Edge e;
while (!q.empty()&&t<m-1)
{
e=q.top();
long v1=e.from;
long v2=e.to;
if (Find(v1)!=Find(v2))
{
Unition(v1,v2);
cost+=e.cost;
++t;
}
q.pop();
}
print(cost);
}
int main()
{
while(~scanf("%ld",&m))//输入点与边
{
Kruskal();
}
return 0;
}