題意:輸入s,m,n三個數,分別代表可樂,和兩個杯子,三個容器可以互相倒,問能不能把s平分,能的話輸出最小步數,不能就輸出no。
思路:bfs,一共有六種情況,s->m(s向m裡倒),s->n,m->n,m->s,n->s,n->m。用bfs暴搜,從佇列裡每取出乙個,就用這六種情況擴充套件一次,並把步數加一,直到搜到終止狀態。
stl版本:
#include#include#define max 105
using namespace std;
struct point
;bool vis[max][max][max];
int s,m,n;
void change_ab(int &a,int &b,int ra,int rb)//a倒入b
else
}}int bfs()
change_ab(ta,tb,s,m);
if(!vis[ta][tb][tc])
ta=start.x;
tb=start.y;
tc=start.z;
change_ab(ta,tc,s,n);
if(!vis[ta][tb][tc])
ta=start.x;
tb=start.y;
tc=start.z;
change_ab(tb,tc,m,n);
if(!vis[ta][tb][tc])
ta=start.x;
tb=start.y;
tc=start.z;
change_ab(tb,ta,m,s);
if(!vis[ta][tb][tc])
ta=start.x;
tb=start.y;
tc=start.z;
change_ab(tc,ta,n,s);
if(!vis[ta][tb][tc])
ta=start.x;
tb=start.y;
tc=start.z;
change_ab(tc,tb,n,m);
if(!vis[ta][tb][tc])
} return 0;
}int main()
if(bfs()!=0)
printf("%d\n",bfs());
else
printf("no\n");
} }
陣列模擬版本:
#include#include#define max 105
using namespace std;
struct point
;bool vis[max][max][max];
point p[1000100];
int s,m,n;
void change_ab(int &a,int &b,int ra,int rb)//a倒入b
else
}}int bfs()
ta=start.x;
tb=start.y;
tc=start.z;
change_ab(ta,tb,s,m);
if(!vis[ta][tb][tc])
ta=start.x;
tb=start.y;
tc=start.z;
change_ab(ta,tc,s,n);
if(!vis[ta][tb][tc])
ta=start.x;
tb=start.y;
tc=start.z;
change_ab(tb,tc,m,n);
if(!vis[ta][tb][tc])
ta=start.x;
tb=start.y;
tc=start.z;
change_ab(tb,ta,m,s);
if(!vis[ta][tb][tc])
ta=start.x;
tb=start.y;
tc=start.z;
change_ab(tc,ta,n,s);
if(!vis[ta][tb][tc])
ta=start.x;
tb=start.y;
tc=start.z;
change_ab(tc,tb,n,m);
if(!vis[ta][tb][tc])
} return 0;
}int main()
if(bfs()!=0)
printf("%d\n",bfs());
else
printf("no\n");
} }
非常可樂 HDU 1495 bfs
大家一定覺的運動以後喝可樂是一件很愜意的事情,但是seeyou卻不這麼認為。因為每次當seeyou買了可樂以後,阿牛就要求和seeyou一起分享這一瓶可樂,而且一定要喝的和seeyou一樣多。但seeyou的手中只有兩個杯子,它們的容量分別是n 毫公升和m 毫公升 可樂的體積為s s 101 毫公升...
hdu 1495 非常可樂 bfs
題目 剛開始那做這個題 怎麼也想不出為什麼可以用bfs 我認為做這個題目 你想到有6種情況哦 假設s 是瓶子 n,m 是有容量的杯子,s可以倒入n中 s也可以倒入m中 n可以倒入s中 n 也可以倒入m中 m也是一樣的哦 所以就有六種情況哦。下面看具體ac 裡面有註解哦 include include...
HDU 1495 非常可樂 (BFS)
problem description 大 家一定覺的運動以後喝可樂是一件很愜意的事情,但是seeyou卻不這麼認為。因為每次當seeyou買了可樂以後,阿牛就要求和seeyou一起分享這 一瓶可樂,而且一定要喝的和seeyou一樣多。但seeyou的手中只有兩個杯子,它們的容量分別是n 毫公升和m...