首页 > 代码库 > UVA 1513 - Movie collection(树状数组)

UVA 1513 - Movie collection(树状数组)

UVA 1513 - Movie collection

题目链接

题意:有一些光盘,一开始是n-1叠上去的(1最顶),现在每次抽出一张,要问这一张上面有多少张,然后把抽出来这张放到最顶,输出每次询问

思路:树状数组,数组维护每个位置下面有多少张光碟,这样每次拿出一张,就在相应位置-1就可以了,然后在最顶位置上多一个位置+1

代码:

#include <cstdio>
#include <cstring>

#define lowbit(x) (x&(-x))
const int N = 200005;
int t, n, m, arr[N], bit[N];

void add(int x, int v) {
    while (x < N) {
	bit[x] += v;
	x += lowbit(x);
    }
}

int query(int x) {
    int ans = 0;
    while (x) {
	ans += bit[x];
	x -= lowbit(x);
    }
    return ans;
}

int main() {
    scanf("%d", &t);
    while (t--) {
	memset(bit, 0, sizeof(bit));
	scanf("%d%d", &n, &m);
	for (int i = 1; i <= n; i++) {
	    arr[i] = n + 1 - i;
	    add(i, 1);
	}
	int v;
	for (int i = 1; i <= m; i++) {
	    scanf("%d", &v);
	    int under = query(arr[v]);
	    printf("%d%c", n - under, i == m ? '\n' : ' ');
	    add(arr[v], -1);
	    arr[v] = n + i;
	    add(n + i, 1);
	}
    }
    return 0;
}