题目大意:求(1^K + 2^K + 3K + … + N^K) % 2^32
解题思路:
借用别人的图
可以先打表,求出Cnm,用杨辉三角可以快速得到
#include<cstdio>
typedef unsigned long long ll;
const int N = 55;
const ll mod = (1LL << 32);
struct Matrix{
ll mat[N][N];
}A, B, tmp;
ll n, num[N];
ll C[N][N];
int K;
void init2() {
C[0][0] = 1;
for(int i = 1; i <= 50; i++) {
C[i][i] = C[i][0] = 1;
for(int j = 1; j < i; j++)
C[i][j] = (C[i-1][j-1] + C[i-1][j]) % mod;
}
}
Matrix matMul(const Matrix &x, const Matrix &y) {
for(int i = 0; i < K + 2; i++)
for(int j = 0; j < K + 2; j++) {
tmp.mat[i][j] = 0;
for(int k = 0; k < K + 2; k++) {
tmp.mat[i][j] = (tmp.mat[i][j] + x.mat[i][k] * y.mat[k][j]) % mod;
}
}
return tmp;
}
void solve() {
while(n) {
if(n & 1)
B = matMul(B,A);
A = matMul(A,A);
n >>= 1;
}
}
void init() {
for(int i = 0; i < K + 2; i++)
for(int j = 0; j < K + 2; j++) {
B.mat[i][j] = A.mat[i][j] = 0;
if(i == j)
B.mat[i][j] = 1;
}
A.mat[0][0] = 1;
for(int i = 1; i < K + 2; i++)
A.mat[i][0] = A.mat[i][1] = C[K][i-1];
for(int i = 2; i < K + 2; i++)
for(int j = i; j < K + 2; j++) {
A.mat[j][i] = C[K-i+1][j-i];
}
}
int main() {
int test, cas = 1;
scanf("%d", &test);
init2();
while(test--) {
scanf("%lld%d", &n, &K);
printf("Case %d: ", cas++);
ll ans = ( (n % mod) * ( (n + 1) % mod) / 2) % mod;
if(K == 1) {
printf("%lld\n", ans);
continue;
}
init();
n--;
solve();
ans = 0;
for(int i = 0; i < K + 2; i++)
ans = (ans + B.mat[i][0] ) % mod;
printf("%lld\n", ans);
}
return 0;
}
时间: 2024-10-10 00:38:03