铁轨(UVa 514)
利用栈实现
C++11 代码如下:
1 #include<iostream> 2 #include<stack> 3 using namespace std; 4 #define maxn 1001 5 int n, num[maxn]; 6 7 int main() { 8 while ((cin >> n)&&n!=0) { 9 while (n) { 10 for (int i = 1; i <= n; i++) { 11 cin >> num[i]; 12 if (num[1] == 0) { 13 n = 0; break; 14 } 15 } 16 if (n == 0)break; 17 stack<int>s; 18 int A = 1, B = 1; 19 bool flag = true; 20 while (B <= n) { 21 if (A == num[B]) { A++; B++; } 22 else if ((!s.empty()) && s.top() == num[B]) { s.pop(); B++; } 23 else if (A <= n) s.push(A++); 24 else { flag = false; break; } 25 } 26 cout << (flag ? "Yes" : "No") << endl; 27 } 28 cout << endl; 29 } 30 return 0; 31 }