树状数组全WA求助

P1168 中位数

K__J__M @ 2023-12-10 12:22:31

#include<bits/stdc++.h>
using namespace std;
#define int long long
const int N = 1e6+10;
int n,b[N],c[N];//b[i]为树状数组,c[i]为在a[i]中大小为i的数的下标 
struct node{
    int ID,VAL,HASH;
}a[N];
int lowbit(int x){
    return x&(-x);
}
int getsum(int x){//找左边比它小的数的个数 
    int sum=0;
    while(x){
        sum+=b[x];
        x-=lowbit(x);
    }
    return sum;
}
void add(int x,int val){
    while(x<=n){
        b[x]+=val;
        x+=lowbit(x);
    }
}
bool cmp1(node a ,node b){
    return  a.ID<b.ID;
}
bool cmp2(node a ,node b){
    return a.VAL<b.VAL;
}
int check(int len){
    int l=0,r=len+1;
    while(l<r-1){
        int mid=(l+r)>>1;
        if(getsum(mid)-1>=len/2) r=mid;
        else l=mid+1;
    }
    return a[c[r]].VAL;
}//二分哈希值 
signed main(){
    cin>>n;
    for(int i=1;i<=n;i++){
        cin>>a[i].VAL;
        a[i].ID=i;
    } 
    sort(a+1,a+n+1,cmp2);
    a[1].HASH=1;
    for(int i=2;i<=n;i++){
        if(a[i].VAL==a[i-1].VAL){
            a[i].HASH=a[i-1].HASH;
        }else{
            a[i].HASH=a[i-1].HASH+1;
        }
    }//离散化 
    sort(a+1,a+n+1,cmp1);
    for(int i=1;i<=n;i++) c[a[i].HASH]=i;//处理c 
    for(int i=1;i<=n;i++){
        add(a[i].HASH,1);
        if(i&1){
            cout<<check(i)<<endl;
            continue;
        }
    }
    return 0;
}

|