LintCode 629: Minimum Spanning Tree (最小生成树经典题)

计算机考研复试之常问问题篇(2) 常问问题(2) 1. 你知道的排序算法 1)冒泡排序: 从数组中第一个数开始,依次遍历数组中的每一个数,通过相邻比较交换,每一轮循环下来 找出剩余未排序数的中的最大数并“冒泡”至顶端。 稳定; 平均时间复杂度:O(n ^ 2) 2)插入排序: 待排序的依次与已排序序列比较并寻找插入的位置,每次外循环结束后,将当前的数插入到合适的位置。 稳定; 平均时间复杂度:O(n ^ 2) 有折半插入排序,稳定,n^2复杂度 3)希尔排序(缩小增量排序): 希尔排序是把记录按下表的一定增量分组,对每组使用直 阅读详情
  1. Minimum Spanning Tree
    Given a list of Connections, which is the Connection class (the city name at both ends of the edge and a cost between them), find some edges, connect all the cities and spend the least amount.
    Return the connects if can connect all the cities, otherwise return empty list.

Example
Gievn the connections = [“Acity”,“Bcity”,1], [“Acity”,“Ccity”,2], [“Bcity”,“Ccity”,3]

Return [“Acity”,“Bcity”,1], [“Acity”,“Ccity”,2]

Notice
Return the connections sorted by the cost, or sorted city1 name if their cost is same, or sorted city2 if their city1 name is also same.

最⼩小⽣生成树的概念是在⼀一个⽆无向图中,找出⼀一些边,组成⼀一棵树,使得这些边的权值
加起来最⼩小。主要解法有Prim和Krusal等。

解法1:
Prim。我的方法是先将City按名称排序,先取第一个放入joint set,然后更新每个节点跟joint set的距离,再看那个节点离joint set 最近,将该节点放入joint set,同时更新每个节点跟joint set的距离,如此反复,直到所有节点都放入了joint set。
但我的solution不能pass,我看了一下fail的case,我的方案的output跟expected基本一样,只有一个distance不同 ,但distance的cost是一样的。这个可能是因为MST不唯一。
顺便提一下,什么样的图的MST唯一呢? 根据
https://zhidao.baidu.com/question/509521548.html

  1. 当带权连通图的任意一个环中所包含的权值均不相同,其MST是唯一的。
  2. 先正常求出最小生成树,再求次小生成树(具体可以枚举图上其他边加到树里,同时删去重复的边,找到权值和最小的删边方法),如果求出次小生成树的权值和与最小生成树不相等,则最小生成树唯一,否则不唯一。
/**
 * Definition for a Connection.
 * class Connection {
 * public:
 *   string city1, city2;
 *   int cost;
 *   Connection(string& city1, string& city2, int cost) {
 *       this->city1 = city1;
 *       this->city2 = city2;
 *       this->cost = cost;
 * }
 */
 
/**
 * Definition for a Connection.
 * class Connection {
 * public:
 *   string city1, city2;
 *   int cost;
 *   Connection(string& city1, string& city2, int cost) {
 *       this->city1 = city1;
 *       this->city2 = city2;
 *       this->cost = cost;
 * }
 */

bool operator < (const Connection& c1, const Connection& c2) {
    if (c1.cost != c2.cost)
      return c1.cost < c2.cost;

    if (c1.city1 != c2.city1)
      return c1.city1 < c2.city1;

   return c1.city2 < c2.city2;
}


