题解:B4400 [蓝桥杯青少年组国赛 2025] 第五题

· · 题解

题目传送门

我们可以通过广度优先搜索模拟所有可能的倾倒操作,寻找最少的操作次数。

注意,题目有一个大坑,题目说的是任意一个桶的牛奶量恰好为 \frac{v}{2},而当 v 的容量是奇数时,无论如何都不可能达成目标,所以在输入时要特判一下。

#include<bits/stdc++.h>
using namespace std;
struct node
{
    int a,b,c,step;
    node(int a,int b,int c,int step):a(a),b(b),c(c),step(step){}//结构体初始化函数
};
bool vh[205][205][205];//标记状态,防止重复搜索过
queue<node> Q;
void bfs(int a,int b,int c,int d)
{
    node start(a,0,0,0);
    Q.push(start);
    vh[a][0][0]=true;
    while(!Q.empty())
    {
        node cur=Q.front();
        Q.pop();
        if(cur.a==d||cur.b==d||cur.c==d)//如果到达目标状态
        {
            cout<<cur.step;//输出最少步数
            exit(0);
        }
        //枚举6种不同的倾倒操作
        int pourCA=min(cur.c,a-cur.a);//c倒a
        node nextCA(cur.a+pourCA,cur.b,cur.c-pourCA,cur.step+1);
        if(!vh[nextCA.a][nextCA.b][nextCA.c])
        {
            Q.push(nextCA);
            vh[nextCA.a][nextCA.b][nextCA.c]=true;
        }
        int pourCB=min(cur.c,b-cur.b);//c倒b
        node nextCB(cur.a,cur.b+pourCB,cur.c-pourCB,cur.step+1);
        if(!vh[nextCB.a][nextCB.b][nextCB.c])
        {
            Q.push(nextCB);
            vh[nextCB.a][nextCB.b][nextCB.c]=true;
        }
        int pourAC=min(cur.a,c-cur.c);//a倒c
        node nextAC(cur.a-pourAC,cur.b,cur.c+pourAC,cur.step+1);
        if(!vh[nextAC.a][nextAC.b][nextAC.c])
        {
            Q.push(nextAC);
            vh[nextAC.a][nextAC.b][nextAC.c]=true;
        }
        int pourAB=min(cur.a,b-cur.b);//a倒b
        node nextAB(cur.a-pourAB,cur.b+pourAB,cur.c,cur.step+1);
        if(!vh[nextAB.a][nextAB.b][nextAB.c])
        {
            Q.push(nextAB);
            vh[nextAB.a][nextAB.b][nextAB.c]=true;
        }
        int pourBC=min(cur.b,c-cur.c);//b倒c
        node nextBC(cur.a,cur.b-pourBC,cur.c+pourBC,cur.step+1);
        if(!vh[nextBC.a][nextBC.b][nextBC.c])
        {
            Q.push(nextBC);
            vh[nextBC.a][nextBC.b][nextBC.c]=true;
        }
        int pourBA=min(cur.b,a-cur.a);//b倒a
        node nextBA(cur.a+pourBA,cur.b-pourBA,cur.c,cur.step+1);
        if(!vh[nextBA.a][nextBA.b][nextBA.c])
        {
            Q.push(nextBA);
            vh[nextBA.a][nextBA.b][nextBA.c]=true;
        }
    }
}
int main()
{
    int a,b,c;
    cin>>a>>b>>c;
    if(a&1)//特判a为奇数的情况。
    {
        cout<<-1;
        return 0;
    }
    bfs(a,b,c,a/2);
    cout<<-1;//如果不可能达成目标,则输出-1
    return 0;
}