zoukankan      html  css  js  c++  java
  • Kattis之旅——Chinese Remainder

    Input

    The first line of input consists of an integers T where 1≤T≤1000, the number of test cases. Then follow T lines, each containing four integers a, n, b, m satisfying 1≤n,m≤10e9, 0≤a<n, 0≤b<m. Also, you may assume gcd(n,m)=1.
    Output

    For each test case, output two integers x, K, where K=n*m and 0≤x<K, giving the solution x(mod K) to the equations x=a(mod n),x=b(mod m).

    Sample Input 1 Sample Output 1
    2
    1 2 2 3
    151 783 57 278
    
    5 6
    31471 217674
    

    感谢Pursuit_大神的一波支援。

    由 ( x ≡ a )%n 以及  (x≡ b)%m这两个同余方程。可以联立得出一个二元一次方程—— k0*m+k1*(-n) = a-b。

    然后就是解这个二元一次方程,得出最优解。对n*m取余。

    直接上扩展欧几里德就好。

    //Asimple
    #include <bits/stdc++.h>
    using namespace std;
    typedef long long ll;
    ll n, m, a, b;
    
    void ex_gcd( ll a  , ll b , ll &g , ll &x , ll &y ) {
        
        if( b == 0 ) {
            x = 1 ; y = 0 ;     
            g = a ; 
        }
        ex_gcd( b , a%b , g , y , x ) ; 
        y-= x*(a/b); 
    }
    
    void slove(){
        ll x , y , g ; 
        ex_gcd( m , -n , g , x , y ) ;
        x =( x*(a-b)/g %(-n /g ) - n/g )%(-n/g); 
        printf( "%lld %lld
    " , ((x * m + b)%(n*m)+ n*m )%(n*m) , n*m )    ; 
    }
    
    void input(){
        int t ; 
        scanf( "%d" , &t ) ; 
        while( t-- ) {
            scanf( "%lld%lld%lld%lld" , &a , &n , &b , &m ) ; 
            slove( ) ; 
        }
    }
    
    
    int main(){
        input();
        return 0;
    }
  • 相关阅读:
    node读写文件
    idea下建立bootstrap项目
    webpack
    Bootstrap-javascript插件
    Bootstrap-other内置组件
    Centos 修改当前路径显示为全路径
    深入理解java虚拟机(4)类加载的过程
    深入理解java虚拟机(3)垃圾收集器与内存分配策略
    深入理解java虚拟机(2)
    Scala学习笔记(3)
  • 原文地址:https://www.cnblogs.com/Asimple/p/6782704.html
Copyright © 2011-2022 走看看