[Depth First Search] Luogu: Mother's Milk

Depth-first search:

dfs(a,b,c): The volume of the current ABC bucket of milk

if(a==0) record the value of c

Take a->b as an example: when a is not empty and b is not full

if(b+a>B)

dfs(a-(B-b),B,c)

if(a+b<=B)dfs(0,b+a,c);

Pay attention to deduplication:

If after C->A, after A->C, C->A, ..., it will always recurse, then stackoverflow

You can use the state to uniquely represent a selection, that is, open a three-dimensional array, vis[a][b][c], mark each time before making a selection

#include<iostream>
using namespace std;
int res[21];
int A,B,C;
bool vis[21][21][21]; 
void dfs(int a,int b,int c){
	if(vis[a][b][c]==true)return;
	if(a==0&&res[c]==0){
		res[c]=1;
		return;
	}
	vis[a][b][c]=true;
	if(c!=0&&b<B){
	    if(b+c>B){
			dfs(a,B,c-(B-b));
		}
		else{
			dfs(a,b+c,0);
		}
	}
	if(c!=0&&a<A){
		if(a+c>A){
			dfs(A,b,c-(A-a));
		}
		else{
			dfs(a+c,b,0);
		}
	}
	if(a!=0&&b<B){
		if(a+b>B){
			dfs(a-(B-b),B,c);
		}
		else{
			dfs(0,b+a,c);
		}
	}

	if(a!=0&&c<C){
		if(a+c>C){
			dfs(a-(C-c),b,C);
		}
		else{
			dfs(0,b,a+c);
		}
	}

	if(b!=0&&c<C){
		if(b+c>C){
			dfs(a,b-(C-c),C);
		}
		else{
			dfs(a,0,b+c);
		}
	}
	if(b!=0&&a<A){
		if(a+b>A){
			dfs(A,a+b-A,c);
		}
		else{
			dfs(a+b,0,c);
		}
	}
}

int main(){
	cin>>A>>B>>C;
	res[C]=1; 
	dfs(0,0,C);
	for(int i=0;i<=20;i++){
		if(res[i]==1){
			cout<<i<<" ";
		}
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/m0_52043808/article/details/123929998