首页 > 代码库 > UVa514 Rails (栈)

UVa514 Rails (栈)

链接:http://acm.hust.edu.cn/vjudge/problem/19641
分析:车厢符合后进先出的原则,因此是一个栈。

 1 #include <cstdio> 2 #include <stack> 3 using namespace std; 4  5 const int maxn = 1000 + 10; 6  7 int n, target[maxn]; 8  9 int main() {10     while (scanf("%d", &n) == 1 && n) {11         while (scanf("%d", &target[1]) && target[1]) {12             stack<int> s;13             for (int i = 2; i <= n; i++) scanf("%d", &target[i]);14             int A = 1, B = 1;15             bool ok = true;16             while (B <= n) {17                 if (A == target[B]) { A++; B++; }18                 else if (!s.empty() && s.top() == target[B]) { s.pop(); B++; }19                 else if (A <= n) s.push(A++);20                 else { ok = false; break; }21             }22             printf("%s\n", ok ? "Yes" : "No");23         }24         printf("\n");25     }26     return 0;27 }

 

UVa514 Rails (栈)