生活随笔
收集整理的這篇文章主要介紹了
nyoj 21 三个水杯 BFS
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
三個(gè)水杯
時(shí)間限制:
1000 ms ?|? 內(nèi)存限制:
65535 KB 難度:
4 描述
給出三個(gè)水杯,大小不一,并且只有最大的水杯的水是裝滿的,其余兩個(gè)為空杯子。三個(gè)水杯之間相互倒水,并且水杯沒有標(biāo)識(shí),只能根據(jù)給出的水杯體積來(lái)計(jì)算。現(xiàn)在要求你寫出一個(gè)程序,使其輸出使初始狀態(tài)到達(dá)目標(biāo)狀態(tài)的最少次數(shù)。輸入
第一行一個(gè)整數(shù)N(0<N<50)表示N組測(cè)試數(shù)據(jù)
接下來(lái)每組測(cè)試數(shù)據(jù)有兩行,第一行給出三個(gè)整數(shù)V1 V2 V3 (V1>V2>V3 V1<100 V3>0)表示三個(gè)水杯的體積。
第二行給出三個(gè)整數(shù)E1 E2 E3 (體積小于等于相應(yīng)水杯體積)表示我們需要的最終狀態(tài)輸出
每行輸出相應(yīng)測(cè)試數(shù)據(jù)最少的倒水次數(shù)。如果達(dá)不到目標(biāo)狀態(tài)輸出-1樣例輸入
2
6 3 1
4 1 1
9 3 2
7 1 1 樣例輸出
3
-1 View Code #include<stdio.h>
#include<queue>
#include<string.h>
using namespace std;
struct node
{int c[3];int move[3]; int step;
};
int visit[1010100];int hash(node a)
{
return (a.move[1]*10000+a.move[1]*100+a.move[2]*10);
}int judge(node a,node b)
{return (a.move[0]==b.move[0]&&a.move[1]==b.move[1]&&a.move[2]==b.move[2]);
}int main()
{int x,i,j,min,ok;node begin,end;queue<node>s;scanf("%d",&x);while(x--){scanf("%d%d%d",&begin.c[0],&begin.c[1],&begin.c[2]);begin.move[0]=begin.c[0];begin.move[1]=begin.move[2]=0;begin.step=0;s.push(begin);scanf("%d%d%d",&end.move[0],&end.move[1],&end.move[2]); //后面是判定move數(shù)組ok=0;memset(visit,0,sizeof(visit));visit[hash(begin)]=1;while(!s.empty()){node u=s.front();s.pop();if(judge(u,end)){printf("%d\n",u.step);ok=1;break;}for(i=0;i<3;i++)//從i倒到j(luò)for(j=0;j<3;j++)if(i!=j){min=u.c[j]-u.move[j];if(u.move[i]<min)min=u.move[i];node v=u;v.move[i]-=min;v.move[j]+=min;v.step++;if(!visit[hash(v)]){visit[hash(v)]=1;s.push(v);}}}if(!ok)printf("-1\n");while(!s.empty())s.pop();}return 0;
} 本題主要是用BFS搜索各種情況,用隊(duì)列存貯狀態(tài),直到搜到所要答案。以后這種情況很多的類型,相互變換的都可以用BFS嘗試下
轉(zhuǎn)載于:https://www.cnblogs.com/zibuyu/archive/2013/03/13/2957290.html
總結(jié)
以上是生活随笔為你收集整理的nyoj 21 三个水杯 BFS的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。