链接:http://lightoj.com/volume_showproblem.php?problem=1132
1132 - Summing up Powers
PDF (English) | Statistics | Forum |
Time Limit: 2 second(s) | Memory Limit: 32 MB |
Given N and K, you have to find
(1K + 2K + 3K + ... + NK) % 232
Input
Input starts with an integer T (≤ 200), denoting the number of test cases.
Each case contains two integers N (1 ≤ N ≤ 1015) and K (0 ≤ K ≤ 50) in a single line.
Output
For each case, print the case number and the result.
Sample Input |
Output for Sample Input |
3 3 1 4 2 3 3 |
Case 1: 6 Case 2: 30 Case 3: 36 |
题意:给n和k 计算那串公式的值。
做法:
找出 1^k 怎么推到2^k 再推到n^k的方法,再开一维记录总的值,就ok了。
初始矩阵
1^ 0 1^1 1^2 1^3 .....1^k 总
构造矩阵:
C(0,0) C(0,1) C(0,2) C(0,3)...C(0,k-1) C(0,k) 0
0 C(1,1) C(1,2) C(1,3)...C(1,k-1) C(1,k) 0
......
0 0 0 0 C(k-1,k-1) C(k-1,k) 0
0 0 0 0 0 C(k,k) 1
0 0 0 0 0 0 1
C(n,m)=C(n-1,m)+C(n-1,m-1);
#include<stdio.h> #include<string.h> #define Matr 55 //矩阵大小,注意能小就小 矩阵从1开始 所以Matr 要+1 最大可以100 #define ll unsigned int #define LL long long struct mat//矩阵结构体,a表示内容,size大小 矩阵从1开始 但size不用加一 { ll a[Matr][Matr]; mat()//构造函数 { memset(a,0,sizeof(a)); } }; int Size ; mat multi(mat m1,mat m2)//两个相等矩阵的乘法,对于稀疏矩阵,有0处不用运算的优化 { mat ans=mat(); for(int i=1;i<=Size;i++) for(int j=1;j<=Size;j++) if(m1.a[i][j])//稀疏矩阵优化 for(int k=1;k<=Size;k++) ans.a[i][k]=(ans.a[i][k]+m1.a[i][j]*m2.a[j][k]); //i行k列第j项 return ans; } mat quickmulti(mat m,LL n)//二分快速幂 { mat ans=mat(); int i; for(i=1;i<=Size;i++)ans.a[i][i]=1; while(n) { if(n&1)ans=multi(m,ans);//奇乘偶子乘 挺好记的. m=multi(m,m); n>>=1; } return ans; } void print(mat m)//输出矩阵信息,debug用 { int i,j; printf("%d\n",Size); for(i=1;i<=Size;i++) { for(j=1;j<=Size;j++) printf("%u ",m.a[i][j]); printf("\n"); } } int main() { LL n; int t; int cas=1; int k; scanf("%d",&t); while(t--) { scanf("%lld%d",&n,&k); mat gouzao=mat(),chu=mat(); printf("Case %d: ",cas++); Size=k+2; for(int i=1;i<=k+1;i++) { chu.a[1][i]=1; } for(int j=1;j<=k+1;j++) { for(int i=1;i<=j;i++) { if(i==1||i==j) { gouzao.a[i][j]=1; continue; } else { gouzao.a[i][j]=gouzao.a[i][j-1]+gouzao.a[i-1][j-1]; } } } gouzao.a[k+1][k+2]=1; gouzao.a[k+2][k+2]=1; /*printf("chu\n"); print(chu); printf("gouzao\n"); print(gouzao);*/ printf("%u\n",multi(chu,quickmulti(gouzao,n)).a[1][k+2]); } return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。