题意:
一个人喜欢收集电影,电影的碟子从小到大放好,现在给定他每次要看的电影编号,输出有多少个碟子在该电影的上端,每次看完一个将会放回顶端。
PS:第一次做树状数组的题,查了好多树状数组的详解,但还是感觉只是很浅显的了解了一下,海带 !!努力啊。
思路:用数组记录每个编号碟子所在的位置,用树状数组维护。是个树状数组的简单应用,但是费了好大劲才看懂,中间还请教了同学,感觉自己要笨死了![大哭](http://static.blog.csdn.net/xheditor/xheditor_emot/default/wail.gif)
下面代码还是借鉴别人的,不过注释是我自己写的希望能帮助读者更好的理解一下吧。
AC:
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define lowbit(x) ((x)&(-x))
const int maxn = 1e5+5;
int N, M, fenw[maxn*2],;
int pos[maxn];//记录每个编号碟子所在位置
int lowbit(int x)
{
return (x&(-x));
}
void add (int x, int v)//作用:每改变一个数后循环改变与他相关的数(即:把看完的书放置顶端后,重新整理相关数据)
{
while (x < 2*maxn) {
fenw[x] += v;
x += lowbit(x);
}
}
int sum (int x)//作用:求出所要求碟子下面的碟子数
{
int ret = 0;
while (x) {
ret += fenw[x];
x -= lowbit(x);
}
return ret;
}
int main () {
int cas;
scanf("%d", &cas);
while (cas--) {
scanf("%d%d", &N, &M);
memset(fenw, 0, sizeof(fenw));
int n = N, x;
for (int i = 1; i <= N; i++) {
pos[i] = N - i + 1;
add(pos[i], 1);//预处理每个位置的下面碟子数
}
for (int i = 1; i <= M; i++) {
scanf("%d", &x);
printf("%d%c", n - sum(pos[x]), i == M ? '\n' : ' ');
add(pos[x], -1);//取走该碟子后加和包括该位置的数都减1
pos[x] = ++N;//看完放上去的盘子的新位置
add(pos[x], 1);放上后加和包括该位置的数都减1
}
}
return 0;
}