CodeForces 710D Two Arithmetic Progressions

題目鏈接: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;
}






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章