0
点赞
收藏
分享

微信扫一扫

Jzzhu and Sequences CodeForces - 450B


​​Jzzhu and Sequences CodeForces - 450B​​​
题意:f(i)=f(i-1)-f(i-2) 给n问f(n)的值为多少。
思路:就是n的值很大,直接暴力是肯定不行的,有这种递推式的都可以使用矩阵快速幂求出答案。

#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
typedef long long ll;
const ll mod=1000000007;
struct matrix{
ll x[2][2];
};
matrix multi(matrix a,matrix b){
matrix temp;
memset(temp.x,0,sizeof(temp.x));
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
for(int k=0;k<2;k++)
{
temp.x[i][j]+=a.x[i][k]*b.x[k][j];
temp.x[i][j]=(temp.x[i][j]+mod)%mod;//负数取模的问题,除法取模
}
return temp;
}
matrix quick_multi(matrix a,ll n)//矩阵快速幂
{
matrix temp=a;
n--;
while(n){
if(n&1)
temp=multi(temp,a);
a=multi(a,a);
n>>=1;
}
return temp;
}
int main()
{
ll x,y,n;//f(i)=f(i-1)-f(i-2)
while(scanf("%lld%lld",&x,&y)!=EOF)
{
scanf("%lld",&n);
//x=(x+mod)%mod;y=(y+mod)%mod;
matrix a,b;
memset(a.x,0,sizeof(a.x));
a.x[0][0]=1;a.x[1][0]=-1;a.x[0][1]=1;
b.x[0][0]=y;b.x[0][1]=x;
if(n>2)
{
a=quick_multi(a,n-2);
b=multi(b,a);
cout<<(b.x[0][0]+mod)%mod<<endl;
}
else
{
x=(x+mod)%mod;y=(y+mod)%mod;
n==1?printf("%lld\n",x):printf("%lld\n",y);
}
}
return 0;
}


举报

相关推荐

0 条评论