1. 程式人生 > >三個水杯

三個水杯

時間 並且 ret lin tar arch 輸出 nbsp void

三個水杯

時間限制:1000 ms | 內存限制:65535 KB 難度:4
描述
給出三個水杯,大小不一,並且只有最大的水杯的水是裝滿的,其余兩個為空杯子。三個水杯之間相互倒水,並且水杯沒有標識,只能根據給出的水杯體積來計算。現在要求你寫出一個程序,使其輸出使初始狀態到達目標狀態的最少次數。
輸入
第一行一個整數N(0<N<50)表示N組測試數據
接下來每組測試數據有兩行,第一行給出三個整數V1 V2 V3 (V1>V2>V3 V1<100 V3>0)表示三個水杯的體積。
第二行給出三個整數E1 E2 E3 (體積小於等於相應水杯體積)表示我們需要的最終狀態
輸出
每行輸出相應測試數據最少的倒水次數。如果達不到目標狀態輸出-1
樣例輸入
2
6 3 1
4 1 1
9 3 2
7 1 1
樣例輸出
3
-1
來源
經典題目

廣度優先搜索,貌似可以用A*,可惜不怎麽會,以後試試。

# include <stdio.h>  
# include <stdlib.h>  
# include <string.h>  
# include <string>  
  
void check (int queue[], int x, int &tail) {  
    for (int i = 0; i <= tail; ++ i) {  
        
if (queue[i] == x) { return; } } ++ tail; //printf ("%d -> ", x); queue[tail] = x; return; } int getans(int to[], int i) { if (i == to[1] * 10000 + to[2] * 100 + to[3]) return 1; return 0; } int daoshui(int queue[], int &a, int
&b, int to, int from[]) { if (a) { int t = from[to] - b; if (t > a) { b += a; a = 0; return 1; } else if (t) { a -= t; b += t; return 1; } } return 0; } int main () { int n; scanf ("%d", &n); while (n --) { int from[4]; int to[4]; scanf ("%d %d %d %d %d %d", &from[1], &from[2], &from[3], &to[1], &to[2], &to[3]); int head = 0; int tail = 0; int step = 0; int queue[100000]; queue[0] = from[1] * 10000; int flag = 0; if (queue[0] == to[1] * 10000 + to[2] * 100 + to[3]) {printf("0\n");continue;} while (head <= tail) { ++ step; //printf("******************************%d************************************\n", step); int size = tail - head; for (int i = head; i <= head + size; ++ i) { int a, b, c; //printf ("|%d|", queue[i]); a = queue[i] / 10000; b = queue[i] % 10000 / 100; c = queue[i] % 100; if (daoshui(queue, a, b, 2, from)) { //printf ("(a -> b)"); check(queue, a * 10000 + b * 100 + c, tail); } a = queue[i] / 10000; b = queue[i] % 10000 / 100; c = queue[i] % 100; if (daoshui(queue, a, c, 3, from)) { //printf ("(a -> c)"); check(queue, a * 10000 + b * 100 + c, tail); } a = queue[i] / 10000; b = queue[i] % 10000 / 100; c = queue[i] % 100; if (daoshui(queue, b, a, 1, from)) { //printf ("(b -> a)"); check(queue, a * 10000 + b * 100 + c, tail); } a = queue[i] / 10000; b = queue[i] % 10000 / 100; c = queue[i] % 100; if (daoshui(queue, b, c, 3, from)) { //printf ("(b -> c)"); check(queue, a * 10000 + b * 100 + c, tail); } a = queue[i] / 10000; b = queue[i] % 10000 / 100; c = queue[i] % 100; if (daoshui(queue, c, a, 1, from)) { //printf ("(c -> a)"); check(queue, a * 10000 + b * 100 + c, tail); } a = queue[i] / 10000; b = queue[i] % 10000 / 100; c = queue[i] % 100; if (daoshui(queue, c, b, 2, from)) { //printf ("(c -> b)"); check(queue, a * 10000 + b * 100 + c, tail); } } //printf ("\n****************************************************************"); head += size + 1; for (int i = head; i <= tail; ++ i) { if (getans(to, queue[i])) { printf ("%d\n", step); flag = 1; break; } } if (flag) break; } //printf("\n"); if (!flag) printf ("-1\n"); } return 0; }

三個水杯