CF776C Molly's Chemicals

题面翻译

题目描述

Tohru从异世界带回来 n 种化学品,排列成一行。 每一种化学品有一个效果值, 第i个效果值为a i

Tohru想要Kobayashi爱上她。 她把连续的区间上的化学品混合在一起做成总效果值为k的非负整数幂的媚药。总效果值为连续区间上的化学品效果值的总和。

帮帮她找到符合要求的区间的方案数。

输入格式

第一行有两个整数n和k,表示化学品的总数,以及k的值. (1 ≤ n ≤ 10^5, 1 ≤ |k| ≤ 10).

下一行有n 整数a_1_, a_2_, ..., a_n_ ( - 10^9 ≤ ai ≤ 10^9)表示化学品的效果值。

输出格式

输出一个整数,表示方案总数。

题目描述

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.

输入格式

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 ( $ -10{9}<=a_{i}<=10 $ ) — affection values of chemicals.

输出格式

Output a single integer — the number of valid segments.

样例 #1

样例输入 #1

4 2
2 2 2 2

样例输出 #1

8

样例 #2

样例输入 #2

4 -3
3 -6 -3 12

样例输出 #2

3

提示

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] .


思路

题目的意思就是:

求有多少对(i,j)满足i=1jai=km (m0)

显然想到,求区间和需要用到前缀和,所以题目还可以写成:

求有多少对(i,j)满足 sumjsumi1=km(m0)

所以不难推理出,要想求出(i,j),只需提前求出可能的km,然后枚举j,看看数组中是否存在i1,使得sumi1=sumj+km。复杂度近似于O(nlogn)

最后的最后,要特判k=±1的情况,我在这里卡了30min

代码实现

// Problem: [ABC268D] Unique Username
// URL: https://www.luogu.com.cn/problem/AT_abc268_d
// Memory Limit: 1 GB
// Time Limit: 2000 ms
//
// Powered by CP Editor (https://cpeditor.org)
#include<bits/stdc++.h>
using namespace std;
long long a[100005];
long long s[100];
long long sum[100005];
map<long long,int> m;
int main()
{
ios::sync_with_stdio(false);
long long n,k;
cin>>n>>k;
for(int i=1;i<=n;i++)
{
cin>>a[i];
sum[i]=sum[i-1]+a[i];
}
int cnt=1;
for(long long i=1;cnt<=60;cnt++,i*=k)
{
if(abs(i)>1e14)
{
break;
}
s[cnt]=i;
}
m[0]=1;
long long ans=0;
for(int i=1;i<=n;i++)
{
if(k==1) ans+=m[sum[i]-1];
else if(k==-1) ans+=m[sum[i]-1]+m[sum[i]+1];
else
{
for(int j=1;j<=cnt;j++)
{
ans+=m[sum[i]-s[j]];
// cout<<ans<<" "<<sum[i]-s[j]<<endl;
}
}
m[sum[i]]++;
}
cout<<ans<<endl;
return 0;
}
posted @   j1hx  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话
点击右上角即可分享
微信分享提示