Hdu6058 Kanade's sum(2017多校第3场)

来源:互联网 发布:mac双系统默认windows 编辑:程序博客网 时间:2024/06/08 16:32

Kanade's sum

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


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
15 21 2 3 4 5
 

Sample Output
30
 

Source
2017 Multi-University Training Contest - Team 3

————————————————————————————————————

题目的意思是给出一个序列,求各个区间第k大数之和

思路:当一个数是第k大的时候,前面有x个比它大的数,那么后面就有k-x-1个比它大的数,所以我们一开始先维护一个满的链表,然后从小到大删除,每次算完一个数,就在链表里面删除,算x的时候,保证删除的数都比x小,都可以用来算贡献。i和pre[i]和nxt[i]的距离就是小于当前的数的数目+1。


#include <iostream>#include <cstdio>#include <algorithm>#include <cmath>#include <cstring>#include <string>#include <queue>#include <stack>#include <set>#include <map>using namespace std;#define LL long longconst LL mod=1e9+7;const int INF=0x3f3f3f3f;#define MAXN 500005#define mem(a,b) memset(a,b,sizeof a)int nt[MAXN],pre[MAXN],pos[MAXN],p[MAXN],n,k;void del(int x){    pre[nt[x]]=pre[x];    nt[pre[x]]=nt[x];}LL sumup(int x){    int a[100],b[100];    int la=0,lb=0;    for(int i=x; i>0; i=pre[i])    {        a[++la]=i-pre[i];        if(la==k)            break;    }    for(int i=x; i<=n; i=nt[i])    {        b[++lb]=nt[i]-i;        if(lb==k)            break;    }    LL ans=0;    for(int i=1; i<=la; i++)    {        if(lb>=k-i+1)            ans+=1LL*a[i]*b[k-i+1];    }    return ans;}int main(){    int T;    for(scanf("%d",&T); T--;)    {        scanf("%d%d",&n,&k);        for(int i=1; i<=n; i++)        {            scanf("%d",&p[i]);            pos[p[i]]=i;            pre[i]=i-1;            nt[i]=i+1;        }        pre[0]=0,nt[0]=1,pre[n+1]=n,nt[n+1]=n+1;        LL ans=0;        for(int i=1; i<=n; i++)        {            int x=pos[i];            ans+=sumup(x)*i;            del(x);        }        printf("%lld\n",ans);    }    return 0;}