Uva 514 Rails
阿新 • • 發佈:2020-07-19
根據題可以得知C是一個棧滿足先進後出的原則。
所以為了判斷能得到的序列,通過模擬這個過程。
1 #include <iostream> 2 #include <stack> 3 4 using namespace std; 5 const int MAXN = 1000 + 10; 6 int n, target[MAXN]; 7 8 int main() { 9 10 while (cin >> n, n) { 11 12 while (true) { 13 stack<int> s; 14 intA = 1, B = 1;//A表示的是1-n中的數,B是target的下標 15 for (int i = 1; i <= n; ++i)//輸入目標 16 { 17 cin >> target[i]; 18 if (target[1] == 0) 19 break; 20 } 21 if (target[1] == 0) 22 { 23 cout <<endl; 24 break; 25 } 26 //核心程式碼 27 bool ok = true; 28 while(B <= n) { 29 if (A == target[B]) { A++, B++; }//如果A==target[B]則直接入棧出棧到B. 30 else if (!s.empty() && s.top() == target[B]) { s.pop(), B++; }//棧頂元素就等於target[B]出棧就行 31 else if (A <= n) s.push(A++);//將剩餘的數入棧 32 else { 33 ok = false; 34 break; 35 } 36 } 37printf("%s\n", ok ? "Yes" : "No"); 38 } 39 } 40 return 0; 41 }