1. 程式人生 > >HDU 5667 :Sequence

HDU 5667 :Sequence

word break epp 一個數 1.4 end ims wid iter

Sequence

Accepts: 59 Submissions: 650 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others) 問題描寫敘述
\ \ \ \    Lcomyn 是個非常厲害的選手,除了喜歡寫17kb+的代碼題,偶爾還會寫數學題.他找到了一個數列:

f_n=\left\{\begin{matrix} 1 ,&n=1 \\ a^b,&n=2 \\ a^bf_{n-1}^cf_{n-2},&otherwise \end{matrix}\right.
f?n??=?????????1,?a?b??,?a?b??f?n?1?c??f?n?2??,???n=1?n=2?otherwise??
\ \ \ \ 他給了你幾個數:nn,aa,bb,cc,你須要告訴他f_nf?n??pp後的數值.
輸入描寫敘述
\ \ \ \    第一行一個數T,為測試數據組數.

\ \ \ \    每組數據一行,一行五個正整數,按順序為nn,aa,bb,cc,pp.

\ \ \ \ 1\le T \le 10,1\le n\le 10^{18}    1T10,1n10?18??,1\le a,b,c\le 10^91a,b,c10?
9
??
,p是質數且p\le 10^9+7p10?9??+7.
輸出描寫敘述
\ \ \ \    對每組數據輸出一行一個數,輸出f_nf?n??pp取模後的數值.
輸入例子
1
5 3 3 3 233
輸出例子
190

發現f序列就是a的不同指數的形式。所以對每個f對a取對數。發現就是f[n]=b+c*f[n-1]+f[n-2]。

構造矩陣,高速冪搞。

註意由於是在指數上。所以模的值須要是歐拉函數p,由於p是質數。所以直接是p-1。

代碼:

#pragma warning(disable:4996)
#include <iostream>
#include <functional>
#include <algorithm>
#include <cstring>
#include <vector>
#include <string>
#include <cstdio>
#include <cmath>
#include <queue>
#include <stack>
#include <deque>
#include <set>
#include <map>
using namespace std;
typedef long long ll;

#define INF 0x333f3f3f
#define repp(i, n, m) for (int i = n; i <= m; i++)
#define rep(i, n, m) for (int i = n; i < m; i++)
#define sa(n) scanf("%d", &(n))

const ll mod = 100000007;
const int maxn = 5e5 + 5;
const double PI = acos(-1.0);

ll n, a, b, c, p;

struct ma
{
	ll val[4][4];
	ma operator *(const ma &b)
	{
		int i, j, k;
		ma res;
		memset(res.val, 0, sizeof(res.val));

		for (k = 1; k <= 3; k++)
		{
			for (i = 1; i <= 3; i++)
			{
				for (j = 1; j <= 3; j++)
				{
					res.val[i][j] += (this->val[i][k] * b.val[k][j]) % (p - 1);
					res.val[i][j] %= (p - 1);
				}
			}
		}
		return res;
	}
};

ll po(ll x, ll y)
{
	ll res = 1;
	while (y)
	{
		if (y & 1)
			res = res*x%p;
		x = x*x%p;
		y >>= 1;
	}
	return res;
}

ma po_matrix(ma &x, ll y)
{
	ma res;
	res.val[1][1] = 1, res.val[1][2] = 0, res.val[1][3] = 0;
	res.val[2][1] = 0, res.val[2][2] = 1, res.val[2][3] = 0;
	res.val[3][1] = 0, res.val[3][2] = 0, res.val[3][3] = 1;
	while (y)
	{
		if (y & 1)
			res = res*x;
		x = x*x;
		y >>= 1;
	}
	return res;
}

void solve()
{
	ll i, j, k;
	scanf("%lld%lld%lld%lld%lld", &n, &a, &b, &c, &p);
	
	ll res;
	ma r;
	if (n == 1)
	{
		puts("1");
	}
	else if (n == 2)
	{
		res = po(a, b);
		printf("%lld\n", res);
	}
	else
	{
		r.val[1][1] = c, r.val[1][2] = 1, r.val[1][3] = b;
		r.val[2][1] = 1, r.val[2][2] = 0, r.val[2][3] = 0;
		r.val[3][1] = 0, r.val[3][2] = 0, r.val[3][3] = 1;

		r = po_matrix(r, n - 2);
		res = r.val[1][3] + r.val[1][1] * b;
		res = po(a, res);
		printf("%lld\n", res);
	}
}

int main()
{
#ifndef ONLINE_JUDGE  
	freopen("i.txt", "r", stdin);
	freopen("o.txt", "w", stdout);
#endif

	int t;
	scanf("%d", &t);

	while (t--)
	{
		solve();
	}

	return 0;
}


HDU 5667 :Sequence