sgu 106(扩展欧几里得)

题意:给出一个式子 ax+by+c=0,求x在z1~x2内y在y1~y2内有几组数据;

分析:本题a,b,c均有可能为0,所以要先看a,b,c有为0时的情况,此外,还要判断x1是否小于x2,y1是否小于y2。剩下的就是用扩展欧几里得来计算是否有解,有几个解。

代码:

#include <set>
#include <map>
#include <stack>
#include <queue>
#include <math.h>
#include <vector>
#include <utility>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <functional>

using namespace std;
long long gcd(long long a,long long b){
    if(b==0)return a;
    return gcd(b,a%b);
}
void _gcd(long long a,long long b,long long &x,long long &y){
    if(b==1){
        x=1;
        y=1-a;
    }
    else {
        long long x1,y1;
        _gcd(b,a%b,x1,y1);
        x=y1;
        y=x1-(a/b)*x;
    }
}
int main(){
    long long a,b,c,x1,x2,y1,y2;
    cin>>a>>b>>c>>x1>>x2>>y1>>y2;
        c=-c;
        if(c<0){
            a=-a;
            b=-b;
            c=-c;
        }
        if(a<0){
            a=-a;swap(x1,x2);
            x1=-x1;
            x2=-x2;
        }
        if(b<0){
            b=-b;swap(y1,y2);
            y2=-y2;
            y1=-y1;
        }//a<0,b<0,c<0时要分别作一下处理,因为扩展欧几里得中没有负数
        if(x1>x2||y1>y2){
            cout<<0<<endl;
            return 0;
        }
        if(!a||!b){
            if(!a&&!b){
                if(!c)
                cout<<(x2-x1+1)*(y2-y1+1)<<endl;
                else cout<<0<<endl;
            }
            if(!a&&b){
                if(c%b==0){
                    if(c/b-y1>=0&&c/b-y2<=0)
                    cout<<x2-x1+1<<endl;
                    else cout<<0<<endl;
                }
                else{
                    cout<<0<<endl;
                }
            }
            if(a&&!b){
                if(c%a==0){
                    if(c/a-x1>=0&&c/a-x2<=0)
                    cout<<y2-y1+1<<endl;
                    else cout<<0<<endl;
                }
                else{
                    cout<<0<<endl;
                }
            }
            return 0;
        }
        long long g=gcd(a,b);
        a/=g;
        b/=g;
        if(c%g!=0){
            cout<<0<<endl;
            return 0;
        }
        c/=g;
        long long x,y;
        _gcd(abs(a),abs(b),x,y);
        x=x*c;
        y=y*c;
//        cout<<y<<endl;
        long long sum1=floor((double)(x2-x)/(double)b);
        long long sum2=ceil((double)(x1-x)/(double)b);
        long long sum3=floor((double)(y-y1)/(double)(a));
        long long sum4=ceil((double)(y-y2)/(double)(a));
//        cout<<sum1<<" "<<sum2<<endl;
//        cout<<sum3<<" "<<sum4<<endl;
        if(min(sum1,sum3)-max(sum2,sum4)>=0)
        cout<<min(sum1,sum3)-max(sum2,sum4)+1<<endl;
        else cout<<0<<endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值