hdu5358 First One 尺取法 多校联合第六场

本文解析了一道算法竞赛题目,该题目要求计算特定数组上的一种复杂表达式的总和,并提供了一个高效的解决方案,通过枚举不同区间范围并利用尺取法优化计算过程。

First One

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 1511    Accepted Submission(s): 457


Problem Description
soda has an integer array a1,a2,,an. Let S(i,j) be the sum of ai,ai+1,,aj. Now soda wants to know the value below:
i=1nj=in(log2S(i,j)+1)×(i+j)

Note: In this problem, you can consider log20 as 0.
 

Input
There are multiple test cases. The first line of input contains an integerT, indicating the number of test cases. For each test case:

The first line contains an integer n(1n105), the number of integers in the array.
The next line contains n integers a1,a2,,an(0ai105).
 

Output
For each test case, output the value.
 

Sample Input
1 2 1 1
 

Sample Output
12

  计算上面给的那个公式。

  比赛的时候想了个方法,以每个位置作为终点,二分log每种取值对应的起点,这样的复杂度是O(NlogN*35)左右,但是超时。这道题时间卡的很紧,复杂度O(N*35)的都要运行1000多ms。

  枚举log不同取值的区间范围,在O(N)的复杂度下算出这个范围对应的所有i,j和。采用尺取法,假设以i为起始位置,对应[p1,p2]这个区间为终止位置,这些区间都是满足的,那么当i+1时,一定有终止位置p1'>=p1,p2'>=p2才可能满足。

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<vector>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<algorithm>
using namespace std;
typedef long long LL;

const LL MAXN=100010;
const LL INF=0x3f3f3f3f;
const LL SIGMA_SIZE=28;

int T,N;
int a[MAXN];
LL sum[MAXN];

//[l,r) i+j的和
LL solve(LL l,LL r){
    LL ret=0;
    int p1=1,p2=1;
    for(int i=1;i<=N;i++){
        if(p1<i) p1=i;
        if(p2<i) p2=i;
        while(p1<=N&&sum[p1]-sum[i-1]<l) p1++;
        while(p2<=N&&sum[p2]-sum[i-1]<r) p2++;
        p2--;
        if(p1<=p2&&sum[p1]-sum[i-1]>=l&&sum[p2]-sum[i-1]<r){
            LL n=p2-p1+1;
            ret+=i*n+p1*n+n*(n-1)/2;
        }
    }
    return ret;
}

int main(){
    freopen("in.txt","r",stdin);
    scanf("%d",&T);
    while(T--){
        scanf("%d",&N);
        sum[0]=0;
        for(int i=1;i<=N;i++){
            scanf("%d",&a[i]);
            sum[i]=sum[i-1]+a[i];
        }
        LL ans=0;
        ans+=solve(0,1);
        for(int i=0;i<35;i++){
            ans+=solve(1LL<<i,1LL<<(i+1))*(i+1);
        }
        printf("%I64d\n",ans);
    }
    return 0;
}



评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值