URAL 1915 Titan Ruins: Reconstruction of Bygones (栈)

1915. Titan Ruins: Reconstruction of Bygones


http://acm.timus.ru/problem.aspx?space=1&num=1915

Time limit: 1.0 second
Memory limit: 64 MB
`It seems that we're in a trap,' said Soren.
`A very familiar phrase,' Alba replied.
The friends were locked in a room, which, apparently, had been a sort of laboratory where object copying experiments had been conducted. They decided so because there were large piles of coins in the room and the coins in each pile were identical to each other up to tiny scratches.
Soren studied the room and found a row of holes in one of the walls. The size of each hole was equal to the size of a coin, and he conjectured that the door would open when certain coins were put in the holes. At the same time, Alba examined the book on the table and discovered in it a description of an experiment with coins. In this experiment, coins were put one upon another forming a stack. Sometimes the top coin was removed, and sometimes the Copying Spell was applied, which produced an identical stack located on top of the existing stack.
Soren and Alba decided to repeat the experiment, putting the coins removed from the top of the stack into the holes one by one. They supposed that the door would open after that. However, they didn't know the Copying Spell, so they had to find out which coins were at top of stack without actual reproducing of all experiment. There were lots of various coins in the room they could use, but still it wasn't easy to choose which coins had to be put in the holes.

Input

The first line contains the number  n of operations in the experiment (1 ≤  n ≤ 10 6). In each of the following  n lines you are given an integer  x (−1 ≤  x ≤ 10 9). If  x > 0, then a coin of type  x is put on top of the stack. If  x = −1, then the top coin is taken from the stack and put into the next hole in the wall. If  x = 0, then the stack is copied. It is guaranteed that during the experiment each time a coin was to be removed the stack was not empty.

Output

Output the types of coins removed from the top of the stack in the course of the experiment. The numbers should be given one per line.

Sample

input output
8
3
4
0
-1
-1
-1
-1
1
4
3
4
3


开数组的技巧:够用就行,当栈足够大时,复制是多余的。


完整代码:

/*656ms,4236KB*/

#include <cstdio>

int stack[2000010];///开2*n大小

int main(void)
{
	int n, i, j, p, x;
	while (~scanf("%d", &n))
	{
		p = 0;
		for (i = 1; i <= n; i++)
		{
			scanf("%d", &x);
			if (x > 0)
				stack[p++] = x;
			else if (x < 0)
				printf("%d\n", stack[--p]);
			else if (p < n - i)///小技巧:当p足够大时,后面的复制是多余的
			{
				for (j = 0; j < p; j++)
					stack[j + p] = stack[j];
				p <<= 1;
			}
		}
	}
	return 0;
}



你可能感兴趣的:(C++,ACM,ural)