POJ3185-The Water Bowls-反转问题

来源:互联网 发布:近几年大学生就业数据 编辑:程序博客网 时间:2024/06/05 20:54

原题链接
The Water Bowls
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 6210 Accepted: 2443
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]
Source

USACO 2006 January Bronze
题意:有20个碗排成一排,有些碗口朝上,有些碗口朝下。每次可以反转其中的一个碗,但是在反转该碗时,该碗左右两边的碗也跟着被反转(如果该碗为边界上的碗,则只有一侧的碗被反转)。求最少需要反转几次,可以使得所有碗口均朝上。
思路:对于第0只碗可以选择反转或者不翻转,如果反转第i只碗,那么第i+1,第i+2只碗也会反转,但是我们只是记录下来第i只碗是否反转即可,由于
这里写图片描述
的奇偶决定了i处是否需要反转,而
这里写图片描述
决定了i+1处是否需要反转,其实我们发现二者就是+f[i]和-f[i-k+1]的关系,所以我们维护的其实就是一个区间的和,这样的话我们就可以把复杂度从O(nk)降低到O(n)

#include <cstdio>#include <cstring>#include <iostream>using namespace std;const int INF = 0x3f3f3f3f;const int maxn = 22;int a[maxn],f[maxn];//假设0和21位置有一个瓶子,0位置的瓶子是否倒置作为初始条件,而最后一次操作就停留在19上,我们认为每次操作只是以区间最左端的元素是否倒立来确定是否需要对这个区间进行反转int c(int first,int k){    memset(f,0,sizeof(f));    int sum=0,res=0;    if(first==1){        sum=1;res=1;f[0]=1;    }    for(int i=1;i<20;i++){        if((sum+a[i])&1) f[i]=1;        if(i+1-k>=0) sum -= f[i+1-k];         sum += f[i];    }    if((f[18]+f[19]+a[20])&1) return INF;    for(int i=1;i<20;i++){        if(f[i]) res++;    }    return res;}int main(){    for(int i=1;i<=20;i++) scanf("%d",&a[i]);    cout << min(c(0,3),c(1,3)) << endl;    return 0;}
0 0
原创粉丝点击