【并查集+贪心】 CodeForces - 731C - Socks

CodeForces - 731C Socks (并查集+贪心) C. Socks time limit per test  2 seconds memory limit per test  256 megabytes input  standard input output  standard output Arseniy is already grown-up and independent. H 阅读详情

【并查集+贪心】 CodeForces - 731C - Socks


【题目链接】http://codeforces.com/problemset/problem/731/C


题目大意

输入第一行一个zz有n只袜子,要在接下来的m天穿,袜子有k种颜色
第二行是n只袜子的颜色
接下来m行是每天穿的两只袜子的编号

输出至少要改变几只袜子的颜色才能使这个zz不会因为穿了两只不同颜色的袜子而被嘲笑


解题思路

把袜子作为结点,两只同一天穿的袜子连起来,则改变颜色后每个连通图上的袜子颜色要一样。

第一步:并查集找出连通图
第二步:把袜子的颜色存在它的祖先的vector里
第三步:遍历所有大于1的vector,用map找出颜色最多的,剩下的都要改变颜色


AC代码

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
#include <map>
using namespace std;
typedef long long LL;
const int maxn=200007;
int a[maxn];
vector <int> v[maxn];

int father[maxn];
int find_father(int x)
{
    if(x==father[x])
        return x;
    return father[x]=find_father(father[x]);
}

void join(int x,int y)
{
    int fx=find_father(x),fy=find_father(y);
    if(fx!=fy)
    {
        father[fy]=fx;
    }
}

int main()
{
    int n,m,k,i,j,x,y,ans=0;
    scanf("%d%d%d",&n,&m,&k);
    for(i=1;i<=n;i++)
    {
        scanf("%d",&a[i]);
        father[i]=i;
    }
    for(i=0;i<m;i++)
    {
        scanf("%d%d",&x,&y);
        join(x,y);
    }
    for(i=1;i<=n;i++)
    {
        v[find_father(i)].push_back(a[i]);
    }
    ans=0;
    int mmax=0;
    for(i=1;i<=n;i++)
    {
        if(v[i].size()>1)
        {
            mmax=0;
            map <int,int> m;
            for(j=0;j<v[i].size();j++)
            {
                //printf("v[%d][%d]=%d ",i,j,v[i][j]);
                m[v[i][j]]++;
                if(mmax<m[v[i][j]]) mmax=m[v[i][j]];
            }
            ans+=v[i].size()-mmax;
        }
    }
    printf("%d\n",ans);
    return 0;
}
利用绝对式编码器实现电机无限旋转的配置与优化 本文详细解析了如何利用绝对式编码器实现电机的无限旋转功能。通过切换驱动器编码器工作模式、精确计算逻辑位置范围等关键配置步骤,解决了传统方案在多圈计数溢出时的定位难题。该方案无需硬件改造,适用于大型回转台、连续供料系统等需要大范围连续绝对定位的自动化场景。 阅读详情

相关推荐

告别“静态组件”:Adobe XD的堆栈+状态,打造“活”的响应式UI

今天,我想分享一套能彻底告别这种“笨方法”的、Adobe XD中的进阶技巧,通过组合使用“堆栈”、“内边距”和“组件状态”,去构建一个能自动适应内容、真正“活”起来的智能响应式组件。

Kingsdesigner的博客 767

codeforces 731C(DFS)

题目链接:http://codeforces.com/contest/731/problem/C 题意:有n只袜子(1~n),k种颜色(1~k),在m天中,左脚穿下标为l,右脚穿下标为r的袜子,问最少修改几只袜子的颜色,可以使每天穿的袜子左右两只都同颜色。 好恶心的袜子,一会儿看成改袜子的颜色,一会儿看成改l,r的颜色,一会下标看混......不过,菜是原罪=_= 思路:先建图,在每个连...

weixin_30553777的博客 187

OpenCV实战:高效检测与识别多类型条码与二维码

本文详细介绍了如何利用OpenCV的BarcodeDetector和QRCodeDetector模块,高效实现EAN-13条形码与常见二维码的检测与识别。内容涵盖从环境搭建、单码识别到处理多二维码的完整流程,并分享了提升识别率的图像预处理与性能优化等实战技巧,帮助开发者一站式解决视觉项目中的条码识别需求。

weixin_29094539的博客 500

codeforces 731C (并查集 水)

题目链接:点击这里题意:给出n只袜子的颜色,每天选择两只袜子,每次能把一只袜子染色。问最少染色几只袜子能使的每天的袜子颜色一样。给每天穿的两只袜子连边,很显然一个分量的袜子要一起考虑,并查集维护分量就好了。然后搜出最多的颜色,把分量的点都染成这个颜色即可。#include <cstdio> #include <cmath> #include <algorithm> #include <iostrea

morejarphone~ 636

