1355. 母亲的牛奶【一般 / DFS爆搜】

在这里插入图片描述
https://www.acwing.com/problem/content/1357/

#include<bits/stdc++.h>
using namespace std;
int a,b,c;
set<int>st;
unordered_map<string,int>mp;
void dfs(int s1,int s2,int s3)
{
    
    
    if(s1==0) st.insert(s3);
    if(s1)//s1有奶,s1倒
    {
    
    
        int temp=min(b-s2,s1);//s1->s2
        string s=to_string(s1-temp)+" "+to_string(s2+temp)+" "+to_string(s3);
        if(!mp[s]) mp[s]=1,dfs(s1-temp,s2+temp,s3);
        temp=min(c-s3,s1);//s1->s3;
        s=to_string(s1-temp)+" "+to_string(s2)+" "+to_string(s3+temp);
        if(!mp[s]) mp[s]=1,dfs(s1-temp,s2,s3+temp);
    }
    if(s2)//s2有奶,s2倒
    {
    
    
        int temp=min(a-s1,s2);//s2->s1
        string s=to_string(s1+temp)+" "+to_string(s2-temp)+" "+to_string(s3);
        if(!mp[s]) mp[s]=1,dfs(s1+temp,s2-temp,s3);
        temp=min(c-s3,s2);//s2->s3
        s=to_string(s1)+" "+to_string(s2-temp)+" "+to_string(s3+temp);
        if(!mp[s]) mp[s]=1,dfs(s1,s2-temp,s3+temp);
    }
    if(s3)//s3有奶,s3倒
    {
    
    
        int temp=min(a-s1,s3);//s3->s1;
        string s=to_string(s1+temp)+" "+to_string(s2)+" "+to_string(s3-temp);
        if(!mp[s]) mp[s]=1,dfs(s1+temp,s2,s3-temp);
        temp=min(b-s2,s3);//s3->s2;
        s=to_string(s1)+" "+to_string(s2+temp)+" "+to_string(s3-temp);
        if(!mp[s]) mp[s]=1,dfs(s1,s2+temp,s3-temp);
    }
}
int main(void)
{
    
    
    cin>>a>>b>>c;
    dfs(0,0,c);
    for(auto i=st.begin();i!=st.end();i++) cout<<*i<<" ";
    return 0;
}

其实数据很小,可以开一个三元数组判重。

#include<bits/stdc++.h>
using namespace std;
int a,b,c,mp[25][25][25];
set<int>st;
void dfs(int s1,int s2,int s3)
{
    
    
    if(s1==0) st.insert(s3);
    if(mp[s1][s2][s3]) return;
    mp[s1][s2][s3]=1;
    
    int t=min(b-s2,s1);//s1->s2
    dfs(s1-t,s2+t,s3);
    t=min(c-s3,s1);
    dfs(s1-t,s2,s3+t);
    
    t=min(a-s1,s2);//s2->s1
    dfs(s1+t,s2-t,s3);
    t=min(c-s3,s2);//s2->s3
    dfs(s1,s2-t,s3+t);
    
    t=min(a-s1,s3);//s3->s1;
    dfs(s1+t,s2,s3-t);
    t=min(b-s2,s3);//s3->s2;
    dfs(s1,s2+t,s3-t);
}
int main(void)
{
    
    
    cin>>a>>b>>c;
    dfs(0,0,c);
    for(auto i=st.begin();i!=st.end();i++) cout<<*i<<" ";
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_46527915/article/details/121228418