您的位置:首页 > 大数据 > 人工智能

uva 514 Rails

2017-08-08 15:26 375 查看
题目:Rails

题意:一串火车可以通过一条中转的铁轨从一条铁轨开到另一条铁轨,中转铁轨满足后进先出的原则。初始时火车的顺序为1~n,给定一串全部完成后的火车顺序,问是否可行。

思路:

(1)用stack保存中转铁轨中的顺序。

(2)顺序遍历给定序列,如果当前a[i]的值等于stack.top(),则当前的i满足条件,stack.pop()。如果不等,则再放一列火车到中转车站。

代码:

#include<cstdio>
#include<iostream>
#include<string>
#include<cstring>
#include<vector>
#include<set>
#include<map>
#include<algorithm>
#include<cmath>
#include<queue>
#include<stack>
#include<deque>
using namespace std;

int n;
int main() {

while(scanf("%d",&n)==1&&n!=0){
while(true){
int a[1005]={0};
scanf("%d",&a[1]);
if(a[1]==0) break;
for(int i=2;i<=n;i++){
scanf("%d",&a[i]);
}
stack<int> s;
int x=1,y=0;
bool flag=true;
while(x<=n){
if(!s.empty()&&a[x]==s.top()){
s.pop();
x++;
}else if(y<n){
y++;
s.push(y);
}else{
flag=false;
break;
}
}
if(flag==true) printf("Yes\n");
else printf("No\n");
}
printf("\n");
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  uva