poj 2828

从进阶指南看到这道题,其实跟奶牛那道题是一样的。网上好多人都用的是线段树,其实树状数组也是可以的。不过也侧面说明了线段树的可扩展性是强于树状数组的。

题意:
插队的问题,每个案例给出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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值