您的位置:首页 > 产品设计 > UI/UE

Number Sequence(HDU 1005 构造矩阵 )

2016-05-06 11:44 411 查看

Number Sequence

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 147964 Accepted Submission(s): 35964


[align=left]Problem Description[/align]
A number sequence is defined as follows:

f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7.

Given A, B, and n, you are to calculate the value of f(n).

[align=left]Sample Input[/align]

1 1 3
1 2 1
0
0 0 0

[align=left]Sample Output[/align]

2

5

因为数据量比较大,可以打表找到循环规律,但这种类型的题发现都可以构造矩阵求解
f
      = a b * f[n-1]
f[n-1] 1 0   f[n-2]

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;
int a,b,n;
int m[1000];
struct Matrix
{
int mat[2][2];
}p;
Matrix mul(Matrix a,Matrix b)
{
Matrix c;
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
{
c.mat[i][j]=0;
for(int k=0;k<2;k++)
c.mat[i][j]=(c.mat[i][j]+a.mat[i][k]*b.mat[k][j])%7;
}
}
return c;
}
Matrix mod_pow(Matrix x,int n)
{
Matrix res;
memset(res.mat,0,sizeof(res.mat));
for(int i=0;i<2;i++)
res.mat[i][i]=1;
while(n)
{
if(n&1)
res=mul(res,x);
x=mul(x,x);
n>>=1;
}
return res;
}
int main()
{
freopen("in.txt","r",stdin);
while(scanf("%d%d%d",&a,&b,&n)!=EOF)
{
if(a==0&&b==0&&n==0)
break;
if(n<2)
{
printf("1\n");
continue;
}
p.mat[0][0]=a;
p.mat[1][0]=1;
p.mat[0][1]=b;
p.mat[1][1]=0;
Matrix ans= mod_pow(p,n-2);
printf("%d\n",(ans.mat[0][0]+ans.mat[0][1])%7);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: