JD 1204:农夫、羊、菜和狼的故事

OJ题目:click here~~


#define vegetable_go   0
#define vegetable_come 1
#define sheep_go 2
#define sheep_come 3
#define wolf_go 4
#define wolf_come 5
#define nothing_go 6
#define nothing_come 7

using namespace std ;
typedef long long LL ;
string ope[8] = {"vegetable_go" , "vegetable_come" ,"sheep_go" , "sheep_come" ,
                 "wolf_go" , "wolf_come" , "nothing_go" ,"nothing_come" } ;

void Print(vector<int> &g){
    for(int i = 0;i < g.size();i++)
        cout << ope[g[i]] << endl ;
    puts("succeed") ;
    puts("") ;
}

bool IsValid(int state , int func){
    switch(func){
        case vegetable_go : return (state&1) == 0 && (state&8) == 0 ;
        case vegetable_come : return (state&1) == 1 && (state&8) == 8 ;
        case sheep_go : return (state&2) == 0 && (state&8) == 0 ;
        case sheep_come : return (state&2) == 2 && (state&8) == 8 ;
        case wolf_go : return (state&4) == 0 && (state&8) == 0 ;
        case wolf_come : return (state&4) == 4 && (state&8) == 8 ;
        case nothing_go : return (state&8) == 0 ;
        case nothing_come : return (state&8) == 8 ;
    }
}


bool IsSafe(int state){
    int a1, a2 , a4 , a8 ;
    if(state&1) a1 = 1 ;
    else a1 = 0 ;
    if(state&2) a2 = 1 ;
    else a2 = 0 ;
    if(state&4) a4 = 1 ;
    else a4 = 0 ;
    if(state&8) a8 = 1 ;
    else a8 = 0 ;
    if(a1 == a2 && a8 != a1) return false ;
    if(a2 == a4 && a8 != a2) return false ; ;
    return true ;
}

int gao(int last , int func){
    switch(func){
        case vegetable_go : return last|9 ;
        case vegetable_come : return last&6 ;
        case sheep_go : return last|10 ;
        case sheep_come : return last&5 ;
        case wolf_go : return last|12 ;
        case wolf_come : return last&3 ;
        case nothing_go : return last|8 ;
        case nothing_come : return last&7 ;
    }
}
bool NotYet(int state , vector<int> &g){
    return find(g.begin() , g.end(), state) == g.end() ;
}

void process(vector<int> &g,vector<int> &op){
    int last = g.back() ;
    if(last == 15){
        Print(op) ;
        return ;
    }
    for(int i = 0;i < 8;i++){
        if(IsValid(last,i)) {
            int now = gao(last,i) ;
            if(!IsSafe(now)) continue ;
            if(!NotYet(now , g)) continue ;
            g.push_back(now) ;
            op.push_back(i) ;
            process(g , op) ;
            g.pop_back() ;
            op.pop_back() ;
        }
    }
}

int main(){
    vector<int> g ;
    vector<int> op ;
    g.push_back(0) ; //初始状态0000(2),表示农夫,狼,羊,蔬菜都在河岸左边
                    //目标状态1111(2),表示农夫,狼,羊,蔬菜都在河岸右边
    process(g , op) ;
    return 0 ;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值