zoukankan      html  css  js  c++  java
  • 1213 解的个数[一中数论随堂练]

    1213 解的个数

     

     时间限制: 1 s
     空间限制: 128000 KB
     题目等级 : 黄金 Gold
     
     
    题目描述 Description

    已知整数x,y满足如下面的条件:

    ax+by+c = 0

    p<=x<=q

    r<=y<=s

    求满足这些条件的x,y的个数。

    输入描述 Input Description

    第一行有一个整数nn<=10),表示有n个任务。n<=10

    以下有n行,每行有7个整数,分别为:a,b,c,p,q,r,s。均不超过108。

    输出描述 Output Description

    n行,第i行是第i个任务的解的个数。

    样例输入 Sample Input

    2

    2 3 -7 0 10 0 10

    1 1 1 -10 10 -9 9

    样例输出 Sample Output

    1

    19

    数据范围及提示 Data Size & Hint
     

    分类标签 Tags 点此展开 

     
     
    两种AC代码:
    1、扩展欧几里得算法,需要考虑特殊数据
    #include<iostream>
    #include<algorithm>
    #include<math.h>
    using namespace std;
    typedef long long ll;
    double z[10];
    void exgcd(ll a,ll b,ll &d,ll &x,ll &y){
        if(!b){d=a;x=1;y=0;return;}
        exgcd(b,a%b,d,y,x);y-=x*(a/b);
    }
    int main(){
        ll a,b,c,p,q,r,s,x,y,d,k;
        int n;cin>>n;
        while(n--){
            cin>>a>>b>>c>>p>>q>>r>>s;c=-c;
            if(p>q||r>s||(!a&&!b&&c)){cout<<0<<endl;continue;}
            if(!a||!b){
                if(!a) a=q-p+1;
                else if(c%a==0&&(c/a)<=q&&(c/a)>=p) a=1;
                else a=0;
                if(!b) b=s-r+1;
                else if(c%b==0&&(c/b)<=s&&(c/b)>=r) b=1;
                else b=0;
                cout<<a*b<<endl;
                continue;
            }
            exgcd(a,b,d,x,y);
            if(c%d!=0){cout<<0<<endl;continue;}
            k=c/d;x*=k;y*=k;
            a=a/d;b=b/d;
            z[0]=(q-x)*1.0/b;
            z[1]=(p-x)*1.0/b;
            z[2]=(y-s)*1.0/a;
            z[3]=(y-r)*1.0/a;
            sort(z,z+4);
            a=floor(z[2]);b=ceil(z[1]);
            cout<<a-b+1<<endl;
        }
        return 0;
    }

    2、直接枚举

    #include<cstdio>
    #include<iostream>
    #define ll long long
    using namespace std;
    ll n,a,b,c,p,q,r,l,ans;
    int main(){
        cin>>n; 
        for(int i=1;i<=n;i++){
            cin>>a>>b>>c>>p>>q>>l>>r;
            ans=0;
            if(b==0){
                for(int x=p;x<=q;x++){
                    if(x*a==-c) ans++;
                }
                cout<<ans*(r-l+1)<<endl;
            }
            else{
                for(int x=p;x<=q;x++){
                    if((-c-a*x)%b==0&&(-c-a*x)*1.0/b>=l&&(-c-a*x)*1.0/b<=r) ans++;
                }
                cout<<ans<<endl;
            }
        }
        return 0;
    }
  • 相关阅读:
    TCMalloc 内存分配原理简析
    技术人沟通中的几个常见问题
    不同路径
    Js将字符串转数字的方式
    防抖节流模式
    Location对象
    React生命周期
    fgrep命令
    数据访问对象模式
    保持城市天际线
  • 原文地址:https://www.cnblogs.com/shenben/p/5658562.html
Copyright © 2011-2022 走看看