HDU 3579 扩展中国剩余定理

来源:互联网 发布:薛之谦和李雨桐 知乎 编辑:程序博客网 时间:2024/05/22 00:51

唉,对于这类题目,其实我觉的就是模版问题

One day I was shopping in the supermarket. There was a cashier counting coins seriously when a little kid running and singing "门前大桥下游过一群鸭,快来快来 数一数,二四六七八". And then the cashier put the counted coins back morosely and count again... 
Hello Kiki is such a lovely girl that she loves doing counting in a different way. For example, when she is counting X coins, she count them N times. Each time she divide the coins into several same sized groups and write down the group size Mi and the number of the remaining coins Ai on her note. 
One day Kiki's father found her note and he wanted to know how much coins Kiki was counting.
Input
The first line is T indicating the number of test cases. 
Each case contains N on the first line, Mi(1 <= i <= N) on the second line, and corresponding Ai(1 <= i <= N) on the third line. 
All numbers in the input and output are integers. 
1 <= T <= 100, 1 <= N <= 6, 1 <= Mi <= 50, 0 <= Ai < Mi
Output
For each case output the least positive integer X which Kiki was counting in the sample output format. If there is no solution then output -1. 
Sample Input
2214 575 56519 54 40 24 8011 2 36 20 76
Sample Output
Case 1: 341Case 2: 5996

题目看完 ,再看下数据,发现就是中国剩余定理的扩展;

模版性的问题;

对于这种题,我觉得需要加强对模版的认识,对于模版 我们需要输进去什么,需要输出什么,要有中想法。

看代码,代码不需要完全懂,我认为;

会用就行;

#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>using namespace std;typedef long long LL;int n;  int times;    const int MAXN = 1010;  LL A[MAXN], r[MAXN];    LL lcm;    LL gcd(LL a, LL b)  //欧几里得{      return b == 0? a : gcd(b, a%b);  }    void ex_gcd(LL a, LL b, LL &d, LL &x, LL &y) // 扩展欧几里得  {      if(!b) { d = a; x = 1; y = 0;}      else { ex_gcd(b, a%b, d, y, x); y -= x*(a/b);}  }    void read_case()  // 数据输入{      scanf("%d", &n);      lcm = 1;      for(int i = 1; i <= n; i++)      {          scanf("%lld", &A[i]);          lcm = lcm / gcd(lcm, A[i]) * A[i];      }      for(int i = 1; i <= n; i++) scanf("%lld", &r[i]);  }    void solve()  //关键的代码{      read_case();      printf("Case %d: ", ++times);      LL a, b, c, d, x, y;      for(int i = 2; i <= n; i++)            // 这是模版的关键;我们需要了解的是我们需要输入的数组是什么?    {          a = A[1], b = A[i], c = r[i]-r[1];  // 碰到其他的地方我们怎么再次利用?        ex_gcd(a, b, d, x, y);          if(c % d) { printf("-1\n"); return ;}          LL b1 = b / d;          x *= c / d;          x = (x%b1 + b1) % b1;          r[1] = A[1]*x + r[1];          A[1] = A[1]*(A[i] / d);      }      if(r[1] == 0) printf("%lld\n", lcm);      else printf("%lld\n", r[1]);  }    int main()  {      int T;      times = 0;      scanf("%d", &T);      while(T--)      {          solve();      }      system("pause");    return 0;  }