D. GCD and MST(思维+模拟)

52 篇文章 1 订阅

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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值