A Very Simple Problem
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 1126 Accepted Submission(s): 554
Problem Description
This is a very simple problem. Given three integers N, x, and M, your task is to calculate out the following value:
Input
There are several test cases. For each case, there is a line with three integers N, x, and M, where 1 ≤ N, M ≤ 2*10
9, and 1 ≤ x ≤ 50.
The input ends up with three negative numbers, which should not be processed as a case.
The input ends up with three negative numbers, which should not be processed as a case.
Output
For each test case, print a line with an integer indicating the result.
Sample Input
100 1 10000 3 4 1000 -1 -1 -1
Sample Output
5050 444
/*
Sn=1^x * x^1 + 2^x * x^2 +...+ n^x * x^n;
Sn+1=1^x * x^1 + 2^x * x^2 +...+ n^x * x^n+(n+1)^x * x^(n+1)
=Sn+(n+1)^x * x^(n+1),将(n+1)^x二项式展开然后用矩阵快速幂
构造矩阵:
|1 xC(x,0) xC(x,1) xC(x,2) ... xC(x,x)| |Sn | |S(n+1) |
|0 xC(x-1,0) ...... xC(x-1,x-1) | |x^n * n^x| |x^(n+1) * (n+1)^x|
|0 0 xC(x-2,0)...... xC(x-2,x-2) | *|... |=|... |
|... | |x^n * n^2| |x^(n+1) * (n+1)^2|
|... | |x^n * n^1| |x^(n+1) * (n+1)^1|
|0 0 0 0 xC(0,0) | |x^n * n^0| |x^(n+1) * (n+1)^0|
*/
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
long long c[51][51] ,N,M;
int x;
struct Node {
long long M[55];
}res;
struct Node_a {
long long M[55][55];
}ori;
void calc_comb() //组合数打表
{
c[0][0] = c[1][0] = c[1][1]=1;
for(int i=2;i<51;i++)
{
c[i][0] = c[i][i] = 1;
for(int j=1;j<i;j++)
c[i][j] = (c[i-1][j]+c[i-1][j-1])%M;
}
}
Node mul(Node a,Node_a b) //系数矩阵自乘
{
Node tem;
memset(tem.M,0,sizeof(tem.M));
for(int i=0;i<x+2;i++)
for(int j=0;j<x+2;j++)
tem.M[i]=(tem.M[i]+ori.M[i][j]*res.M[j])%M;
return tem;
}
Node_a mul1(Node_a a ,Node_a b)
{
Node_a tem;
memset(tem.M,0,sizeof(tem.M));
for(int i=0;i<x+2;i++)
for(int j=0;j<x+2;j++)
for(int k=0;k<x+2;k++)
tem.M[i][j]=(tem.M[i][j]+a.M[i][k]*b.M[k][j])%M;//防止越界
return tem;
}
void calc()
{
memset(ori.M,0,sizeof(ori.M)); ori.M[0][0]=1;
for(int i=1;i<=x+1;i++) //初始化系数矩阵第一行
ori.M[0][i]=(c[x][i-1]*x)%M;
for(int i=1;i<x+2;i++) //初始化第二行,往后
for(int j=i;j<x+2;j++)
ori.M[i][j]=(c[x+1-i][j-i]*x)%M;
for(int i=0;i<x+2;i++)
res.M[i]=x;
N--;
while(N)
{
if(N&1)
res=mul(res,ori);
N>>=1;
ori=mul1(ori,ori);
}
}
int main()
{
while(scanf("%lld%d%lld",&N,&x,&M))
{
if(N==-1 && M==-1 && x==-1)
break;
calc_comb();
calc();
printf("%lld\n",res.M[0]%M);
}
return 0;
}