Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

水水并查集

Posted by steins1 at 2016-10-18 20:11:22 on Problem 2524
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;

const int N=50005;
int pre[N];
int num;

void init(int x)
{
	int i;
	for(i=1;i<=x;i++)
	  pre[i]=i;
    num=x;
}

int find(int x)
{
	int r=x;
	while(r!=pre[r])
	  r=pre[r];
    int t=x,j;
    while(t!=r)
    {
    	j=pre[t];
    	pre[t]=r;
    	t=j;
    }
    return r;
}

void join(int x,int y)
{
	int fx=find(x);
	int fy=find(y);
	if(fx!=fy)
	{
		num--;
		pre[fx]=fy;
	}
}

int main()
{
	int n,m,j,i,x,y,t;
	t=0;
	while(~scanf("%d%d",&n,&m)&&n&&m)
	{
		t++;
		init(n);
		for(i=0;i<m;i++)
		{
			scanf("%d%d",&x,&y);
			join(x,y);
		}
		printf("Case %d: %d\n",t,num);
	}
	return 0;
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator