POJ 2349 Arctic Network (Kruskal) .

本文介绍了一种基于Kruskal算法的实现方法,用于找到图中第P-S长的边,通过具体代码展示了如何计算特定条件下边的权重,并采用最小生成树算法解决问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目地址: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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值