LQB-近似 GCD

题意:给出长度为 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;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值