1 solutions

  • 1
    @ 2022-4-11 17:49:32
    #include<iostream>
    using namespace std;
    const int N=100010;
    int p[N];
    int find(int x)
    {
    	if(p[x]!=x) p[x]=find(p[x]);
    	return p[x];
    }
    void merge(int x,int y)
    {
    	int xx=find(x);
    	int yy=find(y);
    	if(xx!=yy) p[xx]=yy;
    }
    int main(){
    	int n,m;
    	while(cin>>n>>m)
    	{
    		for(int i=1;i<=n;i++) p[i]=i;
    		for(int i=1;i<=m;i++)
    		{
    			int x,y;
    			cin>>x>>y;
    			merge(x,y);
    		}
    		int sum=0;
    		for(int i=1;i<=n;i++)
    			if(p[i]==i)
    				sum++;
    		cout<<sum-1<<endl;
    	}
    	return 0;
    }
    
    • 1

    Information

    ID
    273
    Time
    1000ms
    Memory
    256MiB
    Difficulty
    6
    Tags
    # Submissions
    28
    Accepted
    18
    Uploaded By