POJ:3185-The Water Bowls(枚举反转)

The Water Bowls

Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 7402 Accepted: 2927

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]


解题心得:

  1. 有一行的碗,有的碗朝上有的碗朝下(1为上,0为下)。每次可以反转一只碗,如果反转一只碗,那么和这个碗相邻的碗也会反转,问最少反转多少次让所有的碗朝下。
  2. 想了很多种方法,最后还是枚举,总共二十只碗,有2^20次方中可能性,勉强可以接受。然后在枚举的过程中可以剪一下枝。

#include <algorithm>
#include <stdio.h>
#include <cstring>
#include <climits>
using namespace std;
const int maxn = 25;

int num[maxn];

int get(int x) {//较快的获得x的二进制中有多少个1
    int cnt = 0;
    while(x) {
        x &= (x-1);
        cnt++;
    }
    return cnt;
}

bool check(int x) {//检查是否完全反转向下
    int num2[maxn];
    memcpy(num2,num,sizeof(num));
    for(int i=0;i<20;i++) {
        if(1&(x>>i)) {
            num2[i]++;
            if(i-1>=0)
                num2[i-1]++;
            num2[i+1]++;
        }
    }
    for(int i=0;i<20;i++) {
        if(num2[i]%2)
            return true;
    }
    return false;
}

int main() {
    for(int i=0;i<20;i++)
        scanf("%d",&num[i]);
    int ans = INT_MAX;
    for(int i=0;i<(1<<20);i++) {
        int num_1 = get(i);
        if(num_1 > ans)//如果现在枚举的数二进制中1的个数比当前答案还多可以直接剪去
            continue;
        if(check(i))
            continue;
        else
            ans = min(ans,get(i));
    }
    printf("%d\n",ans);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值