HDU 5667 Sequence

来源:互联网 发布:windows 杀进程 编辑:程序博客网 时间:2024/06/05 02:18
Problem Description
    Holion August will eat every thing he has found.

    Now there are many foods,but he does not want to eat all of them at once,so he find a sequence.

fn=1,ab,abfcn1fn2,n=1n=2otherwise

    He gives you 5 numbers n,a,b,c,p,and he will eat fn foods.But there are only p foods,so you should tell him fn mod p.
 

Input
    The first line has a number,T,means testcase.

    Each testcase has 5 numbers,including n,a,b,c,p in a line.

    1T10,1n1018,1a,b,c109,p is a prime number,and p109+7.
 

Output
    Output one number for each case,which is fn mod p.
 

Sample Input
15 3 3 3 233
 

Sample Output
190

把次数拿下来就可以用矩阵递推了,要注意会有a%p=0的情况

#pragma comment(linker, "/STACK:102400000,102400000")#include<map>#include<set>#include<cmath>#include<queue>#include<stack>#include<bitset>#include<cstdio>#include<string>#include<cstring>#include<iostream>#include<algorithm>#include<functional>using namespace std;typedef long long LL;const int low(int x) { return x&-x; }const int INF = 0x7FFFFFFF;const int mod = 1e9 + 7;const int maxn = 2e5 + 10;LL n, a, b, c, p;int T;struct martix{LL a[3][3];}A, B;martix operator*(const martix&a, const martix&b){martix c;for (int i = 0; i < 3; i++){for (int j = 0; j < 3; j++){c.a[i][j] = 0;for (int k = 0; k < 3; k++){(c.a[i][j] += a.a[i][k] * b.a[k][j] % (p - 1)) %= (p - 1);}}}return c;}martix get(martix a, LL x){martix c;for (int i = 0; i < 3; i++){for (int j = 0; j < 3; j++){c.a[i][j] = i == j;}}for (x; x; x >>= 1){if (x & 1) c = c*a;a = a*a;}return c;}LL get(LL x, LL y){if (n > 1 && y == 0) y = p - 1;LL ans = 1;for (y; y; y >>= 1){if (y & 1) ans = ans*x%p;x = x*x%p;}return ans;}int main(){scanf("%d", &T);while (T--){cin >> n >> a >> b >> c >> p;A.a[0][0] = 0;    A.a[0][1] = b;    A.a[0][2] = b;B.a[0][0] = 0;    B.a[0][1] = 1;    B.a[0][2] = 0;B.a[1][0] = 1;    B.a[1][1] = c;    B.a[1][2] = 0;B.a[2][0] = 0;    B.a[2][1] = 1;    B.a[2][2] = 1;if (n == 1) { cout << 1 << endl; continue; }B = get(B, n - 1);A = A*B;cout << get(a, A.a[0][0]) << endl;}return 0;}


0 0