//自己写的,用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;
}
else
stack[++top] = cur++;
}
if(!top && cur > n)
printf("Yes\n");
else
printf("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;
}
算法竞赛入门经典 6.1.2 (Y型)铁轨
最新推荐文章于 2021-03-02 20:37:35 发布