hdu 4565
So Easy!
Time Limit: 2000/1000 MS (Java/Others)????Memory Limit: 32768/32768 K (Java/Others)Problem Description A sequence Sn is defined as:
Where a, b, n, m are positive integers.┌x┐is the ceil of x. For example, ┌3.14┐=4. You are to calculate Sn.
You, a top coder, say: So easy!
Input There are several test cases, each test case in one line contains four positive integers: a, b, n, m. Where 0< a, m < 215, (a-1)2< b < a2, 0 < b, n < 231.The input will finish with the end of file.
Output For each the case, output an integer Sn.
Sample Input 2 3 1 2013 2 3 2 2013 2 2 1 2013
Sample Output 4 14 4
題目要求這個(gè)得值
但是取模前有更號(hào),所以無(wú)法直接計(jì)算,我們發(fā)現(xiàn)
0< a, m < 215, (a-1)2< b < a2, 0 < b, n < 231
所以 0 <|?a+sqrt( b )?|?< 1
可得表達(dá)式:,由二項(xiàng)式展開(kāi)可知等號(hào)右邊一坨是整數(shù)并且加的數(shù)小于一,所以等式成立
然后我們?cè)O(shè) Kn 為為等號(hào)的左邊,將表達(dá)式化為遞推形式后,再利用矩陣連乘來(lái)解決 Kn 的問(wèn)題
轉(zhuǎn)化過(guò)程就是移兩次項(xiàng),每次都將指數(shù)約去即可化簡(jiǎn),具體過(guò)程戳這里點(diǎn)擊打開(kāi)鏈接
AC:<pre name="code" class="cpp">#include <cstdio> #include <cstring> #include <cmath> #include <iostream> using namespace std; typedef __int64 ll; #define N 3 // 這里開(kāi)大了超時(shí),原來(lái)開(kāi)的32int K,mod; struct Matrix {int r,c;ll m[N][N];Matrix(){}Matrix(int r,int c):r(r),c(c){}Matrix operator *(const Matrix& B){Matrix T(r,B.c);for(int i=1;i<=T.r;i++){for(int j=1;j<=T.c;j++){ll tt = 0;for(int k=1;k<=c;k++)tt += m[i][k]*B.m[k][j] % mod;T.m[i][j] = tt % mod;}}return T;}Matrix Unit(int h) // 對(duì)角線矩陣{Matrix T(h,h);memset(T.m,0,sizeof(T.m));for(int i=1;i<=h;i++)T.m[i][i] = 1;return T;}Matrix Pow(int n){Matrix P = *this,Res = Unit(r);while(n){if(n&1)Res = Res*P;P = P*P;n >>= 1;}return Res;}void Print(){for(int i=1;i<=r;i++){for(int j=1;j<=c;j++)printf("%d ",m[i][j]);printf("\n");}} }Single;int main(){freopen("in.txt","r",stdin);ll a,b,n;while(cin >> a >> b >> n >> mod){Matrix p(2,2),ans(2,1);if(n==1){cout << (2*a)%mod << endl;continue;}// 初始矩陣ans.m[1][1] = (b + a*a%mod )%mod * 2 %mod; ans.m[2][1] = 2 * a %mod;// 操作矩陣p.m[1][1] = ans.m[2][1]; p.m[1][2] = (b-a*a %mod +mod)%mod;p.m[2][1] = 1; p.m[2][2] = 0;ans = p.Pow(n-2) * ans;cout << ans.m[1][1] << endl;}return 0; }總結(jié)