[原创]HDU 5818 Joint Stacks [栈]【模拟】
[原创]HDU 5818 Joint Stacks [栈]【模拟】
2017-02-01 16:40:41 Tabris_ 阅读数:218
博客爬取于2020-06-14 22:41:54
以下为正文
版权声明:本文为Tabris原创文章,未经博主允许不得私自转载。
https://blog.csdn.net/qq_33184171/article/details/54809490
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5818
---------------------------------------------------------------------------.
I 2017 口碑商家客流量预测大赛》
Joint Stacks
Time Limit: 8000/4000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 1522 Accepted Submission(s): 709
Problem Description
A stack is a data structure in which all insertions and deletions of entries are made at one end, called the “top” of the stack. The last entry which is inserted is the first one that will be removed. In another word, the operations perform in a Last-In-First-Out (LIFO) manner.
A mergeable stack is a stack with “merge” operation. There are three kinds of operation as follows:
- push A x: insert x into stack A
- pop A: remove the top element of stack A
- merge A B: merge stack A and B
After an operation “merge A B”, stack A will obtain all elements that A and B contained before, and B will become empty. The elements in the new stack are rearranged according to the time when they were pushed, just like repeating their “push” operations in one stack. See the sample input/output for further explanation.
Given two mergeable stacks A and B, implement operations mentioned above.
Input
There are multiple test cases. For each case, the first line contains an integer N(0< N≤105), indicating the number of operations. The next N lines, each contain an instruction “push”, “pop” or “merge”. The elements of stacks are 32-bit integers. Both A and B are empty initially, and it is guaranteed that “pop” operation would not be performed to an empty stack. N = 0 indicates the end of input.
Output
For each case, print a line “Case #t:”, where t is the case number (starting from 1). For each “pop” operation, output the element that is popped, in a single line.
Sample Input
4
push A 1
push A 2
pop A
pop A
9
push A 0
push A 1
push B 3
pop A
push A 2
merge A B
pop A
pop A
pop A
9
push A 0
push A 1
push B 3
pop A
push A 2
merge B A
pop B
pop B
pop B
0
Sample Output
Case #1:
2
1
Case #2:
1
2
3
0
Case #3:
1
2
3
0
---------------------------------------------------------------------------.
题目大意
就是有三种操作,
- push A x: insert x into stack A --------------------------- 将x插入到栈A
- pop A: remove the top element of stack A -------------- 将栈A的栈顶出栈并输出.
- merge A B: merge stack A and B ------------------------- 将栈B合并到栈A中,按照时间戳的顺序来。
解题思路
首先就是一个模拟,我们可以多引用一个栈C,来存储所有栈中的数据,但是注意只能在合并的时候将数据合并存储到栈C中,切莫直接合并到栈C中,其中的某些数据可能,在之前就已经出栈了。在合并的时候和marge_sort差不多,用时间戳比较就行了。
对于pop的时候直接pop当前栈就行了,如果栈是空的话 那么我们就对栈C pop就行了。因为输入数据均为合法数据,不会对空栈进行pop操作,所以正确性是有保证的。
最后注意一下输入就行了。
附本题代码
---------------------------------------------------------------------------.
1 | char op[20],ch,hc; |