codeforce C. Success Rate
2017-05-08 19:05
246 查看
写完这道题目才发现自己对二分的理解太浅了 这题是典型的利用二分“假定一个问题可行并求最优解”
二分是通过不断缩小区间来缩小解的范围,最终得出解的算法 我们定义一个c(x) 表示判断函数
如果对任意y>=x 当x满足条件的时候 y也满足条件 那么我们就一个不断缩小区间范围来确定最后的解
好扯了这么多犊子 来说下这道题目。。
我们的目的是对A,B 有 (x+A)/(y+B) == (p/q) 其中A<=B
那么可以转换为 A+x=k*p B+y=k*q;
既 A=k*p-x, B=k*q-y;(A>=0,B>=0)
这里可以验证 对任意k >= x 当x满足条件的时候 k也满足条件(自己模拟一下就知道了)
ok 二分开搞
二分是通过不断缩小区间来缩小解的范围,最终得出解的算法 我们定义一个c(x) 表示判断函数
如果对任意y>=x 当x满足条件的时候 y也满足条件 那么我们就一个不断缩小区间范围来确定最后的解
好扯了这么多犊子 来说下这道题目。。
我们的目的是对A,B 有 (x+A)/(y+B) == (p/q) 其中A<=B
那么可以转换为 A+x=k*p B+y=k*q;
既 A=k*p-x, B=k*q-y;(A>=0,B>=0)
这里可以验证 对任意k >= x 当x满足条件的时候 k也满足条件(自己模拟一下就知道了)
ok 二分开搞
#include <iostream> #include <cstdio> #include <cstring> #include <vector> #include <map> #include <stack> #include <algorithm> #include <queue> #include <string> #include <cmath> using namespace std; const int inf=1000000000; int main() { int t; cin>>t; long long int x,y,p,q; while(t--) { cin>>x>>y>>p>>q; long long int temp=-1; long long int l=1; long long int r=inf; while(l <= r) { long long int mid=(l+r)/2; long long int A=mid*p-x; long long int B=mid*q-y; if(A>=0 && B>=0 && A<=B) { temp=mid; r=mid-1; } else l=mid+1; } if(temp==-1) cout<<"-1"<<endl; else cout<<temp*q-y<<endl; } return 0; }
相关文章推荐
- Codeforces Round#412 C Success Rate
- Success Rate CodeForces - 807C 二分答案
- 【数学】codeforces A. Success Rate
- codeforce 583C GCD
- codeforce C. Ray Tracing(扩展欧几里得|模拟)
- Codeforce 632E(背包变形)
- Error : An error occurred while creating the WebJob schedule: Response status code does not indicate success: 409 (Conflict).
- Codeforce 731A. Night at the Museum
- codeforce-343D:Water Tree(线段树+脑洞)
- codeforce 66C. Petya and File System(MAP)
- codeforce 298 A Snow Footprints
- codeforce 247 div.2 B
- codeforce 580D Kefa and Dishes (状压DP)
- Codeforce 729B. Spotlights
- codeforce 381 div2
- Codeforce Round #438 C.Bus(贪心)
- (540A)codeforce
- CodeForce#190 Div1
- codeforce #387 D. Winter Is Coming
- codeforce C. Valera and Elections (DFS)