并查集板子题。
答案就是
附代码:
#include<iostream> #include<algorithm> #include<cstdio> #define MAXN 100010 using namespace std; int n,m,fa[MAXN]; char tp[100000],*p1=tp,*p2=tp; char get_char(){ return p1==p2&&(p2=(p1=tp)+fread(tp,1,100000,stdin),p1==p2)?EOF:*p1++; } inline int read(){ int date=0,w=1;char c=0; while(c<'0'||c>'9'){if(c=='-')w=-1;c=get_char();} while(c>='0'&&c<='9'){date=date*10+c-'0';c=get_char();} return date*w; } int find(int x){return fa[x]==x?x:fa[x]=find(fa[x]);} void uniun(int x,int y){x=find(x);y=find(y);if(x!=y)fa[x]=y;} void work(){ long long ans=0; for(int i=1;i<=n;i++)if(fa[i]==i)ans++; printf("%lld\n",ans-1); } void init(){ n=read();m=read(); for(int i=1;i<=n;i++)fa[i]=i; for(int i=1,x,y;i<=m;i++){ x=read();y=read(); uniun(x,y); } } int main(){ init(); work(); return 0; }