Created
September 5, 2019 15:06
-
-
Save shininglion/0c89233fe7f62f2f8be333bfe4fbe310 to your computer and use it in GitHub Desktop.
Accepted implementation for the problem 1208D in codeforces
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* ===================================================================================== | |
* | |
* Filename: 1208D.cpp | |
* | |
* Description: codeforces 1208D. Restore Permutation | |
* | |
* Version: 1.0 | |
* Created: 2019年09月05日 | |
* Revision: none | |
* Compiler: gcc | |
* | |
* Author: lionking | |
* Organization: None | |
* | |
* ===================================================================================== | |
*/ | |
#include <cstdio> | |
using namespace std; | |
typedef long long int lli_t; | |
// update the value at index 'index' with change 'val' in binary indexed tree | |
void update(lli_t *bit, int N, int index, lli_t val) | |
{ | |
for (; index <= N; index += (index & (-index))) { | |
bit[index] += val; | |
} | |
} | |
// Given val (s[i] in problem description), find the desired p[i] | |
int query(lli_t *bit, int N, int logN, lli_t val) | |
{ | |
int ans = 0; | |
for (int i = logN; i >= 0; --i) { | |
auto idx = ans + (1 << i); | |
if ((idx <= N) && (bit[idx] <= val)) { | |
ans = idx; | |
val -= bit[idx]; | |
} | |
} | |
return (ans + 1); | |
} | |
int main() | |
{ | |
constexpr int MAXN = 200007; | |
// bit: binary indexed tree (BIT) | |
lli_t bit[MAXN] = {0}, p[MAXN]; | |
int N; | |
scanf("%d", &N); | |
// read s[i] and construct BIT | |
for (int i = 1; i <= N; ++i) { | |
scanf("%lld", p + i); | |
update(bit, N, i, i); | |
} | |
int logN = 0; | |
for (int x = N; x > 0; x >>= 1, ++logN) {} | |
// find the answer with the help of BIT from back to front | |
for (int i = N; i > 0; --i) { | |
const auto ans = query(bit, N, logN, p[i]); | |
p[i] = ans; | |
update(bit, N, ans, -ans); | |
} | |
for (int i = 1; i <= N; ++i) { | |
printf("%lld ", p[i]); | |
} | |
putchar('\n'); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment