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

51nod-1537 1537 分解(矩阵快速幂+找规律)

时间:2016-09-02 18:58:49      阅读:433      评论:0      收藏:0      [点我收藏+]

标签:

题目链接:

1537 分解

 问(1+sqrt(2)) ^n  能否分解成 sqrt(m) +sqrt(m-1)的形式 
如果可以 输出 m%1e9+7 否则 输出no
Input
一行,一个数n。(n<=10^18)
Output
一行,如果不存在m输出no,否则输出m%1e9+7
Input示例
2
Output示例
9

题意:

思路:

发现跟奇数偶数有关系,然后就找出递推式,然后就快速幂,然后就A了;

AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <bits/stdc++.h>
#include <stack>
#include <map>
 
using namespace std;
 
#define For(i,j,n) for(int i=j;i<=n;i++)
#define mst(ss,b) memset(ss,b,sizeof(ss));
 
typedef  long long LL;
 
template<class T> void read(T&num) {
    char CH; bool F=false;
    for(CH=getchar();CH<‘0‘||CH>‘9‘;F= CH==‘-‘,CH=getchar());
    for(num=0;CH>=‘0‘&&CH<=‘9‘;num=num*10+CH-‘0‘,CH=getchar());
    F && (num=-num);
}
int stk[70], tp;
template<class T> inline void print(T p) {
    if(!p) { puts("0"); return; }
    while(p) stk[++ tp] = p%10, p/=10;
    while(tp) putchar(stk[tp--] + ‘0‘);
    putchar(‘\n‘);
}
 
const LL mod=1e9+7;
const double PI=acos(-1.0);
const int inf=1e9;
const int N=5e5+20;
const int maxn=1e4+220;
const double eps=1e-12;

struct matrix
{
    LL a[2][2];
};

matrix cal(matrix A,matrix B)
{
    matrix C;
    for(int i=0;i<2;i++)
    {
        for(int j=0;j<2;j++)
        {
            C.a[i][j]=0;
            for(int k=0;k<2;k++)
            {
                C.a[i][j]=(C.a[i][j]+A.a[i][k]*B.a[k][j])%mod;
            }
        }
    }
    return C;
}
matrix pow_mod(LL x)
{
    matrix s,base;
    base.a[0][0]=base.a[1][1]=base.a[1][0]=1;base.a[0][1]=2;
    s.a[0][0]=s.a[1][1]=1;s.a[0][1]=s.a[1][0]=0;
    while(x)
    {
        if(x&1)s=cal(s,base);
        base=cal(base,base);
        x>>=1;
    }
    return s;
}
int main()
{
    LL n,ans=0;
    read(n);
    if(n<0)cout<<"no\n";
    else if(n==0)cout<<"1\n";
    else {
    matrix temp=pow_mod(n-1);
    if(n%2==0)
    {
        ans=(temp.a[0][0]+temp.a[0][1])%mod;
        ans=ans*ans%mod;
    }
    else 
    {
        //cout<<temp.a[1][0]<<t
        ans=(temp.a[1][0]+temp.a[1][1])%mod;
        ans=ans*ans%mod*2%mod;
    }
    cout<<ans<<endl;
}
    return 0;
}

  



51nod-1537 1537 分解(矩阵快速幂+找规律)

标签:

原文地址:http://www.cnblogs.com/zhangchengc919/p/5834525.html

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