class Solution {
public:
    /**
     * @param connections given a list of connections include two cities and cost
     * @return a list of connections from results
     */
    vector<Connection> lowestCost(vector<Connection>& connections) {
        // MST - Prime algorithm
        vector<Connection> result;
        if (connections.size() == 0) return result;

        sort(connections.begin(), connections.end());
	 set<string> nameSet;
        for (auto c : connections) {
            nameSet.insert(c.city1);
            nameSet.insert(c.city2);
        }
        
        int len = nameSet.size();
        vector<string> nameVec(nameSet.begin(), nameSet.end());
        
        map<string, int> nameMap; //city_name, city_index
        int index = 0;
        for (auto s : nameSet) {
            nameMap[s] = index++;
        }
        
        string dummy = "INVALID";
        vector<vector<Connection>> graph(len, vector<Connection>(len, Connection(dummy, dummy, INT_MAX))); //need to do this because Connection does not provide default construction

        for (int i = 0; i < len; ++i) {
            for (int j = 0; j < len; ++j) {
                graph[i][j] = Connection(nameVec[i], nameVec[j], INT_MAX);
            }
        }
        

        for (auto c : connections) {
            if ((c < graph[nameMap[c.city1]][nameMap[c.city2]]) &&
                (c < graph[nameMap[c.city2]][nameMap[c.city1]])) {
                graph[nameMap[c.city1]][nameMap[c.city2]] = c;
                graph[nameMap[c.city2]][nameMap[c.city1]] = c;
            } 
        }
        vector<bool> visited(len, false);
        visited[0] = true;
        
        map<int, Connection *> dist; //city_index, distance to mst
        for (int i = 0; i < len; ++i) {
                dist[i] = &graph[0][i];
        }

        for (int i = 1; i < len; ++i) {
            int minDist = INT_MAX;
            for (int j = 0; j < len; ++j) {
                if (!visited[j] && dist[j]->cost < minDist) {
                    minDist = dist[j]->cost;
                    index = j;
                }
            }
            
            if (minDist == INT_MAX) return vector<Connection>();
            visited[index] = true;
            result.push_back(*dist[index]);

            for (int j = 0; j < len; ++j) {
                if (!visited[j]) {
                  if (dist[j]->cost > graph[index][j].cost) dist[j] = &graph[index][j];
                }
            }
        }
        sort(result.begin(), result.end());
        return result;
    }
};

解法2:Kruskal + union-find
Kruska 算法:⾸首先按照每条边的边权排序。然后依次按下面步骤将各条边加入MST:

  1. 判断该边两个端点是否都已经在MST中。若都在,说明连这条边就会形成环,故不能选该边;否则至少有一端点不在MST中,所以把这条边加⼊入MST中。
  2. 如何判断两个端点是否在一个结合中呢?并查集。
    注意:最后result里面的connection数应为所有城市数-1。因为2个城市一个connection,而且又没有环。
/**
 * Definition for a Connection.
 * class Connection {
 * public:
 *   string city1, city2;
 *   int cost;
 *   Connection(string& city1, string& city2, int cost) {
 *       this->city1 = city1;
 *       this->city2 = city2;
 *       this->cost = cost;
 * }
 */

bool operator < (const Connection & a, const Connection & b) {
    if (a.cost == b.cost) {
        if (a.city1 == b.city1) {
            return a.city2 < b.city2;
        } else {
            return a.city1 < b.city1;
        }
    } else {
        return a.cost < b.cost;
    }
}

class Solution {
public:
    /**
     * @param connections given a list of connections include two cities and cost
     * @return a list of connections from results
     */
    vector<Connection> lowestCost(vector<Connection>& connections) {
        sort(connections.begin(), connections.end());
        unordered_map<string, int> hashmap; //cityname, index
        int index = 0;
        
        for (auto connection : connections) {
            if (hashmap.find(connection.city1) == hashmap.end()) {
                hashmap[connection.city1] = index++;
            }
            if (hashmap.find(connection.city2) == hashmap.end()) {
                hashmap[connection.city2] = index++;
            }
        }
        
        int numCities = index; 
        father.resize(numCities);
        for (int i = 0; i < numCities; ++i) {
            father[i] = i;
        }
        vector<Connection> results;
        
        for (auto connection : connections) {
    
            int cityIndex1 = hashmap[connection.city1];
            int cityIndex2 = hashmap[connection.city2];

            int root1 = find(cityIndex1);
            int root2 = find(cityIndex2);
            if (root1 != root2) {
                father[root1] = root2;
                results.push_back(connection);
            }
        }
        
        if (results.size() != numCities - 1) return {};
        return results;
    }
    
private:
    vector<int> father;
    int find(int num) {
        if (father[num] == num) return num;
        father[num] = find(father[num]);
        return father[num];
    }
};

代码同步在
https://github.com/luqian2017/Algorithm

最小生成树(minimum spanning tree)问题的两种解法 最小生成树实际上就是最小连通图,找最小生成树就是找权值和最小连通图。 以下题为例: 城市公交网建设问题 【问题描述】   有一张城市地图,图中的顶点为城市,无向边代表两个城市间的连通关系,边上的权为在这两个城市之间修建高速公路的造价,研究后发现,这个地图有一个特点,即任一对城市都是连通的。现在的问题是,要修建若干高速公路把所有城市联系起来,问如何设计可使得工程的总造价最少? 【输入格式】 阅读详情

