其他分享
首页 > 其他分享> > 2019牛客暑期多校训练营(第十场)Han Xin and His Troops——扩展中国剩余定理

2019牛客暑期多校训练营(第十场)Han Xin and His Troops——扩展中国剩余定理

作者:互联网

题意

求解 $n$ 个模方程 $x \equiv a (mod \ b)$,不保证模数互素($1 \leq n \leq 100$,$0 \leq b < a< 10^5$).

分析

套扩展中国剩余定理的模板,

然而__int128都会爆(好像也可以改成不会爆的),

不管,直接扔给队友改成Python版。

def gcd(a,b):
    if b==0:
        return a
    else :
        return gcd(b,a%b)
 
def exgcd(a,b):
    if b == 0:
        return 1,0
    else:
        y,x = exgcd(b, a%b)
        y = y - (a//b)*x
        return x,y
 
def inv(a,b):
    x,y = exgcd(a,b)
    while x<0 :
        x = b+x
    return x,y
 
MAXN = int(1e6+10)
C = [0]*110
M = [0]*110
str = input().split(" ")
k = int(str[0])
lim = int(str[1])
for i in range(1,k+1):
    str = input().split(" ")
    M[i] = int(str[0])
    C[i] = int(str[1])
flag = True
for i in range(2,k+1):
    M1 = M[i-1]
    M2 = M[i]
    C2 = C[i]
    C1 = C[i-1]
    T = gcd(M1,M2)
    if (C2-C1)%T != 0:
        flag = False
        break
    M[i] = (M1*M2)//T
    x,y = inv(M1//T,M2//T)
    C[i] = (x * (C2 - C1) // T ) % (M2 // T) * M1 +C1
    C[i] = (C[i] % M[i] + M[i]) % M[i]
 
if flag:
    if C[k] > lim :
        print("he was probably lying")
    else :
        print(C[k])
else :
    print("he was definitely lying")

 

标签:His,return,Troops,Han,exgcd,else,leq,print,def
来源: https://www.cnblogs.com/lfri/p/11372193.html