算法竞赛入门经典 6.1.2 (Y型)铁轨

来源:互联网 发布:中国万方数据库官网 编辑:程序博客网 时间:2024/04/30 03:47
//自己写的,用array-based stack来解题代码(逻辑不够简洁清晰)#include <stdio.h>const int MAXN = 100;int stack[MAXN];int target[MAXN];int main(){int n = 0;while(scanf("%d", &n) != EOF){for(int i = 0; i < n; ++i)scanf("%d", &target[i]);int top = 0;int cur = 1;int k = 0;while(cur == target[k] || (top && stack[top] == target[k]) ||  cur <= n){if(cur == target[k]){++cur;++k;}else if(top && stack[top] == target[k]){--top;++k;}elsestack[++top] = cur++;}if(!top && cur > n)printf("Yes\n");elseprintf("No\n");}return 0;}//书本上,用array-based stack来解题(简洁)#include <stdio.h>const int MAXN = 100;int n = 0, stack[MAXN];int main(){while(scanf("%d", &n) != EOF){int top = 0, target[MAXN];for(int i = 0; i < n; ++i)scanf("%d", &target[i]);int cur = 1;//现在几号车进站int k = 0;//读到第几个应该出站的车的车号bool ok = 1;while(k < n){if(cur == target[k]){++cur;++k;}else if(top && stack[top] == target[k]){--top;++k;}else if(cur <= n)stack[++top] = cur++;else{ok = 0;break;}}printf("%s\n", ok ? "Yes" : "No");}return 0;}//使用STL的stack解题#include <cstdio>#include <stack>using namespace std;const int MAXN = 100;int n = 0, target[MAXN];int main(){while(scanf("%d", &n) != EOF){for(int i = 0; i < n; ++i)scanf("%d", &target[i]);stack<int> s;int cur = 1;int k = 0;bool ok = true;while(k < n){if(cur == target[k]){++k;++cur;}else if(!s.empty() && s.top() == target[k]){++k;s.pop();}else if(cur <= n)s.push(cur++);else{ok = false;break;}}printf("%s\n", ok ? "Yes" : "No");}return 0;}

0 0