题目链接:点击打开链接
给你一个n,接下来一行是n个数字,代表出火车站的顺序,进火车站的顺序是1-n,问你是否可以按照给定的顺序出火车站。
火车站好比一个栈,火车进站代表入栈,火车出站代表出栈,可以模拟这个过程来判断是否符合题意。
不用stack的写法:
对读入数据后的for循环进行分析,每一个cnt代表是火车的序号,火车每出站和入站匹配时就匹配下一列火车,为-1时说明所有火
车都匹配完成,每次匹配失败时i++,表示当前火车没有出火车站,最后判断j是否为n即火车是否全部出站。
AC代码:
#include "iostream"
#include "cstdio"
#include "cstring"
#include "algorithm"
using namespace std;
const int MAXN = 1005;
int n, out[MAXN], in[MAXN];
int main(int argc, char const *argv[])
{
while(scanf("%d", &n) != EOF && n) {
int x;
while(scanf("%d", &x) != EOF && x) {
out[0] = x;
for(int i = 1; i < n; ++i)
scanf("%d", &out[i]);
int j = 0, cnt = 1;
for(int i = 0; cnt <= n; ) {
in[i] = cnt;
while(in[i] == out[j]) {
i--, j++;
if(i == -1) break;
}
i++, cnt++;
}
if(j == n) printf("Yes\n");
else printf("No\n");
}
printf("\n");
}
return 0;
}</span>
用stack的写法:
与上面相同,每次i入栈,代表火车进站,匹配成功且栈不为空时就弹出,也就是火车出站,最后也是通过j是否等于n判断火车是
否全部出站,最后还要初始化,否则会wa,因为下一次可能会继续匹配下去。。
AC代码:
#include "iostream"
#include "cstdio"
#include "cstring"
#include "algorithm"
#include "stack"
using namespace std;
const int MAXN = 1005;
int n, out[MAXN];
stack<int> in;
int main(int argc, char const *argv[])
{
while(scanf("%d", &n) != EOF && n) {
int x;
while(scanf("%d", &x) != EOF && x) {
out[0] = x;
for(int i = 1; i < n; ++i)
scanf("%d", &out[i]);
int j = 0;
for(int i = 1; i <= n; ++i) {
in.push(i);
while(!in.empty() && in.top() == out[j]) {
in.pop();
j++;
}
}
if(j == n) printf("Yes\n");
else printf("No\n");
memset(out, 0, sizeof(out));
}
printf("\n");
}
return 0;
}</span>