ZYB's Premutation
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)Total Submission(s): 1023 Accepted Submission(s): 523
Problem Description
ZYB
has a premutation
P
,but he only remeber the reverse log of each prefix of the premutation,now he ask you to
restore the premutation.
Pair (i,j)(i<j) is considered as a reverse log if Ai>Aj is matched.
restore the premutation.
Pair (i,j)(i<j) is considered as a reverse log if Ai>Aj is matched.
Input
In the first line there is the number of testcases T.
For each teatcase:
In the first line there is one number N .
In the next line there are N numbers Ai ,describe the number of the reverse logs of each prefix,
The input is correct.
1≤T≤5 , 1≤N≤50000
For each teatcase:
In the first line there is one number N .
In the next line there are N numbers Ai ,describe the number of the reverse logs of each prefix,
The input is correct.
1≤T≤5 , 1≤N≤50000
Output
For each testcase,print the ans.
Sample Input
1 3 0 1 2
Sample Output
3 1 2
题目大意:
ZYB有一个排列P,但他只记得P中每个前缀区间的逆序对数,现在他要求你还原这个排列. (i,j)(i<j)被称为一对逆序对当且仅当Ai>Aj
思路:
1、一开始觉得要正序处理然后考虑到一个数字大小对逆序数的增加的影响来二分做。
后来发现这样做要枚举很多很多情况,Dfs来搞的话时间复杂度巨高.......................
2、正解是要逆序处理。因为第一个p【0】永远都是0.他确定不了什么,所以我们要逆序处理。
对于第i个数,他增加了的逆序数为:p【i】-p【i-1】;那么表示区间内【0,i-1】有p【i】-p【i-1】个数比他大,那么他在区间【0,i】中排行大小为:i-(p【i】-p【i-1】);
对于答案序列来讲,他是一个全排列的一种情况,对于用过了的数肯定就不再使用了。那么接下来的任务就是在剩余的数中,挑取第i-(p【i】-p【i-1】)大的数,作为这个位子上的答案;
那么这部分我们可以用树状数组+二分来完成任务。
对于树状数组,我们初始化每个位子上的val都是1.表示每个数字都还没被用过。那么sum(i)的操作,就是在查找【1,i】这些数字中还剩余多少个数。
那么我们考虑二分这个最终位子pos,使得【1,pos】中剩余的数字为i-(p【i】-p【i-1】)个即可。
那么很容易理解,ans【i】=pos;
对应每一次找到一个答案之后,对应add(pos,-1)即可,表示这个位子上的这个数字我们已经用过了。
3、过程维护一下,注意细节。
Ac代码:
#include<stdio.h>
#include<string.h>
using namespace std;
int tree[500005];
int ans[500005];
int n;
int p[50005];
int lowbit(int x)//lowbit
{
return x&(-x);
}
int sum(int x)
{
int sum=0;
while(x>0)
{
sum+=tree[x];
x-=lowbit(x);
}
return sum;
}
void add(int x,int c)//加数据。
{
while(x<=n)
{
tree[x]+=c;
x+=lowbit(x);
}
}
int Slove(int k)
{
int ans;
int l=1;
int r=n;
while(r-l>=0)
{
int mid=(l+r)/2;
if(sum(mid)>=k)
{
ans=mid;
r=mid-1;
}
else l=mid+1;
}
return ans;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
memset(tree,0,sizeof(tree));
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
add(i,1);
scanf("%d",&p[i]);
}
for(int i=n;i>=1;i--)
{
int k=p[i]-p[i-1];
k=i-k;
ans[i]=Slove(k);
add(ans[i],-1);
}
for(int i=1;i<=n;i++)
{
if(i>1)printf(" ");
printf("%d",ans[i]);
}
printf("\n");
}
}