poj3185 The Water Bowls 开关问题

来源:互联网 发布:手机淘宝退货流程图 编辑:程序博客网 时间:2024/06/06 03:28
Total Submission(s) : 3   Accepted Submission(s) : 3
Problem 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
 
题意:有20个碗依次排列,有的碗口朝上,有的碗口朝下,牛希望所有的碗口都能朝上,每次翻动某个碗时,他左边和右边的碗也会翻转到相反的状态,问要想将这些碗碗口都朝上,至少要翻动多少次。
首先没每个碗最多翻动一次,否则重复,而且碗先翻与否不影响结果,故可以贪心法从头到尾考虑每一个碗,对于没个碗,如果左边的碗朝上,则它不能翻动,反之则需要翻动,对第一个碗分翻与不翻两种情况考虑,判断最后一个碗是否朝上且取较小的值即可。
因为只有两边的碗是最特殊的,然后我们对第一第二个碗的状态进行枚举,是能够改变最后两个碗的状态的。所以,我们通过枚举前两个碗的状态,然后再进行朴素算法来进行求解
#include <iostream>#include <algorithm>#include <string.h>#include <stdio.h>#include <cmath>#include <vector>#include <queue>#include <utility>using namespace std;int bowls1[25], bowls2[25];int main() {        //freopen("in.txt", "r", stdin);    int ans1 = 1, ans2 = 0;    for (int i = 1; i <= 20; ++i) {        cin >> bowls1[i];        bowls2[i] = bowls1[i];    }        bowls1[1]++; bowls1[2]++;    for (int i = 2; i <= 20; ++i) {        if (bowls1[i - 1] % 2) {            bowls1[i - 1]++;            bowls1[i]++;            bowls1[i + 1]++;            ans1++;        }    }        for (int i = 2; i <= 20; ++i) {        if (bowls2[i - 1] % 2) {            bowls2[i - 1]++;            bowls2[i]++;            bowls2[i + 1]++;            ans2++;        }    }    cout << min(ans1, ans2) << endl;}