Kanade's sum(链表优化)
来源:互联网 发布:自然排名优化软件 编辑:程序博客网 时间:2024/06/07 10:17
Kanade's sum
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 2017 Accepted Submission(s): 813
Problem Description
Give you an array A[1..n] of length n .
Letf(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 youk , 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
Let
Specially ,
Give you
There are T test cases.
Input
There is only one integer T on first line.
For each test case,there are only two integersn ,k on first line,and the second line consists of n integers which means the array A[1..n]
For each test case,there are only two integers
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
Recommend
liuyiding | We have carefully selected several similar problems for you: 6066 6065 6064 6063 6062
我们只要求出对于一个数x左边最近的k个比他大的和右边最近k个比他大的,扫一下就可以知道有几个区间的k大值是x.
我们考虑从小到大枚举x,每次维护一个链表,链表里只有>=x的数,那么往左往右找只要暴力跳k次,删除也是O(1)的。
时间复杂度:O(nk)
计算每个数的贡献, 找到左边k-1个大于 pi的,右边 大于pi 的, 所有有贡献的区间都在这个范围内。
注意题目中是1到n的序列, 用链表维护位置,结束后删除pi, 从小到大 枚举,可以保证链表中的数 >=pi; 然后再把pi删除, 这点很重要,题中从1遍历到n,因为1对2并不会影响2是第k大,从而大大减少了时间。
#include<iostream>#include<algorithm>#include<cstdio>using namespace std;typedef long long ll;const int mod =1e9+7;const int Size = 510000;int pre[Size],nxt[Size],pos[Size];//前一个数,后一个数,这个数的位置int main(){ std::ios::sync_with_stdio(false); int t,n,k; cin>>t; while(t--) { int p=0,x; cin>>n>>k; for(int i=1;i<=n;i++)//pre[1]=0 { cin>>x; pos[x]=i; nxt[p]=x; pre[x]=p; p=x; } nxt[x]=n+1; //防止溢出 pos[n+1]=n+1; ll ans=0; for(int i=1;i<=n;i++)//题中数据是一个1到n的序列 { p=i; int cnt=1,p1=i; ll sum=0; while(cnt<k && pre[p]) p=pre[p],cnt++;//从这个数往左找第k个比他大的数 while(cnt<k && nxt[p1]!=n+1) p1=nxt[p1],cnt++;//往右找 if(cnt<k) continue; for(;p!=nxt[i];p=nxt[p])//找到左边k-1个大于 pi的,右边第1个大于pi 的 { int l1=pos[p] - pos[pre[p]]; int r1=pos[nxt[p1]] - pos[p1]; sum+= l1*r1; p1=nxt[p1]; //p1往右推,p也往右推 if(p1>=n+1) break; } pre[nxt[i]]=pre[i];//删除i nxt[pre[i]]=nxt[i]; ans+=(ll) sum*i;//这个数乘以他的贡献值 } printf("%lld\n",ans); }}
阅读全文
1 0
- Kanade's sum(链表优化)
- hdu 6058 Kanade's sum 维护链表
- Hdu 6058 Kanade's sum【思维+链表模拟】
- HDU 6058 Kanade's sum 思维+ 模拟链表
- HDU6058-Kanade's sum
- hdu6058-Kanade's sum
- hdu6058 Kanade's sum
- HDU6058-Kanade's sum
- 6058 Kanade's sum
- HDU6058 Kanade's sum
- Kanade's sum HDU
- Kanade's sum
- HDU6058-Kanade's sum
- HDU6058A Kanade's sum
- HDU6058 Kanade's sum
- hdu6058 Kanade's sum
- HDU-6058 Kanade's sum
- hdu 6058 Kanade's sum
- 手动开栈
- iptables学习笔记:端口转发命令优化
- C++全局变量和局部变量详解
- Seacms漏洞分析利用复现 By Assassin
- android接入华为推送
- Kanade's sum(链表优化)
- css(二)----属性(1)
- 高通平台USB2.0和3.0接口充电器识别原理
- HDU 2026
- spring容器初始化的时候执行一个方法。
- jdbc深入~连接池
- Android开发动态添加标签
- DOM节点删除之remove()的有参用法和无参用法
- HDU 6038 函数问题