您的位置:首页 > 其它

POJ 3483 A Very Simple Problem

2014-04-06 02:06 316 查看
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*109, and 1 ≤ x ≤ 50.

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

方法:矩阵快速幂,把x看成常数,x次幂一般规格为(x+2)*(x+2)的,矩阵构造不多说了,按照二项式展开对比就行

/*AC*/
#include <stdio.h>
#include <string.h>
#include <iostream>

using namespace std;
typedef long long LL;
typedef struct matrix {
LL a[55][55];
} matrix;

matrix E, M, R;
LL n, x, m;

void InitE() {
for (int i = 0; i < 55; i++)
for (int j = 0; j < 55; j++)
E.a[i][j] = (i == j);
}

void InitM() {
memset(M.a, 0, sizeof (M.a));
for (int i = 0; i <= x; i++) {
M.a[i][0] = x;
for (int j = 1; j <= i; j++)
M.a[i][j] = (M.a[i - 1][j - 1] + M.a[i - 1][j]) % m;
}
for (int j = 0; j <= x; j++)
M.a[x + 1][j] = M.a[x][j];
M.a[x + 1][x + 1] = 1;
}

void InitR() {
memset(R.a, 0, sizeof (R.a));
for (int i = 0; i <= x + 1; i++)
R.a[i][0] = x;
}

matrix mul(matrix A, matrix B) {
matrix C;
for (int i = 0; i <= x + 1; i++)
for (int k = 0; k <= x + 1; k++) {
C.a[i][k] = 0;
for (int j = 0; j <= x + 1; j++)
C.a[i][k] = (C.a[i][k] + (A.a[i][j] * B.a[j][k]) % m) % m; //尼玛把乘号写成了加号,找了半天的错误
}
return C;
}

matrix pow(matrix A, int n) {
matrix C = E;
while (n) {
if (n & 1)
C = mul(C, A);
A = mul(A, A);
n >>= 1;
}
return C;
}

int main() {
InitE();
while (cin >> n >> x >> m) {
if (n < 0 && x < 0 && m < 0)
break;
InitM();
InitR();
matrix B = pow(M, n - 1);
B = mul(B, R);
LL ans = B.a[x + 1][0];
cout << ans << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: