HDU - 5592 ZYBs Premutation(線段樹,逆序對)

題目鏈接:點擊查看

題目大意:給出 n 個數,分別表示數列 p 前綴 [ 1 , i ] 的逆序對個數,現在要求還原數列 p

題目分析:設 a[ i ] 爲前綴 [ 1 , i ] 的逆序對個數,則 a[ i ] - a[ i - 1 ] 代表的就是 p[ i ] 前面有 a[ i ] - a[ i - 1 ] 數比他自己大,換句話說,p[ i ] 就是目前的第 a[ i ] - a[ i - 1 ] + 1 大的數,用線段樹倒着維護就好了

代碼:
 

#include<iostream>
#include<cstdio>
#include<string>
#include<ctime>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<stack>
#include<climits>
#include<queue>
#include<map>
#include<set>
#include<sstream>
#include<cassert>
using namespace std;

typedef long long LL;

typedef unsigned long long ull;

const int inf=0x3f3f3f3f;

const int N=1e5+100;

int a[N],ans[N];

struct Node
{
	int l,r,sum;
}tree[N<<2];

void build(int k,int l,int r)
{
	tree[k].l=l;
	tree[k].r=r;
	tree[k].sum=r-l+1;
	if(l==r)
		return;
	int mid=l+r>>1;
	build(k<<1,l,mid);
	build(k<<1|1,mid+1,r);
}

int query(int k,int pos)
{
	tree[k].sum--;
	if(tree[k].l==tree[k].r)
		return tree[k].l;
	int mid=tree[k].l+tree[k].r>>1;
	if(tree[k<<1|1].sum>=pos)
		return query(k<<1|1,pos);
	else
		return query(k<<1,pos-tree[k<<1|1].sum);
}

int main()
{
#ifndef ONLINE_JUDGE
//  freopen("data.in.txt","r",stdin);
//  freopen("data.out.txt","w",stdout);
#endif
//  ios::sync_with_stdio(false);
	int w;
	cin>>w;
	while(w--)
	{
		int n;
		scanf("%d",&n);
		for(int i=1;i<=n;i++)
			scanf("%d",a+i);
		build(1,1,n);
		for(int i=n;i>=1;i--)
			ans[i]=query(1,a[i]-a[i-1]+1);
		printf("%d",ans[1]);
		for(int i=2;i<=n;i++)
			printf(" %d",ans[i]);
		puts("");
	}


















    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章