HDU 6058 Kanade's sum [链表]

4 篇文章 0 订阅

题意:给你n个数求所有区间第k的的值得总和

题解:求出对于一个数x左边最近的k个比他大的和右边最近k个比他大的,然后从左到右统计答案。我们考虑从大到小枚举x,每次维护一个链表,加入数据用set处理,时间复杂度O(n(k+logn))。

AC代码:

#include<set>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<time.h>
struct node{
	long long x,y;
}a[500010];
bool cmp(const node&a,const node&b){return a.x>b.x; }

long long ans,t,n,k,c,d,xc,xx,yy,l[500010],r[500010],cc[100],dd[100];
using namespace std;

set<int> st;
int main(){
    scanf("%lld",&t);
    while(t--){
        ans=0;
        st.clear();
        scanf("%lld%lld",&n,&k);
        for(int i=1;i<=n;i++){
            scanf("%lld",&a[i].x);
            a[i].y=i;
        }
        sort(a+1,a+n+1,cmp);
        st.insert(0); st.insert(n+1);
        for (int i = 1; i <= n; i++){

            pair<set<int>::iterator, bool> it = st.insert(a[i].y);
            set<int>::iterator pre = it.first, suc = it.first;
            --pre; ++suc;
            int ll = *pre;
            int rr = *suc;

            r[ll] = a[i].y;l[rr] = a[i].y;
            r[a[i].y] = rr;l[a[i].y] = ll;
            c=0;d=0;
            cc[0]=a[i].y;dd[0]=a[i].y;
            xc=a[i].y;while(xc!=0 && c<=80){c++;xc=l[xc];cc[c]=xc;}
            xc=a[i].y;while(xc!=n+1 && d<=80){d++;xc=r[xc];dd[d]=xc;}

            c--;d--;
            int lx=min(k-1,c);int ry=min(k-1,d);


            for(int xx=0;xx<=lx;xx++){
                yy=k-1-xx;
                if(yy>ry)continue;
                ans+=a[i].x*(cc[xx]-cc[xx+1])*(dd[yy+1]-dd[yy]);
            }
        }
        printf("%lld\n",ans);
    }    
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值