相关推荐

计算机综合考试真题

408 2017年计算机综合考试试题加答案,讲解非常详细。

PPPoE-在配置PPPoE的用户名和密码的时候一定要准确严格,不要在后面加空格,千万记住,特别是复制张贴的时候,同时还有注意大小写的问题!!!

PPPoE-在配置PPPoE的用户名和密码的时候一定要准确严格,不要在后面加空格,千万记住,特别是复制张贴的时候,同时还有注意大小写的问题!!!

LinuxKernelCiscoIOS的博客 5169

【塑料加工工程】气体辅助注塑成型工艺技术:厚壁件中空减重与缩痕控制的系统性解决方案

内容概要:本文系统阐述了气体辅助注塑成型(GAIM)在厚壁塑料制品中实现中空减重与缩痕控制的核心技术原理与工程应用方案。针对传统注塑中因保压压力衰减、浇口冻结导致的缩痕、缩孔、内应力、超重及高锁模力等耦合缺陷,GAIM通过“短射+注气”方式,在熔体芯部形成连续中空气道,利用高压氮气实现内部等压补缩,从根本上重构了压力传递路径。文章深入剖析了短射率、延迟时间、分段气压、氮气纯度等关键参数的作用机制,提出了涵盖模具设计(气针布局、气道拓扑、溢料井)、CAE仿真前置、质量评价体系(CT检测、壁厚均匀性、缩痕等级)及量产管控(SPC、缺陷诊断矩阵)的全流程解决方案。; 适合人群:从事注塑工艺开发、模具设计、高分子材料成型及相关制造领域的工程师与技术人员,尤其适用于具备一定注塑基础、致力于解决厚壁件成型难题的研发人员。; 使用场景及目标:①解决厚壁注塑件的缩痕、缩孔与残余应力问题;②实现产品轻量化设计并降低锁模力与生产周期;③指导GAIM工艺调试、模具开发与缺陷排查,提升量产稳定性与经济效益;④为新材料、新结构的工艺可行性评估提供理论依据。; 阅读建议:此资源强调理论与实践结合,建议读者在掌握聚合物流变学与传热学基础知识的前提下,结合实际案例对照参数窗口与缺陷诊断矩阵进行学习,并重视CAE仿真与首件CT检测在工艺开发中的前置作用,避免仅凭经验调机。

静态与单臂路由的结合1

单臂和静态路由实验 说明 PC1 、 PC2 、PC3、 PC4 分别在vlan2、3、4、5中。使用C类网段192.168.1.0/24 实验内容RI与SW1 、 R2与SW2配置单臂路由,R1、R2、R3配置静态路由,实现相互ping通。 拓扑图 ...

weixin_34387468的博客 234

群晖NAS断电后IP变了?3步搞定静态IP设置(附Linux挂载指南)

本文针对群晖NAS因断电重启导致IP地址变化的问题,提供了从根源到实践的完整解决方案。核心内容包括如何为NAS配置静态IP以彻底解决连接中断,并详细讲解了在Linux系统中通过NFS协议稳定挂载NAS共享文件夹的步骤与指南,确保网络存储服务持久可靠。

weixin_29271263的博客 862

Windows7 64位系统PL2303驱动无法安装问题解决

问题描述:电脑安装的是Win7 64位的旗舰版,USB to RS232这种线很简单,对于笔记本如果要用串口,就不能少了它了。USB to RS232转换芯片种类繁多,常见的有ch340,0108,PL2303,FT232等,这里面FT232的应该价格是相对比较贵的,因为FTDI的芯片本身比较贵。由于买了一根PL2303芯片的USB to RS232转换线,于是插上后发现驱动无法安装,又是在设备管

suxiang198的博客 5810

【考研真题408】2017年 数据结构

42(3)对任意的带权连通图,满足什么条件时,其 最小(代价)生成树MST 是唯一的?4.要使一棵非空二叉树的先序序列与中序序列相同,其所有非叶结点须满足的条件是(B)11.下列排序方法中,若将顺序存储更换为链式存储,则算法的时间效率会降低的是(D)当带权连通图的任意一个环中所包含的边的权值均不相同时,其 MST 是唯一的。8.下列二叉树中,可能成为折半查找判定树(不含外部结点)的是(A)解释:一般了解B+树是做数据库中的索引的,所以我选B。9.下列应用中,适合使用B+树的是(B)A.编译器中的词法分析。

