【HDU - 5187】zhx's contest (快速幂+ 快速乘,模板)
題干:
| 2018百度之星復賽晉級名單出爐(增加20%晉級名額)~ |
zhx's contestTime Limit: 2000/1000 MS (Java/Others)????Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 3779????Accepted Submission(s): 1226 ? Problem Description As one of the most powerful brushes, zhx is required to give his juniors n problems. ? ?Input Multiply test cases(less than 1000 ). Seek EOF as the end of the file. ? ?Output For each test case, output a single line indicating the answer. ? ?Sample Input ?2 233 3 5 ? ?Sample Output ? 2 1Hint In the first case, both sequence {1, 2} and {2, 1} are legal. In the second case, sequence {1, 2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1}, {3, 1, 2}, {3, 2, 1} are legal, so the answer is 6 mod 5 = 1? ?Source BestCoder Round #33 ? |
解題報告:
? ? ? 首先這題找規(guī)律,題目推出來通式是:2^n - 2。證明如下:
推的過程就是一共有四種情況: 升升,升降,降升,降降,其中升升和降降最簡單,一共有兩種,復雜的就是升降和降升這兩種情況,首先來看降生,那么ai一定是最小值,因為兩邊都算ai了,所有當在第一個空的時候,前面一共有Cn-11, 后面就自動的確定了,在第二位的時候,有Cn-12, 同理到最后Cn-1n-2,所以加起來就是2n-1-2,這是降升,同理升降也是這么多,所以最后結果就是(2n-1-2) * 2 + 2 =?2n-2;
? ? ? 注意的是這題的乘法不能直接乘法,因為longlong * longlong可能會爆掉,所以這里用快速乘法,把longlong * longlong轉化成longlong +?longlong 去做。
AC代碼:
#include<iostream> #include <cstdio> #include <cstdlib> using namespace std; typedef long long LL;LL qmul(LL a, LL k, LL mod) { //快速乘法LL ans = 0;//加法的幺元while (k) {if (k & 1) ans = (ans + a)%mod;a = (a + a) % mod;//和快速冪一樣,只不過這里是加k >>= 1;}return ans; } LL qpow(LL a, LL k, LL mod) { //快速冪LL ans = 1;while (k) {if (k & 1) ans = qmul(ans, a, mod);//不能直接乘a = qmul(a, a, mod);k >>= 1;}return ans; }int main() {LL n, p;while (~scanf("%I64d %I64d", &n, &p)) {if (n == 1) { //特判一下printf("%I64d\n", 1 % p);continue;}printf("%I64d\n", (qpow(2, n, p) - 2 + p) % p);//這一步注意,不要為負數(shù)}return 0; }?
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎總結
以上是生活随笔為你收集整理的【HDU - 5187】zhx's contest (快速幂+ 快速乘,模板)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: e平台3.0首款车型!比亚迪海豚纯色版发
- 下一篇: 卢伟冰老东家 金立公司成老赖:失信总额超