Restore Permutation
题目连接
题意: 有一个数组未知数组 B,给一个数组 A A A, A [ i ] A[i] A[i] 表示 i i i 的前缀比 B [ i ] B[i] B[i] 小的数的和。还原数组 B, 满足数组 A 这个条件。
思路: 和 HDU 5592 区别不大。从后往前还原,假设现在还原的是最后一个数 x ,那么二分枚举这个数 x ,满足条件 A [ n ] A[n] A[n] 即可,然后删掉 x,重复操作即可。
Code:
#include<bits/stdc++.h>
#define debug(x) cerr << "[" << #x <<": " << (x) <<"]"<< endl
#define pii pair<int,int>
#define clr(a,b) memset((a),b,sizeof(a))
#define rep(i,a,b) for(int i = a;i < b;i ++)
#define pb push_back
#define MP make_pair
#define LL long long
#define ull unsigned LL
#define ls i << 1
#define rs (i << 1) + 1
#define fi first
#define se second
#define ptch putchar
#define CLR(a) while(!(a).empty()) a.pop()
using namespace std;
inline LL read() {
LL s = 0,w = 1;
char ch = getchar();
while(!isdigit(ch)) {
if(ch == '-') w = -1;
ch = getchar();
}
while(isdigit(ch))
s = s * 10 + ch - '0',ch = getchar();
return s * w;
}
inline void write(LL x) {
if(x < 0)
putchar('-'), x = -x;
if(x > 9)
write(x / 10);
putchar(x % 10 + '0');
}
#ifndef ONLINE_JUDGE
clock_t prostart = clock();
#endif
const int maxn = 2e5 + 10;
LL a[maxn],coun[maxn << 2],sum[maxn << 2];
LL ans[maxn];
int n;
void build(int l,int r,int i){
if(l == r){
sum[i] = 1;
coun[i] = l;
return ;
}
int mid = (l + r) >> 1;
build(l,mid,ls);
build(mid + 1,r,rs);
sum[i] = sum[ls] + sum[rs];
coun[i] = coun[ls] + coun[rs];
}
void update(int l,int r,int pos,int i){
if(l == r){
sum[i] = 0;
coun[i] = 0;
return ;
}
int mid = (l + r) >> 1;
if(pos <= mid) update(l,mid,pos,ls);
if(pos > mid) update(mid + 1,r,pos,rs);
sum[i] = sum[ls] + sum[rs];
coun[i] = coun[ls] + coun[rs];
}
LL query(int l,int r,int i,int k){
if(sum[i] <= k) return coun[i];
int mid = (l + r) >> 1;
if(sum[ls] >= k)
return query(l,mid,ls,k);
return coun[ls] + query(mid + 1,r,rs,k - sum[ls]);
}
int queryMin(int l,int r,int i,int k){
if(l == r) return l;
int mid = (l + r) >> 1;
if(sum[ls] >= k)
return queryMin(l,mid,ls,k);
return queryMin(mid + 1,r,rs,k - sum[ls]);
}
bool check(int mid,LL x){
return query(1,n,1,mid) >= x;
}
int main() {
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
n = read();
for(int i = 1;i <= n;++ i) a[i] = read();
build(1,n,1);
for(int i = n;i >= 1;-- i){
int l = 1,r = n;
while(l <= r){
int mid = (l + r) >> 1;
if(check(mid - 1,a[i])){
ans[i] = queryMin(1,n,1,mid);
r = mid - 1;
}
else l = mid + 1;
}
update(1,n,ans[i],1);
}
for(int i = 1;i <= n;++ i)
write(ans[i]), ptch(' ');
ptch('\n');
#ifndef ONLINE_JUDGE
cout << "time: " << 1.0 * (clock() - prostart) / CLOCKS_PER_SEC << " s" << endl;
#endif
return 0;
}