题目:M - 非常可乐
思路:找最小步数,就是BFS,类似于质数路径那个题
注意:最后一定是第一大和第二大的杯子来完成相等,所以一开始要将第二个杯子保证是第二大的杯子
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
int v[5];
int st[110][110][110];
struct cup
{
int v[5];
int step;
} t;
void pour(int x, int y)
{// x杯倒入y杯
int sum = t.v[x] + t.v[y];
if(sum >= v[y]) t.v[y] = v[y];
else t.v[y] = sum;
t.v[x] = sum - t.v[y];
}
void bfs(int x, int y, int z)
{
memset(st, 0, sizeof st);
queue <cup> qu;
cup now;
now.v[1] = x;
now.v[2] = y;
now.v[3] = z;
now.step = 0;
qu.push(now);
st[v[1]][0][0] = 1;
while(!qu.empty())
{
now = qu.front();
qu.pop();
if(now.v[1] == now.v[2] && !now.v[3])
{
cout << now.step << endl;
return ;
}
for(int i = 1; i < 4; i ++)
{
for(int j = 1; j < 4; j ++)
{
if(i != j)
{
t = now; // 每次倒水都要初始化成初始值
pour(i, j);
if(!st[t.v[1]][t.v[2]][t.v[3]])
{
t.step ++;
qu.push(t);
st[t.v[1]][t.v[2]][t.v[3]] = 1;
}
}
}
}
}
cout << "NO" << endl;
}
int main()
{
while(cin >> v[1] >> v[2] >> v[3])
{
if(!v[1] && !v[2] && !v[3]) break;
if(v[2] < v[3]) swap(v[2], v[3]);
bfs(v[1], 0, 0);
}
return 0;
}