CSUOJ 1150-食用油

http://acm.csu.edu.cn/OnlineJudge/problem.php?id=1150

这是道BFS的题,打油师要用容量为A和B的油桶打出C升的油,有六种操作方式,我们从前一种

状态到后一种状态的变化是有规律的,广搜所有的操作方式,对每种状态都标记,直到找到需要

的C升油。搞了好久才把队列和广搜搞明白一点,纠结ING!

#include<iostream>
#include<string.h>
#define N 105
using namespace std;

int vis[N][N], qa[64*N], qb[64*N], d[64*N];
int A, B, C, front, tail;
void init( int na, int nb, int front, int tail)
{
d[tail] = d[front] + 1;
vis[na][nb] = 1;
qa[tail] = na;
qb[tail] = nb;
}

void bfs()
{
int a, b, na, nb;
memset( vis, 0, sizeof vis);
vis[0][0] = 1;
front = tail = 0;
d[0] = 0;
qa[tail] = qb[tail] = 0;
tail ++;
while( front < tail)
{
a = qa[front];
b = qb[front];
if( a == C || b == C) break;
// 1
na = A;
nb = b;
if( !vis[na][nb]) {
init( na, nb, front, tail);
tail ++;
}
// 2
na = a;
nb = B;
if( !vis[na][nb]) {
init( na, nb, front, tail);
tail ++;
}
// 3
if( a + b <= B) {
na = 0;
nb = a + b;
}
else {
na = a + b - B;
nb = B;
}
if( !vis[na][nb]) {
init( na, nb, front, tail);
tail ++;
}
// 4
if( a + b <= A) {
na = a + b;
nb = 0;
}
else {
na = A;
nb = a + b - A;
}
if( !vis[na][nb]) {
init( na, nb, front, tail);
tail ++;
}
// 6
na = a;
nb = 0;
if( !vis[na][nb]) {
init( na, nb, front, tail);
tail ++;
}
// 5
na = 0;
nb = b;
if( !vis[na][nb]) {
init( na, nb, front, tail);
tail ++;
}
front ++;
}
}

int main()
{
while( cin >> A >> B >> C)
{
bfs();
cout << d[front] << endl;
}
return 0;
}

 

你可能感兴趣的:(OJ)