hdu 3292 No more tricks, Mr Nanguo

题目:No more tricks, Mr Nanguo

思路:佩尔方程,剩下的递归用矩阵快速幂做 

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <iostream>
using namespace std;
#define mod 8191
struct Matrix
{
    int m[3][3];
}D,E;
void init()
{
    for(int i=1;i<=2;i++)
        for(int j=1;j<=2;j++)
            E.m[i][j]=(i==j);
}
Matrix Multi(Matrix A,Matrix B)
{
    Matrix ans;
    for(int i=1;i<=2;i++)
        for(int j=1;j<=2;j++)
        {
            ans.m[i][j]=0;
            for(int k=1;k<=2;k++)
                ans.m[i][j]=(ans.m[i][j]+A.m[i][k]*B.m[k][j])%mod;
        }
    return ans;
}
Matrix Pow(Matrix A,long long k)
{
    Matrix ans=E;
    while(k)
    {
        if(k&1)
        {
            k--;
            ans=Multi(ans,A);
        }
        else
        {
            k/=2;
            A=Multi(A,A);
        }
    }
    return ans;
}
int get_first(int n)
{
    long long y=1;
    while(1)
    {
        int x=sqrt(n*y*y+1);
        if(x*x==n*y*y+1)
            return y;
        y++;
    }
    return -1;
}
bool is_sqr(int x)
{
    int tmp=sqrt(x);
    if(tmp*tmp==x)
        return true;
    return false;
}
int main()
{
    int n,k;
    init();
    while(cin>>n>>k)
    {
        if(is_sqr(n))
            cout<<"No answers can meet such conditions"<<endl;
        else
        {
            int y=get_first(n);
            int x=(int)sqrt(n*y*y+1);
            D.m[1][1]=x;
            D.m[2][2]=x;
            D.m[1][2]=n*y;
            D.m[2][1]=y;
            D=Pow(D,k);
            cout<<D.m[1][1]<<endl;
        }
    }
    return 0;
}
View Code

 

posted @ 2013-07-16 16:33  over_flow  阅读(309)  评论(0编辑  收藏  举报