Uva514-Rails
2016-11-13 19:19
435 查看
有n辆火车入栈出栈,判断出栈顺序是否合法
逆向思维,将出栈后的火车重新入栈看能否构成1-n
用a,b两个变量标记,将a入栈直到找到第一个t[a] == b的数,然后判断栈内的数与t[b]是否匹配。
逆向思维,将出栈后的火车重新入栈看能否构成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; }
相关文章推荐
- Uva514——Rails
- UVa514-Rails-铁轨--栈的使用
- UVA514 Rails 栈初步..
- Uva 514 Rails(栈应用)
- UVA - 514 Rails
- UVA 514 rails
- uva514 Rails 栈相关问题
- UVA 514 Rails(栈)
- UVa 514 Rails
- 【STL】uva 514 Rails
- UVA 514 Rails
- UVa_514 - Rails
- Uva 514 Rails
- UVa 514 Rails(stack)
- Uva Oj 514 - Rails
- UVa 514 Rails(铁轨) 栈
- Uva - 514 - Rails
- UVa - 514 Rails(栈模拟)
- UVa 514 - Rails
- UVa 514 - Rails【栈+格式】