最小生成樹+並查集:洛谷P1991 無線通訊網
阿新 • • 發佈:2021-11-09
水一題,此題和洛谷P4047 [JSOI2010]部落劃分完全一樣,沒有任何區別,程式碼就調換了一下n和m輸入的順序以及最後while(ans>=m)改成了while(ans>m)
#include<bits/stdc++.h> #define INF 2147483647 using namespace std; int dad[5003]; struct node{ int num,to; int value; }; int find(int x){ if(dad[x]==x) return x; dad[x]=find(dad[x]);return dad[x]; } bool operator < (const node &a, const node &b){ return a.value > b.value; } int main(){ vector<node>a[5003]; int ax[1003],ay[1003]; priority_queue<node> q; int n,m,i,x,y,z,ans,ansn; node t;t.value=INF; memset(dad,0,sizeof(dad)); cin>>m>>n; for(i=1;i<=n;i++){ dad[i]=i; scanf("%d%d",&ax[i],&ay[i]); for(int j=1;j<i;j++){ node b; b.num=i;b.to=j;b.value=(ax[i]-ax[j])*(ax[i]-ax[j])+(ay[i]-ay[j])*(ay[i]-ay[j]); q.push(b); } } ans=n;node b; while(ans>m){ b=q.top();q.pop();x=b.to; if(find(x)==find(b.num)) continue; dad[find(x)]=b.num;ans--; // printf("%d->%d:%d\n",b.num,b.to,b.value); } printf("%.2lf",sqrt(b.value)); }