补一道训练赛的题
假设每次由x杯倒入y杯,每次倒水都会选择把y杯倒满或者直到x杯倒完为止,因此问题简化为三个杯子互相倒的六种状态变化,利用bfs求最优解即可,数学公式好像也可以推出来啊。。
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<set>
#include<map>
#include<queue>
#include<cmath>
#define ll long long
#define inf 0x3f3f3f3f
using namespace std;
bool vis[105][105];
int a, b, n;
struct node
{
int n, a, b, t;
};
int bfs()
{
node h, next;
h.a = 0, h.b = 0, h.n = n, h.t = 0;
queue<node> q;
q.push(h);
vis[0][0] = 1;
while(! q.empty())
{
h = q.front();
q.pop();
if(h.n == h.a && h.b == 0)
{
return h.t;
}
if(h.n>0&&h.a!=a)
{
if(h.n >= a - h.a)
{
next.a = a;
next.n = h.n - (a - h.a);
}
else
{
next.a = h.a + h.n;
next.n = 0;
}
next.b = h.b;
next.t = h.t + 1;
if(!vis[next.a][next.b])
{
vis[next.a][next.b] = 1;
q.push(next);
}
}
if(h.n>0&&h.b!=b)
{
if(h.n >= b - h.b)
{
next.b = b;
next.n = h.n - (b - h.b);
}
else
{
next.b = h.b + h.n;
next.n = 0;
}
next.a = h.a;
next.t = h.t + 1;
if(!vis[next.a][next.b])
{
vis[next.a][next.b] = 1;
q.push(next);
}
}
if(h.a>0&&h.n!=n)
{
if(h.a >= n - h.n)
{
next.n = n;
next.a = h.a - (n - h.n);
}
else
{
next.n = h.n + h.a;
next.a = 0;
}
next.b = h.b;
next.t = h.t + 1;
if(!vis[next.a][next.b])
{
vis[next.a][next.b] = 1;
q.push(next);
}
}
if(h.a>0&&h.b!=b)
{
if(h.a >= b - h.b)
{
next.b = b;
next.a = h.a - (b - h.b);
}
else
{
next.b = h.b + h.a;
next.a = 0;
}
next.n = h.n;
next.t = h.t + 1;
if(!vis[next.a][next.b])
{
vis[next.a][next.b] = 1;
q.push(next);
}
}
if(h.b>0&&h.n!=n)
{
if(h.b >= n - h.n)
{
next.n = n;
next.b = h.b - (n - h.n);
}
else
{
next.n = h.n + h.b;
next.b = 0;
}
next.a = h.a;
next.t = h.t + 1;
if(!vis[next.a][next.b])
{
vis[next.a][next.b] = 1;
q.push(next);
}
}
if(h.b>0&&h.a!=a)
{
if(h.b >= a - h.a)
{
next.a = a;
next.b = h.b - (a - h.a);
}
else
{
next.a = h.a + h.b;
next.b = 0;
}
next.n = h.n;
next.t = h.t + 1;
if(!vis[next.a][next.b])
{
vis[next.a][next.b] = 1;
q.push(next);
}
}
}
return -1;
}
int main()
{
while(scanf("%d%d%d", &n, &a, &b) != EOF && (n + a + b))
{
if(n % 2)
{
printf("NO\n");
continue;
}
memset(vis, 0, sizeof(vis));
if(a < b) swap(a, b);
int ans = bfs();
if(ans >= 0) printf("%d\n", ans);
else printf("NO\n");
}
return 0;
}