题解:P16757 [GKS 2020 #C] Perfect Subarray

· · 题解

P16757 [GKS 2020 #C] Perfect Subarray

题意

给定长度为 N 的整数数组 a,求有多少个连续非空子数组的和是完全平方数。

思路

刚看到题,没过一会儿就想到了用前缀和 + 哈希表优化,但不出意料,两个测试点全都超时了(还没我暴力得的分多)。

这时我们再重新思考一下问题。

设前缀和为 S,子数组 [j+1, i] 的和就是 S_i - S_j。题目要求 S_i - S_j = k^2,移项得 S_j = S_i - k^2。

这下思路就出来了:从左到右扫数组,维护当前的前缀和 P_i。对于每个 P_i,枚举 k \ge 0,去桶里查一下之前有多少个 P_j 等于 P_i - k^2,累加进答案就可以了。

小细节:因为前缀和有负数,所以桶的下标要加个偏移量 off = 1e7 。

但一定要记住:把数组清零千万不能用 memset,要不然必超时!!!(本人就挂了好几次)。

:::success[AC CODE]

#include<bits/stdc++.h>
#define ll long long
#define ull unsigned long long
using namespace std;
const int MAX=2e7+10,off=1e7;
int t,n,cnt[MAX];
int main(){
    cin>>t;
    for(int c=1;c<=t;c++){
        cin>>n;
        vector<int>a(n+1);
        for(int i=1;i<=n;i++){
            cin>>a[i];
        }
        vector<int>u;
        ll ans=0,sum=0;
        cnt[0+off]++;
        u.push_back(0+off);
        for(int i=1;i<=n;i++){
            sum+=a[i];
            for(int j=0;;j++){
                ll k=1LL*j*j,v=1LL*sum-k;
                if(v<-off) break;
                if(v>=-off&&v<=off){
                    ans+=cnt[v+off];
                }
            }
            cnt[sum+off]++;
            u.push_back(sum+off);
        }
        for(int i:u){
            cnt[i]=0;
        }
        cout<<"Case #"<<c<<": "<<ans<<'\n';
    }
    return 0;
}

:::