HDU 3292 No more tricks, Mr Nanguo(佩尔方程,矩阵快速幂)

题目: LINK

题意可以理解为: y^2 - n*x^2 == 1 已知n,求(x, y)的第k小的解.
这个式子可以用佩尔方程定理来解,可以把用到的前29个最小的解先打表。至于求第k小解,k比较大,可以用矩阵快速幂来做。

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<cmath>
#include<queue>
#include<map>
#include<set>
using namespace std;
#define INF 1000000000
typedef __int64 LL;
#define mod 8191
LL n, k;
LL a[44][2] = {-1,-1,3,2,2,1,-1,-1,9,4,5,2,8,3,3,1,-1,-1,19,6,10,3,7,2,649,180,15,4,4,1,-1,-1,33,8,17,4,170,39,9,2,55,12,197,42,24,5,5,1,-1,-1,51,10,26,5,127,24,9801,1820};
struct node
{
    LL mat[4][4];
};
node mul(node x, node y)
{
    node ret;
    memset(ret.mat, 0, sizeof(ret.mat));
    for(int i=1; i<=2; i++) {
        for(int j=1; j<=2; j++) {
            for(int k = 1; k<=2; k++) {
                ret.mat[i][j] += x.mat[i][k]*y.mat[k][j];
                ret.mat[i][j] %= mod;
            }
        }
    }
    return ret ;
}
node pow_(node x, LL y)
{
    node ret ;
    ret.mat[1][1]= ret.mat[2][2]= 1;
    ret.mat[1][2]= ret.mat[2][1]= 0;

    while(y) {
        if(y&1) {
            ret = mul(ret, x);
        }
        y>>=1;
        x = mul(x, x);
    }
    return ret;
}
int main()
{
#ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
#endif // ONLINE_JUDGE
    while(scanf("%I64d%I64d", &n, &k) != EOF) {
        if(a[n-1][0] == -1) {
            printf("No answers can meet such conditions\n");
            continue;
        }
        node ans;
        ans.mat[1][1]= a[n-1][0]; ans.mat[1][2] = a[n-1][1];
        ans.mat[2][1]= a[n-1][1]*n; ans.mat[2][2]= a[n-1][0];
        ans = pow_(ans, k-1);
        LL out = 0;
        out += a[n-1][0] * ans.mat[1][1];
        out %= mod;
        out += a[n-1][1] * ans.mat[2][1];
        out %= mod;
        printf("%I64d\n", out);
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值