次小生成树

严格次小生成树(LCA+Kruskal) 次小生成树是指在给定的无向图中,如果存在最小生成树和次小生成树,那么对于任何一颗最小生成树来看,都存在一颗次小生成树,使得这两棵树只有一条边不同。如果有严格次小生成树和非严格次小生成树之分,边权之和严格大于最小生成树的且权值最小的树,就是严格次小生成树。从非树边中找到一条严格大于树边的边取而代之,至于去掉树中哪条边.因为要求数的权值次小,所以我们发现只要去掉树中最大边就可以让树的权值尽可能的小,然后从所有非树边中找一条边取代树中最大的边,每次取一次Min就可以找到次小生成树。的生成树中最小的一个。 阅读详情

严格次小生成树

1.先求出最小生成树

2.枚举不在最小生成树上的每一条边,加入最小生成树构成环

3.每个环上找到原来最小生成树上的最长的边和次长的边

4.如果最长的边小于新加的边,将最长边去掉,否则去掉次长的边,如果次长的边等于最长的边,不存在严格次小生成树.

5.求权值

非严格次小生成树只需要找到原来最小生成树上的最长的边去掉即可,允许出现结果权值与最小生成树相同.

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<vector>
using namespace std;
typedef long long ll;
const int N=2e5+10,M=3e5+10;
const ll inf=1e18;
int con=1,h[N],nex[2*M],to[2*M],par[N][17],lg[N],vis[N],p[N],s[M],use[M];
ll w[2*M],d[N],max1[N][32],max2[N][32];
struct edge
{
    int c,t;
    ll v;
    edge(int x,int y,ll z):c(x),t(y),v(z){}
};
vector<edge>e;
void add(int x,int y,ll z)
{
    nex[con]=h[x];
    h[x]=con;
    to[con]=y;
    w[con++]=z;
}
ll find(int x)
{return p[x]=p[x]==x?x:find(p[x]);}
bool cmp(int x,int y)
{
    return e[x].v<e[y].v;
}
ll kruskal()
{
    ll res=0;
    for(int i=0;i<(int)e.size();i++)
    {
        int x=find(e[s[i]].c),y=find(e[s[i]].t);
        if(x==y)
        continue;
        use[s[i]]=1;
        add(e[s[i]].c,e[s[i]].t,e[s[i]].v);
        add(e[s[i]].t,e[s[i]].c,e[s[i]].v);
        p[y]=x;
        res+=e[s[i]].v;
    }
    return res;
}
void calmax1max2(ll a1,ll b1,ll c1,ll d1,ll &x,ll &y)
{
    if(a1>c1)
    {
        x=a1;
        y=max(c1,b1);
    }
    else if(a1==c1)
    {
        x=a1;
        y=max(b1,d1);
    }
    else
    {
        x=c1;
        y=max(a1,d1);
    }
}
queue<int>q;
void bfs(int x,int deep)
{
   q.push(x);
   d[x]=0;
   while(!q.empty())
   {
      x=q.front();q.pop();
    for(int i=1;i<=lg[d[x]];++i)
    {
        par[x][i]=par[par[x][i-1]][i-1];
        calmax1max2(max1[x][i-1],max2[x][i-1],max1[par[x][i-1]][i-1],max2[par[x][i-1]][i-1],max1[x][i],max2[x][i]);
    }
    for(int i=h[x];i;i=nex[i])
    {
        if(vis[to[i]])
        continue;
        vis[to[i]]=1;
        par[to[i]][0]=x;
        max1[to[i]][0]=w[i];
        max2[to[i]][0]=-inf;
        d[to[i]]=d[x]+1;
        q.push(to[i]);
    }
   }
}
void lca(int x,int y,ll &h1,ll &k1)
{
    if(d[x]<d[y])
    swap(x,y);
    ll m1,m2,m3,m4;
    m1=m2=m3=m4=-inf;
    int  check=0;
    while(d[x]>d[y])
    {
        check++;
        if(check==50)
        break;
        int mid=d[x]-d[y];
    calmax1max2(m1,m2,max1[x][lg[mid]],max2[x][lg[mid]],m1,m2);
    x=par[x][lg[mid]];
    }
    if(x==y)
    {
    calmax1max2(m1,m2,m3,m4,h1,k1);
    return;
    }
    for(int i=lg[d[x]];i>=0;--i)
    {
        if(par[x][i]!=par[y][i])
        {
            calmax1max2(m1,m2,max1[x][i],max2[x][i],m1,m2);
            calmax1max2(m3,m4,max1[y][i],max2[y][i],m3,m4);
            x=par[x][i];
            y=par[y][i];
        }
    }
    calmax1max2(m1,m2,max1[x][0],max2[x][0],m1,m2);
    calmax1max2(m3,m4,max1[y][0],max2[y][0],m3,m4);
    calmax1max2(m1,m2,m3,m4,h1,k1);    
}
int main()
{
    int n,m;cin>>n>>m;
    for(int i=0;i<m;++i)
    {
        int x,y;
        ll z;
        scanf("%d%d%lld",&x,&y,&z);
        if(x==y)
        continue;
        e.push_back(edge(x,y,z));
    }
    for(int i=0;i<=n;++i)
    p[i]=i;
    for(int i=0;i<(int)e.size();++i)
    s[i]=i;
    int tmp=e.size();
    sort(s,s+tmp,cmp);
    ll ans=kruskal();
    for(int i=2;i<=n;++i)
        lg[i]=(i&(i-1))==0?lg[i-1]+1:lg[i-1];
    vis[1]=1;
    bfs(1,0);
    ll se=1e16;
    for(int i=0;i<(int)e.size();++i)
    {
        if(use[i])
        continue;
        ll m1=0,m2=0;
        lca(e[i].c,e[i].t,m1,m2);
        if(m1<e[i].v)
        se=min(se,ans+e[i].v-m1);
        else if(m2!=-inf)
        se=min(se,ans+e[i].v-m2);
    }
    cout<<se<<endl;
    return 0;
}

 

