https://codeforces.com/contest/1513/problem/D
思路:
开始直接On双指针扫过去做了。想的不对。因为一旦区间内出现了1,那么答案就知道了。
这个角度可以考虑到,如果其最小值为1,那么答案最小,从而考虑到要从值来枚举。
对于每个值,我要处理出他的能覆盖的区间,就是最终答案。
只要保证不重复扫,那么可以做到扫区间的总复杂度是On。
那么模拟出每个值他能到达的最远位置再计算就好了。
#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=2e5+1000;
typedef long long LL;
inline LL read(){LL x=0,f=1;char ch=getchar(); while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}while (isdigit(ch)){x=x*10+ch-48;ch=getchar();}
return x*f;}
struct P{
LL pos,val;
}a[maxn];
LL pre[maxn];
bool cmp(P A,P B){
return A.val<B.val;
}
bool vis[maxn];
int main(void){
cin.tie(0);std::ios::sync_with_stdio(false);
LL t;cin>>t;
while(t--){
LL n,p;cin>>n>>p;
for(LL i=0;i<n+10;i++) vis[i]=0;
for(LL i=1;i<=n;i++) {
cin>>pre[i];a[i].val=pre[i];a[i].pos=i;
}
sort(a+1,a+1+n,cmp);
LL ans=0;LL edge=n-1;
for(LL i=1;i<=n;i++){
LL val=a[i].val;
LL pos=a[i].pos;
LL cnt=0;
if(val>=p) break;
if(vis[pos]) continue;///保证扫总长为n的区间
for(LL j=pos;j>=1;j--){
if(pre[j]%val!=0) break;///不满足先停止
if(vis[j]) {cnt++;break;}
vis[j]=1;
cnt++;
}
for(LL j=pos+1;j<=n;j++){
if(pre[j]%val!=0) break;
if(vis[j]) {cnt++;break;}
vis[j]=1;
cnt++;
}
if(cnt==1) vis[pos]=0;
else ans+=(cnt-1)*val,edge-=(cnt-1);
}
ans+=edge*p;
cout<<ans<<"\n";
}
return 0;
}