问题 J: Stop Counting!

本文介绍了一种赌博游戏“StopCounting!”,玩家通过决定是否将显示的牌计入总和来影响游戏收益。文章提供了算法解决方案,利用前缀和后缀平均值策略找到最大可能的平均收益,并附带了实现这一策略的C++代码。

题目描述
The Martingale casino is creating new games to lure in new gamblers who tire of the standard fare. Their latest invention is a fast-paced game of chance called Stop Counting! , where a single customer plays with a dealer who has a deck of cards. Each card has some integer value.
One by one, the dealer reveals the cards in the deck in order, and keeps track of the sum of the played cards and the number of cards shown. At some point before a card is dealt, the player can call “Stop Counting!” After this, the dealer continues displaying cards in order, but does not include them in the running sums. At some point after calling “Stop Counting!”, and just before another card is dealt, the player can also call “Start Counting!” and the dealer then includes subsequent cards in the totals. The player can only call “Stop Counting!” and “Start Counting!” at most once each, and they must call “Stop Counting!” before they can call “Start Counting!”. A card is “counted” if it is dealt before the player calls “Stop Counting!” or is dealt after the player calls “Start Counting!”
The payout of the game is then the average value of the counted cards. That is, it is the sum of the counted cards divided by the number of counted cards. If there are no counted cards, the payout is 0.
You have an ‘in’ with the dealer, and you know the full deck in order ahead of time. What is the maximum payout you can achieve?

输入
The first line of the input contains a single integer 1 ≤ N ≤ 1 000 000, the number of cards in the deck.
The second line of input contains N space-separated integers, the values on the cards. The value of each card is in the range [−109 , 109 ]. The cards are dealt in the same order they are given in the input.

输出
Output the largest attainable payout. The answer is considered correct if the absolute error is less than 10−6 , or the relative error is less than 10−9 .

