【题解】P10688 Buy Tickets
BpbjsGreen · · 题解
树状数组上二分。
经过人工模拟,发现正着做对序列的操作是很繁琐的。
不妨从最后一个人开始往前考虑。
以样例 #1 为例。
最后一个人
| 空位 | 空位 | 空位 |
|---|
倒数第二个人
| 空位 | 空位 |
|---|
倒数第三个人
| 空位 |
|---|
再对于倒数第四个人
考虑用树状数组维护:每个位置初始化成
// ID: @BpbjsGreen
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
int n, c[N], ans[N], t[N], r[N];
int lowbit(int x) { return x & (-x); }
void add(int x, int d)
{
for (; x <= 2e5; x += lowbit(x))
c[x] += d;
}
int query(int x) // 树状数组上二分
{
int pos = 0, sum = 0;
for (int j = 18; j >= 0; j--)
{
if (pos + (1 << j) <= n && sum + c[pos + (1 << j)] <= x)
{
pos += (1 << j);
sum += c[pos];
}
}
return pos;
}
int main()
{
// freopen("I.in", "r", stdin);
// freopen("O.out", "w", stdout);
while (scanf("%d", &n) != EOF) // 读入
{
for (int i = 1; i <= n; i++)
add(i, 1);
for (int i = 1; i <= n; i++)
scanf("%d%d", &t[i], &r[i]);
for (int i = n; i >= 1; i--)
{
int pos = query(t[i]);
pos += 1; // + 1 找到当前人的位置
ans[pos] = r[i]; // 记录答案
add(pos, -1); // 空位 - 1
}
for (int i = 1; i <= n; i++)
printf("%d ", ans[i]);
printf("\n");
}
}