hdu 4990 Reading comprehension(矩阵乘法)

来源:互联网 发布:苹果版解压缩软件 编辑:程序博客网 时间:2024/06/10 23:44

Problem Description
Read the program below carefully then answer the question.
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <cstdio>
#include<iostream>
#include <cstring>
#include <cmath>
#include <algorithm>
#include<vector>

const int MAX=100000*2;
const int INF=1e9;

int main()
{
  int n,m,ans,i;
  while(scanf("%d%d",&n,&m)!=EOF)
  {
    ans=0;
    for(i=1;i<=n;i++)
    {
      if(i&1)ans=(ans*2+1)%m;
      else ans=ans*2%m;
    }
    printf("%d\n",ans);
  }
  return 0;
}
 

Input
Multi test cases,each line will contain two integers n and m. Process to end of file.
[Technical Specification]
1<=n, m <= 1000000000
 

Output
For each case,output an integer,represents the output of above program.
 

Sample Input
1 103 100
 

Sample Output
15

根据上面的代码可以发现就是让求一个数组的第n项

奇数项等于前一项*2+1,偶数项等于前一项*2:

a0 = 0;

a1 = a0*2+1;

a2 = a1*2;

a3 = a2*2+1;

a4 = a3*2;

如果直接构造矩阵求第n项好像不太好求,但是我们发现偶数项或者奇数项之间的公式是固定的,我们就是偶数项为例吧。

可以推出:

a2 = 4*a0 + 2;

a4 = 4*a2 + 2;

这样就可以很轻松的构造出矩阵,如果n是偶数的话,直接就可以求出答案,如果是奇数项,那么就*2+1.


#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>#define LL long longusing namespace std;int mod;struct Matrix{    long long m[2][2];    int n;    Matrix(int x)    {        n = x;        for(int i=0;i<n;i++)            for(int j=0;j<n;j++)                m[i][j] = 0;    }    Matrix(int _n,int a[2][2])    {        n = _n;        for(int i=0;i<n;i++)            for(int j=0;j<n;j++)            {                m[i][j] = a[i][j];            }    }};Matrix operator *(Matrix a,Matrix b){    int n = a.n;    Matrix ans = Matrix(n);    for(int i=0;i<n;i++)        for(int j=0;j<n;j++)            for(int k=0;k<n;k++)            {                ans.m[i][j] += (a.m[i][k]%mod)*(b.m[k][j]%mod)%mod;                ans.m[i][j] %= mod;            }    return ans;}Matrix operator ^(Matrix a,int k){    int n = a.n;    Matrix c(n);    int i,j;    for(i=0;i<n;i++)        for(j=0;j<n;j++)            c.m[i][j] = (i==j);    for(;k;k>>=1)    {        if(k&1)            c=c*a;        a = a*a;    }    return c;}int main(void){    int n,m,i,j;    while(scanf("%d%d",&n,&m)==2)    {        mod = m;        int a[2][2] = { 4,0,                        2,1};        Matrix A(2,a);        A = A^(n/2);        LL ans = A.m[1][0];        if(n % 2 == 1)            ans = (ans*2+1)%mod;        cout << ans << endl;    }    return 0;}


原创粉丝点击