[BFS] HDU 1495

来源:互联网 发布:淘宝法律咨询 编辑:程序博客网 时间:2024/06/11 02:32

和上面那个倒来倒去的差不多啦hhh

只不过这次是三个杯子互相倒,有三个记录的点

#include <cstdlib>#include <cstring>#include <iostream>#include <queue>#define N 1000using namespace std;struct Node {        int a, b, s;        int cnt;} cur, nex;int A, B, S;bool vis[ N ][ N ];//六种操作,要传指针void operate ( Node *c, Node *n, int i ) {        switch ( i ) {                // Pour b to a        case 0: {                n->a = min ( A, c->a + c->b );                n->b = c->b - ( n->a - c->a );                break;        }                // Pour a to b        case 1: {                n->b = min ( B, c->b + c->a );                n->a = c->a - ( n->b - c->b );                break;        }                // Pour s to a        case 2: {                n->a = min ( A, c->a + c->s );                n->s = c->s - ( n->a - c->a );                break;        }                // Pour s to b        case 3: {                n->b = min ( B, c->b + c->s );                n->s = c->s - ( n->b - c->b );                break;        }                // Pour a to s        case 4: {                n->s = min ( S, c->s + c->a );                n->a = c->a - ( n->s - c->s );                break;        }                // Pour b to s        case 5: {                n->s = min ( S, c->s + c->b );                n->b = c->b - ( n->s - c->s );                break;        }        }}int bfs () {        memset ( vis, false, sizeof ( vis ) );        cur.a = 0, cur.b = 0, cur.s = S;        cur.cnt = 0;        vis[ cur.a ][ cur.b ] = true;        queue<Node> q;        q.push ( cur );        while ( !q.empty () ) {                cur = q.front ();                q.pop ();                if ( cur.s == S / 2 && ( cur.a == S / 2 || cur.b == S / 2 ) )                        return cur.cnt;                for ( int i = 0; i < 6; ++i ) {                        nex.a = cur.a, nex.b = cur.b, nex.s = cur.s;                        operate ( &cur, &nex, i );                        nex.cnt = cur.cnt + 1;                        if ( !vis[ nex.a ][ nex.b ] ) {                                vis[ nex.a ][ nex.b ] = true;                                q.push ( nex );                        }                }        }        return -1;}int main () {        while ( cin >> S >> A >> B ) {                if ( !( S || A || B ) )                        break;                if ( S % 2 ) {                        cout << "NO" << endl;                        continue;                }                int sol = bfs ();                if ( sol == -1 )                        cout << "NO" << endl;                else                        cout << sol << endl;        }        return 0;}