传送门:牛客
题目描述:
ZZT 创造了一个队列 Q。这个队列包含了 N 个元素,队列中的第 i 个元素用 Qi 表示。Q1 表示队头元素,QN 表示队尾元素。队列中的元素是 N 的一个全排列。
ZZT 需要在这个队列上执行 P 次操作,操作分两种:
FIRST X: 将元素 X 移到队头。
LAST X: 将元素 X 移到队尾。
在 P 次操作之后,ZZT 想知道队列中的元素的排列方式,由于他最近很忙,因此需要请你帮他解决这个问题。
输入:
4
4 2 1 3
3
FIRST 4
LAST 2
LAST 1
输出:
4 3 2 1
这个题目的操作有点像双向队列,但是肯定是不能用双向队列直接模拟的
主要思路:
方法一
我们可以直接记录每一个数字刚开始的位置,然后在每次进行操作1时,都在该序列的最前方将该数字放入,将其原位置置为0即可(所以我们还需每一次的位置),进行操作2时同理(所以需要开2倍空间才行,要为前后留出空间),在操作结束后判断是不是为0,不是输出即可
方法二
记录每一个数字刚开始的位置,并在每次进行操作1时将该数字保存的位置改为最前面(因为此时我们的位置不是在数组下标,因此我们并不需要开多倍空间),最后以保存的位置来排序原数组即可(这种排序的名字应该是"索引排序")
方法一的代码:
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <string.h>
#include <stack>
#include <deque>
using namespace std;
typedef long long ll;
#define inf 0x3f3f3f3f
#define root 1,n,1
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
inline ll read() {
ll x=0,w=1;char ch=getchar();
for(;ch>'9'||ch<'0';ch=getchar()) if(ch=='-') w=-1;
for(;ch>='0'&&ch<='9';ch=getchar()) x=x*10+ch-'0';
return x*w;
}
#define maxn 10000000
#define ll_maxn 0x3f3f3f3f3f3f3f3f
const double eps=1e-8;
int pos[maxn];int a;
int ppos[maxn];
int main() {
int n;int num;n=read();
for(int i=n+1e5+1;i<=2*n+1e5;i++) {
num=read();
pos[i]=num;
ppos[num]=i;
}
int l=n+1e5+1,r=2*n+1e5;
a=read();string opt;
for(int i=1;i<=a;i++) {
cin>>opt;num=read();
if(opt[0]=='F') {
pos[ppos[num]]=0;
pos[--l]=num;
ppos[num]=l;
}else {
pos[ppos[num]]=0;
pos[++r]=num;
ppos[num]=r;;
}
}
for(int i=l;i<=r;i++) {
if(pos[i]!=0) printf("%d ",pos[i]);
}
return 0;
}
方法二的代码:
const ll N = 4e4+50,M = 1e7+50;
ll n,q,x;
string op;
ll a[M],pos[M];
ll l,r;
bool cmp(ll x,ll y){
return pos[x]<pos[y];
}
int main(){
ios::sync_with_stdio(false);
cin>>n;
for(ll i=1;i<=n;i++){
cin>>a[i];
pos[a[i]]=i;
}
l=1;
r=n;
cin>>q;
while(q--){
cin>>op>>x;
if(op=="FIRST"){
pos[x]=--l;
}
else{
pos[x]=++r;
}
}
sort(a+1,a+n+1,cmp);
for(ll i=1;i<=n;i++){
cout<<a[i]<<" ";
}
return 0;
}