H Pots

 
 

这道题不是很难, 但是因为一些细节问题, 导致了我整整两个小时的时间, 用来调试;

后来学姐帮我来找问题, 结果找了好久才发现, 以后一定, 一定注意细节问题。

///////////////////////////////////

思路是, 一共两个罐子, 每个罐子可以进行两个操作, 一共6个操作, 在这些基础上进行一个广搜就可以了。

#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <math.h>
#include <queue>
#include <vector>
#include <iostream>
using namespace std;
#define N 2000
char a[10][100] ={ "FILL(1)","FILL(2)","DROP(1)","DROP(2)","POUR(1,2)","POUR(2,1)"};
struct node
{
    int x, y, t;
    char op[N];
};
int v[N][N];
int n, m, k;

void bfs()
{
    node q, p;
    queue<node>Q;
    p.x=0;
    p.y=0;
    p.t=0;
    p.op[0]='\0';
    v[0][0]=1;
    Q.push(p);
    while(Q.size())
    {
        p=Q.front();
        Q.pop();
        if(p.x==k || p.y==k)
        {
            printf("%d\n", p.t);
            for(int i=0;i<p.t;i++)
                printf("%s\n",a[p.op[i]-'0']);
            return;
        }
        for(int i=0;i<6;i++)
        {
            q.t = p.t;
            q.x = p.x;q.y = p.y;
            strcpy(q.op, p.op);
            if(i==0)
            {
                q.x=n,q.y = p.y;
                q.op[q.t] = '0';
            }
            else if(i==1)
            {
                q.y=m,q.x = p.x;
                q.op[q.t] = '1';
            }
            else if(i==2)
            {
                q.x=0,q.y = p.y;
                q.op[q.t] = '2';
            }
            else if(i==3)
            {
                q.y=0,q.x = p.x;
                q.op[q.t] = '3';
            }
            else if(i==4)
            {
                if(q.x+q.y<=m)
                {
                    q.y+=q.x;
                    q.x=0;
                }
                else
                {
                    q.x=q.x+q.y-m;
                    q.y=m;
                }
                q.op[q.t] = '4';
            }
            else if(i==5)
            {
                if(q.x+q.y<=n)
                {
                    q.x+=q.y;
                    q.y=0;
                }
                else
                {
                    q.y=q.x+q.y-n;
                    q.x=n;
                }
                q.op[q.t] = '5';
            }
            if(v[q.x][q.y]==0)
            {
                v[q.x][q.y]=1;
                q.t++;
                q.op[q.t]='\0';
                Q.push(q);
            }
        }
    }
    printf("impossible\n");
}

int main()
{
    while(scanf("%d%d%d", &n, &m, &k)!=EOF)
    {
        memset(v, 0, sizeof(v));
        bfs();
    }
    return 0;
}

Sample Input

3 5 4

Sample Output

6
FILL(2)
POUR(2,1)
DROP(1)
POUR(2,1)
FILL(2)
POUR(2,1)


原文地址:https://www.cnblogs.com/zct994861943/p/6769348.html