用棧模擬不難
// Problem#: 1509
// Submission#: 878974
// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/
// All Copyright reserved by Informatic Lab of Sun Yat-sen University
#include <iostream>
#include <stack>
#include <vector>
using namespace std;
int main()
{
int coach_num; //車廂的數目
while( cin >> coach_num && coach_num != 0 ) //車廂數目爲0將不會操作
{
int test;
while(cin >> test && test != 0)
{
vector<int> coach_out; //coach_out記錄用戶希望出站的車廂順序
vector<int>::iterator it;
stack<int> coach_in; //coach_in用於在站內可以出站的車廂的順序
int coach_counter = 0; //記錄已出站的車廂數目
for( int i = 1; i <= coach_num; ++i ) //coach_out記錄用戶希望出站的車廂順序
{
int temp;
if( i == 1 )
coach_out.push_back(test);
else
{
cin >> temp;
coach_out.push_back(temp);
}
}
it = coach_out.begin();
for( int j = 1; j <= coach_num; ++j) //如果將要入站的標號與用戶希望出站的標號相同,則出站
{ //j用於表示入站的順序
if( j == (*it)) //如果將要入站的車廂與用戶希望接下來要出站的車廂編號一致,則將此車廂出站
{
it = coach_out.erase(it);
coach_counter++; //標記出站的車廂數目加1
}
else //如果來到的車廂不是用戶想要出站的就先入站
{
while( !coach_in.empty() && coach_in.top() == (*it))
{
it= coach_out.erase(it);
coach_counter++;
coach_in.pop();
}
coach_in.push(j);
}
}
if(coach_out.empty())
;
else
for(it = coach_out.begin(); it != coach_out.end(); ++it)
{
if(coach_in.top() == (*it))
{
coach_in.pop();
coach_counter++;
}
}
if(coach_counter == coach_num)
cout << "Yes" << endl;
else
cout << "No" << endl;
}
cout << endl;
}
return 0;
}