UVA514 - Rails(棧)

來源:互聯網
上載者:User

標籤: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(棧)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.