week2 homework 2-pour water

Title

Pour water problem "fill A" means to fill A cup, "empty A" means to empty A cup, "pour AB" means to pour A's water into B cup and empty B cup or A. The input contains multiple sets of data. Each set of data input A, B, C data range 0 <A <= B, C <= B <= 1000, A and B are relatively prime. The output of your program will consist of a series of instructions. These output lines will cause any tank to contain exactly C units of water. The output of the last line of each set of data should be "success". The output line starts at column 1, and there should be no blank lines or any trailing spaces.

Ideas

This is a typical implicit graph problem. For each cup, we have 6 alternative operations to change its state, which is equivalent to a full 6-branch tree. Traverse this tree to find the required C. Here we use It is a wide search, and it searches while calculating the points of the next layer.
For the access path, the method of storing constant array indexes is used here. The index is added to the end of the string without performing an operation. Only the character string needs to be traversed by character when outputting

to sum up

The implementation of the queue here can also be solved in a non-queue form. Opening a large array uses the relative position of the two cursors to determine whether the queue is empty and achieves the same effect

Code

#include<stdio.h>
#include<string>
#include<string.h>
#include<iostream>
#include<queue>
using namespace std;
int ca,cb,n;
bool vis[4000][4000];
struct cup{
	int a,b;
	string s;//存储路径 
	cup(){}
	cup(int qa,int qb,string ss){
		a=qa;
		b=qb;
		s=ss;
	}
};
queue<cup> qu;
string caozuo[6]={"fill A","empty A","fill B","empty B","pour A B","pour B A"};
void bfs(){
	qu.push(cup(0,0,string()));
	vis[0][0]=1;
	while(!qu.empty()){
		int a=qu.front().a;
		int b=qu.front().b;
		string s=qu.front().s;
		qu.pop();
		if(b==n||a==n){ //特判终点 
			for(int i=0;i<s.size();i++){//输出路径 
				cout<<caozuo[s[i]-48]<<endl;
			}
			cout<<"success"<<endl;
			return;
		}
		if(!vis[ca][b]){// fill A 
			qu.push(cup(ca,b,s+"0"));
			vis[ca][b]=1;
		}
		if(!vis[0][b]){//empty A
			qu.push(cup(0,b,s+"1"));
			vis[0][b]=1;
		}
		if(!vis[a][cb]){//fill B
			qu.push(cup(a,cb,s+"2"));
			vis[a][cb]=1;
		}

		if(!vis[a][0]){//empty B
			qu.push(cup(a,0,s+"3"));
			vis[a][0]=1;
		}
		int c=a+b>cb?cb:a+b;//pulll A B
		if(!vis[a+b-c][c]){//B中水量可能满也可能不满 
			qu.push(cup(a+b-c,c,s+"4"));
			vis[a+b-c][c]=1;
		}
		c=a+b>ca?ca:a+b;  //pull B A 
		if(!vis[c][a+b-c]){//A中水量可能满也可能不满 
			qu.push(cup(c,a+b-c,s+"5"));
			vis[c][a+b-c]=1;
		}

	}
	return;
}
int main() {
    while(~scanf("%d%d%d",&ca,&cb,&n)){
    	memset(vis,0,sizeof(vis));
    	while(!qu.empty())qu.pop();//多组数据将队列置空 
    	bfs();
	}
    return 0;
}

Published 20 original articles · praised 3 · visits 463

Guess you like

Origin blog.csdn.net/qq_44893580/article/details/104644693