CF 483B. Friends and Presents 数学 (二分) 难度:1

B. Friends and Presents
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
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.

Input

The only line contains four positive integers cnt1, cnt2, xy (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 xy are prime.

Output

Print a single integer — the answer to the problem.

Sample test(s)
input
3 1 2 3
output
5
input
1 3 2 3
output
4
感想:其实直接二分就行了,但是我分类了好一会儿,直接算的
思路:
分成四种情况,1 不能被x,y整除(a) 2 不能被x整除(b) 3 不能被x整除(c) 4 同时能被x,y整除
那么就需要满足
a+b>=cnt2
a+c>=cnt1
a+b+c>=cnt1+cnt2
于是算来算去就算出来了,还是二分好用
 
#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
",ans);
    return 0;
}

  

 
原文地址:https://www.cnblogs.com/xuesu/p/4065212.html