「杂题乱刷2」CF402D Upgrading Array

题目链接

CF402D Upgrading Array (luogu)

CF402D Upgrading Array (codeforces)

解题思路

首先你会发现你一旦在第 \(i\) 个位置上做了一次操作后,那么你之后所有在第 \(j(i \le j)\) 个位置做的操作都是无效的,因为此时该序列前 \(i\) 个数的的公因数为 \(1\)

因此有个很显然的结论就是操作从后往前做是最优的

然后我们只做对答案有贡献的操作,有贡献指的是做了这个操作后的答案大于等于原本不做这个操作的的答案或者说是这个操作区间的最大公因数的价值小于 \(0\)

于是根据以上方式进行操作即可,时间复杂度 \(O(n \sqrt V )\),其中 \(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;
}
posted @ 2024-07-05 23:07  wangmarui  阅读(3)  评论(0编辑  收藏  举报