hdu 4490 Mad Veterinarian(bfs)

来源:互联网 发布:mfc串口编程实例 编辑:程序博客网 时间:2024/05/21 17:58

有三种物品,每个物品可以变换成一个或多个其他物品。这种变换关系是可逆的。

然后求从初始状态转换到目标状态所需的最少步数。直接bfs就能搞了,记录状态的话小hash一发话就行了。

#include<algorithm>#include<iostream>#include<cstring>#include<fstream>#include<sstream>#include<cstdlib>#include<vector>#include<string>#include<cstdio>#include<bitset>#include<queue>#include<stack>#include<cmath>#include<map>#include<set>#define FF(i, a, b) for(int i=a; i<b; i++)#define FD(i, a, b) for(int i=a; i>=b; i--)#define REP(i, n) for(int i=0; i<n; i++)#define CLR(a, b) memset(a, b, sizeof(a))#define debug puts("**debug**")#define LL long long#define PB push_back#define MP make_pairusing namespace std;const int maxm = 1e5;char str[10] = "ABCabc";/***************012345************/int on[maxm], trans[5][5], pre[2000000], path[2000000];bool vis[200][200][200];struct Node{    int v[3], steps;    void get()    {        REP(i, 3) scanf("%d", &v[i]);        steps = 0;    }    bool operator < (const Node& rhs) const    {        return steps > rhs.steps;    }}S, T;inline int hash(Node x){    return x.v[0]*10008+x.v[1]*108+x.v[2];}bool move(Node x, Node& y, int type){    y = x;    if(type < 3)    {        if(x.v[type] > 0)        {            y.v[type]--;            REP(i, 3) y.v[i] += trans[type][i];            return !vis[y.v[0]][y.v[1]][y.v[2]];        }        return false;    }    else    {        type -= 3;        REP(i, 3) if(y.v[i] < trans[type][i]) return false;        REP(i, 3) y.v[i] -= trans[type][i];        y.v[type]++;        return !vis[y.v[0]][y.v[1]][y.v[2]];    }    return false;}bool bfs(){    CLR(vis, 0); vis[S.v[0]][S.v[1]][S.v[2]] = 1;    CLR(pre, -1);    priority_queue<Node> q; q.push(S);    while(!q.empty())    {        Node x = q.top(), y; q.pop();        if(x.v[0] == T.v[0] && x.v[1] == T.v[1] && x.v[2] == T.v[2])        {            T.steps = x.steps;            return true;        }        REP(i, 3) if(x.v[i] > 108) return false;        REP(i, 6) if(move(x, y, i))        {            y.steps = x.steps + 1;            pre[hash(y)] = hash(x);            path[hash(y)] = i;            vis[y.v[0]][y.v[1]][y.v[2]] = 1;            q.push(y);        }    }    return false;}void print(int x){    if(pre[x] == -1) return ;    print(pre[x]);    putchar(str[path[x]]);}int P, id, cas, q;int main(){   // freopen("input.txt", "r", stdin);   // freopen("output.txt", "w", stdout);    scanf("%d", &P);    while(P--)    {        scanf("%d%d", &cas, &q);        REP(i, 3) REP(j, 3) scanf("%d", &trans[i][j]);        printf("%d %d\n", cas, q);        while(q--)        {            scanf("%d ", &id);            printf("%d ", id);            S.get(); T.get();            if(!bfs()) puts("NO SOLUTION");            else            {                printf("%d ", T.steps);                print(hash(T));                puts("");            }        }    }    return 0;}


原创粉丝点击