数据结构:栈 - UVA 514 - Rails
题目链接:https://vjudge.net/problem/UVA-514
思路:
用两个指针 A , B 分别表示 ' 理论上驶出车站的车厢 ' 、 ' 实际上驶出车站的车厢 '
用循环、栈模拟
(是的这就是刘哥的代码)
1 #include <cstdio> 2 #include <stack> 3 using namespace std; 4 const int MAXN = 1000 + 10; 5 int n, target[MAXN]; 6 int main(){ 7 while (scanf("%d",&n) && n) { 8 while (scanf("%d",&target[1]) && target[1]) { 9 stack<int> s; 10 int A = 1, B = 1; 11 int ok = 1; 12 if(target[1] == 0) 13 continue; 14 for (int i = 2; i <= n; i++) { 15 scanf("%d",&target[i]); 16 } 17 while (B <= n) { 18 if (A == target[B]) { 19 A++; B++; // 正常出 20 }else if(!s.empty() && s.top() == target[B]){ 21 s.pop(); B++; // 从栈出 22 }else if(A <= n){ // 入栈 23 s.push(A++); 24 }else{ 25 ok = 0; 26 break; 27 } 28 } 29 printf("%s\n",ok ? "Yes":"No"); 30 } 31 printf("\n"); 32 } 33 return 0; 34 }
---- suffer now and live the rest of your life as a champion ----