題目連結
CF402D Upgrading Array (luogu)
CF402D Upgrading Array (codeforces)
解題思路
首先你會發現你一旦在第 \(i\) 個位置上做了一次操作後,那麼你之後所有在第 \(j(i \le j)\) 個位置做的操作都是無效的,因為此時該序列字首的公因數為 \(1\)。
因此有個很顯然的結論就是操作需要從後往前做。
然後我們只做對有貢獻的操作,有貢獻指的是做了這個操作後答案大於等於原本的答案或者說等價於這個操作的區間的最大公因數的價值小於 \(0\)。
於是根據以上方式進行操作即可,時間複雜度 \(O(n \sqrt v )\)。
不過需要注意的是,本題比較卡常,記得在各個地方加上記憶化以加快程式效率。
參考程式碼
點選檢視程式碼
#include<bits/stdc++.h>
using namespace std;
#define map unordered_map
#define re register
#define ll long long
#define forl(i,a,b) for(re ll i=a;i<=b;i++)
#define forr(i,a,b) for(re ll i=a;i>=b;i--)
#define forll(i,a,b,c) for(re ll i=a;i<=b;i+=c)
#define forrr(i,a,b,c) for(re ll i=a;i>=b;i-=c)
#define lc(x) x<<1
#define rc(x) x<<1|1
#define mid ((l+r)>>1)
#define cin(x) scanf("%lld",&x)
#define cout(x) printf("%lld",x)
#define lowbit(x) (x&-x)
#define pb push_back
#define pf push_front
#define IOS ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
#define endl '\n'
#define QwQ return 0;
#define db long double
#define ull unsigned long long
#define lcm(x,y) x/__gcd(x,y)*y
#define Sum(x,y) 1ll*(x+y)*(y-x+1)/2
#define aty cout<<"Yes\n";
#define atn cout<<"No\n";
#define cfy cout<<"YES\n";
#define cfn cout<<"NO\n";
#define xxy cout<<"yes\n";
#define xxn cout<<"no\n";
#define printcf(x) x?cout<<"YES\n":cout<<"NO\n";
#define printat(x) x?cout<<"Yes\n":cout<<"No\n";
#define printxx(x) x?cout<<"yes\n":cout<<"no\n";
#define maxqueue priority_queue<ll>
#define minqueue priority_queue<ll,vector<ll>,greater<ll>>
ll t;
ll n,m,ans=-1e18;
map<ll,ll>mp,mp2;
ll a[100010],b[100010],lst[100010];
ll lst2;
ll gcd[100010];
map<ll,ll>mp3;
bool pdzs(ll a)
{
if(mp3[a])
return mp3[a]-1;
if(a==1)
return 0;
if(a==2)
return 1;
for(ll i=2;i<=sqrt(a);i++)
if(a%i==0)
{
mp3[a]=1;
return 0;
}
mp3[a]=2;
return 1;
}
bool pd[1000010];
long long A[2000010],K;
void work(ll n)
{
for(ll i=2;i<=n;i++)
{
if(pd[i]==0)
A[++K]=i;
for(ll j=1;j<=K && i*A[j]<=n;j++)
{
pd[i*A[j]]=1;
if(i%A[j]==0)
break;
}
}
}
ll f(ll x)
{
ll num=x;
if(mp2[num])
return mp2[num];
ll an=0;
if(pdzs(num))
return mp[num]==0?1:-1;
forl(i,1,K)
if(x%A[i]==0)
{
ll pd=mp[A[i]]==0?1:-1;
while(x%A[i]==0)
x/=A[i],an+=pd;
if(x==1)
return mp2[num]=an;
}
if(pdzs(x))
return mp2[num]=an+(mp[x]==0?1:-1);
return mp2[num]=an;
}
void solve()
{
lst2=1;
cin>>n>>m;
forl(i,1,n)
cin>>a[i],lst[i]=a[i];
gcd[1]=a[1];
forl(i,2,n)
gcd[i]=__gcd(gcd[i-1],a[i]);
forl(i,1,m)
cin>>b[i],mp[b[i]]=1;
ll sum=0;
forl(i,1,n)
sum+=f(a[i]);
// cout<<sum<<endl;
forr(i,n,1)
if(f(gcd[i]/lst2)<0)
sum+=f(gcd[i]/lst2)*-1*i,lst2=gcd[i];
cout<<max(ans,sum)<<endl;
}
int main()
{
work(40000);
IOS;
t=1;
// cin>>t;
while(t--)
solve();
QwQ;
}