日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

【HDU - 4990】 Reading comprehension (构造+矩阵快速幂)

發布時間:2023/12/10 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【HDU - 4990】 Reading comprehension (构造+矩阵快速幂) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

題干:

Read the program below carefully then answer the question.?
#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;?
}

Input

Multi test cases,each line will contain two integers n and m. Process to end of file.?
[Technical Specification]?
1<=n, m <= 1000000000

Output

For each case,output an integer,represents the output of above program.

Sample Input

1 10 3 100

Sample Output

1 5

解題報告:

? ? ? 根據題干找規律,發現f(n) = f(n-1) + 2 * f(n-2) +1

AC代碼:

#pragma comment(linker, "/STACK:1024000000,1024000000") #include <cstdio> #include<iostream> #include <cstring> #include <cmath> #include <algorithm> #define ll long long struct Matrix {ll arr[4][4]; }unit,trans; ll n,m,ans; Matrix mul( Matrix a,Matrix b,ll mod) {Matrix c;for(int i = 1; i<=3; i++) {for(int j = 1; j<=3; j++) {c.arr[i][j] = 0; for(int k = 1; k<=3; k++) { // if(a.arr[i][k] && b.arr[k][j])c.arr[i][j] = (c.arr[i][j] + a.arr[i][k]*b.arr[k][j])%mod;}}}return c; } Matrix q_pow(Matrix a, ll k,ll mod) {Matrix ans;ans = unit;while(k) {if(k&1) {ans=mul(ans,a,m);}k>>=1;a=mul(a,a,m);}return ans; } void init() {memset(unit.arr,0,sizeof(unit.arr) );for(int i = 1; i<=3; i++) {unit.arr[i][i] = 1;trans.arr[i][1] = trans.arr[i][2] = trans.arr[i][3] = 0;}trans.arr[1][1]=trans.arr[1][3] =trans.arr[2][1]=trans.arr[3][3] = 1;trans.arr[1][2] = 2; } int main() { Matrix ans;ll sum=0;while(scanf("%lld%lld",&n,&m)!=EOF) {sum = 0;init();if(n==1) {printf("%lld\n",1%m);continue; }else if(n == 2) {printf("%lld\n",2%m);continue;}ans = q_pow(trans,n-2,m);sum = ans.arr[1][1]*2 + ans.arr[1][2]*1 + ans.arr[1][3];printf("%lld\n",sum%m);}return 0; }

總結:

? ? ? 這題坑很多啊,總是巧妙的跳了進去。

? ? ? 1.全局變量ll的n和m,結果輸入用%d這個題的Mul函數 不是i<=n了!而是i<=3即可,i<=n就錯了! ?此題和HDU - 5015不一樣,不是矩陣是個不確定的矩陣!所以這里是小于等于3!!即

? ? ? 2.輸出的時候n=1和n=2需要特判一下,因為你傳參是n-2。即:這種地方一定要小心!你的函數是有使用條件的,這一點不僅適用于矩陣快速冪,還有很多其他的地方。

? ? ?3.輸出n==2的時候,別忘了也需要取模!!

? ? 4.最后的輸出 也需要取模!

總結

以上是生活随笔為你收集整理的【HDU - 4990】 Reading comprehension (构造+矩阵快速幂)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。