a704困難預留頂部位置的Fenwick動態排名
CPE:Movie collection (UVa 1513)
快速查詢電影上方盒數並移到新頂端。
解題思路
事先在位置1…m預留未來的頂端,原電影i放在m+i。較小位置代表較上方,Fenwick tree在每個有盒子的位置存1。查詢電影x上方數量就是prefix(pos[x]−1),無需在陣列中搬移所有盒子。
每次查完,把舊位置加−1,將電影移到目前top(初值m),新位置加1,再把top減1。預留m個位置恰夠m次操作,其他盒子的相對位置不變;每個電影始終只有一個活躍位置。每組重新建立位置表與樹,輸出m個答案於同一行,單一空白分隔且無尾空白。
Step-by-step animation
示意:n=3,依序拿3、1、1
步驟 1 / 3
拿3
初始1,2,3,3上方2盒;移後3,1,2。
3
1
2
- 本次答案
- 2
- pos3
- 3
#include <iostream>
#include <vector>
using namespace std;
struct Fenwick {
vector<int> bit;
Fenwick(int n) : bit(n + 1) {}
void add(int i, int d) {
for (; i < (int)bit.size(); i += i & -i)
bit[i] += d;
}
int sum(int i) {
int result = 0;
for (; i; i -= i & -i)
result += bit[i];
return result;
}
};
int main() {
int tests;
cin >> tests;
while (tests--) {
int n, m;
cin >> n >> m;
Fenwick tree(n + m);
vector<int> pos(n + 1);
for (int i = 1; i <= n; i++) {
pos[i] = m + i;
tree.add(pos[i], 1);
}
int top = m;
for (int i = 0; i < m; i++) {
int x;
cin >> x;
cout << (i ? " " : "") << tree.sum(pos[x] - 1);
tree.add(pos[x], -1);
pos[x] = top--;
tree.add(pos[x], 1);
}
cout << '\n';
}
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。