Jzzhu and Sequences - CF 450B 矩阵快速幂版

Jzzhu and Sequences
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

Jzzhu has invented a kind of sequences, they meet the following property:

You are given x and y, please calculate fn modulo 1000000007 (109 + 7).

Input

The first line contains two integers x and y (|x|, |y| ≤ 109). The second line contains a single integer n (1 ≤ n ≤ 2·109).

Output

Output a single integer representing fn modulo 1000000007 (109 + 7).

Sample test(s)
input
2 3
3
output
1
input
0 -1
2
output
1000000006
Note

In the first sample, f2 = f1 + f33 = 2 + f3f3 = 1.

In the second sample, f2 =  - 1 - 1 modulo (109 + 7) equals (109 + 6).


题意:f(n)=f(n-1)-f(n-2)。

思路:可以找出规律——六个一循环,但是正解应该是矩阵快速幂。

AC代码如下:

#include
#include
using namespace std;
typedef long long ll;
ll f1,f2,n,ans,mod=1000000007;
struct node
{ ll f[2][2];
};
node mul(node a,node b)
{ int i,j,k;
  node m;
  for(i=0;i<=1;i++)
  { for(j=0;j<=1;j++)
    { m.f[i][j]=0;
      for(k=0;k<=1;k++)
       m.f[i][j]+=a.f[i][k]*b.f[k][j];
      m.f[i][j]%=mod;
    }
  }
  return m;
}
int main()
{ scanf("%I64d%I64d%I64d",&f1,&f2,&n);
   if(n==1)
    printf("%I64d\n",(f1+mod)%mod);
   else if(n==2)
   printf("%I64d\n",(f2+mod)%mod);
    else
    { node ret;
      node first;
      n-=3;
      first.f[0][0]=first.f[0][1]=ret.f[0][0]=ret.f[0][1]=1;
      first.f[1][0]=ret.f[1][0]=-1;
      first.f[1][1]=ret.f[1][1]=0;
      while(n)
      { if(n&1)
         ret=mul(ret,first);
        first=mul(first,first);
        n/=2;
      }
     ans=(f2*ret.f[0][0]+f1*ret.f[1][0])%mod;
     if(ans<0)
      ans+=mod;
     printf("%I64d\n",ans);
    }
}


你可能感兴趣的:(CodeForces,数论)