题意:火车从A驶来,默认车厢顺序是1-N,有一个站点,每次可以选择进站一个车厢或者出站一个车厢至B,车厢运动只能是A-Station-B的顺序不能退回,问是否能通过站点B使列车的车厢顺序满足输入的车厢顺序情况。
思路:把车厢当单个元素考虑,很明显是栈的抽象模型,故可用栈来模拟该过程,先用order数组记录目标顺序,从第一个元素开始遍历,然后从cnt+1开始压栈,cnt初始值为0,例如第一个元素是4则压栈1到4并让4出站且ans++(ans初值为0,最终判断出栈的车箱数是否等于N确定是否满足条件);此时cnt变为5,若第二个元素小于四则不压栈反之压栈,注意输入数据的时候有点坑。
#include <iostream>
#include <iomanip>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <set>
#include <map>
#include <list>
#include <stack>
#include <deque>
#include <queue>
#include <vector>
#include <algorithm>
#include <functional>
#define debug(x) cout << "--------------> " << x << endl
using namespace std;
const double PI = acos(-1.0);
const double eps = 1e-10;
const long long INF = 0x7fffffff;
const long long MOD = 1000000007;
const int MAXN = 1000 + 7;
int order[MAXN];
int main()
{
int n;
while(scanf("%d", &n), n)
{
bool flag = false;
int temp;
while(scanf("%d", &temp))
{
stack<int> st;
if(temp == 0)
{
flag = true;
break;
}
order[0] = temp;
for(int i = 1; i < n; ++i)
{
scanf("%d", &temp);
order[i] = temp;
}
int index = 0;
int cnt = 0;
int ans = 0;
int pos = 0;
while(index < n)
{
for(int i = cnt+1; i <= order[index]; ++i)
{
st.push(i);
cnt = i;
}
index++;
int a = INF;
if(!st.empty()) a = st.top();
//一定要判断栈非空再令a等于栈顶元素
int b = order[pos];
while(a == b)
{
pos++;
b = order[pos];
ans++;
st.pop();
if(st.empty())break;
a = st.top();
}
}
if(ans == n)
printf("Yes\n");
else
printf("No\n");
}
if(flag)
{
printf("\n");
}
}
return 0;
}