sgu 106 The equation

本文详细介绍了如何通过扩展欧几里得算法求解线性方程 ax + by + c = 0 在给定区间 [x1, x2] 和 [y1, y2] 内的整数解数量。通过分析基本解和区间合并策略,实现高效计算。包括边界条件处理,如 a 或 b 为零的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

106. The equation

time limit per test: 0.5 sec.
memory limit per test: 4096 KB

There is an equation ax + by + c = 0. Given a,b,c,x1,x2,y1,y2 you must determine, how many integer roots of this equation are satisfy to the following conditions : x1<=x<=x2,   y1<=y<=y2. Integer root of this equation is a pair of integer numbers (x,y).

Input

Input contains integer numbers a,b,c,x1,x2,y1,y2 delimited by spaces and line breaks. All numbers are not greater than 108 by absolute value.

Output

Write answer to the output.

Sample Input

1 1 -3
0 4
0 4

Sample Output

4

WA无数次啊,我好水啊。。。。
先扩展欧几里德解出基本解,然后做判断。
这里各种错。(一定要思考清楚再敲啊)
基本思路就是求得一个符合条件的区间,然后合并他们。
记得要对a,b做等0的讨论。

附上好不容易AC的代码:
#include<iostream>
#include<cstring>
#include<cstdio>
#include<set>
#include<algorithm>
#include<vector>
#include<cstdlib>

#define inf 0xfffffff
#define CLR(a,b) memset((a),(b),sizeof((a)))
#define int long long

using namespace std;
int const nMax = 100010;
typedef int LL;
typedef pair<LL,LL> pij;

int extgcd(int a,int b,int &x,int &y){
    if(b==0){
        x=1,y=0;
        return a;
    }
    int d=extgcd(b,a%b,x,y);
    int t=y;
    y=x-a/b*y;
    x=t;
    return d;
}

int x1,x2,y1,y2;
int mini,maxi;

int up(int R,int d){
    if(R>=0)    return R/d;
    return (R+1)/d-1;
}
int lo(int L,int d){
    if(L<=0) return L/d;
    return (L-1)/d+1;
}
void relax(int L,int R,int d){
    if(d<0)L=-L,R=-R,d=-d,swap(R,L);
    mini=max(mini,lo(L,d));
    maxi=min(maxi,up(R,d));
}

int equ(int a,int b,int n){
    int x,y;
    int d=extgcd(a,b,x,y);
    if(n%d)return 0;
    x=x*(n/d);
    y=y*(n/d);
    mini=-inf,maxi=inf;
    relax(x1-x,x2-x,b/d);
    relax(y1-y,y2-y,-a/d);
    int ans=maxi-mini+1;
    if(ans<0)ans=0;
    return ans;
}

int a,b,c;
main()
{
   // cout<<-3/2<<endl;
    cin>>a>>b>>c>>x1>>x2>>y1>>y2;
    int ans=0;
    if(a==0&&b){
        if(c%b!=0){
            cout<<0<<endl;
        }else{
            int y=c/b;
            y=-y;
            if(y>=y1&&y<=y2)cout<<1<<endl;
            else cout<<0<<endl;
        }
    }else if(a&&b==0){
        if(c%a!=0){
            cout<<0<<endl;
        }else {
            int x=c/a;
            x=-x;
            if(x>=x1&&x<=x2)cout<<1<<endl;
            else cout<<0<<endl;
        }
    }else if(a==0&&b==0){
        if(c==0){
            cout<<(x2-x1+1)*(y2-y1+1)<<endl;
        }else cout<<0<<endl;
    }else{
        ans=equ(a,b,-c);
        if(ans<0)ans=0;
        cout<<ans<<endl;
    }
    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值