天天看點

Codeforces 483B Friends and Presents (二分+數論基礎知識)

題目連結:http://codeforces.com/problemset/problem/483/B

#include<bits/stdc++.h>
using namespace std;

#define debug puts("YES");
#define rep(x,y,z) for(int (x)=(y);(x)<(z);(x)++)
#define ll long long

#define lrt int l,int r,int rt
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define root l,r,rt
#define mst(a,b) memset((a),(b),sizeof(a))
const int  maxn =1e3+5;
const int mod=9999991;
const int ub=1e6;
ll powmod(ll x,ll y){ll t; for(t=1;y;y>>=1,x=x*x%mod) if(y&1) t=t*x%mod; return t;}
ll gcd(ll x,ll y){return y?gcd(y,x%y):x;}

/*
題意明顯要二分,
關鍵是确定一個答案是否可行,
在去除了x數的其他數中,不能少于n,
在去除了y數的其他數中,不能少于m。

當然,去除不能選擇的數(公倍數)之後的數字總和
不能少于n+m.

*/

ll n,m,x,y;
bool judge(ll t)
{
    if(t-t/x<n) return false;
    if(t-t/y<m) return false;
    ll lcm=x/gcd(x,y)*y;
    if(t-t/lcm<n+m) return false;
    return true;
}

int main()
{
    scanf("%lld%lld%lld%lld",&n,&m,&x,&y);
    ll r=2e9+10,l=n+m,ans;
    while(l<r)
    {
        ll mid=l+r>>1;
        if(judge(mid)) {ans=mid;r=mid;}
        else l=mid+1;
    }
    printf("%lld\n",ans);
    return 0;
}
           

繼續閱讀