从进阶指南看到这道题,其实跟奶牛那道题是一样的。网上好多人都用的是线段树,其实树状数组也是可以的。不过也侧面说明了线段树的可扩展性是强于树状数组的。
题意:
插队的问题,每个案例给出n,代表有n个插队的,每个给出p,v,意思是代号为v的人插在了第p个人的后面,问最后的队伍的排列?
题目中一开始整个队列是空的,也就是说如果输入i,j:代表代号为j的人插在了第i个人的后面,也就是说在他之前一定有了i个人,而他的位置是i+1。
Sample Input
4
0 77
1 51
1 33
2 69
4
0 20523
1 19243
1 3890
0 31492
Sample Output
77 33 69 51
31492 20523 3890 19243
思路:由后向前推到,每个遇到的都是确定位置的,最后的人选定的位置不会改变,因为是倒叙输入,在第i个人后插队,相当于他的前面一定要留下i个空格。
#include <cstdio>
#include <iostream>
#include <iomanip>
#include <string>
#include <cstdlib>
#include <cstring>
#include <queue>
#include <set>
#include <vector>
#include <map>
#include <algorithm>
#include <math.h>
#include <stack>
#define INF 0x3f3f3f3f
#define IMAX 2147483646
#define LINF 0x3f3f3f3f3f3f3f3f
#define ll long long
#define ull unsigned long long
#define uint unsigned int
using namespace std;
int maxn = 2000001;
int bits[2000011];
void add(int x, int v) {
for (int i = x; i <= maxn; i += (i&-i))
bits[i] += v;
}
int sum(int x) {//前x个数的和等于res,已知x求res
int res = 0;
for (int i = x; i; i -= (i&-i))
res += bits[i];
return res;
}
int find(int res) {//前x个数的和等于res,已知res求x
int x = 0;
for (int i = 19; i >= 0; --i) {
if (x + (1 << i) > maxn || bits[x + (1 << i)] > res - 1)
continue;
x += (1 << i);
res -= bits[x];
}
return x + 1;//找不到的时候会返回maxn
}
int n,k;
struct Node {
int ins, val,pos;
}a[2000001];
bool cmp(const Node &p, const Node &q) {
return p.pos < q.pos;
}
int main() {
while (scanf("%d", &n) != EOF) {
for (int i = 0; i < n; i++)
scanf("%d%d", &a[i].ins, &a[i].val), a[i].ins++;
//为何不需要memset?因为每个1最后都会被减掉
for (int i = 1; i <= n; i++)
add(i, 1);//a[i]值为1,表示这个位置是空位
for (int i = n - 1; i >= 0; i--) {
a[i].pos = find(a[i].ins);
add(a[i].pos, -1);
}
sort(a, a + n,cmp);
for (int i = 0; i < n; i++)
printf("%d ", a[i].val);
printf("\n");
}
return 0;
}