参考:
算法辅导课
DP1 时间复杂度:$O(n^2 m)$
import java.util.*;
public class Main {
public static void main(String [] args) {
int [][] f = new int[101][11];
int n , m;
Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
n = sc.nextInt();
m = sc.nextInt();
for(int i = 1 ;i <= n ;i ++) f[i][1] = i; // 测量长度为i,有1个鸡蛋。最坏情况的最小值i
for(int i = 1 ;i <= m ;i ++) f[1][i] = 1; // 测量长度为1,有i个鸡蛋。最坏情况的最小值1
for(int i = 2;i <= n ;i ++)
for(int j = 2 ;j <= m ;j ++) {
f[i][j] = f[i][j - 1];
for(int k = 2 ;k <= i ;k ++)
f[i][j] = Math.min(f[i][j],Math.max(f[k - 1][j - 1], f[i - k][j]) + 1);
}
System.out.println(f[n][m]);
}
}
}
DP2 时间复杂度:$O(nm)$
import java.util.*;
public class Main {
public static void main(String [] args) {
Scanner sc = new Scanner(System.in);
int [][] f = new int[101][11];
int n , m;
while(sc.hasNext()) {
n = sc.nextInt();
m = sc.nextInt();
for(int i = 1 ;i <= n ;i ++) {
// f[i - 1][j] 没碎
// f[i - 1][j - 1] 碎了
for(int j = 1 ;j <= m ;j ++) f[i][j] = f[i - 1][j] + f[i - 1][j - 1] + 1;
if(f[i][m] >= n) {
System.out.println(i);
break;
}
}
}
}
}