首页 > 专题系列 > Java解POJ > POJ 3185 The Water Bowls [解题报告] Java
2013
11-12

POJ 3185 The Water Bowls [解题报告] Java

The Water Bowls

问题描述 :

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?

输入:

Line 1: A single line with 20 space-separated integers

输出:

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.

样例输入:

0 0 1 1 1 0 0 1 1 0 1 1 0 0 0 0 0 0 0 0

样例输出:

3

温馨提示:

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]

解题代码:

/* @author: */
import java.util.Scanner;
public class Main {
	
  static boolean b[]=new boolean[20];
  
  static void set( int k ) {
	if( k !=0) b[k-1] = !b[k-1];
	b[k] = !b[k];
	if( k< 19 ) b[k+1] = !b[k+1];
}

 public static void main(String[] args) {
  Scanner sc = new Scanner(System.in);
   int a[]=new int[20];
   int i, j, ans, count;

   for( i=0; i< 20; i++ )
     a[i]=sc.nextInt();
   ans = 20;

   for( i=0; i< 2; i++ ) {
    for( j=0; j< 20; j++ )
	b[j] = (a[j]==1?true:false);
   count = 0;
   if( (i & 1)!=0 ) {
	set( 0 );
	count ++;
   }

   for( j=0; j< 19; j++ ) {
	if( b[j] == true ) {
		set( j+1 );
		count++;
	}
   }

  if( b[19] == false && count < ans )
	ans = count;
  }

  System.out.printf( "%d\n", ans );
  }
}