kuangbin 专题十九 矩阵(HDU 4990)Reading comprehension

Reading comprehension

Time limit1000 ms
Memory limit32768 kB
OSWindows

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和m。处理到文件结尾。
【技术规范】
1<=N,m<=100000000 
  • 输出
对于每种情况,输出一个整数,表示上述程序的输出。 

样例输入输出如上。
先不考虑余m
可以直接看代码知道第奇数个ans是前一个的两倍加一,第偶数个ans是前一个的两倍
然后列个式子就能知道f(n) = f(n-1) + 2 * f(n-2) + 1
也可以直接复制代码跑一遍找下规律
最后输出f(n) % m
矩阵a [ 2 1 1 0 0 0 0 0 0 ] (4) \begin{bmatrix} 2 & 1 & 1 \\ 0 & 0 & 0 \\ 0 & 0 & 0 \end{bmatrix} \tag{4} 200100100(4)
矩阵b [ 1 1 0 2 0 0 1 0 1 ] (4) \begin{bmatrix} 1 & 1 & 0 \\ 2 & 0 & 0 \\ 1 & 0 & 1 \end{bmatrix} \tag{4} 121100001(4)

Time31ms
Memory1220kB
Length1069
LangG++
#include <stdio.h>
#include <string.h>
using namespace std;
#define ll long long

struct matrix{
  ll m[4][4];/*我习惯写矩阵下标从1到3,所以会多开一个*/
}a,b;

matrix multiply(matrix a, matrix b,int mod){
  matrix temp;
  memset(temp.m,0,sizeof(temp.m));
  for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 3; j++) {
      for (int k = 1; k <= 3; k++) {
        temp.m[i][j] += a.m[i][k] * b.m[k][j];
        temp.m[i][j] = temp.m[i][j] % mod;
      }
    }
  }
  return temp;
}

matrix power (matrix a, matrix b, int p, int mod){
  while (p) {
    if(p & 1) a = multiply(a, b, mod);
    b = multiply(b, b, mod);
    p = p >> 1;
  }
  return a;
}

int main(int argc, char const *argv[]) {
  int n, m;
  memset(a.m, 0, sizeof(a.m));
  memset(b.m, 0, sizeof(b.m));
  a.m[1][1] = 2; a.m[1][2] = 1; a.m[1][3] = 1;
  b.m[1][1] = 1; b.m[1][2] = 1; b.m[2][1] = 2; b.m[3][1] = 1; b.m[3][3] = 1;
  while(~scanf("%d %d", &n, &m)){
    matrix end;
    if(n <= 2){
      printf("%lld\n", a.m[1][3-n] % m);/*注意前两个也要取余,我就因为这个WA了两发*/
      continue;
    }
    end = power(a, b, n-2, m);
    printf("%lld\n" , end.m[1][1] % m);
  }
  return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值