算法与设计分析作业2(动态规划)

程序设计思维与实践 Week11 作业 程序设计思维与实践 Week11 作业 A - 必做题11-1题目分析代码B - 必做题11-2分析代码C - 必做题11-3题目分析D - 必做题11-4题目分析E - 选做题11-1 东东与 ATM题目分析F - 选做题11-2 东东开车了题目题目分析 A - 必做题11-1 题目 题目地址 分析 简单的模拟题,只要在20年内模拟每一年的价格就可以 代码 #include<iostrea... 阅读详情

算法与设计分析作业2(动态规划)


1 Largest Divisible Subset

Given a set of distinct positive integers, find the largest subset such that every pair (Si,Sj) of elements in this subset satisfies:Si%Sj = 0 or Sj%Si = 0.

The optimal substructure and DP equation

首先将数组升序排序,这样我们就可以把较大的问题转换成较小的问题。dp[i]表示以dp[i]为最大数的符合要求子集的最大元素个数,max[i]表示到i位置为止符合要求子集的最大元素个数。因此该题可以将n个元素的符合要求的最大子集转变为前n-1个元素符合要求的最大子集(直至只剩下一个元素)。递推式为:1 1.2

另外我们利用pre[]数组记录前一个可整除的值的下标,最后根据这些下标找到自己元素。

Pseudo-code
# @param {Integer[]} nums
# @return {Integer[]}
function largest_divisible_subset(nums)
      if nums.length==0 then return [] end  
      nums数组升序排序
      建立dp数组并填充1
      建立max数组并填充1
      建立pre数组并填充为自己的下标
      for i in 1...nums.length
        for j in 0...i
          if nums[i]%nums[j]==0 && dp[i]<dp[j]+1
            dp[i]=dp[j]+1
            pre[i]=j
          end
        end
        max[i]=max(dp[i],max[i-1])
      end
      建立子集subset
        取max数组中第一个最大值的下标x
      while pre[x]!=x
        根据下标指示将元素nums[x]加入到子集subset中
        x=pre[x]
      end
      将最后一个元素nums[x]加入到子集subset中
      返回自己subset
end
Prove the correctness

首先该问题包含最优子结构的性质,我们可以将n个元素的符合要求的最大子集转变为前n-1个元素符合要求的最大子集(直至只剩下一个元素)。其次该问题包含重叠子性质,在解题过程中许多子问题需要重复计算,比如计算dp[3]是需要计算dp[2]+1,计算dp[4]需要计算dp[2]+1,那么dp[2]就是需要重复计算的,因此可以用”备忘录”将其记录。综上该题用动态规划是正确的。

The complexity of your algorithm

首先排序算法的复杂度为O(nlogn),求dp过程中的循环次数为n*(n-1)/2,复杂度为O(n2),最后回溯求子集的复杂度为O(n),因此最后的时间复杂度为O(n2)。

2 Money robbing

A robber is planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

  1. Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
  2. What if all houses are arranged in a circle?
The optimal substructure and DP equation

对于问题1,dp[i]表示从0~i家房子能抢到钱的最大数目,对于每一个房子,我们可以做一个决策,抢钱或者不抢钱。若是不抢钱,我们在该房子位置能抢到的最多钱就是前一个房子的能抢到的最多钱dp[i]=dp[i-1],若是抢钱,我们在该房子位置能抢到的最多钱就是当前房子能抢到钱加上前二个房子能抢到的最多钱dp[i]=dp[i-2]+nums[i]。两种决策的最大值就是该房子位置能抢到的最多钱。因此递推式为: 2

对于问题2,递推式是不变的,由于房子形成一个环,所以第一个房子和最后一个房子不能同时抢,所以只能抢第一个房子或者抢最后一个房子,因此我们只需要求0~nums.length-2号房子能抢到的最多钱和1~nums.length-1号房子能抢到的最多钱,两者比较求最大值。

Pseudo-code
# @param {Integer[]} nums
# @return {Integer}
# question 1:
function rob(nums)
    if nums.length==0 then return 0 
算法设计与分析——独立任务最优调度问题 文章目录问题描述问题分析算法设计——动态规划最优子结构性质:构造最优解算法复杂度分析代码 问题描述 独立任务最优调度问题 ★问题描述: 用2台处理机A和B处理n个作业。设第i个作业交给机器A处理时需要时间ai.若由机器B来处理,则需要时间bi。由于各作业的特点和机器的性能关系,很可能对于某些i,有ai≥bi,而对于某些j≠i,有aj< bj;。既不能将一个作业分开由2台机器处理,也没有一台机... 阅读详情

