zoukankan      html  css  js  c++  java
  • HDU 4993 Revenge of ex-Euclid(BestCoder Round #9)

    Problem Description:
    In arithmetic and computer programming, the extended Euclidean algorithm is an extension to the Euclidean algorithm, which computes, besides the greatest common divisor of integers a and b, the coefficients of Bézout's identity, that is integers x and y such that ax + by = gcd(a, b).
    ---Wikipedia

    Today, ex-Euclid takes revenge on you. You need to calculate how many distinct positive pairs of (x, y) such as ax + by = c for given a, b and c.
     
    Input:
    The first line contains a single integer T, indicating the number of test cases. 

    Each test case only contains three integers a, b and c.

    [Technical Specification]
    1. 1 <= T <= 100
    2. 1 <= a, b, c <= 1 000 000
     
    Output:
    For each test case, output the number of valid pairs.
     
    Sample Input:
    2
    1 2 3
    1 1 4
     
    Sample Output:
    1
    3

    题意:给出a,b,c,输出满足ax+by==c的(x,y)的个数。

    利用扩展欧几里得找出该线性方程的其中一个解(x0,y0),然后可以推广得到其他的解:

    a*x0+b*y0=c;

    a*(x0+b)+b*(y0-a)=c;

    a*(x0+2*b)+b*(y0-2*a)=c;

    ......

    因为该题要求所有正整数解的个数,所以需要通过我们求出的这一个解,寻找边界条件,进而得到解的个数。

    #include<stdio.h>
    #include<string.h>
    #include<queue>
    #include<math.h>
    #include<stdlib.h>
    #include<algorithm>
    using namespace std;
    
    const int N=1e6+10;
    const int INF=0x3f3f3f3f;
    const int MOD=1e9+7;
    
    typedef long long LL;
    
    int x, y;
    
    int Ex_gcd(int a, int b)
    {
        int t, z;
    
        if (b == 0)
        {
            x = 1;
            y = 0;
    
            return a;
        }
    
        z = Ex_gcd(b, a%b);
    
        t = x;
        x = y;
        y = t-(a/b)*y;
    
        return z;
    }
    
    int main ()
    {
        int T, a, b, c, ans, z;
    
        scanf("%d", &T);
    
        while (T--)
        {
            scanf("%d%d%d", &a, &b, &c);
    
            ans = 0;
    
            z = Ex_gcd(a, b); ///得到公约数
    
            a /= z; b /= z; c /= z;
    
            z = Ex_gcd(a, b);
    
            x *= c; y *= c; ///找到满足方程的最小解
    
            while (x - b > 0) ///找到最小的>0的x
            {
                x -= b;
                y += a;
            }
            ///那么此时y肯定>0
            while (y > 0) ///每次让y-a,a+b,那么此时x肯定满足条件,当y<=0时就不满足条件了
            {
                if (x > 0) ans++; ///x可能在一开始是负数
    
                x += b;
                y -= a;
            }
    
            printf("%d
    ", ans);
        }
    
        return 0;
    }
  • 相关阅读:
    一、【注解】Spring注解@ComponentScan
    一致性Hash算法
    垃圾回收器搭配和调优
    JVM的逃逸分析
    简单理解垃圾回收
    类加载机制和双亲委派模型
    VMWare15下安装CentOS7
    HBase协处理器(1)
    依赖注入的三种方式
    Javascript-设计模式_装饰者模式
  • 原文地址:https://www.cnblogs.com/syhandll/p/4920842.html
Copyright © 2011-2022 走看看