2017 Multi-University Training Contest - Team 3 Kanade's sum hd6058

地址:http://acm.split.hdu.edu.cn/showproblem.php?pid=6058

题目:

Kanade's sum

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


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
 

 

Source
 
思路:
  很容易想到按公式算是不可行的(O(n^2)的时间复杂度),然后想到枚举计算每个数的贡献:即第k大为x的区间个数乘以x
  然后只要考虑怎么快速求出第k大为x的区间个数。如果能知道左边大于x的80个数的位置和右边大于x的80个数的位置就可以计算区间个数了。
  之后想到用从小到大枚举或者从大到小,用链表维护即可。
  比赛时用的set模拟的,结果被卡了,T的连妈都不认识。还是觉得时限卡太紧了。
 1 #include <bits/stdc++.h>
 2 
 3 using namespace std;
 4 
 5 #define MP make_pair
 6 #define PB push_back
 7 typedef long long LL;
 8 typedef pair<int,int> PII;
 9 const double eps=1e-8;
10 const double pi=acos(-1.0);
11 const int K=1e6+7;
12 const int mod=1e9+7;
13 
14 int n,k,p[K],pre[K],nxt[K],pos[K],tl[85],tr[85];
15 LL ans;
16 
17 int main(void)
18 {
19     int t;cin>>t;
20     while(t--)
21     {
22         ans=0;
23         scanf("%d%d",&n,&k);
24         for(int i=1;i<=n;i++)
25             scanf("%d",p+i),pos[p[i]]=i;
26         for(int i=1;i<=n;i++)
27             pre[i]=i-1,nxt[i]=i+1;
28         pre[1]=0,nxt[n]=n+1;
29         for(int i=1;i<=n;i++)
30         {
31             int la=0,lb=0;
32             for(int j=pos[i];j>0&&la<=k;j=pre[j])
33                 tl[la++]=j-pre[j];
34             for(int j=pos[i];j<=n&&lb<=k;j=nxt[j])
35                 tr[lb++]=nxt[j]-j;
36             for(int j=0;j<la;j++)
37             if(k-j-1<lb)
38                 ans+=i*1LL*tl[j]*tr[k-j-1];
39             pre[nxt[pos[i]]]=pre[pos[i]];
40             nxt[pre[pos[i]]]=nxt[pos[i]];
41         }
42         printf("%lld\n",ans);
43     }
44     return 0;
45 }

 

 
posted @ 2017-08-01 21:33  weeping  阅读(181)  评论(0编辑  收藏  举报