题目链接:http://codeforces.com/problemset/problem/710/D
题意:给两条直线,a1 * x + b1 和 a2 * x + b2,问存在多少Y∈[L,R],使得a1 * x + b1 = a2 * y + b2 = Y。而且x,y >= 0。
思路:首先确定x和y的范围[L1,R1] , [L2,R2].根据 L <= a1 * x + b1 <= R 可得。
然后a1 * x + b1 = a2 * y + b2
a1 * x + a2 * (-y) = b2 - b1,用扩展欧几里得可得到一组(x,y)然后把(x,y)调整到第一组满足x∈[L1,R1] , y∈[L2,R2]的解,然后再计算范围内的解即可。
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <stack>
#include <map>
#include <set>
#include <vector>
#include <sstream>
#include <queue>
#include <utility>
using namespace std;
#define rep(i,j,k) for (int i=j;i<=k;i++)
#define Rrep(i,j,k) for (int i=j;i>=k;i--)
#define Clean(x,y) memset(x,y,sizeof(x))
#define LL long long
LL a1,a2,b1,b2,L,R;
LL exgcd( LL a , LL b , LL &x , LL &y )
{
if ( b == 0 )
{
x = 1 , y = 0;
return a;
}
LL r = exgcd( b , a % b , y , x );
y -= x * (a/b);
return r;
}
LL solve()
{
if ( b1 > R || b2 > R ) return 0;//x 或 y取最小值 都比范围大
LL L1 = max( 0LL , ( L - b1 + a1 - 1 ) / a1 );
LL R1 = ( R - b1 ) / a1;
LL L2 = max( 0LL , ( L - b2 + a2 - 1 ) / a2 );
LL R2 = ( R - b2 ) / a2;
if ( L1 > R1 || R1 < 0 || L2 > R2 || R2 < 0 ) return 0;
LL A = a1 , B = a2 , C = b2 - b1;
LL x , y , k;
LL gcd = exgcd(A,B,x,y);
y = -y;//得到一组解,因为方程为 a1 * x + a2 * (-y) = b2 - b1 所以算出来的y要取反
if ( C % gcd ) return 0;
x *= C / gcd , y *= C / gcd;//得到一组任意解
LL addx = B / gcd , addy = A / gcd;
if ( x < L1 )
{
k = ( L1 - x + addx - 1 ) / addx;
x += k * addx;
y += k * addy;
}
if ( x > L1 ) //把x调整到第一组大于L1
{
k = ( x - L1 ) / addx;
x -= k * addx;
y -= k * addy;
}
if ( y > R2 ) return 0;
if ( y < L2 ) //x合法后再调整y
{
k = ( L2 - y + addy - 1 ) / addy;
x += k * addx;
y += k * addy;
}
if ( x >= L1 && x <= R1 && y >= L2 && y <= R2 )
return 1 + min( (R1-x)/addx , (R2-y)/addy );
else return 0;
}
int main()
{
cin>>a1>>b1>>a2>>b2>>L>>R;
cout<<solve();
return 0;
}