可撤销并查集:H题解及编程学习

在编程竞赛中,解决问题的关键之一是选择合适的数据结构来处理数据。可撤销并查集(Reversible Disjoint Set Union)是一种常用的数据结构,用于处理集合合并和查询问题。在本文中,我们将介绍如何使用可撤销并查集解决 AtCoder Beginner Contest H 题目 “Ball Collector”,并提供相应的源代码。

【问题描述】

题目中给出了一系列的球,每个球都有一个重量。我们需要进行一系列操作,每个操作可能是以下两种之一:

  1. 放入一颗球:将一颗新球放入一个集合中。
  2. 移除一颗球:从集合中移除一颗球,并计算此前集合中球的总重量。

需要注意的是,每个集合中的球的总重量是不断变化的。我们需要在每次移除球时计算并输出之前的集合中球的总重量。

【解题思路】

对于这个问题,我们可以使用可撤销并查集来解决。可撤销并查集是一种基于并查集的数据结构,它支持撤销(Undo)操作,可以回退到之前的状态。

首先,我们需要定义一个球的结构体,包括球的重量和所属集合的编号。然后,我们可以使用一个数组来表示所有的球,并使用一个数组来表示每个集合的总重量。

我们可以使用路径压缩和按秩合并的策略来进行并查集的操作,以保证效率。当放入一颗新球时,我们将其放入一个新的集合中,并将集合的总重量初始化为球的重量。当移除一颗球时,我们需要查找该球所属的集合,并输出之前的集合总重量。

为了支持撤销操作,我们可以使用一个栈来保存每个操作的状态。当进行放入球的操作时,我们将新的状态压入栈中。当进行移除球的操作时,我们需要弹出栈顶的状态,并将集合的总重量还原到移除球之前的状态。

【源代

7.1.5 蓝桥杯基础数据结构之可撤销并查集 并查集是一种在算法竞赛和计算机科学中广泛使用的数据结构,用于高效处理集合的合并和查询操作。本文将介绍其一个变体——可撤销并查集,并通过C++代码示例来展示其实现和应用。 阅读详情

相关推荐

【信息科学与工程学】计算机科学与自动化——第三十五篇 调度理论和调度算法01——资源调度算法

算法逻辑

weixin_49199313的博客 682

STM32Cubemx+CanFestival:从零到一的CANopen移植实战

本文详细介绍了如何使用STM32CubeMX和CanFestival实现CANopen协议栈的移植,从开发环境搭建到核心配置步骤,再到调试与问题排查。通过实战经验分享,帮助开发者快速掌握STM32与CANopen的结合应用,提升嵌入式系统开发效率。

weixin_42558093的博客 417

以LAN8720A为例的以太网硬件设计方案

输入时钟(XTAL1/CLKIN,XTAL2):推荐外加25MHz(性价比较高)晶振为PHY芯片提供时钟,PHY芯片内部PLL将其倍频为50MHz来使用,亦可使用直接使用50MHz晶振。三位MODE通过高低电平组合分别对应以上8种模式 ,包含10M半双工,10M全双工,100M半双工,100M全双工,是否启用自协商协议,CRS是否有效等。VDDCR:1.2V电源,可由芯片内部稳压电源提供,亦可由外部电源提供,由外部电源提供可降低芯片功耗。REF_CLK:参考时钟,由MAC或外部时钟晶振向PHY芯片提供。

weixin_46154042的博客 5884

光电式烟雾传感器实战指南(一) 光迷宫设计与散射原理篇

本文深入解析了光电式烟雾传感器的核心部件——光迷宫的设计原理与光散射机制。文章详细阐述了如何通过精心设计的光学结构实现‘透气不透光’,并重点探讨了前向散射(尤其是135°角)在提升烟雾监测系统灵敏度与可靠性中的关键作用,为DIY爱好者提供了从理论到实践的完整指南。

weixin_29229055的博客 582

工业质检新利器:手把手教你用AD-DINOv3实现零样本缺陷检测(附MVTec AD实战)

本文详细介绍了AD-DINOv3框架在工业质检中的应用,通过零样本异常检测技术解决传统方法的标注成本高和泛化能力弱问题。文章包含技术原理解析、MVTec AD数据集实战部署、模型训练流程及工业部署优化技巧,帮助读者快速掌握这一创新技术。

seed的博客 763

基于Simulink的双PMSM差速驱动转矩同步控制建模示例

本文详细介绍了基于Simulink的双永磁同步电机(PMSM)差速驱动转矩同步控制建模方法。针对AGV/叉车等双电机独立驱动系统的转矩不同步问题,提出主从式+交叉耦合控制策略,在Simulink中实现直线行驶、90°转弯和单轮打滑恢复三种工况的仿真验证。通过动力学建模、参数差异设置、同步误差定义及控制律设计,最终实现同步误差<3%、转弯半径跟踪误差<5%、打滑后100ms内恢复的性能指标。文章特别强调了实际工程中的参数标定、通信同步和故障处理要点,并提供了完整的Simulink建模步骤和工具箱使

xiaoheshang_123的博客 203

Python全栈入门到实战【进阶篇 1】类与对象:面向对象编程的基石

Python中定义类使用**class关键字**,创建对象使用**类名()**(类似调用函数),语法简洁,我们从最基础的空类开始,逐步拆解。class# 定义空的学生类,pass表示占位,无实际内容 class Student : pass编码规范:类名遵循大驼峰命名法(每个单词首字母大写,无下划线),如StudentCarPhone,这是Python官方推荐的PEP8规范,便于区分类和其他标识符。实例方法必须定义在类内部;实例方法的第一个参数必须是self(名称可自定义,如this。

那些看似不起波澜的日复一日,会在某天让你看到坚持的意义 3403

YOLO11多个点组合创新:GC10-DET缺陷检测 | DCNv4结合SPPF+11Detect创新性结合

DCNv4结合SPPF+11Detect创新性结合,原始mAP50为0.633 提升至0.651

①答疑群聊服务;②YOLO大模型知识问答系统;③计算机视觉论文生成智能体; 1287

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

上一篇: 「iOS编程学习指南」· 第 1 期:入门篇
下一篇: 音视频开发进阶 | 编程学习
普通网友
博客等级 码龄3年 17粉丝 0原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值