非常可樂
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 13223 Accepted Submission(s): 5308
Problem Description
大家一定覺的運動以後喝可樂是一件很愜意的事情,但是seeyou卻不這麼認爲。因爲每次當seeyou買了可樂以後,阿牛就要求和seeyou一起分享這一瓶可樂,而且一定要喝的和seeyou一樣多。但seeyou的手中只有兩個杯子,它們的容量分別是N 毫升和M 毫升 可樂的體積爲S (S<101)毫升 (正好裝滿一瓶) ,它們三個之間可以相互倒可樂 (都是沒有刻度的,且 S==N+M,101>S>0,N>0,M>0) 。聰明的ACMER你們說他們能平分嗎?如果能請輸出倒可樂的最少的次數,如果不能輸出”NO”。
Input
三個整數 : S 可樂的體積 , N 和 M是兩個杯子的容量,以”0 0 0”結束。
Output
如果能平分的話請輸出最少要倒的次數,否則輸出”NO”。
Sample Input
7 4 3
4 1 3
0 0 0
Sample Output
NO
3
題目鏈接:http://acm.hdu.edu.cn/showproblem.php?pid=1495
題意
給出三個杯子的容量,一個杯子是滿的,另外兩個是空的,問能否利用這三個杯子平分可樂?如果可以輸出最少要倒的次數,不可以輸出'NO'。
題解
首先,由於沒有刻度,在倒可樂的時候,要麼把一個杯子倒空,要麼把一個杯子裝滿。
以兩個空杯子的狀態進行bfs寬搜,因爲兩個杯子的狀態確定了,最後一個杯子的狀態也就固定了,由於杯子的容量最多就是101,所以狀態的數量不會超過101x101種。
實現代碼中進行了簡單的轉換,默認cup[2]是裝滿的杯子,前兩個杯子是空杯子。且cup[0]杯子的容量大於cup[1]杯子的容量。
搜索時應注意:
(1)遍歷前兩個杯子的狀態入隊,不能自己倒給自己,且默認是杯子i倒給了杯子j,也就是說杯子i不能爲0,杯子j不能爲滿。
(2)amount = min(cup[j], u.v[i]+u.v[j]) - u.v[j];保證倒的時候不會超出杯子的容量。
(3)搜索停止條件:cup[0] == cup[2] && cup[1] == 0
#include <iostream>
#include <string.h>
#include <algorithm>
#include <stdio.h>
#include <math.h>
#include <stack>
#include <queue>
#include <vector>
#define INF 0xffffffff
using namespace std;
const int maxn = 105;
int vis[maxn][maxn];
int cup[3];
struct Node{
int v[3];
int t;
};
void solve(){
queue<Node> q;
Node st;
st.v[0] = st.v[1] = 0, st.v[2] = cup[2];
st.t = 0;
q.push(st);
vis[st.v[0]][st.v[1]] = 1;
while(!q.empty()){
Node u = q.front();
q.pop();
if(u.v[0] == u.v[2] && u.v[1] == 0){
printf("%d\n", u.t);
return;
}
//遍歷兩個杯子的狀態
for(int i=0; i<3; i++){
for(int j=0; j<3; j++){
if(i != j){
if(u.v[i] == 0 || u.v[j] == cup[2]) continue;
int amount = min(cup[j], u.v[i]+u.v[j]) - u.v[j];
Node u1;
memcpy(&u1, &u, sizeof(u));
u1.v[i] -= amount;
u1.v[j] += amount;
if(!vis[u1.v[0]][u1.v[1]]){
vis[u1.v[0]][u1.v[1]] = 1;
u1.t = u.t + 1;
q.push(u1);
}
}
}
}
}
printf("NO\n");
}
int main(){
int a, b, c;
while(scanf("%d%d%d", &c, &a, &b) == 3 && (a||b||c)){
if(a<b) swap(a, b);
cup[0] = a, cup[1] = b, cup[2] = c;
memset(vis, 0, sizeof(vis));
solve();
}
return 0;
}