HDU 1495 bfs

http://acm.hdu.edu.cn/showproblem.php?pid=1495

Problem Description

大家一定觉的运动以后喝可乐是一件很惬意的事情,但是seeyou却不这么认为。因为每次当seeyou买了可乐以后,阿牛就要求和seeyou一起分享这一瓶可乐,而且一定要喝的和seeyou一样多。但seeyou的手中只有两个杯子,它们的容量分别是N 毫升和M 毫升 可乐的体积为S (S<101)毫升 (正好装满一瓶) ,它们三个之间可以相互倒可乐 (都是没有刻度的,且 S==N+M,101>S>0,N>0,M>0) 。聪明的ACMER你们说他们能平分吗?如果能请输出倒可乐的最少的次数,如果不能输出"NO"。

Input

三个整数 : S 可乐的体积 , N 和 M是两个杯子的容量,以"0 0 0"结束。

Output

如果能平分的话请输出最少要倒的次数,否则输出"NO"。

Sample Input

 

7 4 3 4 1 3 0 0 0

Sample Output

 

NO 3

Author

seeyou

Source

“2006校园文化活动月”之“校庆杯”大学生程序设计竞赛暨杭州电子科技大学第四届大学生程序设计竞赛

思路:bfs,看了好久也没看出来。还是太菜了。设三个水杯分别为A、B、C,对于当前状态,无非就六种情况:A->B,A->C,B->A,B->C,C->A,C->B。bfs来做就好了,第一个满足题意的必定是操作次数最少的,这也是bfs的一个性质。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<queue>
#include<algorithm>
#define INF 0x3f3f3f3f
typedef long long ll;
using namespace std;

struct node //s-a s-b a-s a-b b-s b-a
{
    int s[3],step;
};
int a[3];//存储题目中的s a b
int vis[105][105][105];//标记一个状态是否被访问过

void bfs()
{
    memset(vis,0,sizeof(vis));
    node temp;
    temp.s[0]=a[0],temp.s[1]=0,temp.s[2]=0;
    temp.step=0;
    queue<node> q;
    q.push(temp);
    while(!q.empty())
    {
        node t1=q.front();
        q.pop();
        vis[t1.s[0]][t1.s[1]][t1.s[2]]=1;
        if((t1.s[0]==a[0]/2&&t1.s[1]==a[0]/2)||(t1.s[0]==a[0]/2&&t1.s[2]==a[0]/2)||(t1.s[1]==a[0]/2&&t1.s[2]==a[0]/2))
        {
            printf("%d\n",t1.step);
            return ;
        }
        for(int i=0;i<3;i++)//6种情况
        {
            if(t1.s[i])//杯子里面有水
            {
                for(int j=0;j<3;j++)
                {
                    if(j==i)//同一个杯子
                        continue;
                    node t2=t1;
                    if(t1.s[i]+t1.s[j]>a[j])//i->j可以装满j
                    {
                        t2.s[i]-=a[j]-t1.s[j];
                        t2.s[j]=a[j];
                    }
                    else//i->j装不满j
                    {
                        t2.s[i]=0;
                        t2.s[j]+=t1.s[i];
                    }
                    if(vis[t2.s[0]][t2.s[1]][t2.s[2]])
                        continue;
                    else
                    {
                        t2.step=t1.step+1;
                        q.push(t2);
                    }
                }
            }
        }
    }
    printf("NO\n");
}

int main()
{
    while(~scanf("%d %d %d",&a[0],&a[1],&a[2])&&a[0]+a[1]+a[2])
    {
        if(a[0]&1)//s为奇数 肯定不可能
            printf("NO\n");
        else
            bfs();
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/xiji333/article/details/88383687