[算法日常] 次小生成树 次小生成树。。。。。。。。。。。。。。。。。。 阅读详情

相关推荐

非严格次小生成树+严格次小生成树

非严格次小生成树+严格次小生成树 非严格次小生成树:首先使用最小生成树算法将最小生成树求出来,将生成树建图,然后用倍增维护树上的最大值。 考虑将所有的非树边一次加入最小生成树,并将新边与最小生成树形成的环上最大的边给删了,记录答案,然后答案最小值即为非严格次小生成树。 这个代码并没有求非严格次小生成树,但是除了没有记录答案以外,其他都一样 #include <cstdio> #incl...

qq_45342177的博客 767

次小生成树(树剖,生成树)

原文地址 生成树的概念: 在一个无向图中,设顶点数为\(n\),取其中\(n-1\)条边并使所有点相连,所得到的一棵树即为生成树。 最小生成树: 如果还没有接触过生成树的同学,欢迎戳->最小生成树详解 次小生成树: 次小生成树顾名思义,就是边权之和次小的一棵生成树。有严格次小生成树与非严格次小生成树之分。 尽管这个算法的名字叫做次小生成树,不过其实可以理解成一道数据结构 次小生成树...

669

在不同版本Python中安装PyQT5及PyQT5-Tools

在不同版本Python中安装PyQT5及PyQT5-Tools

zoomgu680的博客 2万+

次小生成树(krusal+prim)

