poj 2182(线段树)

Lost Cows

POJ - 2182

与这题一样Buy Tickets - POJ 2828 - Virtual Judge (csgrandeur.cn)

题意:有1~N N个数字,这N个数字的顺序是打乱的,从第二个数字开始给你它的前面有多少个数字比他小

思路:
输入的数字都要加一,然后我们从后往前遍历,在线段树中如果左子树的sum‘>sum,则进入左子树,否则,将sum-=sum',然后进入右子树,当到达叶子节点时更新答案,并将叶子结点的sum置为0。

为什么能这样写,可以自己模拟一下。

代码:

#define _CRT_SECURE_NO_WARNINGS 1
#include<algorithm>
#include<fstream>
#include<iostream>
#include<cstdio>
#include<deque>
#include<string>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<vector>
#include<stack>
#include<queue>
#include<map>
#include<set>
#include<bitset>
//#include<unordered_map>
using namespace std;
#define INF 0x3f3f3f3f
#define MAXN 310000
#define N 210100
#define endl '\n'
#define exp 1e-8
#define lc p << 1
#define rc p << 1|1
#define lowbit(x) ((x)&-(x))
const double pi = acos(-1.0);
typedef long long LL;
typedef unsigned long long ULL;
inline LL read() {
	ULL x = 0, f = 1;
	char ch = getchar();
	while (ch < '0' || ch>'9') {
		if (ch == '-')
			f = -1;
		ch = getchar();
	}
	while (ch >= '0' && ch <= '9') {
		x = (x << 1) + (x << 3) + (ch ^ 48);
		ch = getchar();
	}
	return x * f;
}
struct tree
{
	int l, r,sum;
}tr[4*N];
map<int, bool>v;
int n, arr[N],ans[N];  //ans存答案
void pushup(int p)
{
	tr[p].sum = tr[lc].sum + tr[rc].sum;
}
void build(int p, int l, int r)
{
	tr[p].l = l, tr[p].r = r;
	if (tr[p].l == tr[p].r)
	{
		tr[p].sum = 1;
		return;
	}
	int m = l + r >> 1;
	build(lc, l, m);
	build(rc, m + 1, r);
	pushup(p);
}
void query(int p, int pos,int sum)
{
	if (tr[p].l == tr[p].r)
	{
		ans[pos] = tr[p].l;
		v[tr[p].l] = 1;
		tr[p].sum = 0;
		return;
	}
	if (tr[lc].sum >= sum)    //左子树大于sum走左边
		query(lc, pos, sum);
	else query(rc, pos, sum-tr[lc].sum); //否则sum减左子树的值,进入右子树
	pushup(p);
}
int main()
{
	cin >> n;
	build(1, 1, n);
	for (int i = 2; i <= n; i++)
	{
		cin >> arr[i];
	}
	for (int i = n; i >= 2; i--)   //从后往前遍历
	{
		query(1, i, arr[i] + 1);
	}
	for (int i = 1; i <= n; i++)  //是找第一个是谁
	{
		if (!v[i])
		{
			ans[1] = i;
			break;
		}
	}
	for (int i = 1; i <= n; i++)
	{
		printf("%d\n", ans[i]);
	}
	return 0;
}
posted @ 2023-04-14 20:35  魏老6  阅读(14)  评论(0编辑  收藏  举报