Codeforces Round #400 (Div. 1 + Div. 2, combined) C:Molly's Chemicals(前缀+思维)

本文介绍了一道算法题目“Molly's Chemicals”,任务是找出给定数组中所有连续子数组,其元素和为给定整数K的非负整数次幂的数量。文章提供了问题的背景故事、输入输出格式、示例及一种高效的解决方案。

C. Molly’s Chemicals

time limit per test:2.5 seconds

memory limit per test:512 megabytes

input:standard input

output:standard output

Molly Hooper has n different kinds of chemicals arranged in a line. Each of the chemicals has an affection value, The i-th of them has affection value ai.

Molly wants Sherlock to fall in love with her. She intends to do this by mixing a contiguous segment of chemicals together to make a love potion with total affection value as a non-negative integer power of k. Total affection value of a continuous segment of chemicals is the sum of affection values of each chemical in that segment.

Help her to do so in finding the total number of such segments.

Input

The first line of input contains two integers, n and k, the number of chemicals and the number, such that the total affection value is a non-negative power of this number k. (1 ≤ n ≤ 105, 1 ≤ |k| ≤ 10).

Next line contains n integers a1, a2, …, an ( - 109 ≤ ai ≤ 109) — affection values of chemicals.

Output

Output a single integer — the number of valid segments.

Examples

Input
4 2
2 2 2 2

Output
8

Input
4 -3
3 -6 -3 12

Output
3

Note

Do keep in mind that k0 = 1.

In the first sample, Molly can get following different affection values:
•2: segments [1, 1], [2, 2], [3, 3], [4, 4];

•4: segments [1, 2], [2, 3], [3, 4];

•6: segments [1, 3], [2, 4];

•8: segments [1, 4].

Out of these, 2, 4 and 8 are powers of k = 2. Therefore, the answer is 8.

In the second sample, Molly can choose segments [1, 2], [3, 3], [3, 4].
题意:给你n个数,问有多少个区间的和满足是k的次幂。
题解:首先很简单的想到求个前缀和sum,然后对于每一个右端点i我们枚举左端点j([0,i])使得sum[i]-sum[j]=k^t.然而这样写是o(n^2)的。简单变形一下等式sum[i]-k^t=sum[j],枚举I,t 然后累计sum[j]统计答案即可。对于当k为1,-1时,可以特殊判断,也可在枚举中去重。
这个方法好像在之前的b题出现过一次。
代码:

#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int N=1e6+10;
ll sum[N];
ll a[N];
ll poww[N];
ll ans;
int n,m;
map<ll,ll>mp;
void solve()
{
    cin>>n>>m;
    memset(sum,0,sizeof(sum));
    for(int i=0; i<n; i++)
    {
        cin>>a[i];
        i==0?sum[i]=a[i]:sum[i]=sum[i-1]+a[i];
    }
}
int main()
{
    solve();
    int zhi=0;
    for(zhi=0;; zhi++)
    {
        if(zhi>55||poww[zhi-1]>=1e15)break;
        zhi==0?poww[zhi]=1:poww[zhi]=poww[zhi-1]*m;
    }
    mp[0]=1;
    ans=0;
    for(int i=0; i<n; i++)
    {
        map<ll,ll>p;
        for(int j=0; j<zhi; j++)
        {
            if(p[poww[j]]==1) continue;
            p[poww[j]]=1;
            ans+=mp[sum[i]-poww[j]];
        }
        mp[sum[i]]++;
    }
    cout<<ans<<endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值