- 1、本文档共4页,可阅读全部内容。
- 2、有哪些信誉好的足球投注网站(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
- 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载。
- 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
Pku1998并查集题解题报告
Pku1998 Cube Stacking
/*
Name: pku1998
Copyright: ecjtu_acm
Author: yimao
Date: 22-08-10 09:19
Description: 并查集
*/
一、题目
DescriptionFarmer John and Betsy are playing a game with N (1 = N = 30,000)identical cubes labeled 1 through N. They start with N stacks, each containing a single cube. Farmer John asks Betsy to perform P (1= P = 100,000) operation. There are two types of operations: moves and counts. * In a move operation, Farmer John asks Bessie to move the stack containing cube X on top of the stack containing cube Y. * In a count operation, Farmer John asks Bessie to count the number of cubes on the stack with cube X that are under the cube X and report that value. Write a program that can verify the results of the game. Input
* Line 1: A single integer, P * Lines 2..P+1: Each of these lines describes a legal operation. Line 2 describes the first operation, etc. Each line begins with a M for a move operation or a C for a count operation. For move operations, the line also contains two integers: X and Y.For count operations, the line also contains a single integer: X. Note that the value for N does not appear in the input file. No move operation will request a move a stack onto itself. Output
Print the output from each of the count operations in the same order as the input file. Sample Input
6
M 1 6
C 1
M 2 4
M 2 6
C 3
C 4Sample Output
1
0
2
二、题目大意及分析
【题意】
摘自《ACM程序设计竞赛入门》。
有n个独立的磁铁(1-n标号)放在桌上,一个人对这n堆进行移动操作,然后另一个人询问。规则:
M: 将含有编号为X的磁铁放在包含Y的顶端上;
C:询问在编号Z下面磁铁的数目;
【分析】
利用并查集,每一堆磁铁看作一个集合,“M a b”就是将a归并到b的上面,每个集合是有序的。设定3个域
Father: 根节点,初始化为本身;
Num: 以该节点为根的集合的元素个数;
Dis: 该点到其根的距离;
那么由num[father[a]]-dis[a]-1就是以a节点为根的集合所含有的元素个数。
三、代码及相关说明
/*1988 Accepted 736K 610MS G++ 1023B 2010-08-22 09:06:36 */
/*1988 Accepted 516K 297MS C++ 1023B 2010-08-22 09:07:03 */
#includestdio.h
#define arr 30005
int father[arr],num[arr],dis[arr];
//查找根节点;
int find(int x)
{
if(x!=father[x])
{
int temp=father[x];
father[x]=find(father[x]);
dis[x]
文档评论(0)