题目如下:

泊松是法国数学家、物理学家和力学家。他一生致力科学事业,成果颇多。有许多著名的公式定理以他的名字命名,比如概率论中著名的泊松分布。
有一次闲暇时,他提出过一个有趣的问题,后称为:“泊松分酒”。在我国古代也提出过类似问题,遗憾的是没有进行彻底探索,其中流传较多是:“韩信走马分油”问题。
有3个容器,容量分别为12升,8升,5升。其中12升中装满油,另外两个空着。要求你只用3个容器操作,最后使得某个容器中正好有6升油。
下面的列表是可能的操作状态记录:
12,0,0
4,8,0
4,3,5
9,3,0
9,0,3
1,8,3
1,6,5
每行3个数据,分别表示12,8,6升容器中的油量
第一行表示初始状态,第二行表示把12升倒入8升容器后的状态,第三行是8升倒入5升,...
当然,同一个题目可能有多种不同的正确操作步骤。

本题目的要求是,请你编写程序,由用户输入:各个容器的容量,开始的状态,和要求的目标油量,程序则通过计算输出一种实现的步骤
例如,用户输入:
12,8,5,12,0,0,6
用户输入的前三个数是容器容量(由大到小),接下来三个数是三个容器开始时的油量配置,最后一个数是要求得到的油量(放在哪个容器里得到都可以)
则程序可以输出(答案不唯一,只验证操作可行性):
12,0,0
4,8,0
4,3,5
9,3,0
9,0,3
1,8,3
1,6,5


——————————————————————————————————————————————————————

方法是搜索。学C++这么久第一次用重载,所以贴代码纪念一下。

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <queue>
#include <vector>
#include <set>
#include <stack>
#include <map>
#include <math.h>
using namespace std;
typedef long long LL;
const int INF = 0x3f3f3f3f;
const int N = 110;
int ans;
bool vis[N][N][N];

struct Node{
    int v[3];
    int pre;
    bool operator == (Node &tmp) {
        return (v[0] == tmp.v[0] && v[1] == tmp.v[1]&&v[2] == tmp.v[2]);
    }
    void operator = (Node &tmp) {
        v[0] = tmp.v[0];
        v[1] = tmp.v[1];
        v[2] = tmp.v[2];
        pre = tmp.pre;
        num = tmp.pre;
    }
    bool compare(){
        if(v[0]==ans || v[1]==ans || v[2]==ans) return true;
        else return false;
    }
    int num;
}node[100000];

queue<struct Node> Q;
struct Node A, B;
int cnt = 0;
struct Node key;
bool BFS(){
    B.pre = -1;
    vis[B.v[0]][B.v[1]][B.v[2]] = 1;
    Q.push(B);
    B.num = 0;
    node[cnt++] = B;
    while(!Q.empty()){
        struct Node u = Q.front();
        Q.pop();
        if(u.compare()){
            key = u;
            return true;
        }
        for(int i = 0; i < 3; i++){
            for(int j = 0; j < 3; j++){
                if(i == j || u.v[i] == 0 || u.v[j] == A.v[j]) continue;
                int k = 0;
                if(u.v[i] > A.v[j] - u.v[j]) k = A.v[j] - u.v[j];
                else k = u.v[i];
                struct Node tmp = u;
                tmp.v[i] -= k;
                tmp.v[j] += k;
                if(vis[tmp.v[0]][tmp.v[1]][tmp.v[2]]) continue;
                tmp.pre = u.num;
                tmp.num = cnt;
                node[cnt++] = tmp;
                Q.push(tmp);
                vis[tmp.v[0]][tmp.v[1]][tmp.v[2]] = 1;
            }
        }


    }
    return -1;
}

int main()
{
    cin>>A.v[0]>>A.v[1]>>A.v[2]>>B.v[0]>>B.v[1]>>B.v[2]>>ans;
    if(BFS()) {
        stack<struct Node> S;
        while(key.pre != -1){
            S.push(key);
            key = node[key.pre];
        }
        S.push(B);
        while(!S.empty()){
            key = S.top();
            S.pop();
            printf("%d %d %d\n", key.v[0], key.v[1], key.v[2]);
        }
    }
    else puts("不可能");
    return 0;
}



Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