Arpa has found a list containing n numbers. He calls a list bad if and only if it is not empty and gcd (see notes section for more information) of numbers in the list is 1.
Arpa can perform two types of operations:
- Choose a number and delete it with cost x.
- Choose a number and increase it by 1 with cost y.
Arpa can apply these operations to as many numbers as he wishes, and he is allowed to apply the second operation arbitrarily many times on the same number.
Help Arpa to find the minimum possible cost to make the list good.
First line contains three integers n, x and y (1 ≤ n ≤ 5·105, 1 ≤ x, y ≤ 109) — the number of elements in the list and the integers x and y.
Second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the list.
Print a single integer: the minimum possible cost to make the list good.
4 23 17 1 17 17 16
40
10 6 2 100 49 71 73 66 96 8 60 41 63
10
In example, number 1 must be deleted (with cost 23) and number 16 must increased by 1 (with cost 17).
A gcd (greatest common divisor) of a set of numbers is the maximum integer that divides all integers in the set. Read more about gcd here.
题目大意:
给出N个数,删除一个数的花费是X,改变一个数从num变成num+1的花费是Y,问将整个序列的Gcd改成不是1的最小花费。
思路:
我们知道,Gcd的结果是素数是最好的,所以我们首先筛出素数,1e6内的素数个数约为8w(8e4)个。
然后考虑对应数字是删除还是增添。很显然我们这里可以Dp去做,但是时间复杂度很爆炸,所以考虑X和Y两种操作之间的关系。
①不难想到,如果X<Y的话,我们就不用进行Y操作了。
②所以我们设定move=X/Y表示我们最多对一个数进行增添数字的次数,如果超过了这个次数,我们不如将其删除来的划算。
接下来考虑如何计算结果。首先我们肯定要O(8e4)去枚举答案,接下来考虑,既然我们已经知道了move这个信息,那么对于当前枚举的素数p,我们有一个区间【p,2p】的话,我们肯定能够通过move这个信息找到区间的一个分界点,使得【p~分界点】的数我们都将其删除,使得【分界点~2p】的数字都增添变成2p.
那么这里我们只要枚举出来一个素数p,然后每一次计算之后将区间移动p个长度即可。整体时间复杂度O(Len*LogLen)这里Len表示素数的个数。
那么过程维护一下即可,具体计算过程参考代码。
Ac代码:
#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
#define ll long long int
ll have[3005000];
ll sum[3005000];
int main()
{
ll n,x,y;
while(~scanf("%lld%lld%lld",&n,&x,&y))
{
memset(have,0,sizeof(have));
memset(sum,0,sizeof(sum));
for(ll i=1;i<=n;i++)
{
ll tmp;scanf("%lld",&tmp);
have[tmp]++;sum[tmp]+=tmp;
}
ll ans=1000000000000000000;
for(ll i=1;i<=2000000;i++)have[i]+=have[i-1],sum[i]+=sum[i-1];
ll move=(x/y);
for(ll i=2;i<=1000000;i++)
{
ll now=0;
for(ll j=i;j<=2000000;j+=i)
{
ll fen=max(j-i+1,j-move);
ll Inum=have[j]-have[fen-1];
ll Isum=sum[j]-sum[fen-1];
ll Dnum=have[fen-1]-have[j-i];
now+=Dnum*x;
now+=y*(j*Inum-Isum);
}
ans=min(ans,now);
}
printf("%lld\n",ans);
}
}