HDU6058-Kanade's sum

来源:互联网 发布:强子纹身器材淘宝 编辑:程序博客网 时间:2024/06/05 14:27

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;}
原创粉丝点击