您的位置:首页 > 大数据 > 人工智能

Uva514-Rails

2016-11-13 19:19 435 查看
有n辆火车入栈出栈,判断出栈顺序是否合法

逆向思维,将出栈后的火车重新入栈看能否构成1-n

用a,b两个变量标记,将a入栈直到找到第一个t[a] == b的数,然后判断栈内的数与t[b]是否匹配。

#include <cstdio>
#include <stack>

using namespace std;

int t[1005];

int main(int argc, char const *argv[]) {
int n;
while (scanf("%d", &n) == 1 && n) {
while (scanf("%d", &t[1]) == 1 && t[1]) {
for (int i = 2; i <= n; i++) {
scanf("%d", &t[i]);
}
stack<int> s;
int a = 1, b = 1;
bool ok = true;
while (b <= n) {
if (a == t[b]) {
a++;
b++;
} else if (!s.empty() && s.top() == t[b]) {
s.pop();
b++;
} else if (a <= n) {
s.push(a++);
} else {
ok = false;
break;
}
}
if (ok) {
puts("Yes");
} else {
puts("No");
}
}
putchar('\n');
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: