fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. // GCD and LCM
  5. int gcd(int a, int b) {
  6. return b == 0 ? a : gcd(b, a % b);
  7. }
  8. int lcm(int a, int b) {
  9. return (a / gcd(a, b)) * b;
  10. }
  11.  
  12. // Checks if it's possible to satisfy A and B with N numbers
  13. bool isEnough(int N, int Num1, int Num2, int X, int Y) {
  14. int L = lcm(X, Y);
  15.  
  16. int onlyX = N / X - N / L; // divisible by X only (usable for B)
  17. int onlyY = N / Y - N / L; // divisible by Y only (usable for A)
  18. int neither = N - (N / X + N / Y - N / L); // not divisible by X or Y
  19.  
  20. int needA = max(0, Num1 - onlyY); // A needs more from neither
  21. int needB = max(0, Num2 - onlyX); // B needs more from neither
  22.  
  23. return (needA + needB) <= neither;
  24. }
  25.  
  26. // Binary search to find the minimum N
  27. int happyPeople(int Num1, int Num2, int X, int Y) {
  28. int low = 1, high = 2000000000, ans = -1;
  29.  
  30. while (low <= high) {
  31. int mid = low + (high - low) / 2;
  32.  
  33. if (isEnough(mid, Num1, Num2, X, Y)) {
  34. ans = mid;
  35. high = mid - 1; // Try smaller N
  36. } else {
  37. low = mid + 1;
  38. }
  39. }
  40.  
  41. return ans;
  42. }
  43.  
  44. int main() {
  45. int Num1, Num2, X, Y;
  46. cin >> Num1 >> Num2 >> X >> Y;
  47. cout << happyPeople(Num1, Num2, X, Y) << endl;
  48. return 0;
  49. }
Success #stdin #stdout 0s 5320KB
stdin
10 5 7 11
stdout
15