BFS——《算法笔记》8.2小节 问题 A: Jugs

首先,我的代码过了样例,但OJ上并没有过,并且神奇的是该题提交记录里没一个人过的(不知道是不是题目的问题)

  

下面是我的代码,用BFS解决,找出最优路径:

#include<iostream>
#include<queue>
#include<string>
using namespace std;
struct node
{
	int a, b;
	int ope;
};
string op[6] = {"fill A","fill B","empty A","empty B","pour A B","pour B A"};
int v_a, v_b, goal;
int vis[1050][1050] = { 0 };
node pre[1050][1050] = { 0 };
bool do_op(node &t, string s)
{
	if (t.a<v_a&&s == "fill A")
	{
		t.a = v_a;
		return true;
	}
	if (t.b<v_b&&s == "fill B")
	{
		t.b = v_b;
		return true;
	}
	if (t.a>0&&s == "empty A")
	{
		t.a = 0;
		return true;
	}
	if (t.b>0 && s == "empty B")
	{
		t.b = 0;
		return true;
	}

	if (t.a>0&&t.b<v_b&&s == "pour A B")
	{
		if (t.a + t.b > v_b)
		{
			t.a -= v_b - t.b;
			t.b = v_b;
		}
		else
		{
			t.b += t.a;
			t.a = 0;
		}
		return true;
	}
	if (t.b > 0 && t.a < v_a&&s == "pour B A")
	{
		if (t.a + t.b > v_a)
		{
			t.b -= v_a - t.a;
			t.a = v_a;
		}
		else
		{
			t.a +=t.b ;
			t.b = 0;
		}
		return true;
	}
	return false;
}

int main()
{
	while (cin >> v_a >> v_b >> goal)
	{
		queue <node> Q;
		node start,end;
		start.a = start.b = 0;
		vis[0][0] = 1;
		Q.push(start);
		int flag = 0;
		while (!Q.empty())
		{
			node vn = Q.front();
			
			Q.pop();
			for (int i = 0; i < 6; i++)
			{
				node temp = vn;
				if (do_op(temp, op[i])&&vis[temp.a][temp.b]==0)
				{
					temp.ope = i;
					vis[temp.a][temp.b] = 1;
					pre[temp.a][temp.b].a = vn.a;
					pre[temp.a][temp.b].b = vn.b;
					pre[temp.a][temp.b].ope = vn.ope;
					if (temp.b == goal)
					{
						end = temp;
						flag = 1;
						break;
					}
					else
					{
						
						Q.push(temp);
					}
				}
			}
			if (flag)break;
		}
		node ans[10050],temp=end;
		int cnt = 0;
		while (temp.a||temp.b)
		{
			ans[cnt++] = temp;
			node t = temp;
			t.a = pre[temp.a][temp.b].a;
			t.b = pre[temp.a][temp.b].b;
			t.ope = pre[temp.a][temp.b].ope;
			temp = t;
		}
		for (int i = cnt - 1; i >= 0; i--)
		{
			cout << op[ans[i].ope] << endl;
		}
		cout << "success\n";
	}
	return 0;
}

如果有同志AC了的 欢迎评论探讨

猜你喜欢

转载自blog.csdn.net/weirdo_coder/article/details/89144560
今日推荐