The Water Bowls
Time Limit: 1000MS Memory Limit: 65536K
Description
The cows have a line of 20 water bowls from which they drink. The bowls can be either right-side-up (properly oriented to serve refreshing cool water) or upside-down (a position which holds no water). They want all 20 water bowls to be right-side-up and thus use their wide snouts to flip bowls.
Their snouts, though, are so wide that they flip not only one bowl but also the bowls on either side of that bowl (a total of three or – in the case of either end bowl – two bowls).
Given the initial state of the bowls (1=undrinkable, 0=drinkable – it even looks like a bowl), what is the minimum number of bowl flips necessary to turn all the bowls right-side-up?
Input
Line 1: A single line with 20 space-separated integers
Output
Line 1: The minimum number of bowl flips necessary to flip all the bowls right-side-up (i.e., to 0). For the inputs given, it will always be possible to find some combination of flips that will manipulate the bowls to 20 0’s.
Sample Input
0 0 1 1 1 0 0 1 1 0 1 1 0 0 0 0 0 0 0 0
Sample Output
3
Hint
Explanation of the sample:
Flip bowls 4, 9, and 11 to make them all drinkable:
0 0 1 1 1 0 0 1 1 0 1 1 0 0 0 0 0 0 0 0 [initial state]
0 0 0 0 0 0 0 1 1 0 1 1 0 0 0 0 0 0 0 0 [after flipping bowl 4]
0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 [after flipping bowl 9]
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 [after flipping bowl 11]
思路:
本题就是两边端点反转2,其他反转3,实际就是中间带着两边反转然后两端的话,左边或者右边没有端点了,所以就反转两个了,题目说了重要的一点,就是一定会全部反转成0,所以不用考虑最后一个的数字的情况,所以的话就有了前面的一个反转是由后面一个决定的。最后的话,就是有两种情况,正着和倒着,所以在之前加个0或1就行了,0是正,1是倒。
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 20;
int a[maxn + 1] = {0}, f[maxn + 1];
int rever(int x) {
memset(f, 0, sizeof(f));
f[0] = x;
int sum = x, res = 0;
for (int i = 1; i < maxn; i++) {
if ((a[i] + sum) & 1 == 1) {
res++;
f[i] = 1;
}
sum += f[i];
if (i >= 2) sum -= f[i - 2];
}
return res;
}
int main() {
for (int i = 1; i <= maxn; i++) scanf("%d", &a[i]);
cout << min(rever(0), rever(1) + 1) << endl;
return 0;
}