天天看點

HDU 1495 非常可樂【隐式圖搜尋,BFS】 非常可樂

非常可樂

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 11592    Accepted Submission(s): 4674

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校園文化活動月”之“校慶杯”大學生程式設計競賽暨杭州電子科技大學第四屆大學生程式設計競賽

原題連結:http://acm.hdu.edu.cn/showproblem.php?pid=1495

就是以前老人常考小孩的倒香油問題,以前就做過,直接模拟,但是TLE,因為有的狀态重複出現過,網上有人說用BFS,但是當時自己太菜(現在也是),并且網上的代碼很繁瑣,現在看到一份比較簡潔的代碼,就參考了一下。

參考部落格:http://blog.csdn.net/zwj1452267376/article/details/49559913

AC代碼:

#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
#include <algorithm>
using namespace std;
const int maxn=105;
bool v[4];
bool vis[maxn][maxn][maxn];
struct Node
{
    int v[4];
    int step;
} temp;

//倒水函數,把a杯子中的可樂倒到b杯子中
void pour(int a,int b)
{
    int sum=temp.v[a]+temp.v[b];
    if(sum>=v[b])
        temp.v[b]=v[b];
    else
        temp.v[b]=sum;
    temp.v[a]=sum-temp.v[b];
}
void BFS()
{
    queue<Node>q;
    Node now;
    now.v[0]=v[0];
    now.v[1]=0;
    now.v[2]=0;
    now.step=0;
    q.push(now);
    memset(vis,false,sizeof(vis));
    vis[v[0]][0][0]=true;
    while(!q.empty())
    {
        now=q.front();
        q.pop();
        if(now.v[0]==now.v[2]&&now.v[1]==0)
        {
            cout<<now.step<<endl;
            return;
        }
        for(int i=0; i<3; i++)
        {
            for(int j=0; j<3; j++)
            {
                if(i!=j)//自己不倒水給自己
                {
                    temp=now;
                    //每個水位情況都要把所有操作枚舉一遍,
                    //是以都要指派為原始水位情況
                    pour(i,j);
                    if(!vis[temp.v[0]][temp.v[1]][temp.v[2]])
                    {
                        temp.step++;
                        q.push(temp);
                        vis[temp.v[0]][temp.v[1]][temp.v[2]]=true;
                    }
                }
            }
        }
    }
    cout<<"NO"<<endl;
}
int main()
{
    while(scanf("%d%d%d",&v[0],&v[1],&v[2])!=EOF)
    {
        if(v[0]+v[1]+v[2]==0)
            break;
        if(v[1]>v[2])
            swap(v[1],v[2]);
        BFS();
    }
    return 0;
}