ROS2 DDS中间件(图文并茂+超详细)

DDS 的目标场景在端上,致力于使端上的应用可以更容易的进行通信,由于它的完全分布式架构,可以方便的将端上的应用拆分为多进程架构,从而提高端的容错能力。从产品定位角度来讲,它和 Chromium 中的 mojo 都是端上的通信中间件,只不过 mojo 不强调分布式,内部集成了更多的特定于端上的机制,比如句柄的传输,消息的缓存等。但由于 mojo 生于 Chromium,目前官方并没有把它独立出来,所以用起来比较不方便。而 DDS 或许可以在简单的场景下作为 mojo 的替代品。

weixin_39939185的博客 5295

Fabric学习笔记(一)- Centos 7下的Fabric 2.3.2环境搭建

一、 环境准备 (一)、在VMware Workstation 15 安装一个Centos 7的虚拟环境,切换到图形化界面: 参考文章链接:Centos 7切换图形化界面 其中可能在yum groupinstall "X Window System"时会报错:Cannot find a valid baseurl for repo: base/7/x86_6,参考这篇文章即可:安装图形化界面报错解决 (二)、打开终端,安装所需的库: 切换root用户,输入命令:su root yum更新,输入命令:y

茕夜 2614

Codeforces 731C. Socks

题目:Socks 题意:有n只颜色的袜子,有m天,每天穿l,r俩个编号的袜子,如果袜子的颜色不同,将其中一只染色为同一色,问最少染多少次? 思路:用并查集将每天穿的袜子合并,然后将每个集合中的一些袜子染色成同一颜色最多的袜子的那个颜色,即为最少染的次数         (1)用vector将每个集合的袜子存放起来 (2)遍历vector,用map集合记录集合中同种颜色袜子的个数,(此处不能

GuoZLH的博客 777

NuPlayer 之 Renderer

触发postDrainAudioQueue_l()或postDrainVideoQueue()开始渲染。解码器输出数据 → NuPlayer::Decoder::onMessageReceived。音频数据存入mAudioQueue,视频数据存入mVideoQueue。• 每次写入后通过mNotifyConsumed通知解码器。• 通过AudioSink::write()写入音频设备。• 根据VSync信号和音频时钟调整渲染时机。• 通过Surface直接提交给显示系统。

aningxiaoxixi的博客 326

CodeForces - 731C

Problem Arseniy is already grown-up and independent. His mother decided to leave him alone for m days and left on a vacation. She have prepared a lot of food, left some money and washed all Arseniy’s clothes. Ten minutes before her leave she realized that

rainbowower的博客 312

STC89C52RC单片机原理图详解

左侧A0和右侧B0为一 一对应的关系,左上角DIR为控制数据方向端口,如果DIR接高电平是将左侧数据A0~A8送到右侧B0~B8,如果DIR接低电平,是将右侧数据B0~B8送到左侧A0~A8,由于在电路板上LE始终与VCC连接,因此这里。74HC595是串行输入,并行输出的移位寄存器,可用3根线输入串行数据,8根线输出并行数据,多片级联后,可输出16位、24位、32位等,常用于I/O口扩展。由于数码管为共阴极,给数码管下面接口输入阳码时,LED才亮,但是直接将P0~P7的高电平输入到数码管时,

m0_50562428的博客 6万+

【WRF-Urban数据集】中国60个城市的1 km分辨率城市冠层参数(UCPs)

中国60个城市的1 km分辨率城市冠层参数(UCPs)

WW、forever的博客 1073

CodeForces 731C(并查集+vector+map)

题目链接:点击打开链接题目大意:就是先输入n,m,k,分别表示袜子数量,天数,颜色数量,接下来n个数字是代表每种袜子的颜色,再接下来m行,每行两个数,表示那一天穿哪两双袜子。要求改最小数量的袜子的颜色来使每天的袜子都是相同颜色的。 题目思路:先按照最正常的并查集,把需要同一颜色的袜子都变成一个集合,然后要先找一遍每个人的老大(之前没找,结果凉了..)如图这步..然后接下来就要进行遍历,从第一双袜子...

smilestruggler_Fly To Higher 366

YOLOv11 损失函数进阶:SlideLoss 让小目标检测精度飙升

创建self.loss_fun = loss_fun # 基础损失函数(如BCEWithLogitsLoss)self.loss_coef = loss_coef # 损失系数# 计算滑动权重:根据预测与真实值的差异判断样本难度# 难度越高,权重越大该类在原有损失函数的基础上,通过diff计算样本预测与真实值的差异(差异越大,样本越难),进而生成动态权重,实现对难样本的重点学习。

m0_64661770的博客 239

codeforces 并查集_CodeForces - 731C Socks (并查集+贪心)

NoteIn the first sample, Arseniy can repaint the first and the third socks to the second color.In the second sample, there is no need to change any colors.题目大意是说,妈妈为孩子准备的袜子(都有自己的序号,不同序号代表不同颜色)。然后给出袜子的...

weixin_32340873的博客 254

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

CodeForces 731C - Socks ( 并查集 + 贪心 )

题意 Arseniy的所有袜子按照1-n编号, 每个袜子的颜色标记为c[i], 现在给出n个袜子和m天的穿袜子方案, 至多有k种颜色( 感觉是无用条件 ), 现在要求她每天穿着方案的两只袜子同色, Arseniy可以将其涂色改变颜色, 求最少的涂色数量 思路 比较容易想到并查集 将每天穿着方案中的两只袜子合并到同一个根节点下, 同一...

a7152326的博客 182

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

CodeForces - 731C Socks(并查集,贪心)

题目: C. Socks time limit per test 2 seconds memory limit per test 256 megabytes input standard input output standard output Arseniy is already grown-up and independe

riba2534的博客 743

深度学习工具包 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")

CodeForces - 731C Socks(并查集)(贪心)

Socks Arseniy is already grown-up and independent. His mother decided to leave him alone for m days and left on a vacation. She have prepared a lot of food, left some money and washed all Ars

Darkarts 1494

CodeForces 731 C.Socks(贪心+并查集)

Description m天n只袜子,袜子有k种颜色,每次操作可以将任一只袜子染成这k种颜色的任一种,要求第i天只能穿第li只和第ri只袜子,问最少操作多少次可以使得每一天穿的袜子颜色都相同 Input 第一行三个整数n,m,k分别表示袜子数,天数和颜色数,之后n个整数c[i]表示第i只袜子的颜色,最后m行每天两个整数li和ri表示第i天要穿的两只袜子(2 Output 输出最少操作数使得

ZSQ 738

CodeForces - 731C Socks(贪心+并查集+STL)

Arseniy is already grown-up and independent. His mother decided to leave him alone for m days and left on a vacation. She have prepared a lot of food, left some money and washed all Arseniy’s clothes....

Than-的博客 685

codeforces 731C Socks

题目链接:http://codeforces.com/problemset/problem/731/C题意:给出n只袜子,m天,k种颜色(感觉没什么用)。接下来给出每只袜子的颜色。然后给出m天里第i天要穿的袜子,要求同一天穿的袜子都是一种颜色。问一次性给袜子染色最少需要染几只。(可以染成任何颜色。)分析:并查集加贪心。首先把所有需要一个颜色的袜子弄到一个集合里(并查集并起来),然后每个集合选择其中颜

Fistice的博客 396

Codeforces Round #376 (Div. 2) C. Socks && 731 C 详解(并查集)

C. Socks time limit per test 2 seconds memory limit per test 256 megabytes input standard input output standard output Arseniy is already grown-up and independent. His m

K键盘里的青春K 1351

Codeforces 731C Socks【Dfs+贪心】

C. Socks time limit per test 2 seconds memory limit per test 256 megabytes input standard input output standard output Arseniy is already grown-up and independent. His m

mengxiang000000 1379

CF731C Socks并查集(森林),连边,贪心,森林遍历方式,动态开点释放内存

http://codeforces.com/problemset/problem/731/C 这个题的题意是。。小明的妈妈给小明留下了n只袜子,给你一个大小为n的颜色序列c 代表第i只袜子的颜色,小明的妈妈在以后的m天要求小明每天穿编号为l[i],r[i]所组成的一双袜子 小明觉得如果颜色不一样的话很丢人。。想一次把袜子的颜色全部改好。。使得。。既按照妈妈的指令去做 又能使每天穿的一双袜子...

weixin_30455661的博客 203

Codeforces Round #376 (Div. 2) C. Socks —— 并查集 + 贪心

题目链接:http://codeforces.com/contest/731/problem/C 题解: 1.看题目时,大概知道,不同的袜子会因为要在同一天穿而差生了关联(或者叫相互制约), 其中一条袜子可以穿多次或者不穿。那么自然就想到用并查集(DSU), 把有关联的袜子放在一个集合(经过处理后,这个集合中所有的袜子的颜色一样)。 2.集合问题搞定了,那么就...

alince20008的博客 160

CodeForces 731C Socks

http://codeforces.com/problemset/problem/731/C 并查集+贪心 将要求颜色相同的袜子序号放入一个集合中 贪心:然后统计这个集合中出现次数最多但颜色 可以得到这个集合要repain的次数 代码有难度 统计集合数 int tot;//总的集合数 for (int i = 1; i <= n; i++)   if(par[i] == i) ...

weixin_30702887的博客 103
上一篇: 并查集模板
下一篇: 【gcd】
xuziling_
博客等级 码龄9年 1粉丝 58原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值