AcWing 244. Mysterious Cow ( Two Points )
Ideas
Initialize all numbers to 1, which means they have not been used
Calculate from back to front to find the number of the first k that has not been used. The smallest x that makes sum(x) == k is the answer.
Then set this number to 0 to indicate that it has been used
There are n cows, their heights are known to be 1~n and they are all different, but the specific height of each cow is not known.
Now these n cows stand in a row, it is known that there is A i A_{i} in front of the i-th cowAiThe cow is lower than it. Find the height of each cow.
Input format
Line 1: Enter the integer n.
Line 2...n: Enter an integer A i A_{i} per lineAi, The i-th line means that there is A i A_{i} in front of the i-th cowAiThe head of cattle is lower than it.
(Note: Because there is no cow in front of the first cow, it is not listed)
Output format
The output contains n lines, and each line outputs an integer representing the height of the cow.
The ith line outputs the height of the ith cow.
data range
1 ≤ n ≤ 1 0 5 1≤n≤10^{5} 1≤n≤105
Code
#include<iostream>
#include<cstdio>
#include<queue>
#include<string>
#include<cstring>
#include<map>
#include<vector>
#include<set>
#include<stack>
#include<algorithm>
#include<vector>
#include<utility>
#include<deque>
#include<unordered_map>
#define INF 0x3f3f3f3f
#define mod 1000000007
#define endl '\n'
#define eps 1e-6
inline int gcd(int a, int b) {
return b ? gcd(b, a % b) : a; }
inline int lowbit(int x) {
return x & -x; }
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int, int> PII;
const int N = 100010;
int tr[N], h[N], ans[N];
int n;
void add(int x, int c) {
for (int i = x; i <= n; i += lowbit(i))tr[i] += c;
}
int query(int x) {
int res = 0;
for (int i = x; i; i -= lowbit(i))res += tr[i];
return res;
}
int check(int x) {
int l = 1, r = n;
while (l < r) {
int mid = l + r >> 1;
if (query(mid) >= x)r = mid;
else l = mid + 1;
}
add(r, -1);
return r;
}
int main() {
cin >> n;
for (int i = 2; i <= n; ++i)scanf("%d", &h[i]);
for (int i = 1; i <= n; ++i)tr[i] = lowbit(i);
for (int i = n; i; --i) {
int k = h[i] + 1;
ans[i] = check(k);
}
for (int i = 1; i <= n; ++i)printf("%d\n", ans[i]);
return 0;
}