AcWing 244. 谜一样的牛

思路

AcWing 244. 谜一样的牛AcWing 244. 谜一样的牛AcWing 244. 谜一样的牛AcWing 244. 谜一样的牛

代码

#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

const int N = 100010;

int n;
int h[N];
int ans[N];
int tr[N];

int lowbit(int x)
{
    return x & -x;
}

void add(int x, int c)
{
    for (int i = x; i <= n; i += lowbit(i)) tr[i] += c;
}

int sum(int x)
{
    int res = 0;
    for (int i = x; i; i -= lowbit(i)) res += tr[i];
    return res;
}

int main(){
    cin >> n;
    for(int i=2;i<=n;i++)cin >> h[i];
    for(int i=0;i<=n;i++)tr[i]=lowbit(i);//add(i,1);
    for(int i=n;i;i--){
        int l=1;int r=n;
        int mid=l+r>>1;
        while (l < r)//二分查找sum值等于h[i]+1的最小索引位置
        {
            int mid = l + r >> 1;
            if (sum(mid) >= h[i]+1) r = mid;
            else l = mid + 1;
        }
        ans[i]=r;
        add(r,-1);
    }
    for (int i = 1; i <= n; i ++ ) printf("%d\n", ans[i]);

    return 0;
}
上一篇:微信小程序轨迹回放实现及遇到的坑


下一篇:244 函数内部的this指向:6种