HDU 6601 ( 主席树 )

HDU 6601 ( 主席树 )

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=6601

题意: n个数组成的序列a,q次查询,在 [ L, R ] 区间内所有数能组成的周长最大三角形有多大。

思路:先思考最暴力的做法,把 [ L, R ] 区间的数排个序,要周长最大肯定从最大的边开始考虑,组成三角形的条件是 a+b>c 可以简化一下就是两个较小的边加起来>最大的边。 所以我们排好序后一定是选择三个相邻长度的边才最优。

然而排序是O( nlogn ) 的,猜测既然要找最大周长,我们大概率只要找到最大的一些边就可以了( 百度这道题有人证明,好像是联系的斐波那契数列,就结论是只和最大的44个数相关 ),我们可以想到用主席树来找第k大值。

代码:

#include<bits/stdc++.h>
#define mid ((left+right)/2)

using namespace std;

const int maxn = 1e5+10;
int n,m,q,tot=0;
int a[maxn],b[maxn];
int T[maxn],tree[maxn*20],L[maxn*20],R[maxn*20];

int built_tree( int left, int right )
{
    int node = tot++;
    if ( left<right ) {
        L[node] = built_tree(left,mid);
        R[node] = built_tree(mid+1,right);
    }
    return node;
}

int update( int pre, int left, int right, int x )
{
    int node = tot++;
    L[node] = L[pre];
    R[node] = R[pre];
    tree[node] = tree[pre] + 1;
    if ( left<right ) {
        if ( x<=mid ) L[node] = update(L[pre],left,mid,x);
        else R[node] = update(R[pre],mid+1,right,x);
    }
    return node;
}

int query( int node1, int node2, int left, int right, int k )
{
    if ( left==right ) return left;
    int rsum = tree[ R[node2] ] - tree[ R[node1] ];
    if ( rsum>=k ) return query( R[node1],R[node2],mid+1,right,k );
    else return query( L[node1],L[node2],left,mid,k-rsum );
}


int main()
{
    while ( cin >> n >> q ) {

    tot = 0;
    memset(T,0,sizeof(T)); memset(tree,0,sizeof(tree));
    memset(L,0,sizeof(L)); memset(R,0,sizeof(R));
    for ( int i=1; i<=n; i++ ) {
        scanf("%d",&a[i]);
        b[i] = a[i];
    }
    sort(b+1,b+n+1);
    m = unique(b+1,b+1+n) - b - 1;
    T[0] = built_tree(1,m);
    for ( int i=1; i<=n; i++ ) {
        a[i] = lower_bound(b+1,b+1+m,a[i])-b;
        T[i] = update(T[i-1],1,m,a[i]);
    }
    while ( q-- ) {
        int l,r,ai[3];
        scanf("%d %d",&l,&r);
        if ( r-l+1<3 ) {
            printf("-1\n");
            continue ;
        }
        int ct = 3;
        ai[2] = b[query(T[l-1],T[r],1,m,1)];
        ai[1] = b[query(T[l-1],T[r],1,m,2)];
        ai[0] = b[query(T[l-1],T[r],1,m,3)];
        while ( ai[0]+ai[1]<=ai[2] ) {
            ct ++;
            if ( ct>r-l+1 ) break;
            ai[2] = b[query(T[l-1],T[r],1,m,ct)];
            sort(ai,ai+3);
        }
        if ( ct>r-l+1 ) printf("-1\n");
        else printf("%lld\n",1ll*ai[0]+ai[1]+ai[2]);
    }
}
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值