HDU6058-Kanade's sum

Kanade’s sum

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

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 r−l+1< k.

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

There are T test cases.

1≤T≤10

k≤min(n,80)

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

∑n≤5∗105

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

Source
2017 Multi-University Training Contest - Team 3

题目大意:有一个1~n的排列,问所有区间中第k大的数的总和是多少?
解题思路:我们只要求出对于一个数x左边最近的k个比他大的和右边最近k个比他大的,扫一下就可以知道有几个区间的k大值是x.
我们考虑从小到大枚举x,每次维护一个双向链表,链表里只有>=x的数,那么往左往右找只要暴力跳k次,删除也是O(1)的。
时间复杂度:O(nk)

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
typedef long long LL;
const int INF=0x3f3f3f3f;
const LL MOD=1e9+7;
const int MAXN=1e6+7;
int a[MAXN],pos[MAXN];
int s[MAXN],t[MAXN];
int pre[MAXN],nxt[MAXN];
int n,k;

void erase(int x)
{
    int pp=pre[x],nn=nxt[x];
    if(pre[x]) nxt[pre[x]]=nn;
    if(nxt[x]<=n) pre[nxt[x]]=pp;
    pre[x]=nxt[x]=0;
}

int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d%d",&n,&k);
        for(int i=1;i<=n;++i)
        {
            scanf("%d",&a[i]);
            pos[a[i]]=i;
        }
        for(int i=1;i<=n;++i)
        {
            pre[i]=i-1;
            nxt[i]=i+1;
        }
//        for(int i=1;i<=n;++i)
//        {
//            cout<<pre[i]<<" "<<nxt[i]<<endl;
//        }
        LL ans=0;
        for(int num=1;num<=n-k+1;++num)
        {
            int p=pos[num];//cout<<p<<endl;
            int s0=0,t0=0;
            for(int d=p;d&&s0<=k;d=pre[d]) s[++s0]=d;
            for(int d=p;d!=n+1&&t0<=k;d=nxt[d]) t[++t0]=d;
            s[++s0]=0;t[++t0]=n+1;
//            cout<<endl;
//            cout<<endl;
//            for(int i=1;i<=s0;i++)
//            {
//                cout<<s[i]<<" ";
//            }
//            cout<<endl;
//            cout<<endl;
//            for(int i=1;i<=t0;i++)
//            {
//                cout<<t[i]<<" ";
//            }
//            cout<<endl;
//            cout<<endl;
            for(int i=1;i<=s0-1;++i)
            {
                if(k+1-i<=t0-1&&k+1-i>=1)
                {
                    ans+=(LL)(t[k+1-i+1]-t[k+1-i])*(s[i]-s[i+1])*num;
                }
            }
            erase(p);
        }
        printf("%lld\n",ans);
    }
    return 0;
}
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值