Movie collection
Mr. K. I. has a very big movie collection. He has organized his collection in a big stack.
Whenever he wants to watch one of the movies, he locates the movie in this stack and removes
it carefully, ensuring that the stack doesn’t fall over. After he finishes watching the movie, he
places it at the top of the stack.
Since the stack of movies is so big, he needs to keep track of the position of each movie.
It is sufficient to know for each movie how many movies are placed above it, since, with this
information, its position in the stack can be calculated. Each movie is identified by a number
printed on the movie box.
Your task is to implement a program which will keep track of the position of each movie.
In particular, each time Mr. K. I. removes a movie box from the stack, your program should
print the number of movies that were placed above it before it was removed.
Input
On the first line a positive integer: the number of test cases, at most 100. After that per test
case:
one line with two integers n and m (1 n;m 100 000): the number of movies in the
stack and the number of locate requests.
one line with m integers a1; : : : ; am (1 ai n) representing the identification numbers
of movies that Mr. K. I. wants to watch.
For simplicity, assume the initial stack contains the movies with identification numbers 1; 2; : : : ; n
in increasing order, where the movie box with label 1 is the top-most box.
Output
Per test case:
one line with m integers, where the i-th integer gives the number of movie boxes above
the box with label ai, immediately before this box is removed from the stack.
Note that after each locate request ai, the movie box with label ai is placed at the top of the
stack.
Input
2
3 3
3 1 1
5 34 4 5
Output
3 0 4
题目意思不说了
一看到这题就想到了树状数组
可是有个不好搞,那就是每次电影移到前面的时候该怎么弄
如果朴素的算法话就要把它本身在序列中的位置置为1,然后它前面的数全加上1,这样肯定会超时
所以我们在该序列前面模拟一个栈来做,具体算法看代码:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <queue>
#include <map>
using namespace std;
int c[300005];
int a[100005];
int ans[100005];
int n,problem;
int lowbit(int x)
{
return x&(-x);
}
int treesum(int m)
{
int sum=0;
while(m>0)
{
sum+=c[m];
m-=lowbit(m);
}
return sum;
}
int insert(int i,int num)
{
while(i<=n+100000)
{
c[i]+=num;
i+=lowbit(i);
}
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&problem);
memset(a,0,sizeof(a));
memset(c,0,sizeof(c));
for(int i=1;i<=n;i++)
{
a[i]=i+100000;
}
for(int i=2;i<=n;i++)
{
insert(i+100000,1);
}
for(int i=1;i<=problem;i++)
{
int num;
scanf("%d",&num);
ans[i]=treesum(a[num]);
insert(a[num],-1);
insert(100000-i+2,1);
a[num]=100000-i+1;
}
for(int i=1;i<=problem;i++)
if(i!=problem)
printf("%d ",ans[i]);
else
printf("%d\n",ans[i]);
}
}