题意:有一堆电影,按1-n顺序排,有m次操作,每次询问第ai个电影之前有多少个电影,然后将其抽出放在堆顶。
思路:pos数组保存位置(倒序排列,便于更新)
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
using namespace std;
const int maxn=100010;
const int MAX=200010;
int n,m;
int tree[maxn*2],pos[maxn];
void update(int x,int val)
{
while(x<=MAX)
{
tree[x]+=val;
x+=x&(-x);
}
}
int getsum(int x)
{
int sum=0;
while(x>0)
{
sum+=tree[x];
x-=x&(-x);
}
return sum;
}
int main()
{
int t,x;
cin>>t;
while(t--)
{
cin>>n>>m;
memset(tree,0,sizeof(tree));
memset(pos,0,sizeof(pos));
for(int i=1;i<=n;i++)
{
pos[i]=n-i+1;
update(i,1);
}
int cur=n;
bool first=true;
for(int i=0;i<m;i++)
{
cin>>x;
if(first)first=false;
else cout<<" ";
cout<<n-getsum(pos[x]);//getsum表示x当前片子的下面有多少个
update(pos[x],-1);//上面的片子的下面的片子都减1
pos[x]=++cur;
update(pos[x],1);
}
cout<<endl;
}
return 0;
}