Codeforces 963A Alternating Sum [Number Theory + Mathematics]

The official solution looks like this, I think it's more clear. Z we can simply preprocess it (pay attention to the multiplication film), the test point for q is [fractional film] that is (a/b)%P = a* inverse of b %P

This involves calculating the inverse of b, and I use the Euclidean algorithm. The following blog post is very clear.

http://www.cnblogs.com/frog112111/archive/2012/08/19/2646012.html

 

 Then there are two details. One is to write fast power so that Z can be preprocessed with O(k * log(n)) complexity. When fast power is used, note that the type of a must be long long, because when a*a It may explode, and I have been WA many times because of this. The second detail is that we need to judge the case of q=1 according to the summation formula of the proportional sequence

 1 #include<iostream>
 2 #define MAXN 200000
 3 #define ll long long
 4 #define P 1000000009
 5 using namespace std;
 6 
 7 int exgcd(int a,int b,int &x,int &y)
 8 {
 9     if(b==0)
10     {
11         x=1;
12         y=0;
13         return a;
14     }
15     int r=exgcd(b,a%b,x,y);
16     int t=x;
17     x=y;
18     y=t-a/b*y;
19     return r;
20 }
21 
22 ll power(ll a,int n){
23     if(n==0) return 1;
24     if(n==1) return a;
25     if(n==2) return (a*a)%P;
26     if(n%2) return power(power(a,n/2),2)*a%P;
27     return power(power(a,n/2),2);
28 }
29 
30 
31 int n,a,b,k,s[MAXN]; 
32 int x,y;
33 ll sum;
34 
35 int main(){
36 
37 scanf("%d%d%d%d",&n,&a,&b,&k);
38 
39 for(int i=0;i<k;i++){
40     char sym; cin>>sym;
41     if(sym=='+') s[i]=1;
42     else s[i]=-1;
43 }
44 
45 for(int i=0;i<k;i++){//Z
46     if(s[i]==1) sum=(sum+power(a,n-i)*power(b,i)%P)%P;
47     else sum=(sum-power(a,n-i)*power(b,i)%P+P)%P;
48 }
49 
50 exgcd(a,P,x,y);//找a的逆元 
51 int inva=x;
52 inva+=P; inva%=P;
53 ll q = power(b,k)*power(inva,k)%P;
54 
55 if(q==1){
56     cout<<sum*((n+1)/k)%P;
57 }
58 else{
59     x=0; y=0;
60     exgcd(q-1,P,x,y); x+=P; x%=P;
61     printf("%d",sum*x%P*( power(q,(n+1)/k) -1 )%P );
62 }
63     
64     return 0;
65 }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325067667&siteId=291194637