Imagine you\'re in a tall building with a cat. The cat can survive a fall out of a low story window, but will die if thrown from a high floor. How can you figure out the lon
You can easily write a little DP (dynamic programming) for the general case of n floors and m cats.
The main formula, a[n][m] = min(max(a[k - 1][m - 1], a[n - k][m]) + 1) : for each k in 1..n
, should be self-explanatory:
k - 1
floors to check (all below k
) and m - 1
cats (a[k - 1][m - 1]
). n - k
floors left (all floors above k
) and still m
cats. max
.+ 1
comes from the fact that we've just used one attempt (regardless of whether cat has survived or not).min(f(k)) : for k in 1..n
.It agrees with Google result from Gaurav Saxena's link for (100, 2).
int n = 100; // number of floors
int m = 20; // number of cats
int INFINITY = 1000000;
int[][] a = new int[n + 1][m + 1];
for (int i = 1; i <= n; ++i) {
// no cats - no game
a[i][0] = INFINITY;
}
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
// i floors, j cats
a[i][j] = INFINITY;
for (int k = 1; k <= i; ++k) {
// try throw first cat from k-th floor
int result = Math.max(a[k - 1][j - 1], a[i - k][j]) + 1;
a[i][j] = Math.min(a[i][j], result);
}
}
}
System.out.println(a[n][m]);
You can easily find strategy (how to throw first cat), if you save best k
in another array.
There's also a faster solution, not involving O(n^3) computations, but I'm a bit sleepy already.
edit
Oh yeah, I remember where I saw this problem before.