动态规划
时间复杂度O(N)
公式:
f(i,0)=f(i-1,1)
f(i,1)=(K-1) * (f(i-1,0) + f(i-1,1))
f(i,0)表示N=i时,以0开头的有效数字数目(其实不是有效数字,算出结果为下一步动态规划准备)
f(i,1)表示N=i时的有效数字数目
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
/**
* DP
* O(N)
* @author fytain
*
*/
public class URAL1009 {
static {
//System.setIn(URAL1009.class.getResourceAsStream("/data/URAL1009.txt"));
}
private static PrintWriter stdout = new PrintWriter(System.out);
private static StreamTokenizer stdin = new StreamTokenizer(new InputStreamReader(System.in));
private static int N;
private static int K;
//RESULT[i][0] -- the result for: N = i, first number = 0,
//RESULT[i][1] -- the result for: N = i, first number != 0,
private static int[][] RESULT = new int[18][2];
/**
* @param args
*/
public static void main(String[] args) throws Exception {
N = readInt();
K = readInt();
RESULT[0][0] = 1;
RESULT[0][1]= K - 1;
for (int i = 1; i < N; i++) {
RESULT[i][0] = RESULT[i-1][1];
RESULT[i][1] = (K - 1) * (RESULT[i-1][1] + RESULT[i-1][0]);
}
stdout.println(RESULT[N-1][1]);
stdout.flush();
}
private static int readInt() throws IOException {
stdin.nextToken();
return (int) stdin.nval;
}
}