HDU-5451

Best Solver

Time Limit: 1500/1000 MS (Java/Others)    Memory Limit: 65535/102400 K (Java/Others)
Total Submission(s): 408    Accepted Submission(s): 219


Problem Description
The so-called best problem solver can easily solve this problem, with his/her childhood sweetheart.

It is known that y=(5+26√)1+2x.
For a given integer x (0x<232) and a given prime number M (M46337), print [y]%M. ([y] means the integer part of y)
 
Input
An integer T (1<T1000), indicating there are T test cases.
Following are T lines, each containing two integers x and M, as introduced above.
 
Output
The output contains exactly T lines.
Each line contains an integer representing [y]%M.
 
Sample Input

7
0 46337
1 46337
3 46337
1 46337
21 46337
321 46337
4321 46337

 
Sample Output

Case #1: 97
Case #2: 969
Case #3: 16537
Case #4: 969
Case #5: 40453
Case #6: 10211
Case #7: 17947

 
Source

 

/**
    题意:对于方程  给出x和mod,求y向下取整后取余mod的值为多少
    做法:矩阵  构造 
**/
#include <iostream>
#include <cstdio>
#include <vector>
#include <cmath>
#include <algorithm>

using namespace std;
typedef long long ll;
ll mod;
typedef vector<ll> vec;
typedef vector<vec> mat;

mat mul(mat& A, mat& B)
{
    mat C(A.size(), vec(B[0].size()));
    for(int i = 0; i < A.size(); ++i) {
        for(int k = 0; k < B.size(); ++k) {
            for(int j = 0; j < B[0].size(); ++j) {
                C[i][j] = (C[i][j] + A[i][k] * B[k][j]) % mod;
            }
        }
    }
    return C;
}
mat pow(mat A, ll n)
{
    mat B(A.size(), vec(A.size()));
    for(int i = 0; i < A.size(); ++i) {
        B[i][i] = 1;
    }
    while(n > 0) {
        if(n & 1) {
            B = mul(B, A);
        }
        A = mul(A, A);
        n >>= 1;
    }
    return B;
}
int solve(long long a, long long b, long long c)
{
    long long ans = 1;
    long long k = a % c;
    while(b > 0)
    {
        if(b % 2 == 1)
        {
            ans = (ans * k) % c;
        }
        b = b / 2;
        k = (k * k) % c;
    }
    return ans;
}
int main()
{
    int T;
    scanf("%d", &T);
    ll a, b, n;
    int Case = 1;
    while(T--) {
        scanf("%I64d %I64d", &n, &mod);
        mat A(2, vec(2, 0));
        A[0][0] = 5;
        A[0][1] = 12;
        A[1][0] = 2;
        A[1][1] = 5;
        long long tt = mod;
        n = solve(2, n, (mod - 1) * (mod + 1)) + 1;
        A = pow(A, n);
        ll ans = (2 * A[0][0] - 1) % mod;
        printf("Case #%d: %I64d
", Case++, ans);
    }
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/chenyang920/p/4831060.html