HDU6069 Kanade's sum(链表+思路)

本文针对 Kanade'ssum 数组问题提供了一种高效解决方案,通过维护一个链表来快速查找区间内的第 k 大元素,并计算所有连续子区间内该元素的和。算法采用 O(nk) 时间复杂度,适用于处理大规模数据集。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



Kanade's sum

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 2292    Accepted Submission(s): 945


Problem Description
Give you an array A[1..n]of length n

Let f(l,r,k) be the k-th largest element of A[l..r].

Specially , f(l,r,k)=0 if rl+1<k.

Give you k , you need to calculate nl=1nr=lf(l,r,k)

There are T test cases.

1T10

kmin(n,80)

A[1..n] is a permutation of [1..n]

n5105
 

Input
There is only one integer T on first line.

For each test case,there are only two integers n,k on first line,and the second line consists of n integers which means the array A[1..n]
 

Output
For each test case,output an integer, which means the answer.
 

Sample Input
1 5 2 1 2 3 4 5
 

Sample Output
30


f(l,r,K)表示区间l,r里面的K大值,问你所有连续子区间的f之和。
维护一个链表,从小到大遍历,每次寻找左边和右边最近k个比它大的数,就可以求出区间长度,然后删去此点,这样链表中存的都是比K大的数
不影响后面结果,需要遍历的点也就越来越少
删点时间复杂度O(1),遍历一点复杂度O(k),总时间复杂度O(nk)
#include<bits/stdc++.h>
typedef long long ll;
const int inf=0x3f3f3f3f;
const int N=5e5+5;
int pos[N],pre[N],nex[N],a[N],b[N],n,k;
ll solve(int x)
{
    int s1=0,s2=0;
    ll ans=0;
    for(int i=x; i&&s1<=k; i=pre[i])
        a[++s1]=i-pre[i];
    for(int i=x; i<=n&&s2<=k; i=nex[i])
        b[++s2]=nex[i]-i;
    for(int i=1; i<=s1; i++)
        if(i+s2-1>=k)
        ans+=(ll)a[i]*b[k-i+1];
    return ans;
}
void del(int x)
{
    pre[nex[x]]=pre[x];
    nex[pre[x]]=nex[x];
}
int main()
{
    int t,x;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&n,&k);
        for(int i=1; i<=n; i++)
        {
            scanf("%d",&x);
            pos[x]=i,pre[i]=i-1,nex[i]=i+1;
        }
        ll ans=0;
        for(int i=1; i<=n; i++)
        {
            ans+=solve(pos[i])*i;
            del(pos[i]);
        }
        printf("%lld\n",ans);
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值