#include<bits/stdc++.h>
using namespace std;
#define ll int
#define IOS ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
#define endl '\n'
const int maxn = 3e5 + 1;
const int N = 1e5;
int a[maxn]={};//存数字
int b[maxn]={};//存数字的位置
void csh(int n)//初始化
{
for( int i = 1e5 ; i < 1e5 + n ; i ++ ) //总共有n个数字
{
b[a[i]] = i;
}
}
int main()
{
IOS;
int n , k;
string s;
cin >> n ;
for( int i = 1e5 ; i < 1e5 + n ; i ++ )// f : 1e5 l: 1e5 + n -1
{
cin >> a[i];
}
csh(n);
cin >> k;
int t,w;//头尾指针
int x;
t = 1e5 , w = 1e5 + n - 1;
for( int i = 1 ; i <= k ; i ++ )
{
cin >> s;
cin >> x;
if( s[0] == 'F' )
{
t--;//新的位置
// 原来的位置 : b[x]
a[t] = x;
a[b[x]] = 0;
b[a[t]] = t;
}
else
{
w ++;//新位置
//原本位置 b[x]
a[w] = x;
a[b[x]] = 0;
b[a[w]] = w;
}
}
for( int i = 0 ; i < maxn ; i ++ )
{
if( a[i] != 0 )
cout << a[i] << ' ';
}
}
这里想到,一个个查找(暴力的做法),T了8次。。。。。
这里想到用空间换时间,用数组存它的位置,每次操作,修改为O1,删除也是O1,这样就过啦。
#include<stdio.h>
#include<string.h>
using namespace std;
const int maxn=3e5+7;
int a[maxn],b[maxn];
char str[5];
void table(int a[],int n)
{
for(int i=1e5;i<=n+100000;i++)
{
b[a[i]]=i;
}
}
int main()
{
int n,m,p,t,i,w;
while(~scanf("%d",&n))
{
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
for( i=1e5;i<1e5+n;i++)
{
scanf("%d",&a[i]);
}
table(a,n);
t=n+1e5;
w=100000;
scanf("%d",&m);
while(m--)
{
scanf("%s%d",str,&p);
if(strcmp(str,"FIRST")==0)
{
a[--w]=p;
a[b[p]]=0;
b[p]=w;
}
else if(strcmp(str,"LAST")==0)
{
a[++t]=p;
a[b[p]]=0;
b[p]=t;
}
}
for(i=0;i<=maxn;i++)
{
if(a[i]!=0)
printf("%d ",a[i]);
}
printf("\n");
}
return 0;
}