NYOJ(21),BFS,三个水杯

时间:2023-03-08 17:57:59

题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=21

BFS判环,vis标记状态即可。

#include <stdio.h>
#include <queue>
#include <string.h> using namespace std; bool vis[][][]; struct Cup
{
int v[];
int step;
}; int s[],t[]; int bfs()
{
memset(vis,false,sizeof(vis));
Cup start;
start.step = ;
start.v[] = s[];
start.v[] = ;
start.v[] = ;
vis[s[]][][] = true;
queue<Cup> Q;
Q.push(start);
while(!Q.empty())
{
start = Q.front();
Q.pop();
if(start.v[]==t[]&&start.v[]==t[]&&start.v[]==t[])
return start.step; for(int i=; i<; i++)
{
for(int j=; j<; j++)
{
Cup tmp = start;
if(i==j||tmp.v[i]==||tmp.v[j]==s[j])
continue; if(tmp.v[i]+tmp.v[j]<=s[j])
{
tmp.v[j] = tmp.v[i]+tmp.v[j];
tmp.v[i] = ;
}
else
{
tmp.v[i] = tmp.v[i] - (s[j]-tmp.v[j]);
tmp.v[j] = s[j];
}
tmp.step++;
if(!vis[tmp.v[]][tmp.v[]][tmp.v[]])
{
Q.push(tmp);
vis[tmp.v[]][tmp.v[]][tmp.v[]] = true;
}
}
}
}
return -;
} int main()
{
int cases;
scanf("%d",&cases);
while(cases--)
{
for(int i=; i<; i++)
scanf("%d",&s[i]);
for(int i=; i<; i++)
scanf("%d",&t[i]);
printf("%d\n",bfs());
}
return ;
}