树状数组40pts3WA求调!

P1168 中位数

hnxxwpf @ 2024-11-20 21:02:19

#include<iostream>
#include<algorithm>
#define lowbit(x) x & -x
using namespace std;
struct Cmp
{
    int key, value;
}a[100001];
int n, cnt, tr[100001], id[100001];
long long sum;
bool cmp(Cmp x, Cmp y)
{
    return x.value < y.value;
}
void add(int x, int k)
{
    while(x <= cnt)
    {
        tr[x] += k;
        x += lowbit(x);
    }
}
int query(int x)
{
    int sum = 0;
    while(x)
    {
        sum += tr[x];
        x -= lowbit(x);
    }
    return sum;
}
int main()
{
    scanf("%d", &n);
    for(int i = 1; i <= n; ++i)
    {
        scanf("%d", &a[i].value);
        a[i].key = i;
    }
    sort(a + 1, a + 1 + n, cmp);
    for(int i = 1; i <= n; ++i)
    {
        if(i == 1 || a[i].value != a[i - 1].value)
        {
            cnt++;
        }
        id[a[i].key] = cnt;
    }
    for(int i = 1; i <= n; ++i)
    {
        add(id[i], 1);
        if(i & 1)
        {
            int l = 1, r = cnt;
            while(l <= r)
            {
                int mid = l + (r - l >> 1);
                if(query(mid) >= i + 1 >> 1)
                {
                    r = mid - 1;
                }
                else
                {
                    l = mid + 1;
                }
            }
            printf("%d\n", a[l].value);
        }
    }
    return 0;
}

|