POJ 2421 Constructing Roads——————最小生成树

Telegram AI Bot自动化实战:5步用Make搭建业务工作台 Telegram Bot 是一种轻量级、高抵达率的消息自动化载体,其核心价值在于将结构化消息(如text、photo、callback_query)转化为可编程的事件流。基于 Bot API 的简洁设计与 Webhook 机制,开发者无需复杂鉴权即可实现毫秒级响应。结合低代码平台 Make,可快速构建具备上下文识别、条件路由、多系统分发与错误熔断能力的自动化流程。该方案特别适用于客服分发、数据同步、IoT告警等高频、规则明确、需即时反馈的业务场景,显著降低对 Python/Node.js 编程与 DevOp 阅读详情

Constructing Roads

Language:Default
Constructing Roads
Time Limit: 2000MSMemory Limit: 65536K
Total Submissions: 27896Accepted: 12293

Description

There are N villages, which are numbered from 1 to N, and you should build some roads such that every two villages can connect to each other. We say two village A and B are connected, if and only if there is a road between A and B, or there exists a village C such that there is a road between A and C, and C and B are connected.

We know that there are already some roads between some villages and your job is the build some roads such that all the villages are connect and the length of all the roads built is minimum.

Input

The first line is an integer N (3 <= N <= 100), which is the number of villages. Then come N lines, the i-th of which contains N integers, and the j-th of these N integers is the distance (the distance should be an integer within [1, 1000]) between village i and village j.

Then there is an integer Q (0 <= Q <= N * (N + 1) / 2). Then come Q lines, each line contains two integers a and b (1 <= a < b <= N), which means the road between village a and village b has been built.

Output

You should output a line contains an integer, which is the length of all the roads to be built such that all the villages are connected, and this value is minimum.

Sample Input

3
0 990 692
990 0 179
692 179 0
1
1 2

Sample Output

179

Source


给的邻接矩阵
和已经连接的点,让求最小生成树


//#include<bits/stdc++.h>
#include<cstdio>
#include<vector>
#include<algorithm>

using namespace std;
const int MAXN=505;
int n,m,pre[MAXN];
struct Edge{
    int x,y,dis;
    Edge(){}
    Edge(int x1,int y1,int dis1)
    {
        x=x1; y=y1; dis=dis1;
    }
};
bool cmp(Edge a,Edge b)
{
    return a.dis<b.dis;
}
vector<Edge>d;
void init(){for(int i=1;i<=n;i++) pre[i]=i; }
int find(int x){return pre[x]==x?x:pre[x]=find(pre[x]); }
bool join(int x,int y)
{
    x=find(x);
    y=find(y);
    if(x!=y)
    {
        pre[x]=y;
        return true;
    }
    return false;
}


int main()
{

    while(~scanf("%d",&n))
    {
        d.clear();
        init();


        for(int i=1;i<=n;i++)
            for(int j=1;j<=n;j++)
            {
                int x;
                scanf("%d",&x);
                if(i==j)                continue;
                d.push_back(Edge(i,j,x));
            }
       scanf("%d",&m);
        int a,b;
        while(m--)
        {
            scanf("%d %d",&a,&b);
            join(a,b);

        }
        sort(d.begin(),d.end(),cmp);
        int cnt=0,ans=0;
        for(int i=0;i<d.size();i++)
        {
            Edge e=d[i];
            if(join(e.x,e.y))
            {
                cnt++;
                ans+=e.dis;
            }
            if(cnt==n-1) break;
        }
        printf("%d\n",ans);
    }
    return 0;
}


零代码搭建专业知识库:Wiki.js+cpolar让团队协作像写笔记一样简单 "项目文档又找不到了!“团队负责人小张第N次在群里看到这样的抱怨——技术文档分散在邮件、网盘和个人电脑里,新人入职要花一周熟悉文档位置,远程协作时版本混乱更是家常便饭。Wiki.js与cpolar内网穿透服务的出现,就像给团队协作装上了"中央大脑”,用写Markdown笔记的简单方式,搭建一个专业的知识库系统。普通人对知识管理的需求其实很简单:方便记录、容易查找、大家能用。但传统方案把这个过程搞得异常复杂:建服务器、配环境、学语法、搞权限……大部分团队还没开始就放弃了。 阅读详情

相关推荐

京东联盟h5st(3.1)加密参数逆向实战与反爬对抗策略

本文详细解析了京东联盟h5st(3.1)加密参数的逆向分析与实战破解过程。通过接口分析定位关键加密函数,拆解h5st结构并还原其基于SHA256和HMAC-SHA256的加密逻辑,最终使用Python集成JavaScript环境成功复现加密算法,并分享了应对反爬的频率限制、IP封禁及算法升级等对抗策略。

weixin_29246195的博客 1738

