uva 1513(线段树)

题目链接:1513 - Movie collection

题意:有一堆电影,按1-n顺序排,有m次操作,每次询问第ai个电影之前有多少个电影,然后将其抽出放在堆顶。

分析:线段树应用。

因为每次查询后要将电影移至堆顶,所以我们可以将线段树的区间开到maxn+n,[1,maxn]先置0,在[maxn+1,maxn+n]建树将值置为1,线段树每一段区间的值代表该区间的和。

每次查询后要将该位置的值更新为0,由于要将电影移至堆顶,用一个指针cnt初始化为maxn,记录当前电影可以移到的位置,

由于位置是变化的,所以要用一个数组indice[]来记录每个电影当前所在的位置,每次移动位置只要indice[x]=cnt--即可。

查询的时候只要查询[1,indice[x]-1]区间和就行了。

AC代码如下:

 #include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
const int maxn=+;
int add[maxn<<];
int tree[maxn<<];
int indice[maxn];
int n,num;
void pushup(int rt)
{
tree[rt]=tree[rt<<]+tree[rt<<|];
}
void update(int p,int x,int l,int r,int rt)
{
if(l==r)
{
tree[rt]=x;
return ;
}
int m=(l+r)>>;
if(p<=m)
update(p,x,lson);
else
update(p,x,rson);
pushup(rt);
}
int query(int L,int R,int l,int r,int rt)
{
if(L<=l&&r<=R)
return tree[rt];
int m=(l+r)>>;
int ret=;
if(L<=m)
ret+=query(L,R,lson);
if(R>m)
ret+=query(L,R,rson);
return ret;
}
void build(int l,int r,int rt)
{
if(l==r)
{
num++;
if(num>maxn)
tree[rt]=;
return ;
}
int m=(l+r)>>;
build(lson);
build(rson);
pushup(rt);
}
int main()
{
int t,m,i,x,index;
scanf("%d",&t);
while(t--)
{
memset(tree,,sizeof(tree));
scanf("%d%d",&n,&m);
num=;
build(,maxn+n,);
for(int i=;i<=n;i++)
indice[i]=maxn+i;
int cnt=maxn;
for(i=;i<m;i++)
{
scanf("%d",&x);
printf("%d",query(,indice[x]-,,maxn+n,));
if(i!=m-) printf(" ");
update(indice[x],,,maxn+n,);
indice[x]=cnt--;
update(indice[x],,,maxn+n,);
}
printf("\n");
}
return ;
}
上一篇:vue使用axios 时 后台接收不到数据


下一篇:Python 函数的作用域