3水杯倒水问题

问题:

给出三个杯子的容量ABC , 其中刚开始时C杯是满的,AB是空的。
现在在保证不会有漏水的情况下进行如下操作:
将一个杯子x的水倒到另一个杯子y中,如果x空了或者y满了就停止(满足其中一个条件才停下)
现问C中水量有多少种可能性(A,B,C为非负整数)

解法1:数论,扩展欧几里得

待补充

解法2:模拟倒水过程,BFS枚举所有情况

只适用杯子容量不是很大的情况。

#include <cstdio>
#include <queue>

using namespace std;

struct situation{
    
    
    int cup[3];
    situation(int x, int y, int z){
    
    
        cup[0] = x;
        cup[1] = y;
        cup[2] = z;
    }
};

int volume[3], ans = 0;
queue<situation> q;
bool visted[105][105][105] = {
    
    };
bool c_vis[105] = {
    
    };

void pour(situation &s, int f, int d);

int main(){
    
    
    scanf("%d%d%d", &volume[0], &volume[1], &volume[2]);
    situation init(0, 0, volume[2]);
    q.push(init);
    while(!q.empty()){
    
    
        situation s = q.front();
        q.pop();
        if(visted[s.cup[0]][s.cup[1]][s.cup[2]]) continue;
        visted[s.cup[0]][s.cup[1]][s.cup[2]] = true;
        if(!c_vis[s.cup[2]]){
    
    
            c_vis[s.cup[2]] = true;
            ans++;
        }
        for(int i=0; i<3; i++){
    
    
            if(s.cup[i]==0) continue;
            for(int j=0; j<3; j++){
    
    
                if(i==j || s.cup[j]==volume[j]) continue;
                pour(s, i, j);
            }
        }
    }
    printf("%d", ans);
    return 0;
}

void pour(situation &s, int f, int d){
    
    
    int ta, tb;
    if(s.cup[f]>(volume[d]-s.cup[d])){
    
    
        ta = s.cup[f] - volume[d] + s.cup[d];
        tb = volume[d];
    }
    else{
    
    
        ta = 0;
        tb = s.cup[d] + s.cup[f];
    }
    situation temp = s;
    temp.cup[f] = ta;
    temp.cup[d] = tb;
    q.push(temp);
    return;
}

猜你喜欢

转载自blog.csdn.net/sinat_37517996/article/details/105516312