课程练习四—problem A

Problem Description There are N villages, which are numbered from 1 to N, and you should build some roads such that every two villages can connect to each other. We say two village A and B are conn

二百五的春天 的博客 401

解密美团外卖API:mtgsig和waimai_sign参数生成原理与Python实现

本文深入解析了美团外卖API中核心风控参数mtgsig和waimai_sign的生成原理与实现方法。文章详细拆解了waimai_sign作为业务数据签名、mtgsig作为请求环境签名的不同角色与生成逻辑,并通过Python代码示例演示了如何通过逆向工程、Frida动态Hook等技术手段模拟签名生成过程,为开发者理解移动端API安全机制提供了实战参考。

weixin_29325515的博客 552

acm_Constructing Roads

题目: Problem Description There are N villages, which are numbered from 1 to N, and you should build some roads such that every two villages can connect to each other. We say two village A and B

xu_acm的博客 410

IEEE Access 上岸指南,附含泪整理的 cover letter 、沟通邮件、终版文档等资料包

终于上岸了! 我是一个小硕,本科期间发表过两篇水文,奈何学校有更高的毕业要求,只能硬着头皮尝试一下 SCI。 想投 IEEE Access 的朋友都应该知道 小木虫论坛 对这个期刊的讨论,褒贬不一,有的人说是大水刊,有的人说有难度。 比如: @wow_: 不可否认,灌水期刊。只要之前中过一篇,再投基本没有不录用的!我们实验室其他老师说过一区除外的收费期刊都应该禁止灌水。 @pssp: 审稿人还...

kurryluo的博客 1万+

win11本地部署 DeepSeek-R1 大模型!免费开源,媲美OpenAI-o1能力,断网也能用

是否安装成功,然后直接运行部署deepseek-r1的命令。,出现下面界面即为安装成功。在cmd窗口中先输入。

记录学习编程的日常 2992

There are N villages, which are numbered from 1 to N, and you should build some roads such that ever

给出总共的村庄的编号,然后在下面的n行n列中,列举出来从i节点,到j节点的所有的权值 ,都为最后输入的那个数,之后在输入q表示有q组数据,表示接下来的q组数据表示已经联通,求出最后的最小生成树的最小权值。...

X131644的博客 578

【PT+Arduino+OneNET基础教程1】PacketTracer中MCU芯片编程教程(零基础入门)

PacketTracer软件内MCU芯片编程入门 零基础

ChloeMax_的博客 9455

一些最小生成树的(水)题

HDU102 Problem Description There are N villages, which are numbered from 1 to N, and you should build some roads such that every two villages can connect to each other. We say two village A and B are connected, if and only if there is a road between A and

m0_51008760的博客 242

Codex 接入国产大模型完整指南:CC-Switch 与 Codex++ 的工程化选型

Codex 默认走 OpenAI Responses API,而 DeepSeek、GLM、Kimi 等国产模型只提供 OpenAI-compatible 的 Chat Completions——两套协议在消息结构、流式响应、reasoning 字段、tool call 上都不兼容,所以"改个 Base URL + 填国产 Key"这种朴素操作根本跑不通。本文从架构师视角出发,把 Codex 接入国产大模型这件事讲透:先剖析协议链路到底卡在哪,再对比 CC-Switch和 Codex++两套主流方案的差异

少说,多做 3853

AutoSAR实验视频讲解:相关资料下载

AutoSAR实验视频讲解:闪烁一颗LED实验【相关资料下载】 总目录 为了方便大家自己的实验顺利进行,这里我们准备了一些实验中可能用到的资料供大家使用 介绍 这里主要是三个文件: MyApp_Core.0是我们的用户代码,在工程集成那集将会讲解 McalConfig.arxml就是我们的Mcal导出文件,用于导入到DaVinci中生成代码 CAN.dbc文件是我们的通信矩阵文件 以上几个文件都是简单的配置,不具有实际项目的实用性,大家仅供参考 // 顺便吐槽一句:百度网盘的吃相真的难看 下载连接

雪云飞星的博客 6668

hdu 1102 Constructing Roads (最小生成树)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1102 There are N villages, which are numbered from 1 to N, and you should build some roads such that every two villages can connect to each other. ...

Evildoer_llc的博客 311

18-XLINX的XC7A100T的BANK0引脚说明

DXP_0和 DXN_0是纯输入引脚,Xilinx Artix-7 FPGA 内部集成的一个片上监控模数转换器​ 的差分模拟输入对,模数转换器​的模拟信号输入端,将外部的模拟电压​ 采样并转换为内部的数字值,是一个单向的信号采集过程。它是与 VCCADC配对的关键引脚,共同为内部的精密模数转换器提供一个纯净、安静、独立的参考地平面。多FPGA同步配置: 在多FPGA系统中,主FPGA配置完成后,可以拉低从FPGA的 INIT_B使其等待,等所有FPGA都准备好后,再同时释放,实现同步启动。