相关推荐

《算法设计与分析》王红梅 第二版部分习题

分治法、动态规划法、贪心法、回溯法、分支限界法。

paidaxinga的博客 6063

北航计算机研究生课程 算法设计与分析 Assignment_1

北航计算机研究生课程 算法设计与分析 Assignment_1

算法分析与设计 期末大作业.doc

C语言版 算法分析与设计 期末大作业 西安电子科技大学 计算机学院 软件学院 C语言版 算法分析与设计 期末大作业 西安电子科技大学 计算机学院 软件学院 C语言版 算法分析与设计 期末大作业 西安电子科技大学 计算机学院 软件学院

2014 《算法设计与分析》 算法设计大作业 选题 (修订版)

算法的古老题目,里面包含了几个典型的算法题目,希望你们感兴趣

安路科技FPSoC开发实战:从芯片特性到边缘计算应用

本文深入解析安路科技FPSoC芯片在边缘计算领域的开发实战,重点介绍SALDRAGON系列芯片的异构计算架构优势,包括RISC-V/ARM处理器与FPGA的协同工作。通过工业控制和智能视觉应用案例,展示硬件加速实现与低功耗设计技巧,帮助开发者高效利用FPSoC进行边缘计算应用开发。

weixin_29248611的博客 375

什么是plm系统?-数字化转型网

当今世界,产品研发能力是企业在激烈的市场竞争中保持战略优势的核心竞争力之一。如何有效地缩短产品研发周期、改善产品服务的设计迭代流程、有效降低产品的研发成本,也是企业面临的主要问题之一。PLM(Product Lifecycle Management,产品生命周期管理)在优化产品研发的全管理流程、增强企业产品的市场竞争力方面具有关键的作用。

cxo17757154043的博客 882

IPsec (主模式,野蛮模式)

IPsec vpn的主模式和野蛮模式

七汣的博客 3414

Android 15网络子系统深度解析(一):ConnectivityService与网络管理框架全解析

深入剖析Android 15核心网络服务ConnectivityService的架构设计、NetworkAgent/Factory机制、网络状态管理、以及WiFi/移动网络切换的完整流程

Cheson的专栏 1749

AIGC游戏测试自动化:AI如何提升游戏QA效率

随着游戏产业的蓬勃发展,游戏的复杂度和规模不断增加,传统的游戏测试方式面临着巨大的挑战。本文章的目的在于深入探讨AIGC技术在游戏测试自动化中的应用,分析AI如何提升游戏QA的效率。范围涵盖了从核心概念到实际应用的各个方面,包括算法原理、数学模型、项目实战案例以及未来发展趋势等。本文将按照以下结构进行阐述:首先介绍核心概念与联系,明确AIGC和游戏测试自动化的相关概念和关系;接着讲解核心算法原理和具体操作步骤,通过Python代码进行详细说明;然后介绍数学模型和公式,并举例说明;

AI 原生应用开发的博客 1352

5、快速入门

点击启动实例按钮,并设计一个business key,每个实例会有一个business key, 业务主键,也相当于一个流程实例唯一key,一般会与一次业务强相关,比如一个订单号 ,此处取为shopping_1;付款程序完成后会流转到物流发货任务,此时java工程的相应订阅会收到任务,并进入断点,且读到到toWhere变量。单击shopping可以进入实时流程图的执行图,此时流程流转到第一个任务,需要业务系统完成此任务,并通知引擎。添加类,分别订阅流程中的加入购物车任务和物流发货任务。

leyoliu的博客 3499

3、保险行业商业智能解决方案的理解与实施

本文详细探讨了商业智能(BI)在保险行业的应用与实施策略,涵盖了从BI环境开发的关键步骤、自下而上与自上而下的数据仓库开发方法,到决策支持工具的选择与使用。文章还分析了BI系统与互联网、内联网和外联网的结合方式,并讨论了购买与自建方案的优劣比较,最后总结了商业智能成功的关键因素及其对保险行业带来的商业价值。通过实际案例与未来趋势展望,展示了商业智能如何推动保险企业的数字化转型和竞争力提升。

moon9的博客 96

Ceph入门到精通-更换osd、扩容osd

【代码】Ceph入门到精通-更换osd、扩容osd。

隔壁老瓦的专栏 1547

深度学习工具包 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新版免狗免安祖昂绿色软件。,新界面,新视觉,

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

上一篇: LeetCode动态规划归纳
下一篇: 算法与设计分析作业3(贪心)
King来写代码
博客等级 码龄12年 68粉丝 30原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值