【BAOJ2456】【mode】【坑题】

本文介绍了一种在有限空间内查找数列中众数的算法。通过扫一遍数列,利用不同数相撞消失的原理,最终剩余的数即为众数。此算法适用于大规模数据集且内存资源有限的场景。

Description

给你一个n个数的数列,其中某个数出现了超过n div 2次即众数,请你找出那个数。

Input

第1行一个正整数n。
第2行n个正整数用空格隔开。

Output

    一行一个正整数表示那个众数。

Sample Input

5
3 2 3 1 3

Sample Output

3

HINT

100%的数据,n<=500000,数列中每个数<=maxlongint。

题解:因为空间只有1M所以随机化,离散化什么的直接不用考虑。因为这个数出现超过n/2次,所以如果这个数和其他数两两相消的话最后剩下的一定是这个数。所以我们扫一遍,让不一样的数相撞消失就好了。

#include<cstdio>
using namespace std;
int now,temp,a,n;
int main()
{
    scanf("%d",&n);
    while (n--)
    {
        scanf("%d",&a);
        if (now==a) temp++;
        else temp--;
        if (temp<=0) {temp=1;now=a;}
    }
    printf("%d",now);
} 


from pydoc import text from PyQt6.QtCore import QTimer, QByteArray from PyQt6.QtGui import QPixmap from PyQt6.QtWidgets import QApplication, QWidget, QPushButton, QProgressBar, QCheckBox from S08dome import Ui_Form from S08mode2 import Ui_Form1 from serial_son import SerialThread from arcade import load_sound, play_sound, stop_sound import serial.tools.list_ports import warnings class sonwindow(QWidget,Ui_Form1): def __init__(self): super().__init__() self.setupUi(self) self.setWindowTitle("Setup") self.sxck() self.pushButton.clicked.connect(self.bh) self.pushButton_2.clicked.connect(self.gb) def bh(self): window.comboBox.setCurrentText(self.comboBox.currentText()) window.comboBox_2.setCurrentText(self.comboBox_2.currentText()) sonwindow.close(self) def gb(self): sonwindow.close(self) def sxck(self): self.comboBox.clear() data = serial.tools.list_ports.comports() for i in data: self.comboBox.addItem(i.device) class MyWindow(QWidget, Ui_Form): def __init__(self): super().__init__() self.setupUi(self) self.setWindowTitle("Serial Com") self.serial_thread = None self.open_serial_flag = False self.zdon = False self.num = False self.num1 = False self.checkBox.clicked.connect(self.hex_sx) self.checkBox_2.clicked.connect(self.hex_fs) self.pushButton.clicked.connect(lambda :self.plainTextEdit.clear()) self.pushButton_7.clicked.connect(self.mode) self.pushButton_8.clicked.connect(self.baoj) self.pushButton_11.clicked.connect(self.zp) self.pushButton_11.clicked.connect(self.zp_sd) self.pushButton_12.clicked.connect(self.nobaoj) self.horizontalSlider_4.valueChanged.connect(self.up) self.spinBox_3.valueChanged.connect(self.dowm) self.horizontalSlider_3.valueChanged.connect(self.up2) self.spinBox_4.valueChanged.connect(self.dowm2) self.pushButton_2.clicked.connect(self.open_serial_modbus) self.pushButton_6.clicked.connect(self.sx_ck) self.pushButton_4.clicked.connect(self.send) self.pushButton_3.clicked.connect(self.son) self.pushButton_2.clicked.connect(self.unlock_tab1) self.pushButton_5.clicked.connect(self.save) # self.checkBox_3.clicked.connect(self.dsfs) self.timer = QTimer(self) self.timer_2 = QTimer(self) # self.tabWidget.currentChanged.connect(self.ckpz) self.toggle_tab1_controls(False) self.son = sonwindow() self.door_state = False # 原 door_2 self.auto_mode = False # 原 mode self.zp_state = False # 原 zp #######进度条 self.jdt_cz = 0 self.flat = 1 self.run = False self.jdt2_flag = True self.auto_mode = False self.progressBar_2.setValue(self.jdt_cz) self.progressBar_2.setRange(0,100) # self.pushButton_9.clicked.connect(self.zidon) self.pushButton_9.clicked.connect(self.door_2) self.pushButton_9.clicked.connect(self.fx_flag) self.pushButton_10.clicked.connect(self.fs) self.beep_time = QTimer(self) self.beep_time.timeout.connect(self.check_alarm) self.beep_time.start(1000) self.timer = QTimer(self) self.timer.timeout.connect(self.update) self.auto_timer = QTimer(self) self.auto_timer.timeout.connect(self.auto_update_progress) self.auto_send_enabled = False self.auto_send_interval = 1000 def hex_sx(self): self.num = not self.num def hex_fs(self): self.num11 = not self.num11 print(f"当前发送模式: {'16进制' if self.num11 else '字符串'}") def toggle_tab1_controls(self, enable): """切换第一个tab页所有控件的可用状态""" tab1 = self.tabWidget.widget(0) # 获取第一个tab页 for widget in tab1.findChildren(QWidget): # 包含所有子控件 widget.setEnabled(enable) # 槽函:解锁按钮点击事件 def unlock_tab1(self): self.toggle_tab1_controls(True) def fx_flag(self): # if self.openmen == False: self.num5 = self.lineEdit_10.text() if self.num5 == "手动": if not self.run: # 如果定时器未运行,启动并设置方向 self.run = True self.timer.start(50) # 间隔50ms else: # 如果定时器在运行,切换方向 self.flat *= -1 def door_2(self): if self.openmen == False: self.door_state = not self.door_state self.lineEdit_6.setText("打开" if self.door_state else "关闭") print(f"门状态已切换:{self.door_state}") self.num4 = self.lineEdit_6.text() if self.num4 == "打开": self.meng = False print("有") else: self.meng = True print("没有") def update(self): if self.openmen == False: self.jdt_cz += self.flat if self.auto_timer.isActive(): self.auto_timer.stop() if not self.openmen: # 仅在手动模式下更新 if self.jdt_cz >= 100: self.jdt_cz = 100 self.timer.stop() self.run = False self.flat = -1 self.pp = False elif self.jdt_cz <= 0: self.jdt_cz = 0 self.timer.stop() self.run = False self.flat = 1 self.pp = True self.progressBar_2.setValue(self.jdt_cz) def auto_update_progress(self): current_value = self.progressBar_2.value() if self.jdt2_flag: # 增加到100 if current_value < 100: self.progressBar_2.setValue(current_value + 1) else: self.auto_timer.stop() else: # 减少到0 if current_value > 0: self.progressBar_2.setValue(current_value - 1) else: self.auto_timer.stop() def son(self): self.son_1 = sonwindow() self.son_1.show() ###滑条 def up(self,num): self.horizontalSlider_4.setValue(num) self.spinBox_3.setValue(num) def dowm(self,num): self.horizontalSlider_4.setValue(num) self.spinBox_3.setValue(num) def up2(self,num2): self.horizontalSlider_3.setValue(num2) self.spinBox_4.setValue(num2) def dowm2(self,num2): self.horizontalSlider_3.setValue(num2) self.spinBox_4.setValue(num2) # 修改 mode 方法 def mode(self): self.auto_mode = not self.auto_mode if self.auto_mode: self.lineEdit_10.setText("自动") self.openmen = True else: self.lineEdit_10.setText("手动") self.openmen = False print(f"当前模式:{'自动' if self.auto_mode else '手动'}") def check_alarm(self): self.num8 = self.lineEdit_6.text() # if self.num8 == "打开": # self.baoj() def baoj(self): self.num8 = self.lineEdit_6.text() self.num9 = self.lineEdit_10.text() if self.num8 == "打开": self.label_23.setStyleSheet("background-color: rgb(255, 0, 0);border-radius:30px;") self.jdt2_flag = False self.timer.stop() self.auto_timer.stop() self.auto_timer.start(50) self.lineEdit_6.setText("关闭") self.jdt_cz = 0 print("报警已打开") self.beep() def beep(self): sound = load_sound("蜂鸣器哔哔响.mp3") self.player = play_sound(sound) def nobaoj(self): self.label_23.setStyleSheet("background-color: rgb(0, 85, 0);border-radius:30px;") sound = load_sound("蜂鸣器哔哔响.mp3") player = play_sound(sound) stop_sound(player) self.jdt2_flag = False self.timer.stop() self.auto_timer.stop() self.auto_timer.start(50) ######来回切换图片 def zp(self): self.zp_state = not self.zp_state self.num6 = self.lineEdit_10.text() if self.num6 == "自动": if self.zp_state: print("切换到防雨模式,启动自动增加") self.label_25.setPixmap(QPixmap("不下雨.png")) self.jdt2_flag = True # 停止所有可能冲突的定时器 self.timer.stop() self.auto_timer.stop() # 确保之前实例被清除 self.auto_timer.start(50) self.lineEdit_6.setText("打开") else: print("切换到下雨模式,启动自动减少") self.label_25.setPixmap(QPixmap("下雨.jpg")) self.jdt2_flag = False self.timer.stop() self.auto_timer.stop() self.auto_timer.start(50) self.lineEdit_6.setText("关闭") self.jdt_cz = 0 def zp_sd(self): self.zp_sd = not self.zp_sd self.num7 = self.lineEdit_10.text() if self.num7 == "手动": if self.zp_sd: print("切换到防雨模式,启动自动增加") self.label_25.setPixmap(QPixmap("不下雨.png")) # self.jdt2_flag = True # # 停止所有可能冲突的定时器 # self.timer.stop() # self.auto_timer.stop() # 确保之前实例被清除 # self.auto_timer.start(50) # self.lineEdit_6.setText("打开") else: print("切换到下雨模式,启动自动减少") self.label_25.setPixmap(QPixmap("下雨.jpg")) # self.jdt2_flag = False # self.timer.stop() # self.auto_timer.stop() # self.auto_timer.start(50) # self.lineEdit_6.setText("关闭") # self.jdt_cz = 0 def auto_update_progress(self): current = self.progressBar_2.value() print(f"当前进度: {current}, jdt2_flag={self.jdt2_flag}") # 调试输出 if self.jdt2_flag: if current < 100: self.progressBar_2.setValue(current + 1) else: self.auto_timer.stop() print("自动增加完成") else: if current > 0: self.progressBar_2.setValue(current - 1) else: self.auto_timer.stop() print("自动减少完成") def convert_to_hex(self): clean_text = text.replace(' ', '').replace('0x', '').replace('0x', '') if len(clean_text) %2 != 0: clean_text = '0' + clean_text return bytes.fromhex(clean_text) ###########串口 def sx_ck(self): self.comboBox.clear() serial_ports = serial.tools.list_ports.comports() for port in serial_ports: self.comboBox.addItem(port.device) def open_serial_modbus(self): self.open_serial_flag = not self.open_serial_flag databits = int(8) stopbits = int(1) parity = serial.PARITY_NONE if self.open_serial_flag: self.pushButton_2.setText("关闭串口") self.label_2.setPixmap(QPixmap("指示灯常亮.png.png")) port = self.comboBox.currentText() baudrate = int(self.comboBox_2.currentText()) try: self.serial_thread = SerialThread(port, baudrate, databits,parity,stopbits) self.serial_thread.data_received.connect(self.FirstReader) self.serial_thread.start() except Exception as e: print(f"无法连接到串口 {port}: {str(e)}") else: self.pushButton_2.setText("打开串口") self.label_2.setPixmap(QPixmap("指示灯熄灭.png")) self.serial_thread.serial_client.close() def send(self): if self.num11: self.serial_thread.serial_client.write(bytes.fromhex(str(self.plainTextEdit_2.toPlainText()))) else: self.serial_thread.serial_client.write(str(self.plainTextEdit_2.toPlainText()).encode("GBK")) def format_data(self, data): return ' '.join(f"{byte:02X}" for byte in data) def FirstReader(self, information): self.lineEdit_9.setText(str(int(str(self.format_data(information).split(" ")[1]).split(" ")[0]))) self.lineEdit_7.setText(str(int(self.format_data(information).split(" ")[2].split(" ")[0]))) self.lineEdit_8.setText(str(int(self.format_data(information).split(" ")[3].split(" ")[0]))) print(self.lineEdit_9.text()) self.num1 = self.lineEdit_9.text() self.num2 = self.lineEdit_7.text() self.num3 = self.lineEdit_8.text() if self.num: self.plainTextEdit.appendPlainText(self.format_data(information)) else: try: shu = bytes.fromhex(self.format_data(information).replace(" ", "")).decode("GBK") self.plainTextEdit.appendPlainText(shu) except Exception as e: self.plainTextEdit.appendPlainText(str(e)) if int(self.num1) > int(self.num2) or int(self.num1) < int(self.num3): self.label_22.setStyleSheet("background-color: rgb(0, 255, 0); border-radius: 30px;") self.lineEdit_6.setText("关闭") self.jdt2_flag = False self.timer.stop() self.auto_timer.stop() self.auto_timer.start(50) self.update else: self.label_22.setStyleSheet("background-color: rgb(0, 85, 0); border-radius: 30px;") # self.lineEdit_6.setText("打开") def save(self): text_content = self.plainTextEdit.toPlainText() f = open("E:/智能门窗.txt", "r", encoding="UTF-8") print(type(f)) print(f.read(10)) print(f.read()) lines = f.readlines() print(type(lines)) print(lines) line1 = f.readlines() line2 = f.readlines() line3 = f.readlines() print(line1) print(line2) print(line3) for line in f: print(line) f.close() f = open("智能门窗.txt", "w", encoding="UTF-8") f.write(f"{text_content}") f.flush() f = open("智能门窗.txt", "a", encoding="UTF-8") print(f"{text_content}") self.spinBox_3 def fs(self): try: # 固定值 self.num = 173 self.zhi = format(self.num, '02X') # 处理lineEdit_9(带补零和默认值) input_str = self.lineEdit_9.text().strip().upper() if not input_str: input_str = "00" elif len(input_str) == 1: input_str = "0" + input_str self.shu1 = int(input_str, 16) self.zhi1 = format(self.shu1, '02X') # 处理spinBox self.shu2 = self.spinBox_3.value() self.zhi2 = format(self.shu2, '02X') self.shu3 = self.spinBox_4.value() self.zhi3 = format(self.shu3, '02X') # 校验和计算 self.num4 = (self.num + self.shu1 + self.shu2 + self.shu3) % 256 self.zhi4 = format(self.num4, '02X') # 组合发送 clean_hex = f"{self.zhi}{self.zhi1}{self.zhi2}{self.zhi3}{self.zhi4}" byte_data = bytes.fromhex(clean_hex) self.serial_thread.serial_client.write(byte_data) except ValueError as ve: print(f"值错误:lineEdit_9输入 '{self.lineEdit_9.text()}' 不是有效十六进制") print(f"详细错误: {ve}") except AttributeError as ae: if not hasattr(self, 'serial_thread') or not self.serial_thread.serial_client.is_open: print("操作失败:先打开串口连接!") else: print(f"意外属性错误: {ae}") except Exception as e: print(f"未处理的异常: {str(e)}") import traceback traceback.print_exc() if __name__ == '__main__': warnings.filterwarnings("ignore", category=DeprecationWarning) app = QApplication([]) son = sonwindow() window = MyWindow() window.show() app.exec()为什么一勾选checkBox_2就报错
最新发布
05-21
from PyQt6.QtCore import QTimer from PyQt6.QtGui import QPixmap from PyQt6.QtWidgets import QApplication, QWidget, QPushButton, QProgressBar, QCheckBox from S08dome import Ui_Form from S08mode2 import Ui_Form1 from serial_son import SerialThread from arcade import load_sound, play_sound, stop_sound import serial.tools.list_ports import warnings import re class sonwindow(QWidget,Ui_Form1): def __init__(self): super().__init__() self.setupUi(self) class MyWindow(QWidget, Ui_Form): def __init__(self): super().__init__() self.setupUi(self) self.setWindowTitle("Serial Com") self.serial_thread = None self.open_serial_flag = False self.zdon = False self.pushButton_7.clicked.connect(self.mode) self.pushButton_8.clicked.connect(self.baoj) self.pushButton_11.clicked.connect(self.zp) self.pushButton_12.clicked.connect(self.nobaoj) self.horizontalSlider_4.valueChanged.connect(self.up) self.spinBox_3.valueChanged.connect(self.dowm) self.horizontalSlider_3.valueChanged.connect(self.up2) self.spinBox_4.valueChanged.connect(self.dowm2) self.pushButton_2.clicked.connect(self.open_serial_modbus) self.pushButton_6.clicked.connect(self.sx_ck) self.pushButton_4.clicked.connect(self.send_custom_instruction_with_delay) # self.checkBox.clicked.connect()# 设置初值 # self.comboBox_2.setValue(1) # 设置初值 self.pushButton_3.clicked.connect(self.son) # self.son = sonwindow() self.timer = QTimer(self) #######进度条 self.jdt_cz = 0 self.flat = 1 self.run = False self.progressBar_2.setValue(self.jdt_cz) self.progressBar_2.setRange(0,100) self.pushButton_9.clicked.connect(self.fx_flag) self.timer = QTimer(self) self.timer.timeout.connect(self.update) def fx_flag(self): if self.openmen == False: if not self.run: # 如果定时器未运行,启动并设置方向 self.run = True self.timer.start(50) # 间隔50ms else: # 如果定时器在运行,切换方向 self.flat *= -1 def update(self): self.jdt_cz += self.flat # 边界保护 if self.openmen == False: if self.jdt_cz >= 100: self.jdt_cz = 100 self.timer.stop() self.run = False self.flat = -1 # 下自动反向 self.lineEdit_6.setText("打开") self.pp = False elif self.jdt_cz <= 0: self.jdt_cz = 0 self.timer.stop() self.run = False self.flat = 1 # 下自动反向 self.lineEdit_6.setText("关闭") self.pp = True self.progressBar_2.setValue(self.jdt_cz) ###子页面 def son(self): self.son_1 = sonwindow() self.son_1.show() ###滑条 def up(self,num): self.horizontalSlider_4.setValue(num) self.spinBox_3.setValue(num) def dowm(self,num): self.horizontalSlider_4.setValue(num) self.spinBox_3.setValue(num) def up2(self,num2): self.horizontalSlider_3.setValue(num2) self.spinBox_4.setValue(num2) def dowm2(self,num2): self.horizontalSlider_3.setValue(num2) self.spinBox_4.setValue(num2) def mode(self): self.mode = not self.mode if self.mode: self.lineEdit_10.setText("自动") self.openmen = True # self.zidon() else: self.lineEdit_10.setText("手动") self.openmen = False ###按键切换标签内容 def zidon(self): if self.openmen == True and self.yv == False: self.lineEdit_6.setText("关闭") else: self.lineEdit_6.setText("打开") #######MP3 def baoj(self): if self.pp == False: self.label_23.setStyleSheet("background-color: rgb(255, 0, 0);border-radius:30px;") sound = load_sound("蜂鸣器哔哔响.mp3") self.player = play_sound(sound) self.lineEdit_6.setText("关闭") def nobaoj(self): self.label_23.setStyleSheet("background-color: rgb(0, 85, 0);border-radius:30px;") sound = load_sound("蜂鸣器哔哔响.mp3") player = play_sound(sound) stop_sound(player) ######来回切换图片 def zp(self): self.zp = not self.zp if self.zp: self.label_25.setPixmap(QPixmap("不下雨.png")) self.yv = True else: self.label_25.setPixmap(QPixmap("下雨.jpg")) self.yv = False # def yvzhi(self): # try: # # 将字符串转换为浮点(假设 self.wd, self.max, self.min 是值字符串) # current_temp = float(self.wd) # upper_limit = float(self.max) # lower_limit = float(self.min) # # # 判断温度是否超出阈值 # if current_temp > upper_limit or current_temp < lower_limit: # self.label_22.setStyleSheet("background-color: rgb(0, 255, 0); border-radius: 30px;") # else: # self.label_22.setStyleSheet("background-color: rgb(0, 85, 0); border-radius: 30px;") # except ValueError as e: # print(f"据格式错误: {e}") # except AttributeError as e: # print(f"属性缺失: 确保已接收到据 - {e}") ###########串口 def sx_ck(self): self.comboBox.clear() serial_ports = serial.tools.list_ports.comports() for port in serial_ports: self.comboBox.addItem(port.device) def open_serial_modbus(self): self.open_serial_flag = not self.open_serial_flag databits = int(8) stopbits = int(1) parity = serial.PARITY_NONE if self.open_serial_flag: self.pushButton_2.setText("关闭串口") self.label_2.setPixmap(QPixmap("指示灯常亮.png.png")) port = self.comboBox.currentText() baudrate = int(self.comboBox_2.currentText()) if self.serial_thread and self.serial_thread.isRunning(): self.serial_thread.terminate() self.serial_thread.wait() try: self.serial_thread = SerialThread(port, baudrate, databits,parity,stopbits) self.serial_thread.data_received.connect(self.FirstReader) self.serial_thread.start() # print(f"串口 {port} 已连接,波特率: {baudrate}") # self.plainTextEdit.appendPlainText(f"串口 {port} 已连接,波特率: {baudrate}") except Exception as e: print(f"无法连接到串口 {port}: {str(e)}") # self.plainTextEdit.appendPlainText(f"无法连接到串口 {port}: {str(e)}") else: self.pushButton_2.setText("打开串口") self.label_2.setPixmap(QPixmap("指示灯熄灭.png")) self.serial_thread.serial_client.close() # 改进后的指令发送方法 def send_custom_instruction_with_delay(self): try: # if self.hex_display == False: instruction = bytes.fromhex(str(self.plainTextEdit_2.toPlainText()))##16 self.send_protocol(instruction) # else: # instruction = str(self.plainTextEdit_2.toPlainText()).encode("GBK")##字符串 # self.send_protocol(instruction) except Exception as e: print(f"发送指令时发送错误: {e}") def send_protocol(self, protocol): if hasattr(self, 'serial_thread') and self.serial_thread.isRunning(): self.serial_thread.serial_client.write(protocol) print("协议发送成功.") else: print("串行Modbus RTU连接未打开.") def format_data(self, data): return ' '.join(f"{byte:02X}" for byte in data) def FirstReader(self, information): # if self.hex_display == False: formatted_data = self.format_data(information) # 将接收到的据格式化为十六进制 self.plainTextEdit.appendPlainText(f"接收到的信息是:{formatted_data}") # else: # self.plainTextEdit.appendPlainText(f"{information}") ##字符串 # print(f"{information}") hex_string = "这个里面填什么才解析出字符串" # 输入的十六进制字符串 # 去掉空格并解码为字节 byte_data = bytes.fromhex(hex_string.replace(" ", "")) # 使用GBK编码解码为字符串 decoded_string = byte_data.decode('GBK') print(decoded_string) ########串口读取据 # def FirstReader(self, information): # self.plainTextEdit.appendPlainText(f"{information}") # self.num1 = information.split(" ")[1].split(" ")[0] # self.num2 = information.split(" ")[2].split(" ")[0] # self.num3 = information.split(" ")[3].split(" ")[0] # self.wd = self.num1.split(" ")[0].strip(" ") # self.max = self.num2.split(" ")[0].strip(" ") # self.min = self.num3.split(" ")[0].strip(" ") # self.lineEdit_9.setText(str(self.wd)) # self.lineEdit_7.setText(str(self.max)) # self.lineEdit_8.setText(str(self.min)) # self.yvzhi() if __name__ == '__main__': warnings.filterwarnings("ignore", category=DeprecationWarning) app = QApplication([]) window = MyWindow() window.show() app.exec()
05-15
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值