开心星人的博客 2103

使用强化学习快速让AI学会玩贪食蛇游戏(轻量级二十分钟训练+代码)

如何让AI玩会贪食蛇,甚至比你厉害概述构建问题(强化学习求解的一般步骤)环境动作定义状态定义奖励设计训练奖励值收敛图效果代码 概述 所用技术:强化学习(Deep Reinforcement Learning),属于一种无监督学习,利用奖励rewardrewardreward教会智能体AgentAgentAgent在合适的场景做合适的决策。 采用算法:试过两种算法D3QN和离散版本的PPO算法,最终采用离散版本PPO算法+GAE(PPO是我用过的性能最好的算法之一) 编程语言与深度学习框架:Python3.

ZYunfei的博客 2万+

数据结构

索引结构和散列结构的区别 索引存储结构是用结点的索引号来确定结点存储地址,其优点是检索速度快,缺点是增加了附加的索引表,会占用较多的存储空间。 散列存储结构是根据结点的值确定它的存储地址(散列函数) 随机存取结构:你想找第几个数据元素直接可以用下标找到。 游标和指针 ...

Hi7brooke的博客 301

Open3D 计算点云配准的旋转和平移误差

通过计算旋转误差和平移误差来量化配准结果与真实变换之间的偏差。

点云侠的博客 254

1.2 amdgpu_bo的设计分析 — gem层和ttm层

本文分析了AMD KFD的BO设计架构,重点介绍了DRM子系统中缓冲对象的多层继承关系。文章首先展示了核心继承层次图,包括DRM通用层(drm_gem_object)、TTM内存管理层(ttm_buffer_object)、AMD驱动层(amdgpu_bo)和KFD计算层(kgd_mem)。随后详细解析了drm_gem_object结构体的关键功能,包括用户空间接口管理、内存映射支持、引用计数机制以及DMA-BUF导入/导出功能。

图形/计算GPU的驱动与虚拟化技术分享园地 2552

[Lintcode] 629. Minimum Spanning Tree

给出一些Connections,即Connections类,找到一些能够将所有城市都连接起来并且花费最小的边。 如果说可以将所有城市都连接起来,则返回这个连接方法;不然的话返回一个空列表。 例 给出 connections = ["Acity","Bcity",1],["Acity","Ccity",2],["Bcity","Ccity",3], 返回 ["Acity","Bcity",1],["Acity","Ccity",2]。

qq_27647073的博客 1470

AI智算-K8s如何利用GPFS分布式并行文件存储加速训练or推理

GPFS(General Parallel File System,通用并行文件系统)是由 IBM 开发的高性能分布式文件系统,最初设计于 1990 年代,用于满足高性能计算(HPC)环境对大规模数据存储和访问的需求。GPFS 现已广泛应用于企业级存储、云计算、大数据分析、人工智能和媒体处理等领域。它以其高性能、可扩展性和可靠性著称,能够支持从小型集群到超大规模系统的各种部署场景。

Kason_iWiki 1132

lintcode 629. Minimum Spanning Tree 的思路与python实现

Given a list of Connections, which is the Connection class (the city name at both ends of the edge and a cost between them), find edges that can connect all the cities and spend the least amount. Retu...

qq_35175413的博客 626

针对小缺陷目标:在YOLOv11中引入小目标检测层

摘要: 针对YOLOv11在工业检测中漏检微小目标(如焊点气泡)的问题,研究发现深层特征下采样导致小目标信息丢失。通过在YOLOv11中增加P2检测层(4倍下采样)并融合浅层高分辨率特征,可显著提升小目标召回率。关键优化包括:调整模型结构、谨慎设计数据增强策略(减少MixUp、增加小目标粘贴)、重新分配损失权重(提升P2层权重)、优化推理速度(动态分辨率、通道裁剪)。同时强调数据质量的重要性,建议根据具体场景特性(目标尺寸、分布)定制方案,而非盲目调整模型。

as1225120794的博客 366

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

MST(Minimum Spanning Tree,最小生成树)

今天从志权师兄那里学会了最小生成树。所谓生成树,就是n个点之间连成n-1条边的图形。 而最小生成树,就是权值(两点间直线的值)之和的最小值! 首先,要用二维数组记录点和权值。如上图所示无向图: nt map[7][7];        map[1][2]=map[2][1]=4;        map[1][3]=map[3][1]=2;        ......

不会思考的机器 584

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