结论就是最大的平均值就是前缀平均值亦或者后缀平均值,
证明:假设前缀平均值为A , 元素个数为x个, 后缀平均值为B , 元素个数为y个, 然后总平均值就是(x * A + y * B) / (x + y) , 我们就假设A <= B , 然后我们就可以得出
(x * A + y * B) / (x + y) <= (x * B + y * B) / (x + y) == B , 也就是得出了该结论的其中一个值, 当B <= A 的时候,得出另一个

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1e6 + 10 ;
double f[N][2] ;
double a[N] ;
int main()
{
	int n ; 
	cin >> n ;
	for(int i = 1 ;i <= n ;i ++)
	 cin >> a[i] ;
	for(int i = 1 ;i <= n ;i ++)
	 f[i][0] = f[i - 1][0] + a[i] , f[n - i + 1][1] = f[n - i + 2][1] + a[n - i + 1] ;
	for(int i = 1 ;i <= n ;i ++)
	 f[i][0] = f[i][0] / i , f[n - i + 1][1] = f[n - i + 1][1] / i ;
    double ans = 0 ;
    for(int i = 1 ;i <= n ; i ++ )
     ans = max(ans , max(f[i][0] , f[n - i + 1][1])) ;
    printf("%.9lf\n" , ans) ;
	return 0 ;
} 
import tkinter as tk from tkinter import ttk, filedialog, messagebox from PIL import Image, ImageTk, ImageSequence import pandas as pd import time import os import random import threading import queue from bubble import Bubble from selection import Selection from insertion import Insertion from shellsort import Shell from cocktailsort import Cocktail from gnomesort import Gnome from combsort import Comb from countingsort import Counting from radixsort import Radix from bucketsort import Bucket from timsort import Tim from heapsort import Heap from quicksort import Quick from mergesort import Merge window = tk.Tk() window.title("排序方法") window.geometry("1200x800+300+100") # 全局变量声明 current_file = "" arr = [] filename = "sort.csv" gif_label = None gif_frames = [] gif_index = 0 gif_speed = 150 gif_after_id = None scroll_after_id = None BATCH_SIZE = 10000 display_queue = queue.Queue() is_displaying = False sorting_thread = None sorting_active = False def load_gif(file_path, size=(400, 300)): # 加载gif global gif_frames, gif_index # 声明全局变量 gif_frames = [] try: img = Image.open(file_path) for frame in ImageSequence.Iterator(img): resized = frame.copy().resize(size, Image.Resampling.LANCZOS) gif_frames.append(ImageTk.PhotoImage(resized)) gif_index = 0 return bool(gif_frames) except Exception as e: print(f"加载 GIF 出错: {e}") return False def animate_gif(): # 循环显示gif的每一帧 global gif_index, gif_after_id if gif_frames: gif_label.config(image=gif_frames[gif_index]) gif_index = (gif_index + 1) % len(gif_frames) gif_after_id = window.after(gif_speed, animate_gif) def update_gif(file_path): global gif_after_id, gif_frames, gif_index if gif_after_id: window.after_cancel(gif_after_id) if load_gif(file_path, size=(500, 300)): animate_gif() else: gif_label.config(text=f"GIF 加载失败: {file_path}") def load_file(): file_path = filedialog.askopenfilename( title="选择数据文件", filetypes=[("CSV文件", "*.csv"), ("文本文件", "*.txt"), ("所有文件", "*.*")] ) if file_path: status_label.config(text=f"正在加载文件: {os.path.basename(file_path)}...") window.update() threading.Thread(target=load_data_thread, args=(file_path,), daemon=True).start() def load_data_thread(file_path): global arr, current_file # 声明全局变量 try: # 分块读取大文件 chunks = [] total_size = os.path.getsize(file_path) processed = 0 for chunk in pd.read_csv(file_path, chunksize=5000): chunks.append(chunk) processed += chunk.memory_usage(index=True, deep=True).sum() progress_value = min(processed / total_size * 100, 100) window.after(0, update_progress, progress_value, f"加载中: {progress_value:.1f}% ({processed / 1e6:.2f}MB/{total_size / 1e6:.2f}MB)") df = pd.concat(chunks) arr = df.values.flatten().tolist() current_file = os.path.basename(file_path) # 更新UI window.after(0, update_treeview_batch, unsort_tree, arr) window.after(0, update_treeview, sort_tree, []) window.after(0, lambda: status_label.config( text=f"已加载: {len(arr)} 条数据 | 文件: {current_file}")) window.after(0, lambda: progress.configure(value=0)) except Exception as e: window.after(0, lambda: messagebox.showerror("错误", f"加载文件失败: {str(e)}")) window.after(0, lambda: status_label.config(text=f"加载失败: {str(e)}")) def update_treeview(treeview, data): treeview.delete(*treeview.get_children()) for value in data: treeview.insert("", "end", values=(value,)) def update_treeview_batch(treeview, data): """分批更新Treeview控件""" treeview.delete(*treeview.get_children()) total = len(data) def add_batch(start_idx=0): end_idx = min(start_idx + BATCH_SIZE, total) for i in range(start_idx, end_idx): treeview.insert("", "end", values=(data[i],)) # 更新进度 progress_value = end_idx / total * 100 window.after(0, lambda: progress.configure(value=progress_value)) if end_idx < total: # 使用计时器安排下一批处理 treeview.after(1, add_batch, end_idx) else: treeview.yview_moveto(1.0) add_batch(0) def scroll_sorted_data(treeview, data): """分批滚动显示排序结果""" global scroll_after_id if scroll_after_id: window.after_cancel(scroll_after_id) treeview.delete(*treeview.get_children()) total = len(data) progress.configure(value=0) def scroll(index=0): # 一次插入一批数据 batch_size = min(BATCH_SIZE, total - index) for i in range(index, index + batch_size): treeview.insert("", "end", values=(data[i],)) # 滚动到底部 treeview.yview_moveto(1.0) # 更新进度 progress_value = (index + batch_size) / total * 100 window.after(0, lambda: progress.configure(value=progress_value)) if index + batch_size < total: # 使用计时器安排下一批显示 scroll_after_id = treeview.after(1, scroll, index + batch_size) else: scroll_after_id = None scroll(0) def generate_random_data(): global arr try: count = int(entry.get()) if count < 100: messagebox.showerror("错误", "请输入100以上的数字") return # 清空现有数组 arr = [] # 更新状态 status_label.config(text=f"正在生成 {count} 条随机数据...") window.update() # 启动线程生成数据 threading.Thread(target=generate_data_thread, args=(count,), daemon=True).start() except ValueError: messagebox.showerror("错误", "请输入有效的数字") def generate_data_thread(count): global arr, current_file, stop_sorting arr = [] # 确保数组为空 stop_sorting = False # 分批生成数据 for i in range(0, count, BATCH_SIZE): batch_size = min(BATCH_SIZE, count - len(arr)) batch = [] for _ in range(batch_size): rand_type = random.choice(["int", "float"]) # 控制整数和浮点数的比例 if len(arr) < count * 0.7: # 70% 整数 batch.append(random.randint(-100000, 100000)) else: batch.append(round(random.uniform(-100000, 100000), 3)) arr.extend(batch) # 更新进度 progress_value = len(arr) / count * 100 window.after(0, lambda: update_progress(progress_value, f"生成进度: {progress_value:.1f}% ({len(arr)}/{count})")) # 保存数据 current_file = "random_data.csv" pd.DataFrame(arr).to_csv(current_file, index=False) # 更新UI window.after(0, lambda: update_treeview_batch(unsort_tree, arr)) window.after(0, lambda: update_treeview(sort_tree, [])) window.after(0, lambda: status_label.config( text=f"已生成 {len(arr)} 条随机数据并保存")) window.after(0, lambda: progress.configure(value=0)) def start_sorting(): global sorting_active # 声明全局变量 if not arr: messagebox.showwarning("警告", "没有数据可排序") return if sorting_active: messagebox.showwarning("警告", "排序正在进行中") return # 更新状态 sorting_active = True algorithm = var.get() algorithm_name = { "bubblesort": "冒泡排序", "selectionsort": "选择排序", "insertionsort": "插入排序", "quicksort": "快速排序", "mergesort": "归并排序", "shellsort": "希尔排序", "cocktailsort": "鸡尾酒排序", "gnomesort": "侏儒排序", "combsort": "梳排序", "countingsort": "计数排序", "radixsort": "基数排序", "bucketsort": "桶排序", "timsort": "Tim排序", "heapsort": "堆排序" }.get(algorithm, algorithm) time_label.config(text="排序耗时: 计算中...") steps_label.config(text="运算步数: 计算中...") result_label.config(text="结果文件: 处理中...") status_label.config(text=f"正在使用 {algorithm_name} 排序数据...") progress.configure(value=0) window.update() # 创建新线程运行排序算法 sorting_thread = threading.Thread(target=choose, daemon=True) sorting_thread.start() def choose(): global sorting_active # 声明全局变量 arr_copy = arr.copy() start_time = time.time() algorithm = var.get() sorted_arr, steps = None, 0 title = "" try: if algorithm == "bubblesort": sorter = Bubble() sorted_arr, steps = sorter.sort(arr_copy) title = "冒泡排序" elif algorithm == "selectionsort": sorter = Selection() sorted_arr, steps = sorter.sort(arr_copy) title = "选择排序" elif algorithm == "insertionsort": sorter = Insertion() sorted_arr, steps = sorter.sort(arr_copy) title = "插入排序" elif algorithm == "quicksort": sorter = Quick() sorted_arr, steps = sorter.sort(arr_copy) title = "快速排序" elif algorithm == "mergesort": sorter = Merge() sorted_arr, steps = sorter.sort(arr_copy) title = "归并排序" elif algorithm == "shellsort": sorter = Shell() sorted_arr, steps = sorter.sort(arr_copy) title = "希尔排序" elif algorithm == "cocktailsort": sorter = Cocktail() sorted_arr, steps = sorter.sort(arr_copy) title = "鸡尾酒排序" elif algorithm == "gnomesort": sorter = Gnome() sorted_arr, steps = sorter.sort(arr_copy) title = "侏儒排序" elif algorithm == "combsort": sorter = Comb() sorted_arr, steps = sorter.sort(arr_copy) title = "梳排序" elif algorithm == "countingsort": sorter = Counting() sorted_arr, steps = sorter.sort(arr_copy) title = "计数排序" elif algorithm == "radixsort": sorter = Radix() sorted_arr, steps = sorter.sort(arr_copy) title = "基数排序" elif algorithm == "bucketsort": sorter = Bucket() sorted_arr, steps = sorter.sort(arr_copy) title = "桶排序" elif algorithm == "timsort": sorter = Tim() sorted_arr, steps = sorter.sort(arr_copy) title = "Tim排序" elif algorithm == "heapsort": sorter = Heap() sorted_arr, steps = sorter.sort(arr_copy) title = "堆排序" else: sorter = Bubble() sorted_arr, steps = sorter.sort(arr_copy) title = "冒泡排序" elapsed_time = time.time() - start_time # 保存结果 with open(filename, "a", encoding="utf-8") as f: # 使用"w"模式覆盖旧文件 f.write(f"\n{title}\n") f.write("\n".join(map(str, sorted_arr))) # 更新UI window.after(0, lambda: scroll_sorted_data(sort_tree, sorted_arr)) window.after(0, lambda: time_label.config( text=f"排序耗时: {elapsed_time:.4f} 秒")) window.after(0, lambda: steps_label.config( text=f"运算步数: {steps}")) window.after(0, lambda: result_label.config( text=f"结果文件: {os.path.abspath(filename)}")) window.after(0, lambda: status_label.config( text=f"{title} 完成! 已处理 {len(arr)} 条数据")) except Exception as e: window.after(0, lambda: messagebox.showerror("排序错误", f"排序过程中出错: {str(e)}")) window.after(0, lambda: status_label.config( text=f"排序失败: {str(e)}")) finally: sorting_active = False progress.configure(value=100) def stop_processing(): stop_sorting = True status_label.config(text="正在停止当前操作...") def on_combobox_select(event=None): algorithm = var.get() gif_map = { "bubblesort": "bubble.gif", "selectionsort": "sele.gif", "insertionsort": "inster.gif", "quicksort": "quick.gif", "mergesort": "merge.gif", "shellsort":"shell.gif", "cocktailsort": "cocktail.gif", "gnomesort": "gnome.gif", "combsort": "comb.gif", "countingsort": "counting.gif", "radixsort": "radix.gif", "bucketsort": "bucket.gif", "timsort": "tim.gif", "heapsort": "heap.gif" } gif_path = gif_map.get(algorithm, "sorting.gif") update_gif(gif_path) # 重置排序结果显示 update_treeview(sort_tree, []) time_label.config(text="排序耗时: --") steps_label.config(text="运算步数: --") result_label.config(text="结果文件: --") def open_file(): file_path = os.path.abspath(filename) if os.path.exists(file_path): try: os.startfile(file_path) # Windows except: import subprocess subprocess.run(['open', file_path]) # macOS else: messagebox.showinfo("信息", "结果文件尚未生成") def reset(): global stop_sorting, arr, current_file # 声明全局变量 stop_sorting = True update_treeview(sort_tree, []) time_label.config(text="排序耗时: --") steps_label.config(text="运算步数: --") result_label.config(text="结果文件: --") progress.configure(value=0) status_label.config(text="已重置应用程序") def update_progress(value, text): progress.configure(value=value) status_label.config(text=text) # 创建UI组件 optuple = ("bubblesort", "selectionsort", "insertionsort", "shellsort", "cocktailsort", "gnomesort", "combsort", "countingsort", "radixsort","bucketsort","timsort","heapsort","quicksort","mergesort") var = tk.StringVar(value=optuple[0]) control_frame = ttk.Frame(window) control_frame.pack(fill=tk.X, padx=10, pady=10) ttk.Label(control_frame, text="选择排序算法:").grid(row=0, column=0, padx=5, pady=5) cb = ttk.Combobox(control_frame, textvariable=var, values=optuple, state="readonly", width=15) cb.grid(row=0, column=1, padx=5, pady=5) cb.bind("<<ComboboxSelected>>", on_combobox_select) ttk.Label(control_frame, text="生成数据量:").grid(row=0, column=2, padx=5, pady=5) entry = ttk.Entry(control_frame, width=10) entry.grid(row=0, column=3, padx=5, pady=5) ttk.Button(control_frame, text="生成随机数据", command=generate_random_data).grid(row=0, column=4, padx=5, pady=5) ttk.Button(control_frame, text="选择数据文件", command=load_file).grid(row=0, column=5, padx=5, pady=5) ttk.Button(control_frame, text="开始排序", command=start_sorting).grid(row=0, column=6, padx=5, pady=5) ttk.Button(control_frame, text="停止排序").grid(row=0, column=7, padx=5, pady=5) # 数据展示区域 data_frame = ttk.Frame(window) data_frame.pack(fill="both", expand=True, padx=10, pady=5) # 未排序数据 unsort_frame = ttk.LabelFrame(data_frame, text="未排序数据") unsort_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=5, pady=5) unsort_tree = ttk.Treeview(unsort_frame, columns=("value",), show="headings", height=15) unsort_tree.heading("value", text="数值") unsort_tree.column("value", width=100) unsort_tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True) unsort_scrollbar = ttk.Scrollbar(unsort_frame, orient=tk.VERTICAL, command=unsort_tree.yview) unsort_scrollbar.pack(side=tk.RIGHT, fill=tk.Y) unsort_tree.configure(yscrollcommand=unsort_scrollbar.set) # 排序后数据 sort_frame = ttk.LabelFrame(data_frame, text="排序后数据") sort_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True, padx=5, pady=5) sort_tree = ttk.Treeview(sort_frame, columns=("value",), show="headings", height=15) sort_tree.heading("value", text="数值") sort_tree.column("value", width=100) sort_tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True) # 添加pack sort_scrollbar = ttk.Scrollbar(sort_frame, orient=tk.VERTICAL, command=sort_tree.yview) sort_scrollbar.pack(side=tk.RIGHT, fill=tk.Y) sort_tree.configure(yscrollcommand=sort_scrollbar.set) gif_frame = ttk.Frame(window) gif_frame.pack(fill=tk.X, padx=10, pady=5) gif_label = ttk.Label(gif_frame) gif_label.pack() # 状态信息 status_frame = ttk.Frame(window) status_frame.pack(fill=tk.X, padx=10, pady=5) time_label = ttk.Label(status_frame, text="排序耗时: --") time_label.grid(row=0, column=0, padx=10, pady=5, sticky="w") steps_label = ttk.Label(status_frame, text="运算步数: --") steps_label.grid(row=0, column=1, padx=10, pady=5, sticky="w") result_label = ttk.Label(status_frame, text="结果文件: --") result_label.grid(row=0, column=2, padx=10, pady=5, sticky="w") progress = ttk.Progressbar(status_frame, orient=tk.HORIZONTAL, length=200, mode='determinate') progress.grid(row=0, column=3, padx=10, pady=5) status_label = ttk.Label(status_frame, text="就绪", foreground="blue") status_label.grid(row=0, column=4, padx=10, pady=5, sticky="ew") # 操作按钮 button_frame = ttk.Frame(window) button_frame.pack(fill=tk.X, padx=10, pady=10) ttk.Button(button_frame, text="查看结果文件", command=open_file).pack(side=tk.RIGHT, padx=5) ttk.Button(button_frame, text="重置", command=reset).pack(side=tk.RIGHT, padx=5) # 初始加载示例数据 update_gif("bubble.gif") window.mainloop() 帮我定义停止排序按钮的程式
06-26
内容概要:本文介绍了一个基于冠豪猪优化算法(CPO)的无人机三维路径规划项目,利用Python实现了在复杂三维环境中为无人机规划安全、高效、低能耗飞行路径的完整解决方案。项目涵盖空间环境建模、无人机动力学约束、路径编码、多目标代价函数设计以及CPO算法的核心实现。通过体素网格建模、动态障碍物处理、路径平滑技术和多约束融合机制,系统能够在高维、密集障碍环境下快速搜索出满足飞行可行性、安全性与能效最优的路径,并支持在线重规划以适应动态环境变化。文中还提供了关键模块的代码示例,包括环境建模、路径评估和CPO优化流程。; 适合人群:具备一定Python编程基础和优化算法基础知识,从事无人机、智能机器人、路径规划或智能优化算法研究的相关科研人员与工程技术人员,尤其适合研究生及有一定工作经验的研发工程师。; 使用场景及目标:①应用于复杂三维环境下的无人机自主导航与避障;②研究智能优化算法(如CPO)在路径规划中的实际部署与性能优化;③实现多目标(路径最短、能耗最低、安全性最高)耦合条件下的工程化路径求解;④构建可扩展的智能无人系统决策框架。; 阅读建议:建议结合文中模型架构与代码示例进行实践运行,重点关注目标函数设计、CPO算法改进策略与约束处理机制,宜在仿真环境中测试不同场景以深入理解算法行为与系统鲁棒性。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值