The Water Bowls POJ - 3185 (反转问题)

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]

题意:给20个数(只含0 1)反转a[i] 连带 反转 a[i-1],a[i+1] 边界只带一个,给定序列一定能翻转完,最少翻多少次翻完

思路:

1,同一个区间肯定最多只能翻转 1 次(偶次==0次,奇次==1次)

2,结果跟反转顺序无关,

3,由 1 ,2 再加上(给定序列一定能翻转完 )可以推出——》答案就是求一个反转集合,

可以从左往右依次判断这个区间是否需要翻转:

4. 只需看此区间最左端是不是1 是就必须反转此区间(前面的都判断过了,只有这个区间有机会能反转它)不是则肯定不能反转(反转了后面区间无法再将其反转)

因为每一个区间都是在不得不反转的情况下反转的,所以答案就是最小的,

注意: a[1]有两种反转方式(被1连带反转 或 被2连带反转)与4前提条件不符,无法根据4处的推理来判断,所以要特判2种a[2] a[1]翻还是不翻;

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<math.h>
using namespace std;
int a[100],b[100];
int main()
{
	int n,m,j,i;
	for(i=1; i<=20; i++)
	{
		scanf("%d",&a[i]);
		b[i]=a[i];
	}
	int min1=0x3f3f3f3f;
	a[1]^=1,a[2]^=1;
	int sum=1;
	for(i=1; i<=19; i++)
	{
		if(a[i]) a[i]^=1,a[i+1]^=1,a[i+2]^=1,sum++;
	}
	if(a[20]==0)
	min1=min(min1,sum);
	sum=0;
	for(i=1; i<=19; i++)
	{
		if(b[i]) b[i]^=1,b[i+1]^=1,b[i+2]^=1,sum++;
	}
	if(b[20]==0)
	min1=min(min1,sum);
	printf("%d",min1);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值