NOJ [1317] Exercise of Sort

链接地址:http://ac.nbutoj.com/Problem/view.xhtml?id=1317

线段树
如果是按照顺序来寻找位置的话,会发现遗漏了许多的信息。
所以,我们应该反过来寻找位置!

出题代码:

#include <set>
#include <map>
#include <list>
#include <stack>
#include <queue>
#include <cmath>
#include <cstdio>
#include <vector>
#include <iomanip>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
using namespace std;

#define maxn 201000
#define lson rt << 1
#define rson rt << 1|1
int sum[maxn * 4];
int val[maxn];
int rank[maxn];
int pos[maxn];
int a[maxn];
int n;

void pushup(int rt)
{
sum[rt] = sum[lson] + sum[rson];
}

void build(int rt, int l, int r)
{
if (l == r)
{
sum[rt] = 1;
return;
}
int m = (l + r) >> 1;
build(lson, l, m);
build(rson, m + 1, r);
pushup(rt);
}

void insert(int rt, int l, int r, int pos, int val)
{
if (l == r)
{
sum[rt] += val;
return;
}
int m = (l + r) >> 1;
if (pos <= m) insert(lson, l, m, pos, val);
else insert(rson, m + 1, r, pos, val);
pushup(rt);
}

int query(int rt, int l, int r, int val)
{
if (l == r)
{
if (sum[rt] == val) return l;
else return l - 1;
}
int m = (l + r) >> 1;
if (sum[lson] <= val) return query(rson, m + 1, r, val - sum[lson]);
else return query(lson, l, m, val);
}

int main()
{
//freopen("data.in", "r", stdin);
//freopen("data.out", "w", stdout);
while (~scanf("%d", &n))
{
memset(val, 0, sizeof(val));
memset(rank, 0, sizeof(rank));
for (int i = 1; i <= n; i++) scanf("%d%d", &a[i], &val[i]);
build(1, 1, n);
for (int i = n; i >= 1; i--)
{
int t;
t = query(1, 1, n, a[i]);
pos[i] = t + 1;
insert(1, 1, n, pos[i], -1);
}
for (int i = 1; i <= n; i++) rank[pos[i]] = i;
for (int i = 1; i <= n; i++)
{
if (i - 1) printf(" ");
printf("%d", val[rank[i]]);
}
printf("\n");
}

return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值