C. Molly‘s Chemicals

https://codeforces.com/problemset/problem/776/C

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 a i.

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 a 1, a 2, ..., a n ( - 109 ≤ a i ≤ 109) — affection values of chemicals.

Output

Output a single integer — the number of valid segments.

Examples

input

Copy

4 2
2 2 2 2

output

Copy

8

input

Copy

4 -3
3 -6 -3 12

output

Copy

3

思路:k的次幂的枚举最多只有60次,其实比较好想。取k=2,2^60>1e14。所以关于每个k的次幂的枚举就是常数级别的。

然后题目求有多少个区间[l,r]满足是k的倍数的。直接枚举的话sum[r]-sum[l-1]==pow(k,i),枚举这个l和r是n^2的复杂度。

所以转化一下sum[r]-pow(k,i)=sum[l-1].直接for(O(n))中统计当前map中sum[1-r]-pow(k,i)的个数,然后更新map[1~(l-1)]的个数。

所以开始的边界注意map[0]=1;

#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=1e5+100;
typedef long long LL;
const LL inf=1e14;
LL a[maxn],sum[maxn];
map<LL,LL>map1;
set<LL>s; 
int main(void)
{
  cin.tie(0);std::ios::sync_with_stdio(false);
  LL n,k;cin>>n>>k;
  for(LL i=1;i<=n;i++) cin>>a[i];
  for(LL i=1;i<=n;i++) sum[i]=sum[i-1]+a[i];
  s.insert(1);
  LL tmp=k;
  for(LL i=1;i<=60;i++)
  {
  	if(tmp>inf) break;
  	s.insert(tmp);
	tmp*=k;	 
  }
  LL ans=0;
  map1[0]++;//边界情况 
  //枚举r 
  for(LL i=1;i<=n;i++){
     for(set<LL>::iterator it=s.begin();it!=s.end();it++){
    	ans+=map1[sum[i]-*it]; 	
	}
	map1[sum[i]]++;
  }
  cout<<ans<<endl;
return 0;
}

猜你喜欢

转载自blog.csdn.net/zstuyyyyccccbbbb/article/details/108357803
今日推荐