Cube Stacking

àì夳堔傛蜴生んèń 2022-06-01 04:20 273阅读 0赞








Cube Stacking


















Time Limit: 2000MS   Memory Limit: 30000K
Total Submissions: 26409   Accepted: 9239
Case Time Limit: 1000MS

Description



Farmer 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

  1. 6
    M 1 6
    C 1
    M 2 4
    M 2 6
    C 3
    C 4

Sample Output

  1. 1
    0
    2

Source


题目大意:有N个立方体和N个格子,1~N编号,一開始i立方体在i号格子上,每一个格子刚好1个立方体。如今m组操作,M a b表示将a号立方体所在的格子的所有立方体放在b号立方体所在的格子的所有立方体上面。C x表示询问x号立方体以下的立方体的个数。

  1. #include<stdio.h>
  2. #include<string.h>
  3. #include<algorithm>
  4. using namespace std;
  5. #define N 30001
  6. int p,fu[N],zi[N],juli[N];
  7. int Make_set()//初始化并查集
  8. {
  9. int i;
  10. for(i=1;i<N;i++)
  11. {
  12. fu[i]=i;//按题目要求对盒子进行编号
  13. zi[i]=1;
  14. juli[i]=0;
  15. }
  16. }
  17. int Find_Set(int x)//找祖宗
  18. {
  19. int fx=fu[x];
  20. if(fu[x]!=x)
  21. {
  22. fx=Find_Set(fu[x]);
  23. juli[x]+=juli[fu[x]];
  24. }
  25. return fu[x]=fx;
  26. }
  27. void Union(int a,int b)//合并两个集合
  28. {
  29. int x,y;
  30. x=Find_Set(a);
  31. y=Find_Set(b);
  32. if(x==y)//相等则在同一个集合中
  33. return ;
  34. fu[y]=x;
  35. juli[y]+=zi[x];
  36. zi[x]+=zi[y];
  37. }
  38. int main()
  39. {
  40. while(scanf("%d",&p)!=EOF)
  41. {
  42. int i,j,a,b;
  43. char s[3];
  44. Make_set();
  45. for(i=1;i<=p;i++)
  46. {
  47. scanf("%s",s);
  48. if(s[0]=='C')
  49. {
  50. scanf("%d",&a);
  51. b=Find_Set(a);
  52. printf("%d\n",zi[b]-juli[a]-1);
  53. }
  54. else
  55. {
  56. scanf("%d%d",&a,&b);
  57. Union(a,b);
  58. }
  59. }
  60. }
  61. return 0;
  62. }

发表评论

表情:
评论列表 (有 0 条评论,273人围观)

还没有评论,来说两句吧...

相关阅读

    相关 POJ 1988 Cube Stacking

    题目: POJ 1988 Cube Stacking ,哈哈,我们今天来看一道复杂一点的题嘛,这是选自POJ上的一道题,好了,我们一起来看看题意吧:考虑到直接复制题目,或...