码迷,mamicode.com
首页 > 其他好文 > 详细

HDU 4990 Reading comprehension(找规律+矩阵快速幂)

时间:2014-09-07 23:51:56      阅读:424      评论:0      收藏:0      [点我收藏+]

标签:hdu   矩阵快速幂   

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4990


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
 
Source


思路:

先用源程序跑几个数出来!1, 2, 5, 10, 21, 42 好了,再用这几个数字找他们的通项式(我是在http://oeis.org/(队友告诉我的)找的);

然后再用矩阵快速幂就OK!


代码如下:

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define LL __int64
struct Matrix
{
    LL  m[5][5];
} I,A,B,T;

LL a,b,n, mod;
int ssize = 3;

Matrix Mul(Matrix a,Matrix b)
{
    int i,j,k;
    Matrix c;
    for (i = 1; i <= ssize; i++)
    {
        for(j = 1; j <= ssize; j++)
        {
            c.m[i][j]=0;
            for(k = 1; k <= ssize; k++)
            {
                c.m[i][j]+=(a.m[i][k]*b.m[k][j]);
                c.m[i][j]%=mod;
            }
        }
    }
    return c;
}

Matrix quickpagow(int n)
{
    Matrix m=A, b=I;
    while(n)
    {
        if(n&1)
            b=Mul(b,m);
        n=n>>1;
        m=Mul(m,m);
    }
    return b;
}

int main()
{
    while(~scanf("%I64d%I64d",&n,&mod))
    {
        memset(I.m,0,sizeof(I.m));
        memset(A.m,0,sizeof(A.m));
        memset(B.m,0,sizeof(B.m));
        for(int i = 1; i <= ssize; i++)
        {
            I.m[i][i]=1;
        }
        B.m[1][1] = 1, B.m[1][2] = 2, B.m[1][3] = 1;
        A.m[1][2] = 2;
        A.m[2][1]=A.m[2][2]=A.m[3][2]=A.m[3][3]=1;
        if(n==1)
        {
            printf("%I64d\n",1%mod);
            continue;
        }
        if(n==2)
        {
            printf("%I64d\n",2%mod);
            continue;
        }
        T = quickpagow(n-2);
        T = Mul(B,T);
        printf("%I64d\n",T.m[1][2]%mod);
    }
    return 0;
}


HDU 4990 Reading comprehension(找规律+矩阵快速幂)

标签:hdu   矩阵快速幂   

原文地址:http://blog.csdn.net/u012860063/article/details/39123605

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!