书山有径勤为路>>>>>>>>

<<<<<<<<学海无涯苦作舟!

DFS解决USACO——Mother's Milk

Description

Farmer John has three milking buckets of capacity A, B, and C liters. Each of the numbers A, B, and C is an integer from 1 through 20, inclusive. Initially, buckets A and B are empty while bucket C is full of milk. Sometimes, FJ pours milk from one bucket to another until the second bucket is filled or the first bucket is empty. Once begun, a pour must be completed, of course. Being thrifty, no milk may be tossed out.

Write a program to help FJ determine what amounts of milk he can leave in bucket C when he begins with three buckets as above, pours milk among the buckets for a while, and then notes that bucket A is empty.

Input

A single line with the three integers A, B, and C.

Output

A single line with a sorted list of all the possible amounts of milk that can be in bucket C when bucket A is empty.

Sample Input

2 5 10

Sample Output

5 6 7 8 9 10

看到了这里的Rest数组没有,
既然是bool类型的,又学习了。
 
 
#include "iostream"
#include "string.h"
using namespace std;
#define size 21
bool Rest[size];
bool flag[size][size];
int A, B, C;
void DFS(int a, int b, int c)
{
	if(flag[a][b]) return;
	flag[a][b] = true;
	if(a==0) Rest[c] = true;
	//min防溢出,max防负数
	if(a>0 && b<B)  //A向B倒, c不变
		DFS(max(0, a+b-B), min(B, a+b), c);
	if(a>0 && c<C)  //A向C倒,b不变
		DFS(max(0, a+c-C), b, min(C, a+c));
	if(b>0 && a<A)  //B向A倒,c不变
		DFS(min(A, a+b), max(0, b+a-A), c);
	if(b>0 && c<C)  //B向C倒,a不变
		DFS(a, max(0, b+c-C), min(C, b+c));
	if(c>0 && a<A)  //C向A倒,b不变
		DFS(min(A, a+c), b, max(0, a+c-A));
	if(c>0 && b<B)  //C向B倒,a不变
		DFS(a, min(B, b+c), max(0, b+c-B));
}
int main()
{
	cin>>A>>B>>C;
	memset(flag, false, sizeof(flag));
	memset(Rest, false, sizeof(Rest));
	DFS(0, 0, C);
	for(int i=0; i<C; i++)
		if(Rest[i])
			cout<<i<<" ";
	cout<<C<<endl;
}

posted on 2011-10-16 18:45  More study needed.  阅读(751)  评论(0编辑  收藏  举报

导航

书山有径勤为路>>>>>>>>

<<<<<<<<学海无涯苦作舟!