hdu 6058 Kanade's sum

来源:互联网 发布:我的世界编程猫 编辑:程序博客网 时间:2024/06/06 16:47

Kanade's sum

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
题意:给你n个数,这n个数是一种全排列,问你所有子区间的第k大的数之和。
思路:遍历A中所有元素 令当前元素为第K大 往右找 上限 再往左找下限 具体看代码

#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)//把下标为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;          }          LL ans=0;          for(int num=1;num<=n-k+1;++num)          {              int p=pos[num];              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;              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;  }  




 
原创粉丝点击