传送门
题目描述
给你一个序列 a i a_{i} ai和一个代价 p p p,任意两个相邻点之间的可以连一条代价为 p p p的边,如果一个区间内的 g c d gcd gcd为这个区间内的最小值的话,那么这个区间的两个端点之间可以连一条代价为这个最小值的边,最你最小生成树为多少
分析
首先最坏情况下的答案是
(
n
−
1
)
∗
p
(n - 1) * p
(n−1)∗p,然后我们就要尽量用代价小的边去代替
我们可以用优先队列存下每个点的权值和坐标,然后求以这个点为最小值,最大的能保证每个数都是这个数的倍数的一个区间是多少,然后进行边的替换即可
代码
#pragma GCC optimize(3)
#include <bits/stdc++.h>
#define debug(x) cout<<#x<<":"<<x<<endl;
#define dl(x) printf("%lld\n",x);
#define di(x) printf("%d\n",x);
#define _CRT_SECURE_NO_WARNINGS
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define SZ(x) ((int)(x).size())
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PII;
typedef vector<int> VI;
const int INF = 0x3f3f3f3f;
const int N = 2e5 + 10;
const ll mod= 1000000007;
const double eps = 1e-9;
const double PI = acos(-1);
template<typename T>inline void read(T &a){char c=getchar();T x=0,f=1;while(!isdigit(c)){if(c=='-')f=-1;c=getchar();}
while(isdigit(c)){x=(x<<1)+(x<<3)+c-'0';c=getchar();}a=f*x;}
int gcd(int a,int b){return (b>0)?gcd(b,a%b):a;}
priority_queue<PII,vector<PII>,greater<PII> >q;
int n,a[N],p;
bool st[N];
int main(){
int T;
read(T);
while(T--){
while(q.size()) q.pop();
read(n),read(p);
ll ans = 1ll * (1ll * n - 1) * p;
for(int i = 1;i <= n;i++){
read(a[i]);
q.push({a[i],i});
st[i] = 0;
}
while(q.size()){
auto t = q.top();
q.pop();
if(t.fi >= p) break;
int k = t.se,u = t.fi;
int r = k,l = k;
while(r + 1 <= n && a[r + 1] % u == 0 && st[r] == 0) st[r] = 1,r++;
while(l - 1 >= 1 && a[l - 1] % u == 0 && st[l - 1] == 0) l--,st[l] = 1;
ans = ans - 1ll * (r - l) * p + 1ll * (r - l) * u;
}
dl(ans);
}
}
/**
* ┏┓ ┏┓+ +
* ┏┛┻━━━┛┻┓ + +
* ┃ ┃
* ┃ ━ ┃ ++ + + +
* ████━████+
* ◥██◤ ◥██◤ +
* ┃ ┻ ┃
* ┃ ┃ + +
* ┗━┓ ┏━┛
* ┃ ┃ + + + +Code is far away from
* ┃ ┃ + bug with the animal protecting
* ┃ ┗━━━┓ 神兽保佑,代码无bug
* ┃ ┣┓
* ┃ ┏┛
* ┗┓┓┏━┳┓┏┛ + + + +
* ┃┫┫ ┃┫┫
* ┗┻┛ ┗┻┛+ + + +
*/