关于一个全排列数组,有k次操作,每次查找元素x移动到队首或者队尾的写法

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值