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<cstdio>
#include<cstring>
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);
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值