HDU 6058 Kanade's sum(链表)

80 篇文章 0 订阅

Kanade's sum

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


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
 
题意:
给你一个排列,求所有区间[l,r]内第k大的数,若没有第k大的数,就为0。求和。
POINT:
建立一个物理意义上的链表,来连接这个排列。
排列固定是1-n的数。所以先从1开始找。那么顺着链表往前和往后都是比1大的,往前最多找k-1个数,往后也一样。
这样往前找0个数,对应往后找k-1个数。往前找1个数,对应往后找k-2个数。依此类推。
只要求出往前找(0-k-1)个数的时候有几种可能,记录l数组。同理对r数组一样的操作。
答案就是对应的l乘r。
找完1就把1删了,找2。
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <math.h>
using namespace std;
#define LL long long
const int N = 5*1e5+33;
int pre[N],nxt[N],pos[N],l[N],r[N];
LL ans;
int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        int n,k;
        ans=0;
        scanf("%d %d",&n,&k);
        for(int i=1;i<=n;i++)
        {
            int a;
            scanf("%d",&a);
            pos[a]=i;
        }
        for(int i=1;i<=n;i++)
        {
            pre[i]=i-1;
            nxt[i]=i+1;
        }
        for(int i=1;i<=n;i++)
        {
            int l_cnt=0;
            int r_cnt=0;
            for(int j=pos[i];j>=1&&l_cnt<k;j=pre[j])
            {
                l[l_cnt++]=j-pre[j];
            }
            for(int j=pos[i];j<=n&&r_cnt<k;j=nxt[j])
            {
                r[r_cnt++]=nxt[j]-j;
            }
            for(int j=0;j<l_cnt;j++)
            {
                if(k-1-j<r_cnt)
                {
                    ans+=(LL)l[j]*r[k-1-j]*i;
                }
            }
            pre[nxt[pos[i]]]=pre[pos[i]];
            nxt[pre[pos[i]]]=nxt[pos[i]];
        }
        printf("%lld\n",ans);
    }
    return 0;
}




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值