1 second
256 megabytes
standard input
standard output
You have two friends. You want to present each of them several positive integers. You want to present cnt1 numbers to the first friend and cnt2 numbers to the second friend. Moreover, you want all presented numbers to be distinct, that also means that no number should be presented to both friends.
In addition, the first friend does not like the numbers that are divisible without remainder by prime number x. The second one does not like the numbers that are divisible without remainder by prime number y. Of course, you're not going to present your friends numbers they don't like.
Your task is to find such minimum number v, that you can form presents using numbers from a set 1, 2, ..., v. Of course you may choose not to present some numbers at all.
A positive integer number greater than 1 is called prime if it has no positive divisors other than 1 and itself.
The only line contains four positive integers cnt1, cnt2, x, y (1 ≤ cnt1, cnt2 < 10^9; cnt1 + cnt2 ≤ 10^9; 2 ≤ x < y ≤ 3·10^4) — the numbers that are described in the statement. It is guaranteed that numbers x, y are prime.
Print a single integer — the answer to the problem.
3 1 2 3
5
1 3 2 3
4
#include<cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
typedef long long ll;
ll x,y,cnt1,cnt2;
ll gcd(ll a,ll b){
if(b==0)return a;
return gcd(b,a%b);
}
ll pos(ll a){
if(a>=0)return a;
return 0;
}
int main(){
scanf("%I64d%I64d%I64d%I64d",&cnt1,&cnt2,&x,&y);
ll d=gcd(x,y);
ll lcm=x*y/d;
ll na=lcm-lcm/x-lcm/y+1;
ll nb=lcm/x-1;
ll nc=lcm/y-1;
ll sumn=na+nb+nc;
ll t=(cnt1+cnt2)/sumn;
t=max(t,cnt2/(na+nb));
t=max(t,cnt1/(na+nc));
ll ta=na*t;
ll tb=nb*t;
ll tc=nc*t;
ll ans=lcm*t;
if((pos(cnt2-tb)+pos(cnt1-tc))<=ta)ans--;
else {
ll r=0x7fffffff;
ll r0=pos(cnt2-tb)+pos(cnt1-tc)-ta;
if(r0>=0&&cnt2>=tb&&cnt1>=tc)r=min(r,r0); ll r1=x*(cnt1-tc-ta)/(x-1);
ll tr11=cnt1-tc-ta+(r1/x-1);
if(tr11/x==r1/x-1)r1=min(r1,tr11);
r1=max(r1,x*(cnt2-tb));
if(cnt1>=tc+ta)r=min(r,r1);
ll r2=y*(cnt2-tb-ta)/(y-1);
ll tr2=cnt2-tb-ta+(r2/y-1);
if(tr2/y==r2/y-1)r2=min(r2,tr2);
r2=max(r2,y*(cnt1-tc));
if(cnt2>=tb+ta)r=min(r,r2);
ans+=r;
}
printf("%I64d\n",ans);
return 0;
}