Divide by Zero 2021 and Codeforces Round #714 (Div. 2)D. GCD and MST


原题传送门

题面不多赘述。
对于题目给我们的要求,我们思考,其中这个gcd对整体的贡献,由于任意两条相邻边之间存在一条权值恒定的边。也就是说,如果gcd的值大于这个值,它就不作贡献,从而能够对答案产生贡献的当且仅当某一段的gcd小于这个给定的p,我们不妨将每个点的值与其索引绑定,然后排序,只需要考虑所有小于p的点的贡献,对于每个点,它的贡献就是将它前面与其后面最长的一段满足gcd等于该值的所有点连向它,即产生这一段的贡献,如果任意两个点之间的影响范围相交,则可以直接跳出,稍微思考模拟一下即可(易证),但是考虑到这样一次扫描后,所有的点未必连在一个块内,我们只需要依次将对应得点以p得权值加入即可。

//#include<bits/stdc++.h> ----万能头----
#include <iostream>
#include<stdio.h>
#include<string>
#include<algorithm>
#include<string.h>
#include<cstring>
#include<cmath>
#include<queue>
#include<list>
#include<map>
#include<unordered_map>
#include<stack>
using namespace std;
const int p = 1e9+7;
const int N = 2e5+5;
const int maxn = 1e5+10;
const long long INF = 1e18;
#define REP(i,n) for(ll i = 1; i <= n; ++i)
#define REPA(i,j,n) for(ll i = j; i <= n; ++i)
#define RREP(i,n) for(ll i = n; i >= 1; --i)
#define REPR(i,j,n) for(ll i = n; i >= j; --i)
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll,ll> PII;
typedef pair<double,ll> pdi;
ll t, n, m;
ll k;
ll a[N];
bool st[N];
ll gcd(ll a,ll b){
    ll res;
    while(b){
        res = a % b;
        a = b;
        b = res;
    }
    return a;
}


void solve(){
    scanf("%lld%lld",&n,&m);
    for(int i = 1; i <= n; ++i)st[i] = 0;
    for(int i = 1; i <= n; ++i)scanf("%lld",&a[i]);
    vector<PII> q;
    ll ans = 0;
    for(int i = 1; i <= n; ++i)q.push_back({a[i],i});
    sort(q.begin(),q.end());
    for(auto &x : q){
        ll pos = x.second;
        ll now_weight = x.first;
        if(now_weight >= m)break;
        while(pos > 1){
            if(st[pos - 1])break;
            if(a[pos - 1] % now_weight == 0){
                ans += now_weight;
                st[pos - 1] = 1;
                --pos;
            }
            else break;
        }
        pos = x.second;
        while(pos < n){
           if(st[pos])break;
           if(a[pos + 1] % now_weight == 0){
               ans += now_weight;
               st[pos] = 1;
               ++pos;
           }
           else break;
        }
    }
    for(int i = 1; i < n; ++i){
        if(!st[i])ans += m;
    }
    cout<<ans<<'\n';
}

int main() {
    //ios::sync_with_stdio(0);
    //cin.tie(0);
    //cout.tie(0);
#ifdef ACM
    freopen("in.txt","r",stdin);
    freopen("out.txt","w",stdout);
#endif

    scanf("%lld",&t);
    while(t--)

        solve();

    fclose(stdin);
    fclose(stdout);
}






  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值