非常可乐(数学,bfs)

原题链接

解题思路:由于数学实在是菜,这里贴一发别人的题解
C++代码
一、数学推导
#include <bits/stdc++.h>
using namespace std;
int gcd(int a, int b)
{
    return b ? gcd(b, a % b) : a;
}

int main()
{
    int a, b, c;
    while (cin >> a >> b >> c, a && b && c)
    {
        a /= gcd(b, c);
        if (a & 1)
        {
            cout << "NO" << endl;
        }
        else cout << a - 1 << endl;
    }
    return 0;
}
二、bfs
#include <bits/stdc++.h>
using namespace std;
const int N = 110;
int v[3];
struct cup
{
    int tv[3], cnt;
}start, temp;
bool st[N][N][N];

void pour(int a, int b)//倒水函数,把a杯子中的可乐倒到b杯子中
{
    int sum = temp.tv[a] + temp.tv[b];
    if(sum >= v[b])
        temp.tv[b] = v[b];
    else
        temp.tv[b] = sum;
    temp.tv[a] = sum - temp.tv[b];
}

void bfs()
{
    queue<cup> q;
    start.tv[0] = v[0], start.tv[1] = 0, start.tv[2] = 0, start.cnt = 0;
    q.push(start);
    st[start.tv[0] ][start.tv[1]][start.tv[2]] = true;
    while (q.size())
    {
        auto t = q.front();
        q.pop();
        if (t.tv[0] == t.tv[2] && t.tv[1] == 0)
        {
            cout << t.cnt << endl;
            return ;
        }
        for (int i = 0; i < 3; i ++ )
        {
            for (int j = 0; j < 3; j ++ )
            {
                if (i != j)
                {
                    temp = t;
                    pour(i, j);
                    if (!st[temp.tv[0]][temp.tv[1]][temp.tv[2]])
                    {
                        temp.cnt ++ ;
                        q.push(temp);
                        st[temp.tv[0]][temp.tv[1]][temp.tv[2]] = true;
                    }
                }
            }
        }
    }
    cout << "NO" << endl;
}

int main()
{
    while (cin >> v[0] >> v[1] >> v[2], v[0] || v[1] || v[2])
    {
        memset(st, 0, sizeof st);
        if (v[1] > v[2]) swap(v[1], v[2]);
        if (v[0] & 1) cout << "NO" << endl;
        else bfs();
    }
    return 0;
}

创作不易,大家可以在AcWing注册账号,参与一下AC之星计划,我的邀请码是MYRGS。对题解有任何疑问可以在评论区下面评论在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值