CodeVS 1226 倒水问题【DFS/BFS】

题目描述 Description
有两个无刻度标志的水壶,分别可装 x 升和 y 升 ( x,y 为整数且均不大于 100 )的水。设另有一水 缸,可用来向水壶灌水或接从水壶中倒出的水, 两水壶间,水也可以相互倾倒。已知 x 升壶为空 壶, y 升壶为空壶。问如何通过倒水或灌水操作, 用最少步数能在x或y升的壶中量出 z ( z ≤ 100 )升的水 来。

输入描述 Input Description
一行,三个数据,分别表示 x,y 和 z;

输出描述 Output Description
一行,输出最小步数 ,如果无法达到目标,则输出"impossible"

样例输入 Sample Input
3 22 1

样例输出 Sample Output
14

数据范围及提示 Data Size & Hint

广度优先搜索 深度优先搜索 迭代搜索 搜索

【DFS:】

#include<bits/stdc++.h>
#define debug() puts("++++")
#define gcd(a,b) __gcd(a,b)
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define fi first
#define se second
#define pb push_back
#define sqr(x) ((x)*(x))
#define ms(a,b) memset(a,b,sizeof(a))
#define sz size()
#define be begin()
#define pu push_up
#define pd push_down
#define cl clear()
#define lowbit(x) -x&x
#define all 1,n,1
#define rep(i,n,x) for(int i=(x); i<(n); i++)
#define in freopen("in.in","r",stdin)
#define out freopen("out.out","w",stdout)
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int,int> P;
const int INF = 0x3f3f3f3f;
const LL LNF = 1e18;
const int maxn = 1e3 + 20;
const int maxm = 1e6 + 10;
const int N = 1e4+10;
const double PI = acos(-1.0);
const double eps = 1e-8;
const int dx[] = {-1,1,0,0,1,1,-1,-1};
const int dy[] = {0,0,1,-1,1,-1,1,-1};
int dir[][3]={ {0,0,1},{0,0,-1},{1,0,0},{-1,0,0},{0,1,0},{0,-1,0} };
const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int f[200][200],a,b,z;
void dfs(int x,int y,int step)
{
    if(f[x][y]!=0 && step+1>=f[x][y]) return ;
    f[x][y]=step+1;
    dfs(x,0,step+1);
    dfs(0,y,step+1);
    dfs(x,b,step+1);
    dfs(a,y,step+1);
    if(x+y<=a) dfs(x+y,0,step+1);
    else dfs(a,x+y-a,step+1);
    if(x+y<=b) dfs(0,x+y,step+1);
    else dfs(x+y-b,b,step+1);
}

int main()
{
    while(~scanf("%d%d%d",&a,&b,&z))
    {
        memset(f,0,sizeof(f));
        int ans=INF;
        dfs(0,0,0);
        for(int i=0;i<=a;i++)
        {
            if(f[i][z]!=0)
            {
                if(f[i][z]<ans)
                    ans=f[i][z];
            }
        }
        for(int i=0;i<=b;i++)
        {
            if(f[z][i]!=0)
            {
                if(f[z][i]<ans)
                    ans=f[z][i];
            }
        }
        if(ans==INF) printf("impossible\n");
        else printf("%d\n",ans-1);
    }
}

猜你喜欢

转载自www.cnblogs.com/Roni-i/p/9288043.html