定义:   设G = (V, E)是连通的无向图,T是图G的一个最小生成树.如果有另外一棵树T1,T1 ≠ T,满足不存在树T',T' ≠ T,w(T') &lt; w(T1),则称T1是图G的次小生成树. 算法: 1:基本算法   最简单也最容易想到的是,设T是G的最小生成树,依次枚举T的边并去掉,再求最小生成树,所得到的这些值的最小值就是次小生成树,由于最小生成树有N-1条边,这种方法...

肘子的博客 716

LT9211 单路mipi转双路mipi芯片,方案成熟,提供技术支持

LT9211 单路mipi转双路mipi芯片

TEL15012949045的博客 5028

消费级显卡跑大模型:RTX 3060 12G 部署 70 亿参数 AI 编程助手的优化实战

本文详细介绍了如何在消费级显卡RTX 3060 12G上,通过量化、投机解码和分页KV-Cache等核心优化技术,成功部署并流畅运行70亿参数的CodeLlama-7B编程助手。文章提供了从环境配置、模型准备到参数调优的完整实战笔记,实测显存占用降至7.3GB,生成速度达21.7 token/秒,为开发者和技术爱好者提供了可行的本地AI部署方案。

weixin_29053067的博客 1266

c++严格次小生成树和非严格次小生成树详讲

c++严格次小生成树和非严格次小生成树详讲

2503_92296128的博客 1494

通用定时器脉冲计数实验(STM32CubeMx配置)

通用定时器脉冲计数实验

a1169511636的博客 5510

13 次小生成树

次小生成树

weixin_45034895的博客 821

从零到一:基于Blazor和Elsa Workflows的工作流系统开发实战

本文详细介绍了如何利用Blazor和Elsa Workflows构建高效的工作流系统,从技术选型到生产环境部署,涵盖动态工作流建模、Blazor前端集成及性能优化等核心内容。通过实战案例,展示如何实现订单处理系统的自动化与灵活性,提升企业流程效率。

weixin_26875109的博客 431

[QMT量化交易小白入门]-四十九、中小盘策略是否还有未来,市值再平衡策略,年化收益率124%

该策略旨在通过定期再平衡持仓,保持投资组合中股票数量恒定(),并优先持有市值较小的股票。具体来说,策略每两天(period = 2)进行一次再平衡,根据当前市值对持仓进行调整,以实现微盘股的投资目标。中小市值策略对资金量要求有限制,资金量太大由于流动性不足,滑点可能较大,资金量太小,可能不能达到10-20只持仓,来分散风险,10-100w可能是比较理想的,后续可以根据波动率动态调仓,或波动率大于一定值时触发再平衡加入ROE或其他财务指标,或者研发投入强度大的专精特新企业,进行组合优化。

木头大左的博客 1188

洛谷 P 4180 次小生成树

题目描述 小C最近学了很多最小生成树的算法,Prim算法、Kurskal算法、消圈算法等等。正当小C洋洋得意之时,小P又来泼小C冷水了。小P说,让小C求出一个无向图的次小生成树,而且这个次小生成树还得是严格次小的,也就是说:如果最小生成树选择的边集是EM,严格次小生成树选择的边集是ES,那么需要满足:(value(e)表示边e的权值)\sum_{e \in E_M}value(e)<\s...

日拱一卒,功不唐捐 2829

qt实现OCC读取STEP模型并显示(附完整源码)

qt实现OCC读取STEP模型并显示(附完整源码)

希望我的博客,能帮上你解决学习中工作中所遇到的问题 1484

次小生成树详解

这阶段在练习图论专题,记得去年学姐讲过次小生成树,当时好像还有一个点比较迷,就是更新两点之间的最大的距离的时候,为啥一定要找已经做标记的点去更新,而且在更新的过程中也有诸多的疑问,然后刚才看了别人的代码,虽然没有注释(其实我非常不喜欢没有注释的代码,这对于入门的童鞋太不公平了),在把这个过程自己模拟弄懂的过程中,我突然感觉有些东西,尽管我们没有细学,但多少了解一些也是好的,至少可以在日后有一天你万...

别止的博客 2565

桌面运维工程师面试题详解(一)

桌面运维工程师面试题详解(一)

jks212454的博客 1428

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...

疯子的算法总结11--次小生成树+严格次小生成树

一、总体思路 首先,我这一题的思路是倍增LCA+Kruskal 首先,kruskal求最小生成树 不会的戳这里 求次小生成树 倍增 LCA 关键在于次小生成树怎么求: 问自己一些问题 怎么求不严格次小生成树 不严格次小生成树为什么不严格 方法每次选择U—V之间的边,前提是最小生成树上不存在的边,添边之后删去较短边,使用LCA找到祖先,删边,这里保证次小生成树的...

日拱一卒,功不唐捐 3027

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

关于次小生成树 详解及模板 仅kruskal

前言 关于次小生成树 详解及模板 仅kruskal (因为kru太好写了了了 后续再补上prim 其实九月份的时候就接触了最小生成树和最短路,迷迷糊糊过了一个月,现在回头看可以发现这两种算法有很多相似的地方/思想(举个栗子:prim和dijkstra \ 次短路和次小生成树) 思路 关于次小生成树,首先求出最小生成树,然后枚举每条不在最小生成树上的边(在原本的节点上添加一个vis属性进行...

放荡者的茶会 897

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

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

严格次小生成树

次小生成树次小生成树的概念简单求法例题参考代码倍增求法例题参考代码 次小生成树的概念 最小生成树大家应该都不陌生, 次小生成树就是边权和大于等于最小生成树的另一颗树,也就是边权之和第二小的生成树, 有严格次小生成树和非严格次小生成树。 边权之和严格大于最小生成树的且权值最小的树,就是严格次小生成树。 若求得的另一颗树与最小生成树权值相等, 则为非严格的次小生成树。 在本文仅介绍对于严格次小生成树的求法, 其实大同小异 简单求法 前置知识 树边:就是在生成树当中的边 非树边:未连接到该生成树上的边 假设我们求

lijing_er的博客 1443

图论 —— 生成树 —— 次小生成树

【概述】 对于给定的无向图 G=(V,E),设 T 是图 G 的一个最小生成树,那么,对于除 T 外的第二小的生成树 T' 即为图的次小生成树。 简单来说,最小生成树是生成树的最小解,次小生成树是生成树的次小解,它有可能和最小生成树的值一样,但肯定不能比最小生成树的值要小。 一般来说,求最小生成树的算法是 Prim 或 Kurskal,那么对于次小生成树,同样可以使用这两种算法来解。 对于...

Alex_McAvoy的博客 1254
上一篇: 差分约束
下一篇: 有向图的强连通分量
sedcftyv
博客等级 码龄8年 7粉丝 73原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值