描述:设大,中,小三个杯子的容量分别为a,b,c。开始时,A中装满了水,B,C都为空。你的任务是,判断经过一系列操作后,能否使其中一个杯子里出现x升水。(一次操作指把x杯子里的水倒入y杯子中,因为杯子没有刻度 ,所以倒水时只允许将x杯子倒空,或将y杯子倒满。
输入:四个整数a,b,c,x.(1<=a<=b<=c<100,0<x<100)
输出:能的话,输出最短的操作步数,否则输出Impossible.
样例:
6 3 1 4
10 8 7 5
输出:
3
impssbile
第一个样例所经过的步骤:(6,0,0)->(3,3,0)->(3,2,1)->(4,2,0)
只有六种状态,BFS一下
a->b,a->c
b->a,b->c
c->a,c->b
#include <stdio.h> #include <string.h> #include <algorithm> #include <iostream> #include <math.h> #include <queue> using namespace std; const double eps = 1e-6; const int MAXN = 100010; const double INF = 1e20; int visit[101][101]; int aa[3]; int x; struct Node { int cap[3],step; Node(int x, int y,int z,int p) { cap[0] = x,cap[1] = y, cap[2] = z , step = p; } Node() {} }; int BFS() { memset(visit,0,sizeof(visit)); queue<Node> Q; Q.push(Node(aa[0],0,0,0)); visit[aa[0]][0] = 1; while(!Q.empty()) { Node temp = Q.front(),temp2; Q.pop(); if(temp.cap[0] == x || temp.cap[1] == x || temp.cap[2] == x) return temp.step; for(int i = 0; i < 3; i++) { for(int j = 0; j < 3; j++) { if(i == j) continue; int cha = aa[j] - temp.cap[j]; temp2 = temp; if(temp2.cap[i] && cha ) { if(temp2.cap[i] > cha) { temp2.cap[j] = aa[j]; temp2.cap[i] -= cha; } else { temp2.cap[j] += temp2.cap[i]; temp2.cap[i] = 0; } if(!visit[temp2.cap[0]][temp2.cap[1]]) { visit[temp2.cap[0]][temp2.cap[1]] = 1; Q.push(Node(temp2.cap[0],temp2.cap[1],temp2.cap[2],temp2.step+1)); } } } } } return -1; } int main() { #ifdef xxz freopen("in.txt","r",stdin); #endif // xxz while(~scanf("%d%d%d%d", &aa[0], &aa[1], &aa[2],&x)) { int ans = BFS(); if(ans == -1) printf("Impossible\n"); else printf("%d\n",ans); } return 0; }
时间: 2024-08-10 17:21:39