1077: Rails

Title Description

PopPush city has a famous train station. The country is full of hills. And this railway station was built in the last century. Unfortunately, the limited time funds. You can only build a rail road. Moreover, this leads to the train station at the same time only one track in use, because it lacks space, two trains will be nowhere to go. In particular see the figure. 
Local custom is to train each direction from A towards B direction of time, will in some way to the cabin restructuring. A train will be assumed that the direction of arrival, the compartment with N (N <= 1000), these compartments labeled in ascending order from 1 to N. Leadership responsible for restructuring the cabin, must know whether it can be pulled out of the compartment recombinant B, and the reorganization of the sequence is a1 \ a2 \ a3 ... aN. Please help him write a program to determine whether it is possible in accordance with the order of carriages required. You can assume that the individual compartments can be separated from the train, before they enter the site. And they can move freely until they are on the B track. You can also assume that at any time the station can be put down numerous cars. But as long as a carriage into the platform, it can not return to the track A, and if it left the platform towards the B track, it can not return to the site. 
 

Entry

Enter multiple sets of test cases. 
For each test, the first line contains a positive integer n (1 <= n <=  1000).
Each line contains the following numbers n, representatives of the train exit sequence. 
0 at a single end of each test. 
To 0 as a single ended input.

Export

For each row of each set of test samples, the output exit order is legitimate. 
Between test samples were separated by an empty line. 

Sample input

5
1 2 3 4 5
5 4 1 2 3
0
6
6 5 4 3 2 1
0
0

Sample Output

Yes
No

Yes 

[Idea] 1 ~ N numbers are sequentially stored in the stack, the 1 ~ N stored in the same time, the top element in the array element with the already stored comparison, if the same, then the top element from the stack, scanning array moves the pointer to a position of X, if different, will sequentially stack numbers 1 ~ N, N stack end when the entire cycle, then determines whether the stack is empty, if empty, is effective, on the contrary, is invalid. Note the input the output format .

#include <iostream>
#include <stack>
using namespace std;
int main() {
	int n, m;
	while (cin>>n&&n) {
		int num[n+1];
		while(cin>>num[1]&&num[1]){//一个n可能有多组数据,0作为结束 
			stack<int> s;
			int x=1;
			for (int i=2;i<=n;i++) 
				cin>>num[i];
			for (int i=1;i<=n;i++) {
				s.push(i);
				while (!s.empty()&&s.top()==num[x]) {
					x++;
					s.pop();
				}
			}
			if (s.size()==0)cout<<"Yes\n";
			else cout<<"No\n";
		}
		cout<<endl; 
	}
	return 0;
} 

 

Published 44 original articles · won praise 1 · views 2272

Guess you like

Origin blog.csdn.net/Do_________/article/details/104069674