10603 Fill
There are three jugs with a volume of a, b and c liters. (a, b, and c are positive integers not greater than 200). The rst and the second jug are initially empty, while the third is completely lled with water. It is allowed to pour water from one jug into another until either the rst one is empty or the second one is full. This operation can be performed zero, one or more times.
You are to write a program that computes the least total amount of water that needs to be poured; so that at least one of the jugs contains exactly d liters of water (d is a positive integer not greater than 200). If it is not possible to measure d liters this way your program should nd a smaller amount of water d′ < d which is closest to d and for which d′ liters could be produced. When d′ is found, your program should compute the least total amount of poured water needed to produce d′ liters in at least one of the jugs.
Input
The rst line of input contains the number of test cases. In the next T lines, T test cases follow. Each test case is given in one line of input containing four space separated integers — a, b, c and d.
Output
The output consists of two integers separated by a single space. The rst integer equals the least total amount (the sum of all waters you pour from one jug to another) of poured water. The second integer equals d, if d liters of water could be produced by such transformations, or equals the closest smaller value d′ that your program has found.
Sample Input
2
2342 96 97 199 62Sample Output
2 2
9859 62
解题思路:
1.将两个水罐中水量(a,b)作为状态量 ,枚举所有状态,共有201*201=40401种情况。
2.每次取倒水量最小的状态展开,因此采用优先队列(priority_queue)进行存储,在state结构类中定义静态成员函数‘<’;
3.记录每个状态需要的最小倒水量。
代码:
1 #include2 #include 3 #include 4 #include 5 #include 6 using namespace std; 7 8 const int maxn=200+5; 9 10 struct state{11 int v[3]={ 0},dist=0;12 bool operator <(const state& u)const {13 return dist>u.dist;14 }15 };16 17 int vis[maxn][maxn],jug[3],ans[maxn],d;18 19 void update_ans(const state& u){20 for(int i=0;i<3;i++){21 int d=u.v[i];22 if(ans[d]==-1||ans[d]>u.dist)23 ans[d]=u.dist;24 }25 }26 27 void solve(int d){28 memset(vis,0,sizeof vis);29 memset(ans,-1,sizeof ans);30 priority_queue q;31 state start;32 start.v[0]=start.v[1]=0;start.v[2]=jug[2];33 start.dist=0;34 q.push(start);35 vis[0][0]=1;36 while(!q.empty()){37 state u=q.top();q.pop();38 update_ans(u);39 if(ans[d]>=0) break;40 for(int i=0;i<3;i++)41 for(int j=0;j<3;j++)42 if(i!=j){43 if(u.v[i]>0&&u.v[j] =0){58 if(ans[d]>=0){59 printf("%d %d\n",ans[d],d);60 return ;61 }62 d--;63 }64 }65 int main() {66 int T;67 scanf("%d",&T);68 while(T--){69 scanf("%d%d%d%d",&jug[0],&jug[1],&jug[2],&d);70 solve(d);71 }72 return 0;73 }