11.12PTA训练 人狼羊菜过河 搜索,位运算

题意

人不在的时候狼吃羊,羊吃菜,用MWGC表示人狼羊草,箭头代表行进方向,输出所有由初始情况到最终情况的解决方案

思路

目前为止写得最头疼的搜索

因为一岸的状态确定了,另一岸也就唯一确定了,所以可以用五位二进制数表示当前状态。之后利用位运算的操作就可以进行搜索,用vector存储进行到当前状态的二进制数,得到结果后输出即可。为了防止重复访问,要开vis数组记录某个状态是否到过

代码
#include<cstdio>
#include<iostream>
#include<iomanip>
#include<map>
#include<unordered_map>
#include<string>
#include<queue>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<cstdlib> 
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define endl "\n"
#define int long long
//#define double long double
using namespace std;
	typedef long long ll;
	const int maxn=100500;
	const int inf=0x3f3f3f3f;
	int n,m;
	bool vis[100] ;
	bool le=0;
	int getBit(int a, int b) {
    return (a >> b) & 1; }
	void draw(int x){
   
		int a=getBit(x,4),b=getBit(x,3),c=getBit(x,2
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
人狼羊菜过河是一个经典的智力游戏,玩家需要帮助一群人、一只狼、一只羊和一堆菜过河,但船只只能承载两个物品或人。同时,如果没有人看守,羊会被狼吃掉,而如果没有羊吃菜,菜也会被吃掉。因此,玩家需要想出一个方案,让所有物品和人都安全地渡河。 以下是人狼羊菜过河的 Python 实现示例: ```python # 定义初始状态 start = {'people': 1, 'wolf': 1, 'sheep': 1, 'vegetable': 1, 'boat': 0} # 定义目标状态 goal = {'people': 0, 'wolf': 0, 'sheep': 0, 'vegetable': 0, 'boat': 1} # 定义移动函数 def move(state, p, q): new_state = state.copy() new_state['people'] -= p new_state['wolf'] -= q new_state['sheep'] += q new_state['vegetable'] += p new_state['boat'] = 1 - state['boat'] return new_state # 定义判断函数 def is_valid(state): if state['wolf'] == state['sheep'] and state['people'] != state['wolf']: return False if state['sheep'] == state['vegetable'] and state['people'] != state['sheep']: return False return True # 定义搜索函数 def search(start, goal): visited = set() queue = [[start]] while queue: path = queue.pop(0) last_state = path[-1] if last_state == goal: return path for p in range(2): for q in range(2): if p + q == 0 or p + q == 2: continue new_state = move(last_state, p, q) if is_valid(new_state) and tuple(new_state.items()) not in visited: visited.add(tuple(new_state.items())) new_path = path + [new_state] queue.append(new_path) # 运行搜索函数并输出结果 result = search(start, goal) for state in result: print(state) ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值