srm#397_div1_500pt 矩阵乘法+快速模幂
題目地址:srm#397_div1_500
題目描述:
Problem Statement | |||||||||||||
| ? | NOTE: This problem statement contains superscripts that may not display properly if viewed outside of the applet. You are given ints n and k. Return the value of the sum 1k + 2k + 3k + ... + nk modulo 1000000007. | ||||||||||||
Definition | |||||||||||||
| ? |
| ||||||||||||
Limits | |||||||||||||
| ? |
| ||||||||||||
Constraints | |||||||||||||
| - | n will be between 1 and 109, inclusive. | ||||||||||||
| - | k will be between 1 and 50, inclusive. | ||||||||||||
Examples | |||||||||||||
| 0) | ? | ||||||||||||
| ? |
| ||||||||||||
| 1) | ? | ||||||||||||
| ? |
| ||||||||||||
| 2) | ? | ||||||||||||
| ? |
| ||||||||||||
| 3) | ? | ||||||||||||
| ? |
| ||||||||||||
This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2003, TopCoder, Inc. All rights reserved. ? ??
構(gòu)造一個k+2階矩陣;
這里n比較大 顯然我們接受不了O(n)的復(fù)雜度
最好的方法就是像求Fibonacci數(shù)列第n項一樣用矩陣乘法+快速冪做
要實現(xiàn)求和長度在k左右的遞推式
首選(n+1)^k-n^k=sigma(c[k][i]*n^i);
?
直接看代碼里面的矩陣構(gòu)造吧
wa了幾次
1 組合數(shù)是要求到c[52][i]的
2 因為mod 10^9+7 所以存在的數(shù)都是可能接近int上限的 ?要進(jìn)行+運(yùn)算 所以要用long long 存儲
代碼:
#include<iostream>typedef long long inta ;using namespace std;struct Matrix {inta m[60][60];};inta n; // 用來表示維度inta c[60][60]; //組合數(shù)const inta mod=1000000007;void init() {for(inta i=0;i<=55;i++)c[i][0]=1;for(inta i=0;i<55;i++)for(inta j=0;j<=i;j++)c[i+1][j+1]=c[i][j+1]+c[i][j];}Matrix multi(Matrix a,Matrix b) {Matrix ans;for(inta i=0;i<n;i++)for(inta j=0;j<n;j++){inta c=0;for(inta k=0;k<n;k++)c=(c+a.m[i][k]*b.m[k][j])%mod;ans.m[i][j]=c;}return ans;}Matrix quick_mod(Matrix a,inta b) {Matrix ans;Matrix p=a;for(inta i=0;i<n;i++)for(inta j=0;j<n;j++)ans.m[i][j]=(i==j?1:0);while(b){if(b&1){ans=multi(ans, p);b--;}b>>=1;p=multi(p, p);}return ans;}class SumOfPowers {public :inta value(inta nn,inta k){init();n=k+2;Matrix A;for(inta i=0;i<n;i++) // so importantfor(inta j=0;j<n;j++)A.m[i][j]=0;for(inta i=0;i<k+1;i++)for(inta j=0;j<=i;j++)A.m[i][j]=c[i][j]%mod;for(inta i=0;i<k+1;i++)A.m[k+1][i]=c[k][i]%mod;A.m[k+1][k+1]=1;A=quick_mod(A, nn-1);inta ans=0;for(inta i=0;i<k+2;i++)ans=(ans+A.m[k+1][i])%mod;return ans;} };int main() {inta nn,k;cin>>nn>>k;SumOfPowers obj;cout<<obj.value(nn, k)<<endl;}tc上提交沒有main()
轉(zhuǎn)載于:https://www.cnblogs.com/jingqi814/p/3644368.html
總結(jié)
以上是生活随笔為你收集整理的srm#397_div1_500pt 矩阵乘法+快速模幂的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MVC4.0网站发布和部署到IIS7.0
- 下一篇: 《软件架构师的12项修炼》读书笔记-技术