图综合练习--拓扑排序_图的概念那么多,这几个易漏点你都会吗?(内附知识点讲解汇总)...

考点1:图的遍历Q1下列关于广度优先算法的说法中,正确的是( )。I. 当各边的权值相等时,广度优先算法可以解决单源最短路径问题II. 当各边的权值不等时,广度优先算法可用来解决单源最短路径问题II.广度优先遍历算法类似于树中的后序遍历算法IV. 实现图的广度优先算法时,使用的数据结构是队列A、I、IVB、II、II、IVC、II、 IVD、I、II、IV(点击选项查看答案)A1广度优...

weixin_39559382的博客 1005

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

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

【数据结构】- 【考研复试面试题】-汇总大合集

数据结构-考研复试面试题-汇总大合集 写在前面的话:第二次写文章,本篇文章涉及内容主要包括数据结构与算法,包含市面上最热门的面试题,加以总结,用于本人的专业课面试复习,包括一些个人理解和总结, 如果能帮到你,欢迎点赞,如有写的不妥当的欢迎指出(WeChat:YEZHENGJIE) 参考主要书目:《数据结构》严蔚敏,以及辅导教材书 王道《数据结构》,天勤《数据结构高分笔记》 文章目录1、常见的数............

weixin_40852935的博客 2万+

【基础问答】数据结构

排序 1、内部排序包括:插入排序、选择排序、交换排序、归并排序、基数排序。其中插入排序包括:直接插入排序、折半插入排序、希尔排序;选择排序包括:简单选择排序,堆排序;交换排序包括:冒泡排序、快速排序。 (1)直接插入排序(稳定):基本思想为:将序列分为有序部分 和无序部分,从无序部分依次选择元素与有序部分比较找到合适的位置,将原来的元素往后移,将元素插入到相应位置上。 时间复杂度为:顺序O(n) 逆序O(n^2) 平均O(n^2),空间复杂度为O(1) 顺序比较n-1次,逆序比较n(n-1)/2次

qq_41427793的博客 1311

2017

1.下列函数的时间复杂度是 。 1 2 3 4 5 int func(int n){  int i=0, sum=0;  while(sum &lt; n) sum += ++i;  return i; } A.O(logn)                         B.O(n1/2...

u011587070的专栏 1万+

argparse - Parser for command-line options, arguments and sub-commands - 3

argparse - Parser for command-line options, arguments and sub-commands - 3 argparse - Parser for command-line options, arguments and sub-commands https://docs.python.org/3/library/argparse.html argpar...

程永强 1174

2017考研计算机真题错题本

2017考研计算机真题错题本 折半查找判定树 二叉判定树是用于描述解决问题的思路,比如可以使用判定树描述N个数的比较过程, 它也可以用于描述折半查找即二分查找的过程。 描述折半查找的二叉判定树,我们也可以叫折半查找判定树 或者 折半(查找)二叉(判定)树, 从这个判定树我们可以分析算法的效率。 取整分为:折半向上取整、折半向下取整 参考extra1 折半(查找)二叉(判定)树 某计算机主存按字...

antRain的博客 1万+

5.4图的应用

图的应用 1.最小生成树(研究问题:N个村庄修路连通,怎样花销最小让N个村庄连通) 一个连通图的生成树是该图的极小连通子图,通常为带权无向图 包含所有顶点,尽量少的边。 删除一条边则变为非连通图,增加一条边则会产生回路。 特点: 1.最小生成树不唯一,但该无向连通图中无相同权值边则最小生成树唯一; 2.最小生成树的权值之和唯一,即代价唯一; 3.该树顶点数为该连通图结点个数n,所有该生成树边为n...

linry的博客 506

minimum spanning tree

首先我们要给出下面一个概念,如何可以节约空间地保存无向图: a = [100 for i in range(int(10*11/2))] def update(i,j,l): if i &gt; j: a[int(i*(i+1)/2+j)] = l else: a[int(j*(j+1)/2+i)] = ...

enockyang的博客 1006

AND Minimum Spanning Tree

2 3 2Problem Description You are given a complete graph with N vertices, numbered from 1 to N. The weight of the edge between vertex x and vertex y (1<=x, y<=N, x!=y) is simply the bitwise AND...

qq_44866969的博客 204
上一篇: Lintcode1046: Prime Number of Set Bits in Binary Reresenation
下一篇: LintCode 1360 Symmetric Tree (经典题)
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值