您的位置:首页 > 其它

POJ 2349 Arctic Network (Kruskal) .

2016-08-16 13:00 363 查看
题目地址:http://poj.org/problem?id=2349

输出用%f而%lf就错了,还好我机智,因为上次被坑过

选第P-S长的边

#include<iostream>
#include<cstdio>
#include<queue>
#include<cmath>
#include<vector>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=500+5;
struct Point{
int x,y;
Point(int x,int y):x(x),y(y){}
};
vector<Point> points;
struct Edge{
int from,to; double weight;
Edge(int f,int t,double w):from(f),to(t),weight(w){}
bool operator < (const Edge& e) const {
return weight<e.weight;
}
};
vector<Edge> edges;

double dist(Point x,Point y){
return hypot(x.x-y.x,x.y-y.y);
}
void initDist(int N)
{
for(int i=0;i<N;i++)
for(int j=i+1;j<N;j++){
double d=dist(points[i],points[j]);
edges.push_back(Edge(i,j,d));
}
}

int p[maxn];
int find(int x) {
return p[x]==x?x:p[x]=find(p[x]);
}
double Kruskal(int S,int n)
{
for(int i=0;i<n;i++) p[i]=i;
sort(edges.begin(),edges.end());
int done=0;
int m=edges.size();
for(int i=0;i<m;i++)
{
Edge e=edges[i];
int u=e.from, v=e.to;double w=e.weight;
int up=find(u), vp=find(v);
if(up!=vp) p[up]=vp,done++;
if(done==n-S) return w; //到P-S条边就结束
}
return 0;
}

int main()
{
int T;
cin>>T;
while(T--)
{
int S,P;
cin>>S>>P;
points.clear();
for(int i=0;i<P;i++){
int x,y;
cin>>x>>y;
points.push_back(Point(x,y));
}
edges.clear();
initDist(P);
printf("%.2f\n",Kruskal(S,P));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: