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 961592690 at 2019-02-25 17:30:31 on Problem 1703
这个题不可以使用Cin
必须使用scanf,另外在每个scanf后面加上getchar()来清空缓冲区
下面是代码
#include<iostream>
#include<stdio.h>
#include<string.h> 
using namespace std;
#define MAX_N 100005
int T;
int par[MAX_N*2]={0};
int rank[MAX_N*2];
void init(int x){
	for(int i=1;i<=x;i++){
		par[i]=i;
		rank[i]=0;
	}
}
int find(int x){
	if(par[x]==x)
	return x;
	else
	return par[x]=find(par[x]);
}
void unite(int x,int y){
	x = find(x);
	y = find(y);
	if(x==y)
	return;
	if(rank[x]<rank[y])
		par[x]=y;
	else{
		par[y]=x;
		if(rank[x]==rank[y])
			rank[x]++;
	}
}
bool same(int x,int y){
	return find(x)==find(y);
}
int main(){
	scanf("%d",&T);
	while(T--){
		int M,N;
		scanf("%d%d",&N,&M);
		getchar();
		memset(par,0,sizeof(par));
		init(2*N);
		for(int i=0;i<M;i++){
			char cmd;
			int c1,c2;
			//cin>>cmd>>c1>>c2;
			scanf("%c %d %d",&cmd,&c1,&c2);
			getchar();
			if(cmd=='D'){
				unite(c1,c2+N);
				unite(c1+N,c2);
			}
			else{
				if(N==2)
				printf("In different gangs.\n");
				else if(same(c1,c2)){
				printf("In the same gang.\n");
				}
				else if (same(c1,c2+N)||same(c1+N,c2))printf("In different gangs.\n");
				else
				puts("Not sure yet.");
			}
		}
	}
}

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