码迷,mamicode.com
首页 > 编程语言 > 详细

【51nod】 第K大区间2(二分+树状数组)

时间:2016-05-22 12:30:45      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:

【51nod】 第K大区间2(二分+树状数组)

技术分享
﹡    LH (命题人)
基准时间限制:1.5 秒 空间限制:131072 KB 分值: 160

定义一个长度为奇数的区间的值为其所包含的的元素的中位数。中位数_百度百科 

现给出n个数,求将所有长度为奇数的区间的值排序后,第K大的值为多少。


样例解释:


[l,r]表示区间的值
[1]:3
[2]:1
[3]:2
[4]:4
[1,3]:2
[2,4]:2


第三大是2

Input
第一行两个数n和k(1<=n<=100000,k<=奇数区间的数量)
第二行n个数,0<=每个数<2^31
Output
一个数表示答案。
Input示例
4 3
3 1 2 4
Output示例
2

二分答案t,统计中位数大于等于t的区间有多少个。

设a[i]为前i个数中有a[i]个数>=t,若奇数区间[l,r]的中位数>=t,则(a[r]-a[l-1])*2>r-l+1,即(a[r]*2-r)>(a[l-1]*2-l+1)。
设b[i]=a[i]*2-i,统计每个b[i]有多少个b[j]<b[i](j<i 且 j和i奇偶性不同)
总复杂度O(nlognlogn)

二分就不用说了。至于a和b,用法讲的也挺明白。就是统计b[j] < b[i]那一步,可以用树状数组处理,注意a[i]*2-i可能为负值(当n个数从小到大有序时 t == 最大数时,a[n] = -n

因此需要+n避免越界


代码如下:

#include <iostream>
#include <cmath>
#include <vector>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <queue>
#include <stack>
#include <list>
#include <algorithm>
#include <map>
#include <set>
#define LL long long
#define Pr pair<int,int>
#define fread() freopen("in.in","r",stdin)
#define fwrite() freopen("out.out","w",stdout)

using namespace std;
const int INF = 0x3f3f3f3f;
const int msz = 32768;
const int mod = 1e9+7;
const double eps = 1e-8;

int num[100100];
int tmp[100100];
int a[100100],bit[2][400400];
int tp,n;

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

void Add(int pos,int x)
{
    //printf("ad:%d\n",x);
    while(x <= 4*n)
    {
        bit[pos][x]++;
        x += Lowbit(x);
    }
}

int Sum(int pos,int x)
{
    //printf("sum:%d\n",x);
    int ans = 0;
    while(x)
    {
        ans += bit[pos][x];
        x -= Lowbit(x);
    }
    return ans;
}

LL cal(int pos)
{
    LL ans = 0;
    memset(bit,0,sizeof(bit));
    a[0] = n;
    Add(2*a[0]);

    for(int i = 1; i <= n; ++i)
    {
        //printf("id:%d\n",i);
        if(i) a[i] = a[i-1]+(num[i]>=tmp[pos]? 1: 0);
        else a[i] = (num[i]>=tmp[pos]? 1: 0);

        if(i&1)
        {
            ans += Sum(0,2*a[i]-i-1);
            Add(1,2*a[i]-i);
        }
        else
        {
            ans += Sum(1,2*a[i]-i-1);
            Add(0,2*a[i]-i);
        }
        //printf("ans:%lld\n",ans);
    }
    //printf("ans:%lld\n",ans);
    return ans;
}

int main()
{
    LL k;

    scanf("%d%lld",&n,&k);
    for(int i = 1; i <= n; ++i)
    {
        scanf("%d",&num[i]);
        tmp[i] = num[i];
    }

    sort(tmp,tmp+n);
    tp = unique(tmp+1,tmp+n+1)-tmp;

    int l,r,ans;
    l = 1,r = tp-1;

    while(l <= r)
    {
        //printf("%d %d\n",l,r);
        int mid = (l+r)>>1;

        if(cal(mid) >= k) ans = mid,l = mid+1;
        else r = mid-1;
        //printf("%d\n",tmp[ans]);
    }

    printf("%d\n",tmp[ans]);

    return 0;
}




【51nod】 第K大区间2(二分+树状数组)

标签:

原文地址:http://blog.csdn.net/challengerrumble/article/details/51469896

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!