At first I did not think of using BFS to do ....
Three cups of water
Time limit: ms | Memory limit:65535 KB
Difficulty:4
Describe
Give three cups, different sizes, and only the largest cup of water is filled, the remaining two are empty cups. Three cups of water are poured between each other, and the cups are not identified and can only be calculated according to the volume of the cups given. You are now asked to write a program that outputs the minimum number of times that the initial state reaches the target State.
-
Enter
-
First row an integer N (0<n <50) represents the N group of test data
The next two lines of test data, the first row gives three integers V1 V2 V3 (v1>v2>v3 v1<100 v3>0) represents the volume of three cups.
The second line gives three integers E1 E2 E3 (volume less than equal to the corresponding Cup volume) represents the final state we need
-
Output
-
Each row outputs the minimum number of water pours for the corresponding test data. If the target status output is not reached-1
-
Sample input
-
26 3 14 1 19 3 27 1 1
-
Sample output
-
3-1
#include <iostream> #include <cstring> #include <queue>using namespace std;int v[3],e[3];//Water cup capacity, target State bool visited[102][102][102];//structure _ Water Cup current state and step struct cupstatus{ int c[3];int step;};/ /Determines whether the current state conforms to the target State requirement (congruent) Bool isobject (cupstatus cur) {int i;for (i=0;i<3;i++) if (cur. C[i]!=e[i]) Return false;return true;} Dumping Void pour (int obj, int sour, cupstatus& cur) {int differ=V[obj]-cur. C[obj];if (cur. C[sour]>=differ) {cur. C[obj]+=differ;cur. C[sour]-=differ;} Else{cur. C[obj]+=cur. C[sour];cur. c[sour]=0;}} Int bfs () {Int i,j,k;cupstatus init;queue<cupstatus> pourstatus;memset (Visited,false, sizeof (visited)); init. C[0]=v[0];init. C[1]=init. C[2]=0;init.step=0;pourstatus.push (init);//initial state into queue visited[init. c[0]][0][0]=true;//set access status to Truewhile (!pourstatus.empty ()) {Cupstatus front=pourstatus.front (); Pourstatus.pop (); if (IsObject (front)) return front.step;for (i=0;i<3;i++) {for (j=1;j<3;j++) {k= (i+j)%3;if (front. C[i]!=0 && front. C[K]<V[K]) {cupstatus newfront=front; Pour (K,i,newfront); Newfront.step=front.step+1;if (!visited[newfront.c[0]][newfront.c[1]][newfront.c[2]]) { Visited[newfront.c[0]][newfront.c[1]][newfront.c[2]]=true;pourstatus.push (Newfront);}}}} Return -1;} Int main () {int n;cin>>n;while (n--) {cin>>v[0]>>v[1]>>v[2];//Input cup capacity cin>> e[0]>>e[1]>>e[2];//Enter the cup target status Cout<<bfs () <<endl;} return 0;}
This article is from the "hacker" blog, make sure to keep this source http://anglecode.blog.51cto.com/5628271/1640230
NYOJ21 Three cups of water