题意:给出长度为 n 的数组 A 和一个整数 g ,问有多少个长度不小于2的子数组(下标连续)满足 “至多修改其中的一个数,使得数组的最大公约数等于g”。
思路: 将数组处理为新的01数组,如果数组元素和g的最大公约数等于g,标记为1,否则标记为0。问题转化为求有多少个长度不小于2的子数组最多包含一个零。
接下来分两步处理:
(1)统计0参与的贡献
单个0的贡献 = 右边紧邻连续1的最大长度 + 左边紧邻连续1的最大长度*(右边紧邻连续1的最大长度 +1)。,累加求和得到 sum1。
(2)统计仅有1参与的贡献
对于每个长度不小于2的连续“1”片段,求其贡献,累加求和得sum2。
ans = sum1 + sum2
代码:
#include <bits/stdc++.h>
#define int long long
using namespace std;
int n,g;
int a[100005];
int d[100005];
int pre[100005];
int pos[100005];
signed main()
{
//freopen("in.txt","r",stdin);
cin >> n >> g;
for(int i = 1; i <= n; i++) cin >> a[i];
for(int i = 1; i <= n; i++) d[i] = (__gcd(a[i],g)== g);
//for(int i = 1; i <= n; i++) cout << d[i] << " " ; cout << endl;
for(int i = 1; i <= n; i++){
if(d[i] == 1) pre[i] = pre[i-1]+1;
else pre[i] = 0;
}
for(int i = n; i >= 1; i--){
if(d[i] == 1) pos[i] = pos[i+1]+1;
else pos[i] = 0;
}
int ans = 0;
for(int i = 1; i <= n; i++){
if(d[i] == 0)ans = ans + pos[i+1] + pre[i-1]*(pos[i+1]+1);
}
for(int i = 1; i <= n; i++){
if(d[i] == 1 && d[i+1] == 0 && pre[i] >= 2){
int len = pre[i];
ans = ans + len * (len + 1) / 2 - len;
}
}
cout << ans << endl;
return 0;
}