G++提交 C++ TLE
#include<cmath> #include<cstdio> #include<cstring> #include<iostream> #include<algorithm> #define MAXN 1010 using namespace std; int fa[MAXN]; int n,m,tot,sum; double x[MAXN],y[MAXN]; struct nond{ int x,y;double z; }v[MAXN*MAXN]; int cmp(nond a,nond b){ return a.z<b.z; } int find(int x){ if(fa[x]==x) return x; else return fa[x]=find(fa[x]); } int main(){ scanf("%d",&n); for(int i=1;i<=n;i++) scanf("%lf%lf",&x[i],&y[i]); for(int i=1;i<=n;i++) for(int j=i+1;j<=n;j++){ double tmp=(x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j]); v[++tot].x=i;v[tot].y=j;v[tot].z=tmp; } scanf("%d",&m); for(int i=1;i<=m;i++){ int x,y;scanf("%d%d",&x,&y); v[++tot].x=x;v[tot].y=y;v[tot].z=0; } for(int i=1;i<=n;i++) fa[i]=i; sort(v+1,v+1+tot,cmp); for(int i=1;i<=tot;i++){ int dx=find(v[i].x); int dy=find(v[i].y); if(dx==dy) continue; fa[dy]=dx;sum++; if(v[i].z!=0) cout<<v[i].x<<" "<<v[i].y<<endl; if(sum==n-1) break; } }