HDU 6058 Kanade's sum(枚举+链表)

Kanade's sum

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


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
 题意:计算一个由1-n数字组成的数列中,所有区间第k大的值的和。

 思路:最普通的想法就是遍历找出所有区间,然后找出每个区间的第k大的数。但是光遍历时间复杂度就有O(n^2),所以最开始都没想就遍历区间然后主席树找区间第k大,直接gg(想到此处真是被自己蠢得要哭了)。转换一下思路,我们不选择枚举所有区间找每个区间的第k大。而通过枚举每一个数,找出每个数是多少个区间的第k大。这样子的话,枚举一个数的x时候,只要找出这个数的左右两边比它大的k个数。为什么不是找k-1个就足够了呢?

不是说是区间第k大吗?那么k-1个比x大的数加上x不就凑成了一个区间第k大是x的区间吗?因为我们想要找到的是区间的个数,例如在x左边比x大的第k-1个数和第k个数之间有一定的位置差,这两个数中间还可能有一些数,设位置差为L,设x右边比x大的第一个数与x 的位置差为R,那么区间的个数为L*R,当然区间第k大为x的区间还不止这些,继续把这个区间往右滚动。用图来表示比较好理解......有时间补个图吧。

接下来就是用链表来处理了,按从小到大的顺序开始枚举,然后依次从链表中删除。比如说刚开始枚举的是1,这个时候1左右两边都是比它大的数。依次找出左右两边的数,然后把1从链表中删除,接下来枚举2,链表中存储的就都是大于等于2的数了,就可以直接找出比2大的数的位置了。

有点头疼的就是边界了,仔细想想就好了。

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<queue>
using namespace std;
int pre[500005],next[500005],pos[500005],n,k;
long long l[500005],r[500005];
//模拟链表
void init()
{
    int t;
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&t);
        pos[t]=i;
    }
    for(int i=1;i<=n;i++)
    {
        pre[i]=i-1;
        next[i]=i+1;
    }
    pre[0]=0;
    next[n+1]=n+1;
}
long long cal(int x)
{
    int num1=0,num2=0;
    long long ans=0;
    for(int i=x;i&&num1<=k;i=pre[i])//计算x左边比x大的相邻两个数之间的位置差
        l[++num1]=i-pre[i];
    for(int i=x;i<=n&&num2<=k;i=next[i])//计算x右边比x大的相邻两个数之间的位置差
        r[++num2]=next[i]-i;
    for(int i=1;i<=num1;i++)
    {
        if(k-i+1<=num2&&k-i+1>=1)
            ans+=l[i]*r[k-i+1];
    }
    return ans;
}
//删除链表元素
void del(int x)
{
    pre[next[x]]=pre[x];
    next[pre[x]]=next[x];
}
int main()
{
    int t;
    long long ans;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d %d",&n,&k);
        init();
        ans=0;
        for(int i=1;i<=n;i++)
        {
            ans+=cal(pos[i])*i;
            del(pos[i]);
        }
        printf("%I64d\n",ans);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值