树状数组uva1513(好)

题意:有一堆电影,按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;
}


  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值