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 houyideng at 2013-11-27 19:27:21 on Problem 1988
#include<stdio.h>
#include<iostream>
using namespace std;
const int N=30010;
struct node {
	int front,last,count;
}pre[N];
int find(int x) {//指向队尾
	if(x!=pre[x].last) {
         int h=pre[x].last;
		pre[x].last=find(pre[x].last);
		pre[x].count=pre[h].count+pre[x].count;//路径压缩
	}
	return pre[x].last;
}
int find1(int x) {//求队首相当于一个并查集指向两个方向,这个指向队首
	if(x!=pre[x].front)
		pre[x].front=find1(pre[x].front);
	return pre[x].front;
}
int main() {
	int n,i,a,b,f1,f2;
	char  s[2];
	while(scanf("%d",&n)!=EOF) {
		for(i=1;i<=N;i++) {
			pre[i].last=i;
			pre[i].front=i;
			pre[i].count=0;
		}
		while(n--) {
			scanf("%s",s);
			if(s[0]=='M') {
				scanf("%d%d",&a,&b);
			  f1=find(a);//a集合的队尾
			  f2=find(b);
			  if(f1==f2)//如果有相同的根节点不用再加了
				  continue;
			  f2=find1(b);//求b集合的队首
			  pre[f1].last=f2;//a集合队尾指向b集合队首
			  pre[f1].count=1;//权值为1
	          pre[f2].front=f1;//b集合的队首指向a集合的队尾
			}
			else  {
				scanf("%d",&a);
		         find(a);//计算
				printf("%d\n",pre[a].count);
			}
		}
	}
	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