hdu 4990 Reading comprehension(矩阵乘法)

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 10 3 100
 

Sample Output
  
  
1 5

根据上面的代码可以发现就是让求一个数组的第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 long
using 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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值