food
检查,尤其是参数值传递过程import numpy as np import pandas as pd from tabulate import tabulate import random import math from collections import deque, defaultdict import heapq import networkx as nx from concurrent.futures import ThreadPoolExecutor, as_completed import matplotlib.pyplot as plt from matplotlib.patches import Patch from tqdm import tqdm import time import itertools # 配置参数 max_weight = 1200 # kg initial_money = 10000 # 元 # 资源参数 per_water_weight = 3 # kg/箱 water_price = 5 # 元/箱 water_sunny = 3 # 箱/天 water_hot = 9 water_sandstorm = 10 per_food_weight = 2 # kg/箱 food_price = 10 # 元/箱 food_sunny = 4 food_hot = 9 food_sandstorm = 10 # 天气类型和消耗量 WEATHER_TYPES = ['晴朗', '高温', '沙暴'] WEATHER_PROBS = [0.3, 0.5, 0.2] WEATHER_CONSUMPTION = { '晴朗': {'water': water_sunny, 'food': food_sunny}, '高温': {'water': water_hot, 'food': food_hot}, '沙暴': {'water': water_sandstorm, 'food': food_sandstorm} } # 地图参数 rows = 5 # 行数 cols = 5 # 列数 total_regions = rows * cols # 总区域数 # 创建邻接矩阵 adj_matrix = [[0 for _ in range(total_regions + 1)] for _ in range(total_regions + 1)] # 创建连接关系 for region in range(1, total_regions + 1): # 计算当前区域的行和列 row = (region - 1) // cols + 1 col = (region - 1) % cols + 1 # 检查上方邻居 if row > 1: neighbor = region - cols adj_matrix[region][neighbor] = 1 adj_matrix[neighbor][region] = 1 # 检查下方邻居 if row < rows: neighbor = region + cols adj_matrix[region][neighbor] = 1 adj_matrix[neighbor][region] = 1 # 检查左侧邻居 if col > 1: neighbor = region - 1 adj_matrix[region][neighbor] = 1 adj_matrix[neighbor][region] = 1 # 检查右侧邻居 if col < cols: neighbor = region + 1 adj_matrix[region][neighbor] = 1 adj_matrix[neighbor][region] = 1 # 节点类型定义 NODE_TYPES = { 'NORMAL': 0, 'START': 1, # 起点 'MINE': 2, # 矿山 'VILLAGE': 3, # 村庄 'END': 4 # 终点 } # 节点类型初始化 node_types = [NODE_TYPES['NORMAL']] * (total_regions + 1) # 设置特殊节点 node_types[1] = NODE_TYPES['START'] node_types[18] = NODE_TYPES['MINE'] node_types[14] = NODE_TYPES['VILLAGE'] node_types[25] = NODE_TYPES['END'] # 场景生成参数 SCENARIO_COUNT = 50 # 场景数量 MAX_DAYS = 30 # 最大天数 def get_node_type_name(node_type): """根据节点类型值获取名称""" for name, value in NODE_TYPES.items(): if value == node_type: return name return "UNKNOWN" # 创建NetworkX图 G = nx.Graph() def generate_weather_scenarios(days, count): """生成指定天数和数量的天气场景""" scenarios = [] for _ in range(count): scenario = random.choices(WEATHER_TYPES, weights=WEATHER_PROBS, k=days) scenarios.append(scenario) return scenarios # 使用全局缓存加速最短路径计算 def init_shortest_path_cache(): """初始化最短路径缓存""" shortest_path_cache = {} for u in range(1, total_regions + 1): for v in range(1, total_regions + 1): if u != v: try: shortest_path_cache[(u, v)] = nx.shortest_path_length(G, u, v) except nx.NetworkXNoPath: shortest_path_cache[(u, v)] = float('inf') return shortest_path_cache # 初始化全局最短路径缓存 shortest_path_cache = init_shortest_path_cache() def heuristic(current, end, remaining_days, money): """启发函数,使用全局缓存""" # 如果无法到达终点,只考虑当前金钱 if shortest_path_cache[(current, end)] == float('inf'): return money # 否则,考虑剩余天数和可能的采矿收益 potential_mines = max(0, remaining_days - shortest_path_cache[(current, end)]) // 2 return money + potential_mines * 1000 def solve_deterministic_model(G, weather_sequence, start=1, end=25, best_money_cache=None): """优化的A*算法""" # 如果有全局缓存,使用它 if best_money_cache is not None and (start, end) in best_money_cache: best_result, best_money = best_money_cache[(start, end)] if best_money > 0: return best_result # 使用优先队列实现A*算法 queue = [] visited = set() # 初始购买策略(在起点购买资源) max_water = min(max_weight // per_water_weight, initial_money // water_price) max_food = min(max_weight // per_food_weight, initial_money // food_price) # 使用更大数据步长 water_steps = list(range(0, max_water + 1, 40)) food_steps = list(range(0, max_food + 1, 40)) # 批量处理初始状态 states = [] for water, food in itertools.product(water_steps, food_steps): cost = water * water_price + food * food_price if cost > initial_money: continue if water * per_water_weight + food * per_food_weight > max_weight: continue money = initial_money - cost state_key = (start, 0, water, food, money) if state_key not in visited: visited.add(state_key) # 计算启发值 h = heuristic(start, end, len(weather_sequence), money) states.append((-h, 0, start, (start,), water, food, money, ())) # 批量推入堆 heapq.heapify(queue) for state in states: heapq.heappush(queue, state) best_result = None best_money = 0 # 使用更轻量级的数据结构 visited_ref = set() visited_ref.update(visited) while queue: h, priority, current, path, water, food, money, mining_days = heapq.heappop(queue) current_h = -h # 提前剪枝 if best_money > 0 and current_h < best_money * 0.85: continue # 如果到达终点 if current == end: # 终点退回剩余资源 refund = water * water_price / 2 + food * food_price / 2 money += refund if money > best_money: best_money = money best_result = (list(path), list(mining_days), money) continue # 如果超过最大天数 if priority >= len(weather_sequence): continue # 获取当前天气 weather = weather_sequence[priority] # 计算基础消耗 water_consumption = WEATHER_CONSUMPTION[weather]['water'] food_consumption = WEATHER_CONSUMPTION[weather]['food'] # 优化邻居获取 neighbors = list(G.neighbors(current)) # 1. 在当前区域停留 if node_types[current] in (NODE_TYPES['VILLAGE'], NODE_TYPES['MINE']): if water >= water_consumption and food >= food_consumption: new_water = water - water_consumption new_food = food - food_consumption # 在村庄停留时可以购买资源 if node_types[current] == NODE_TYPES['VILLAGE']: # 计算最大可购买量 max_water_buy = min((max_weight - (new_food * per_food_weight)) // per_water_weight, money // water_price) max_food_buy = min((max_weight - (new_water * per_water_weight)) // per_food_weight, money // food_price) # 使用更高效的大步长 for buy_water in range(0, max_water_buy + 1, 40): for buy_food in range(0, max_food_buy + 1, 40): cost = buy_water * water_price + buy_food * food_price if money < cost: continue new_water2 = new_water + buy_water new_food2 = new_food + buy_food new_money = money - cost # 检查负重 weight = new_water2 * per_water_weight + new_food2 * per_food_weight if weight > max_weight: continue state_key = (current, priority+1, new_water2, new_food2, new_money) if state_key not in visited_ref: visited_ref.add(state_key) # 计算启发值 remaining_days = len(weather_sequence) - (priority+1) h = heuristic(current, end, remaining_days, new_money) # 优先级是( - 总收益估计, 实际金钱, 当前天数) heapq.heappush( queue, (-h, priority+1, current, path, new_water2, new_food2, new_money, mining_days) ) else: # 矿山停留但不采矿 state_key = (current, priority+1, new_water, new_food, money) if state_key not in visited_ref: visited_ref.add(state_key) # 计算启发值 remaining_days = len(weather_sequence) - (priority+1) h = heuristic(current, end, remaining_days, money) # 优先级是( - 总收益估计, 实际金钱, 当前天数) heapq.heappush( queue, (-h, priority+1, current, path, new_water, new_food, money, mining_days) ) # 2. 移动到相邻区域 for neighbor in neighbors: # 检查资源是否足够一天消耗 if water >= water_consumption and food >= food_consumption: new_water = water - water_consumption new_food = food - food_consumption new_money = money # 在村庄购买资源(到达时立即购买) if node_types[neighbor] == NODE_TYPES['VILLAGE']: # 计算最大可购买量 max_water_buy = min((max_weight - (new_food * per_food_weight)) // per_water_weight, new_money // water_price) max_food_buy = min((max_weight - (new_water * per_water_weight)) // per_food_weight, new_money // food_price) # 使用更高效的大步长 for buy_water in range(0, max_water_buy + 1, 40): for buy_food in range(0, max_food_buy + 1, 40): cost = buy_water * water_price + buy_food * food_price if new_money < cost: continue new_water2 = new_water + buy_water new_food2 = new_food + buy_food new_money2 = new_money - cost # 检查负重 weight = new_water2 * per_water_weight + new_food2 * per_food_weight if weight > max_weight: continue state_key = (neighbor, priority+1, new_water2, new_food2, new_money2) if state_key not in visited_ref: visited_ref.add(state_key) # 计算启发值 remaining_days = len(weather_sequence) - (priority+1) h = heuristic(neighbor, end, remaining_days, new_money2) # 优先级是( - 总收益估计, 实际金钱, 当前天数) heapq.heappush( queue, (-h, priority+1, neighbor, path + (neighbor,), new_water2, new_food2, new_money2, mining_days) ) else: # 非村庄节点 state_key = (neighbor, priority+1, new_water, new_food, new_money) if state_key not in visited_ref: visited_ref.add(state_key) # 计算启发值 remaining_days = len(weather_sequence) - (priority+1) h = heuristic(neighbor, end, remaining_days, new_money) # 优先级是( - 总收益估计, 实际金钱, 当前天数) heapq.heappush( queue, (-h, priority+1, neighbor, path + (neighbor,), new_water, new_food, new_money, mining_days) ) # 3. 在矿山采矿 if node_types[current] == NODE_TYPES['MINE'] and priority < len(weather_sequence) - 1: # 采矿需要两天时间,消耗两天的资源 total_water = water_consumption * 2 total_food = food_consumption * 2 if water >= total_water and food >= total_food: new_water = water - total_water new_food = food - total_food new_money = money + 1000 # 标记采矿天数 new_mining_days = mining_days + (priority + 1,) # 创建新状态 state_key = (current, priority+2, new_water, new_food, new_money) if state_key not in visited_ref: visited_ref.add(state_key) # 计算启发值 remaining_days = len(weather_sequence) - (priority+2) h = heuristic(current, end, remaining_days, new_money) # 优先级是( - 总收益估计, 实际金钱, 当前天数) heapq.heappush( queue, (-h, priority+2, current, path, new_water, new_food, new_money, new_mining_days) ) # 更新全局缓存 if best_money_cache is not None: best_money_cache[(start, end)] = (best_result, best_money) return best_result if best_result else (None, None, 0) # 并行评估所有场景 def evaluate_scenarios_parallel(G, scenarios, start=1, end=25): """优化的并行评估函数""" scenario_results = [] # 使用更大的线程池 with ThreadPoolExecutor(max_workers=12) as executor: futures = [] # 预先计算所有场景 for i, scenario in enumerate(scenarios): future = executor.submit(solve_deterministic_model, G, scenario, start, end) futures.append((i, future)) # 使用更快的进度条 for i, future in enumerate(tqdm(as_completed(futures), total=len(futures), desc="处理场景", ncols=100)): result = future.result() path, mining_days, final_money = result # 计算总行程天数 days = len(scenarios[i]) # 计算路径长度 path_length = len(path) - 1 if path else float('inf') # 记录结果 scenario_results.append({ 'scenario_id': i+1, 'weather_sequence': '→'.join(scenarios[i]), 'path': '→'.join(map(str, path)) if path else '无路径', 'path_length': path_length, 'mining_days': '→'.join(map(str, mining_days)) if mining_days else '无采矿', 'total_days': days, 'final_money': final_money }) return scenario_results def main(): print("=== 5x5地图建模开始 ===") start_time = time.time() # 创建图 G = nx.Graph() # 添加边 for u in range(1, total_regions + 1): for v in range(u + 1, total_regions + 1): if adj_matrix[u][v] == 1: G.add_edge(u, v) # 生成天气场景 print(f"生成 {SCENARIO_COUNT} 个天气场景...") scenarios = generate_weather_scenarios(MAX_DAYS, SCENARIO_COUNT) # 初始化全局缓存 best_money_cache = {} # 评估所有场景 print("评估所有场景...") scenario_results = evaluate_scenarios_parallel(G, scenarios) # 聚合策略 print("聚合策略...") strategies = aggregate_strategies(scenario_results) # 显示结果 display_results(scenario_results, strategies) end_time = time.time() print(f"\n=== 总运行时间: {end_time - start_time:.2f} 秒 ===") if __name__ == "__main__": main()
网址:food https://www.yuejiaxmz.com/news/view/1440155
相关内容
food(food怎么读)Hot Sale High Quality New Design Food Storage Container Airtight Food Storage Baby Container Plastic Set With Lid - Buy Food Storage Container airtight Food Container food Container Plastic Set Product on Alibaba.com
Home Use Refrigerator Kitchen Plastic Containers Vegetables Fruits And Seafood Storage Container For Food - Buy Food Containers Storage containers For Food container Plastic Product on Alibaba.com
Changing Lives Through Better Access to Nutritious Food
Taizhou Xianglong Food container Technology Co., LTD
Superb Quality food storage rooms With Luring Discounts
Ikoo Ribbed Design Freezer Safe Glass Food Storage Containers Glass Meal Prep Containers For Lunch - Buy Glass Food Container glass Meal Prep glass Food Storage Container Set Product on Alibaba.com
Vacuum Seal Bags For Food Fruit Storage With Air Valve Reusable Vacuum Food Storage Bags With Pump Kitchen Foldable Opp Bag Blue
食物清单 (Food Book)
Recipes for New Zealand Vegan Food

