Inversion Sequence 线段树通过逆序数还原原序列

For sequence i1, i2, i3, … , iN, we set aj to be the number of members in the sequence which are prior to j and greater to j at the same time. The sequence a1, a2, a3, … , aN is referred to as the inversion sequence of the original sequence (i1, i2, i3, … , iN). For example, sequence 1, 2, 0, 1, 0 is the inversion sequence of sequence 3, 1, 5, 2, 4. Your task is to find a full permutation of 1~N that is an original sequence of a given inversion sequence. If there is no permutation meets the conditions please output “No solution”.

 

Input

There are several test cases.
Each test case contains 1 positive integers N in the first line.(1 ≤ N ≤ 10000).
Followed in the next line is an inversion sequence a1, a2, a3, … , aN (0 ≤ aj < N)
The input will finish with the end of file.

 

Output

For each case, please output the permutation of 1~N in one line. If there is no permutation meets the conditions, please output “No solution”.

 

Sample Input

5
1 2 0 1 0
3
0 0 0
2
1 1

Sample Output

3 1 5 2 4
1 2 3
No solution

给你一个逆序序列要求求出他原来的序列 例如1 2 0 1 0  1表示1前面有一个数更大,

2表2前有2个数更大,0表示3前有0个数更大。

插入第i个数字,那么就去查找有没有a[i]+1个空位,如果有那么就插入到那个位置,

否则就无解,使用线段树维护空位的个数,即区间和查询

线段树中个节点表示还有多少个空位

 

 

 

#include<iostream>
#include<string>
#include<cstdio>
#include<cstring>
using namespace std;
#define N 20000
struct point
{
	int lc,rc;
	int sum;
}tree[N<<2];
int a[N],ans[N];
void Pushup(int rt)
{
	tree[rt].sum=tree[rt<<1].sum+tree[rt<<1|1].sum;
}
void build(int L,int R,int rt)
{
	tree[rt].lc=L;
	tree[rt].rc=R;
	if(L==R)
	{
		tree[rt].sum=1;
		return ;
	}
	int mid=(L+R)>>1;
	build(L,mid,rt<<1);
	build(mid+1,R,rt<<1|1);
	Pushup(rt);
}
int query(int rt,int x)
{
	if(tree[rt].lc==tree[rt].rc)
	{
		tree[rt].sum=0;
		return tree[rt].lc;
	}
	int ret;
	if(tree[rt<<1].sum>=x)
	{
		ret= query(rt<<1,x);
	}
	else
	{
		ret=query((rt<<1|1),(x-tree[rt<<1].sum));
	}
	Pushup(rt);
	return ret;
}
int main()
{

	int n;
	while(~scanf("%d",&n))
	{
		int ok=1;
		for(int i=1;i<=n;i++)
			scanf("%d",&a[i]);
		build(1,n,1);
		for(int i=1;i<=n;i++)
		{
			if(tree[1].sum<a[i]+1)
			{
				ok=0;
				break;
			}
			else
			{
				ans[query(1,a[i]+1)]=i;
			}
		}
		if(!ok)
		{
			puts("No solution");
		}
		else
		{
			for(int i=1;i<n;i++)
				printf("%d ",ans[i]);
			printf("%d\n",ans[n]);
		}
	}
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值