HDU 1573 解同余模线性方程组

题目意思很直接就是一道裸的解线性同余模方程组的题目

 

 1 #include <cstdio>

 2 #include <cstring>

 3 

 4 using namespace std;

 5 

 6 #define N 15

 7 int r[N] , m[N];

 8 

 9 int ex_gcd(int a , int &x , int b , int &y)

10 {

11     if(b == 0){

12         x = 1 , y = 0;

13         return a;

14     }

15     int ans = ex_gcd(b , x , a%b , y);

16     int t = x;

17     x = y , y = t - (a/b)*y;

18     return ans;

19 }

20 

21 int mod_line(int n , int &t)

22 {

23     int rr = r[0] , x , y;

24     t = m[0];

25     for(int i=1 ; i<n ; i++){

26         int del = r[i] - rr;

27         int g = ex_gcd(t , x , m[i] , y);

28         if(del % g != 0)

29             return -1;

30         int Mod = m[i] / g;

31         x = (((x*del/g)%Mod)+Mod)%Mod;

32 

33         rr = rr + t*x;

34         t = t*m[i] / g; //求二者最小公倍数,更新模项

35         rr %= t;

36     }

37     return rr;

38 }

39 

40 int main()

41 {

42    // freopen("a.in" , "r" , stdin);

43     int T;

44     scanf("%d" , &T);

45     while(T--)

46     {

47         int n , M;

48         scanf("%d%d" , &n , &M);

49         for(int i=0 ; i<M ; i++)

50             scanf("%d" , m+i);

51         for(int i=0 ; i<M ; i++)

52             scanf("%d" , r+i);

53 

54         int t;

55         int r = mod_line(M , t);

56         if(r>n || r == -1) printf("0\n");

57         else{

58             int ans = (n-r)/t + 1;

59             if(r == 0) ans--;

60             printf("%d\n" , ans);

61         }

62     }

63     return 0;

64 }

 

你可能感兴趣的:(HDU)