您的位置:首页 > 其它

UVALive 5902 Movie collection(树状数组)

2015-09-13 01:38 330 查看
UVALive
5902:点击打开链接

题意:有n本书叠放,编号从上到下是1到n,每次操作是先输出编号是i这本书的上面有几本书,然后把这本书抽出来放到顶上。

题解:树状数组。先在前面空m个位置出来,每次取一本书输出前面有多少个1,在吧这本书放到最后一个空位子,更新这本书的位置。

再更新值。

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <string>
#include <map>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <set>
#include <queue>

using namespace std;
const int maxn=3e5+5;
int pos[maxn];
int bit[maxn];
int n,m;
void init()
{
    memset(bit,0,sizeof(bit));
    for(int i=1;i<=n;i++)
    {
        pos[i]=m+i;
    }
}
void update(int i,int d)
{
    while(i<=n+m)
    {
        bit[i]+=d;
        i+=i&-i;
    }
}
int sum(int i)
{
    int res=0;
    while(i>0)
    {
        res+=bit[i];
        i-=i&-i;
    }
    return res;
}
int main()
{
  #ifdef ONLINE_JUDGE
  #else
  freopen("in.txt","r",stdin);
  #endif
  int t;
  scanf("%d",&t);
  while(t--)
  {
      scanf("%d%d",&n,&m);
      init();
      for(int i=1;i<=n;i++)
      {
          update(i+m,1);
      }
      int cao=m;
      for(int i=0;i<m;i++)
      {
          int x;
          scanf("%d",&x);
          int id=pos[x];
          if(i!=0)
            putchar(' ');
          printf("%d",sum(id)-1);
          update(id,-1);
          pos[x]=cao--;
          update(pos[x],1);
      }
      putchar(10);
  }
  return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: