I thought about what I did last night, and I was not in the mood when I went to the dormitory. I found that high precision is really not familiar with various errors, crash, MLE, wa... At last, we can see that there are two digits in an array space, and the precision is 100.
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int N = 1000;
int ans[N*2][N+1];
int tmp[N+1];
void add(int a[], int b[], int res[]){
int i;
for(i = N; i >= 0; i--){
res[i] = a[i] + b[i];
}
for(i = N; i >= 0; i--){
res[i-1] += res[i]/100;
res[i] %= 100;
}
}
void mul(int a[], int k, int res[]){
int i;
for(i = N; i >= 0; i--){
res[i] = a[i] * k;
}
for(i = N; i >= 0; i--){
res[i-1] += res[i]/100;
res[i] %= 100;
}
}
void print(int res[]){
int i = 0;
while(res[i] == 0) i++;
printf("%d", res[i++]);
for(; i <= N; i++){
if(res[i] > 9)
printf("%d", res[i]);
else
printf("0%d", res[i]);
}
putchar('\n');
}
int main(){
//freopen("data.in", "r", stdin);
int n, k, i;
while(scanf("%d%d", &n, &k) != EOF){
//printf("%d %d\n", n, k);
memset(ans, 0, sizeof(ans));
ans[0][N] = k-1;
ans[1][N] = k*(k-1);
for(i = 2; i < n; i++){
memset(tmp, 0, sizeof(tmp));
add(ans[i-1], ans[i-2], tmp);
mul(tmp, k-1, ans[i]);
}
print(ans[n-1]);
}
return 0;
}