题目: 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;
}