This problem is from Timus Online Judge. The original problem description can be found here.
There are k steaks that can be cooked at the same time. So if
The algorithm should be greedy so that asap one side of steak is cooked.
Recursion Analysis (Decomposition)
We can decompose the problem into smaller ones by using recursive formula. Suppose we use
#include <iostream>
using namespace std;
int f(int n, int k) {
if (n <= k) return 2;
// n / k pairs of two mins
if (n % k == 0) return n / k * 2;
if (n > k && n < 2 * k) {
if (n - k > k / 2) {
return 4;
}
return 3;
}
// takes 2 mins to cook k steaks
return f(n - k, k) + 2;
}
int main() {
int n, k;
cin >> n >> k;
cout << f(n, k);
return 0;
}
It is easy to understand that the cases of
There are three steaks, a, b and c. a1, b1 and c1 are first side of steaks, a2, b2 and c2 are second side of streaks. The wrong cooking sequence is
- 1s: a1,b1
- 2s:a2,b2
- 3s:c1
- 4s:c2
The correct order should be:
- 1s:a1,b1
- 2s:a2,c1
- 3s:b2,c2
In other cases, the recursive formula is
The Pure Math Solution.
The above solution shows you how to analyse the problem into a smaller one (decomposition). It is an accepted solution since the problem input size is small (less than 1000). However, it is not the most efficient solution.
The total sides of steaks are
#include <iostream>
using namespace std;
int main() {
int n, k;
cin >> n >> k;
cout << (n<k?2:2*n%k?2*n/k+1:2*n/k);
return 0;
}
–EOF (The Ultimate Computing & Technology Blog) —
Last Post: Coding Exercise – Timus Online Judge – 1409. Two Gangsters, C/C++ solution
Next Post: Draw a Chess Board using LOGO (Turtle Graphics)
