码迷,mamicode.com
首页 > 其他好文 > 详细

1213 解的个数[一中数论随堂练]

时间:2016-07-10 21:51:59      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:

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

 

1213 解的个数[一中数论随堂练]

标签:

原文地址:http://www.cnblogs.com/shenben/p/5658562.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!