P3868 [TJOI2009]猜数字

原题链接

考察:中国剩余定理+龟速幂(这个用不用均可)

是裸题,记录一下关于中国剩余定理的坑点

  1. 最后相乘有爆long long的可能
  2. 龟速幂要注意b不能为负的问题
 1 #include <iostream>
 2 #include <algorithm>
 3 #include <cstdio>
 4 using namespace std;
 5 typedef long long ll;
 6 const int N = 15;
 7 ll a[N],b[N];
 8 ll exgcd(ll a,ll b,ll& x,ll& y)
 9 {
10     if(!b)
11     {
12         x = 1,y = 0;
13         return a;
14     }
15     ll d = exgcd(b,a%b,y,x);
16     y-=a/b*x;
17     return d;
18 }
19 ll gui_mul(ll n,ll k,ll q)
20 {
21     ll ans = 0;
22     while(k)
23     {
24         if(k&1) ans = (ans+n)%q;
25         k>>=1;
26         n = (n+n)%q;
27     }
28     return ans;
29 }
30 int main()
31 {
32     int k; ll res = 1,x,y,ans= 0;
33     scanf("%d",&k);
34     for(int i=1;i<=k;i++) scanf("%lld",&a[i]);
35     for(int i=1;i<=k;i++) scanf("%lld",&b[i]),res*=b[i];
36     for(int i=1;i<=k;i++)
37     {
38         ll t = res/b[i];
39         ll d = exgcd(t,b[i],x,y);
40         ll g = abs(b[i]/d);
41         x = (x%g+g)%g;
42         ans = (ans+gui_mul(gui_mul(a[i],t,res),x,res))%res;
43     }
44     printf("%lld\n",ans);
45     return 0;
46 } 

 

posted @ 2021-01-28 12:38  acmloser  阅读(75)  评论(0编辑  收藏  举报