題解 luogu P1536 【村村通】
阿新 • • 發佈:2018-12-02
非常弱的一道黃題。
明明裸並查集還是要加一個“生成樹”的標籤。
並查集判同村,若不同村就ans++
下面貼程式碼
#include<bits/stdc++.h> using namespace std; int bcj[5010]; int get(int x) { if (bcj[x]==x)return x; else return bcj[x]=get(bcj[x]); } void merge(int x,int y) { bcj[get(x)]=get(y); } int main() { int i,j,x=1,y,n,k; while (x!=0) { cin>>x; if (x==0)return 0; cin>>y; int ans=0; for (i=1;i<=5010;i++) bcj[i]=i; for (i=1;i<=y;i++) { int a,b; cin>>a>>b; merge(a,b); } for (i=2;i<=x;i++) if (get(1)!=get(i)){ans++;merge(1,i);} cout<<ans<<endl;//只要不與第一項同村就++,若第一項不與最大村同村也沒事。 } return 0; }