Watermelon (4A) has one of the highest solve counts on Codeforces, and also one of the highest first-attempt failure rates. The whole problem comes down to a single edge case. Before reading the solution, it is worth trying to find that edge case yourself.
The problem in short
Two friends buy a watermelon weighing w kilos (1 ≤ w ≤ 100). They want to cut it into two pieces so that each piece weighs an even number of kilos. The pieces do not have to be equal, but each must have positive weight. Print YES if such a split exists, otherwise NO.
Full statement: Codeforces 4A – Watermelon.
Thinking it through
If both pieces are even, their sum is even. So an odd w is immediately impossible.
If w is even, can we always do it? The smallest positive even number is 2, so try a split of 2 and w − 2. The second piece is even (even minus even), and it is positive as long as w > 2.
That leaves exactly one even weight that fails: w = 2. The only split into positive whole parts is 1 + 1, and 1 is odd.
So the rule is: YES if w is even and w > 2, otherwise NO.
Checking a few values
- w = 8 → 2 + 6 (or 4 + 4) → YES
- w = 7 → odd → NO
- w = 2 → only 1 + 1 → NO
- w = 4 → 2 + 2 → YES
- w = 1 → odd → NO
Solution in C
#include <stdio.h>
int main(void) {
int w;
scanf("%d", &w);
/* Both parts must be even and positive, so w must be even and at least 4. */
if (w % 2 == 0 && w > 2)
printf("YES\n");
else
printf("NO\n");
return 0;
}
Complexity
One comparison: O(1) time and memory.
Why so many people fail it
The natural first submission is if (w % 2 == 0), which passes every sample and fails on w = 2. The habit to build from this problem is simple: after you write a condition, test it on the smallest valid inputs (here 1, 2, 3, 4) before submitting. Small inputs are where “obvious” rules break.
You may also notice that I removed the 1 ≤ w ≤ 100 range check that some solutions include. The judge guarantees the constraints, so checking them only adds code that can be wrong.
Practice next
For more problems where a tiny observation replaces the whole algorithm, try 50A Domino Piling and 1A Theatre Square.
But it says time limit exceeded !!
ReplyDeleteWhat to do about it? when time has exceeded?? kam time mein kaise solve kare?
ReplyDeletehttps://cp-editorials.blogspot.com/2020/12/watermelon-4a-codeforces.html
ReplyDelete