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;
}






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值