列车调度(Train)
Description
Figure 1 shows the structure of a station for train dispatching.
Figure 1
In this station, A is the entrance for each train and B is the exit. S is the transfer end. All single tracks are one-way, which means that the train can enter the station from A to S, and pull out from S to B. Note that the overtaking is not allowed. Because the compartments can reside in S, the order that they pull out at B may differ from that they enter at A. However, because of the limited capacity of S, no more that m compartments can reside at S simultaneously.
Assume that a train consist of n compartments labeled {1, 2, …, n}. A dispatcher wants to know whether these compartments can pull out at B in the order of {a1, a2, …, an} (a sequence). If can, in what order he should operate it?
Input
Two lines:
1st line: two integers n and m;
2nd line: n integers separated by spaces, which is a permutation of {1, 2, …, n}. This is a compartment sequence that is to be judged regarding the feasibility.
Output
If the sequence is feasible, output the sequence. “Push” means one compartment goes from A to S, while “pop” means one compartment goes from S to B. Each operation takes up one line.
If the sequence is infeasible, output a “no”.
Input
5 2
1 2 3 5 4
Output
push
pop
push
pop
push
pop
push
push
pop
pop
Input
5 5
3 1 2 4 5
Output
No
Restrictions
1 <= n <= 1,600,000
0 <= m <= 1,600,000
Time: 2 sec
Memory: 256 MB
题意:给你一个从1到n的序列,问你是否能通过入栈和出栈操作将1-n按顺序进入的序列变为目标序列。
思路:不能用STL,直接手写栈模拟操作。给目标序列一个指针,如果栈顶元素等于指针指向的目标序列的值,则出栈,否则就下一个数入栈。如果期间栈内元素超过m或者最后所有元素没有完全排列,就是no,否则按顺序输出答案
#include<cstdio>
#include<iostream>
using namespace std;
int a[1600005];
int stack[1600005];
int cnt=0;
void push(int x){
stack[cnt++]=x;
}
void pop(){
if(cnt==0)
return ;
stack[--cnt]=0;
}
int top(){
if(cnt==0)
return -1;
return stack[cnt-1];
}
int ans[3200005];
int main(){
int n,m;
scanf("%d%d",&n,&m);
int now=1;
int cct=0;
int ok=1;
for(int i=1;i<=n;++i){
scanf("%d",&a[i]);
// cout<<cnt<<endl;
}
for(int i=1;i<=n;i++){
if(i==a[now]){
ans[cct++]=1;
ans[cct++]=0;
now++;
}
else{
push(i);
ans[cct++]=1;
}
if(cnt>=m)
ok=0;
while(top()==a[now]){
pop();
ans[cct++]=0;
now++;
}
}
// cout<<now<<endl;
if(now<=n)
ok=0;
if(!ok){
printf("No\n");
return 0;
}
for(int i=0;i<cct;i++){
if(ans[i]==1)
printf("push\n");
else
printf("pop\n");
}
}