poj 2828

線段樹點更新。

最直觀的想法就是用鏈表模擬,發現數據量太大,不可能。然後看能否直接推出每個人在最終序列的位置。很顯然,最後一個插入的人插入的位置p[n]+1就是他在最終序列中的位置,先確定了最後一個人的位置。然後看倒數第二個,先不考慮最後一個人的插入,在他前面所排的人的個數有且僅爲他插入的位置,那在最終的序列中不包括最後一個人,他前面的人數肯定有且僅爲 pos[i]。也就是在長度爲n的序列中,不包括最後一個人的位置中的第pos[i]+1個位置。之前插入的人的道理也是如此,i在最終長度爲n序列中,除去他後面插入的人已經確定的位置,肯定是在poi[i]+1的位置,在這個位置,排在他之前的人的除去後面插入的人有且僅有pos[i]個人。問題就最終轉化爲了從後向前確定每個人早最終序列中的位置,找到所在位置爲除去已經確定的位置的空位中的第p[i]+1個位置,用二分的思想確定此位置,再次用線段樹優化。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
#include <cmath>
#include <stack>
#include <vector>
#define LL long long
using namespace std;
const int inf=0x3f3f3f3f;
const int maxn=200000+10;
int re;
int pos[maxn],id[maxn],ans[maxn];
int seg[maxn*3];
int n;
void build(int no, int left,int right )
{
	if(left==right)
	{
		seg[no]=1;
		return;
	}
	int mid=left+(right-left)/2;
	seg[no]=right-left+1;
	build(no*2+1,left,mid);
	build(no*2+2,mid+1,right);
}
void update(int no,int left,int right,int needed)
{
	if(left==right) 
	{
		re=left;
		seg[no]--;
		return;
	}
	int mid=left+(right-left)/2;
	if(seg[no*2+1]>=needed) update(no*2+1,left,mid,needed);
	else update(no*2+2,mid+1,right,needed-seg[no*2+1]);
	seg[no]--;
}
int main()
{

	while(~scanf("%d",&n))
	{
		int i;
		build(0,1,n);
		for(i=1;i<=n;i++) scanf("%d%d",&pos[i],&id[i]);
		for(i=n;i>=1;i--)
		{
			update(0,1,n,pos[i]+1);
			ans[re]=id[i];
		}
		printf("%d",ans[1]);
		for(i=2;i<=n;i++) printf(" %d",ans[i]);
		printf("\n");
	}
	return 0;
}


發佈了187 篇原創文章 · 獲贊 3 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章