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;
}