標籤:http io ar for sp 代碼 on c amp
題目:UVA514 - Rails(棧)
題目大意:某城市有一個火車站,鐵軌成Y字形,有n節車廂從A方向駛入車站,按進站順序編號1-n,現在給你一個序列代表進入B的順序,你可以藉助一個C中轉站,問能否可以按這樣的序列駛入B。
解題思路:棧類比,中轉站就代表棧,將車廂入棧後,只能從棧頂一個一個出去。注意輸出每個cas都有一個空行。
代碼:
#include <cstdio>#include <cstring>#include <stack>using namespace std;const int N = 1005;int tail[N], n;stack<int> s;bool ok () {while (!s.empty()) {s.pop();}int k = 1;int p = 0;while (k <= n && p < n) {if (k == tail[p]) {p++;k++;} else if (!s.empty() && s.top() == tail[p]) {s.pop();p++;} else {s.push (k);k++;}}while (!s.empty() && p < n) {if (s.top() == tail[p]) {s.pop();p++;} elsebreak;}if (p == n)return true;return false;}int main () {bool flag;while (scanf ("%d", &n) && n) {flag = 1;while (1) {for (int i = 0; i < n; i++) {scanf ("%d", &tail[i]);if (!tail[i]) {flag = 0;break;}}if (!flag)break;printf ("%s\n", ok() ? "Yes": "No");}printf ("\n");}return 0;}
UVA514 - Rails(棧)