hdu4990 矩阵快速幂
生活随笔
收集整理的這篇文章主要介紹了
hdu4990 矩阵快速幂
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題意:
? ? ? 給你一短代碼,讓你優化這個代碼,代碼如下
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <cstdio>
#include<iostream>
#include <cstring>
#include <cmath>
#include <algorithm>
#include<vector>
const int MAX=100000*2;
const int INF=1e9;
int main()
{
? int n,m,ans,i;
? while(scanf("%d%d",&n,&m)!=EOF)
? {
? ? ans=0;
? ? for(i=1;i<=n;i++)
? ? {
? ? ? if(i&1)ans=(ans*2+1)%m;
? ? ? else ans=ans*2%m;
? ? }
? ? printf("%d\n",ans);
? }
? return 0;
},給出n,m讓你輸出ans ? <1<=n, m <= 1000000000>.
思路:
? ? ? 直接跑肯定TLE,這個題目我們可以推公式,如果推不出來可以直接打出來一些,然
后自己找公式,一般公式不會很復雜(復雜的自己一般不會呵呵)。
現在我們要求ai:
如果i是奇數?
a[i] = a[i-1] * 2 + 1 = (a[i-2] * 2 + a[i-1]) + 1 = a[i-2]*2+a[i-1]+1
如果i是偶數
a[i] = a[i-1] * 2 ? ? = (a[i-2] * 2 + 1) + a[i-1] = a[i-2]*2+a[i-1]+1
兩個公式一樣,那么可以作為通式,然后就構造矩陣,之后跑快速冪就行了,矩陣也很好構
造,我構造下:
a1 a2 1 ? ? ? 0 ?2 ?0 ? ? ?a2 a3 1?
? ? ? ? ? * ? 1 ?1 ?0
? ? ? 給你一短代碼,讓你優化這個代碼,代碼如下
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <cstdio>
#include<iostream>
#include <cstring>
#include <cmath>
#include <algorithm>
#include<vector>
const int MAX=100000*2;
const int INF=1e9;
int main()
{
? int n,m,ans,i;
? while(scanf("%d%d",&n,&m)!=EOF)
? {
? ? ans=0;
? ? for(i=1;i<=n;i++)
? ? {
? ? ? if(i&1)ans=(ans*2+1)%m;
? ? ? else ans=ans*2%m;
? ? }
? ? printf("%d\n",ans);
? }
? return 0;
},給出n,m讓你輸出ans ? <1<=n, m <= 1000000000>.
思路:
? ? ? 直接跑肯定TLE,這個題目我們可以推公式,如果推不出來可以直接打出來一些,然
后自己找公式,一般公式不會很復雜(復雜的自己一般不會呵呵)。
現在我們要求ai:
如果i是奇數?
a[i] = a[i-1] * 2 + 1 = (a[i-2] * 2 + a[i-1]) + 1 = a[i-2]*2+a[i-1]+1
如果i是偶數
a[i] = a[i-1] * 2 ? ? = (a[i-2] * 2 + 1) + a[i-1] = a[i-2]*2+a[i-1]+1
兩個公式一樣,那么可以作為通式,然后就構造矩陣,之后跑快速冪就行了,矩陣也很好構
造,我構造下:
a1 a2 1 ? ? ? 0 ?2 ?0 ? ? ?a2 a3 1?
? ? ? ? ? * ? 1 ?1 ?0
? ? ? ? ? ? ? 0 ?1 ?1
#include<stdio.h> #include<string.h> __int64 M;typedef struct {__int64 mat[5][5]; }A;A mat_mat(A a ,A b) {A c;memset(c.mat ,0 ,sizeof(c.mat));for(int k = 1 ;k <= 3 ;k ++)for(int i = 1 ;i <= 3 ;i ++){if(a.mat[i][k]) for(int j = 1 ;j <= 3 ;j ++)c.mat[i][j] = (c.mat[i][j] + a.mat[i][k] * b.mat[k][j])%M;}return c; }A quick_mat(A a ,int b) {A c;memset(c.mat ,0 ,sizeof(c.mat));c.mat[1][1] = c.mat[2][2] = c.mat[3][3] = 1;while(b){if(b&1) c = mat_mat(c ,a);a = mat_mat(a ,a);b >>= 1;}return c; }int main () {A a;int n ,i;while(~scanf("%d %d" ,&n ,&M)){a.mat[1][1] = a.mat[1][3] = a.mat[2][3] = a.mat[3][1] = 0;a.mat[2][1] = a.mat[2][2] = a.mat[3][2] = a.mat[3][3] = 1;a.mat[1][2] = 2;if(n == 1){printf("%d\n" ,1 % M);continue;}a = quick_mat(a ,n-1);__int64 Ans = 1 * a.mat[1][1] + 2 * a.mat[2][1] + 1 * a.mat[3][1];printf("%I64d\n" ,Ans % M);}return 0; }
總結
以上是生活随笔為你收集整理的hdu4990 矩阵快速幂的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SPOJ 2713 线段树(sqrt)
- 下一篇: hdu4982 暴搜+剪枝(k个数和是n