POJ-1751(kruskal算法)
Highways
POJ-1751
注意这里的样例答案也是对的,只是输出顺序改变,但是这也没关系,因为题目加了特殊判断。
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
#include<cstdio>
#include<cmath>
using namespace std;
const int maxn=755;
const int maxm=500004;
int n,m;
int e;
int x[maxn];
int y[maxn];
int set[maxn];
struct node{
int from;
int to;
double cost;
bool operator<(const node& t)const{
return cost<t.cost;
}
};
node edges[maxm];
int find(int x){
return x==set[x]?set[x]:set[x]=find(set[x]);
}
void kruskal(){
sort(edges,edges+e);
for(int i=0;i<e;i++){
int x=edges[i].from;
int y=edges[i].to;
double cost=edges[i].cost;
int from=find(x);
int to=find(y);
if(from!=to){
set[from]=to;
cout<<x<<" "<<y<<endl;
}
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
while(cin>>n){
e=0;
for(int i=1;i<=n;i++){
cin>>x[i]>>y[i];
set[i]=i;
for(int j=1;j<i;j++){
double cost=sqrt((x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j]));
edges[e++]=node({i,j,cost});
}
}
cin>>m;
for(int i=0;i<m;i++){
int a,b;
cin>>a>>b;
int a1=find(a);
int b1=find(b);
if(a1!=b1)
set[a1]=b1;
}
kruskal();
}
return 0;
}
Either Excellent or Rusty
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了