weixin_44479192的博客 232

POJ-2421 Constructing Roads(最小生成树)

题目传送门:(POJ-2421 Constructing Roads) 题目大意: 要修公路,输入一个n,表示n个村庄。接着输入n*n的矩阵,该图的邻接矩阵,然后输入一个q接下来的q行 每行包含两个数a,b,表示a、b这条边联通,就是已经有公路不用修了,要让所有村庄联通在一起问:修路最小代价? 分析: 根据题目输入构造邻接矩阵,然后把已经联通的村庄的距离设置为0,表示不用在修这条公路。...

weixin_34032621的博客 87

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

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

(最小生成树)POJ2421Constructing Roads

POJ2421Constructing Roads 题意&思路: 何以解忧,唯有做题。为什么总是想复杂。 给n个村庄和村庄之间的距离,有些村庄已经存在一条路。问使村庄之间两两连通最少需要修路的长度。 并查集和最小生成树,模板题。 代码: #include<iostream> #include<stdio.h> #include<stdlib.h> #in...

Z7784562的博客 285

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

POJ2421 Constructing Roads 最小生成树

修路 时限:2000MS 内存限制:65536K 提交总数:31810 接受:14215 描述 有N个村庄,编号从1到N,您应该修建一些道路,使每两个村庄可以相互连接。我们说两个村庄A和B是连通的,当且仅当A和B之间有一条道路,或者存在一个村庄C使得A和C之间有一条道路,并且C和B连通时。 我们知道,一些村庄之间已经存在一些道路,您的工作是建造一...

日拱一卒,功不唐捐 2867

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

POJ 2421 Constructing Roads 最小生成树

来源:http://poj.org/problem?id=2421 题意:还是给你n个点,然后求最小生成树。特殊之处在于有一些点之间已经连上了边。 思路:对于已经有边的点,特殊标记一下,加边的时候把这些边的权值赋值为0即可。这样就可以既保证这些边一定存在,又保证了所求的结果正确。 代码: #include #include #include #include #include u

3492

poj 2421 Constructing Roads(最小生成树)

Constructing Roads Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 22124   Accepted: 9431 Description There are N villages, which are numbered from 1 to N,

TUT我好菜啊 2558

POJ2421Constructing Roads 最小生成树

Constructing Roads Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 29366 Accepted: 13044 Description There are N villages, which are numbered from 1 to N, and you should build some roads ...

DouglasConnor的博客 258

POJ 2421 Constructing Roads(并查集+最小生成树)

题目链接:POJ 2421 Constructing Roads 题意: 给出n个点两两之间的权值,然后有m对a,b,表示a,b已经连通了。 问将这n个点都连通最少权值和是多少。 分析: 将m对已连通的点对用并查集合并,然后用Kruskal算法即可。 CODECODE://804K 47MS #include <iostream> #include <cstdio> #include <

ramay7 626

POJ 2421 Constructing Roads(最小生成树)

题意  在n个村庄之间修路使所有村庄连通  其中有些路已经修好了  求至少还需要修多长路 还是裸的最小生成树  修好的边权值为0就行咯 #include #include #include #include using namespace std; const int N = 105, M = 10050; int par[N], n, m, mat[N][N]; int ans; struc

Deng's site \# 988

POJ 2421 Constructing Roads 最小生成树 kruscal+并查集

Constructing Roads Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 18604   Accepted: 7683 Description There are N villages, which are numbered from 1 to N, a

kdwycz的刷题空间 791

POJ 2421 Constructing Roads 最小生成树

题意:求一个图的最小生成树的权值,其中有一些边是已经连通的 思路:在没连通的边中用kruskal求出最小生成树即可 #include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<algorithm> using namespace std; t...

qq_42397248的博客 149

【最小生成树】POJ 2421 Constructing Roads

DescriptionThere are N villages, which are numbered from 1 to N, and you should build some roads such that every two villages can connect to each other. We say two village A and B are connected, if and

。。。。 293

POJ-2421 Constructing Roads (最小生成树)

题意:100个城市,城市之间已经有一些路了,现在需要再建一些使得所有城市联通,问最小代价。

hmc0411的博客 548

D - Constructing Roads POJ - 2421(最小生成树 kruskal)

D - Constructing Roads POJ - 2421(最小生成树 kruskal) There are N villages, which are numbered from 1 to N, and you should build some roads such that every two villages can connect to each other. We say ...

石旭先森的博客 285
上一篇: POJ1258 Agri-Net——————最小生成树
下一篇: POJ 1789Truck History——————最小生成树
陶鸿杰
博客等级 码龄9年 93粉丝 298原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值