解题思路:由于数学实在是菜,这里贴一发别人的题解
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。对题解有任何疑问可以在评论区下面评论