HDU4990 Reading comprehension【矩阵快速幂】

Reading comprehension

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2334    Accepted Submission(s): 959


Problem Description
Read the program below carefully then answer the question.
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include
#include
#include
#include
#include
#include

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
 

Source
BestCoder Round #8

问题链接:HDU4990 Reading comprehension

问题简述:(略)

问题分析:占个位置,不解释

程序说明:(略)

题记:(略)

参考链接:(略)


AC的C++语言程序如下:

/* HDU4990 Reading comprehension */

#include 
#include 
#include 

using namespace std;

typedef long long LL;

const int N = 2;

struct Matrix
{
    LL m[N + 1][N + 1];
    Matrix()
    {
        memset(m, 0, sizeof(m));
    }
};

Matrix Matrix_Mul(Matrix a, Matrix b, LL mod)
{
    Matrix c;

    for(int i=1; i<=N; i++)
        for(int j=1; j<=N; j++)
            for(int k=1; k<=N; k++)
                c.m[i][j] = (c.m[i][j] + a.m[i][k] * b.m[k][j]) % mod;

    return c;
}

// 矩阵模幂
Matrix Matrix_Powmul(Matrix a, int m, LL mod)
{
    Matrix c;

    for(int i=1; i<=N; i++)
        c.m[i][i] = 1;
    while(m) {
        if(m & 1)
            c = Matrix_Mul(c, a, mod);
        a = Matrix_Mul(a, a, mod);
        m >>= 1;
    }

    return c;
}

int main()
{
    LL n, mod;
    Matrix a, t;

    while(~scanf("%lld%lld", &n, &mod)) {
        a.m[1][1] = 4;
        a.m[1][2] = 2;
        a.m[2][1] = 0;
        a.m[2][2] = 1;

        t = Matrix_Powmul(a, n / 2, mod);
        LL ans = t.m[1][2];
        if(n % 2)
            ans = (ans * 2 + 1) % mod;

        printf("%lld\n", ans);
    }

    return 0;
}






你可能感兴趣的:(#,ICPC-备用二,#,ICPC-HDU,ACM百度之星,#,ICPC-矩阵)