Java Python CS 336: Algorithms Problem Set 5 Date: Thursday, October 31, 2024 Due: Thursday, November 7, 2024
Submit your solution on Gradescope.
Please, solve all problems on your own. Do not collaborate with other students.
Problem 1. The page limit for Problem 1 is 2 pages.
Similarly to HW2, you want to travel from city A to city B located on a straight line (A is
located in position 0 and B is located in position M ≥ 0), and you can travel at most distance D ≥ 0 miles per day, and you can only move to the right. Similarly, you have hotels between A and B with locations a1, . . . , an, where you can stay for a night.
You are a person who likes to optimize all aspects of your life. In particular, if you didn’t fully use all D miles per day, it causes you great distress. Namely, if on some day you traveled distance d miles (out of possible D miles), the amount of distress is 2D−d.
You start at city A. Your goal is to reach city B while suffering the least total amount of distress. Example: Assume that D = 4 and city B is located in position 6. You have two hotels in locations
2 and 3. The following routes have the following distress:
• 0→2→6: 24−(2−0) +24−(6−2) =4+1=5
• 0→2→3→6: 24−(2−0) +24−(3−2) +24−(6−3) =4+8+2=14 • 0→2→6: 24−(3−0) +24−(6−3) =2+2=4
The last route is optimal.
Please do the following:
• Formulate the subproblem. Please state it as precisely as possible. • Design a dynamic programming algorithm for solving this problem:
– State the base case.
– State the recurrence relation.
– Explain why the recurrence relation is correct (from your explanation, one should un- derstand how to get your the recurrence relation).
– Please provide the pseudocode. Please use the bottom-up approach.
– Explain:
∗ What is the running time of your algorithm (all arithmetic operations take constant time).
∗ How to recover the maximum reward.
∗ How to recover the optimal route. You don’t need to write a ps CS 336、 java/c++ eudocode.
∗ How your algorithm correctly handles the case when an optimal solution doesn’t
exist.
1
Problem 2. There is a new series in your streaming platform, Panopto. The series contains n episodes in total. Episodes need to be watched in order; that is, you cannot watch episode j before episode i if i < j. Since you’re busy, you decide to skip some subset of episodes (potentially empty). Your goal is to minimize the total amount of energy needed for this series, computed as follows:
• You figure out that if you skip episode i, you would have to spend pi energy at the end of the year to figure out the missed content.
• In addition, each episode has excitement value ei. You don’t want to dramatically change your emotions as well. So, for any consecutive episode i and j you watch, you need to spend |ei − ej | energy to adjust your mood as well.
For example, if there are 5 episodes:
• If you decide to watch episodes 1, 3, and 4, you need to spend p2 +p5 +|e1 −e3|+|e3 −e4| units of energy.
• If you only decide to watch episode 3, you need to spend p1 + p2 + p4 + p5 units of energy.
• If you decide to watch none of the episodes, you need to spend p1 +p2 +p3 +p4 +p5 units of
energy.
Implement the following function, which returns the list of episodes you decided to watch in the sorted order (the episodes are 1-indexed). For example, if you decide to watch first, third, and fourth episodes, your function must return a vector with items 1,3,4, in exactly this order. The input arrays are e and p respectively. It is guaranteed that for all test cases, the optimal answer is unique.
vector Episodes(const vector& excitement, const vector& penalty)
Time limit The instructions are similar to the previous programming assignments. Your program should pass each tests in no more than 1 second. You can assume that 1 ≤ n ≤ 104 and all numbers are between 1 and 109
相关推荐
【信息科学与工程学】【运营科学】第二篇 C4信息与通信网络运营 (C4) ——数据中心网络运营06
13 | 司法诉讼 | 原告律师 | 争取和解优势 | 证据披露的序贯博弈 | 策略性证据释放 | 持有证据集E = {强证据e_s, 中证据e_m, 弱证据e_w}。设公众原有认知人格向量为 Pold=(p1,p2,...,pk), 其中p_i为负面特质(如“不敬业”)。危机后, 通过行为序列 {At}和宣传, 将公众认知向新向量 Pnew引导, 使得在关键维度上, Pnew与 Pold的余弦相似度降低, 并与一个正面的、可接受的“原型”(如“浪子回头”、“慈父”)对齐。
CS 336: Algorithms Problem
Explain:exist.1energy.
FPGA自动售货机工程详解:状态机、按键消抖与仿真调试
数字系统设计是电子工程与计算机领域的基石,而有限状态机则是其核心建模工具。在FPGA开发中,状态机通过离散状态与转移条件控制复杂时序逻辑,广泛应用于工业控制、通信协议和嵌入式交互场景。自动售货机作为经典教学案例,完整覆盖了状态机编码、时序控制、按键消抖、动态扫描显示及仿真验证等关键环节。掌握三段式Moore状态机写法,能有效隔离组合逻辑与时序逻辑,提升代码可维护性与综合稳定性。同时,基于计数器的按键消抖方案和BCD转换算法,真实反映了工程中应对机械抖动与数据通路的实践技巧。从仿真testbench到板级调试
斯坦福CS336个人学习笔记(一)
作业中是使用的GPT2的BPE方法,先处理特殊token,正则分词,编码后对高频字节进行合并,得到字典。actual_num_flops = 2 * B * D * K (因为有 B×K 个输出,每个做 D 次乘法加法)x: (B, D) # 输入,B 是 batch size 或 token 数,D 是维度。参数和梯度使用的浮点格式,一般用 float32,也会用 bf16 和 float16。所有字符按照UTF-8进行编码,每个字符对应一个字节,即一个token。
ESP32使用microPython控制240x240彩色屏幕显示中文
王铭东老师详细讲解了讲了关于240x240屏幕的一些基础东西,我这里在原功能的基础上拓展了中文显示的功能,顺带修改了实际操作过程中程序中遇到的一些问题。
人工势场法三大致命缺陷?我用ROS+Gazebo做了组对比实验
本文通过ROS与Gazebo仿真实验,深入剖析了人工势场法(APF)在机器人路径规划中的三大经典问题:局部最小值、目标不可达和路径震荡。文章不仅复现了这些缺陷,还对比测试了虚拟目标点法、改进斥力场及运动平滑等主流改进方案,为工程选型提供了基于数据的实用建议。
【2025/07/10】GitHub 今日热门项目
今日GitHub热门项目概览(2025-07-10): 📌 精选16个项目,总星标数达248.8K,24小时内新增3.5K关注。AI/ML类项目占比68.8%,Python生态最活跃(37.5%)。 🔥 人气项目: 1️⃣ system-design-101(74.1K星标) - 系统设计面试指南 2️⃣ genai-toolbox(+1K星) - Google开源的多云平台数据库工具 3️⃣ WebAgent(+468星) - 阿里实验室开发的网页智能体框架
【医学影像】超声(UltraSound)影像的增强与目标检测
文章目录1 综述1.1 超声发展简史1.2 超声类型2 超声影像的去噪与增强2.1 各向异性扩散去噪模型2.2 色彩恢复的视网膜增强算法SSR和MSR2.3 MSRCR增强算法(基于MSR算法改进版)2.4 参考文献3 超声影像的目标识别3.1 基于跨模态数据迁移进行DL训练3.2 参考文献 1 综述 因工作需要,最近调研了超声(UltraSound)影像的相关知识,包含超声类型、超声影像的去噪和增强,目标检测等,并对相关资料文献进行梳理整合。 本人另外一篇博文主要讲了UltraSound 影像与CT/MR
C++主题年技巧积累#1——UltraEdit的代码美化
<iframe align="center" marginwidth="0" marginheight="0" src="http://www.zealware.com/csdnblog336280.html" frameborder="0" width="336" scrolling="no" height="280">
GPlates——【将化石点标记在古地理图上时,改变标记点的大小和形状】
GPlates在还原古地理图和计算古坐标点上功能十分卓越,最近在使用它标注某个类群的化石坐标点时,这些点在地图上显示得非常小,让人不易察觉。作为一款优秀的GUI应用,应该具备更改标记点外观的功能,然而在查阅了官方手册,pygplates API后,表明不管是桌面应用还是python接口,都无法简便地修改标记点的外观。在之前GPlates学习和最近的pygplates学习中,印象里有可以改变标记点外观的东西,叫做。当然,这又诱使我翻了一遍资料,然而又没有直接关于symbol的资料。
SV--对象拷贝、参数化的类
对象拷贝,参数化的类
计算机文本处理:编码基础与中文分词技术详解
字符编码是计算机存储和处理文本的基础技术,从ASCII到Unicode再到UTF-8,编码标准不断演进以满足多语言需求。在文本处理流程中,编码一致性直接影响数据质量,而中文分词作为自然语言处理的第一步,其准确性对后续语义分析至关重要。当前主流分词技术包括基于词典、统计和深度学习的方法,各有其适用场景。在实际工程中,编码检测与转换、分词算法选择以及性能优化都是构建高效文本处理系统的关键环节。特别是在电商评论分析、舆情监控等应用场景中,合理的编码处理和精准的分词技术能显著提升系统表现。
手把手学计科--web网页设计
网页的组成:文字、图像和超链接等元素。还可以包括哦音频、视频和动画。分类:静态(固定信息)和动态(与服务器数据库进行实时的数据交换。HTML和CSS 是一种静态网页搭建技术。
计算机电子书 2018 BiliDrive 备份
下载方式 根据你的操作系统下载不同的 BiliDrive 二进制。 执行: bilidrive download <link> 链接 文档 链接 Webpack 中文指南.epub (409.01 KB) bdrive://ce58b7b58292296a61a97de1f89c62b66da24ab6 OpenIntro Statistics 3e.pdf (...
GEE案例教程:融合Sentinel-1 SAR数据、Sentinel-2光学影像和WorldPop人口数据,构建完整的洪水监测与影响评估工作流
本文介绍了一个专为巴基斯坦哈扎拉分区设计的洪水监测系统,该系统整合了Sentinel-1 SAR数据、Sentinel-2光学影像和WorldPop人口数据等多源遥感数据。系统通过VV极化SAR数据的水体提取算法(阈值-13dB)实现洪水范围监测,结合10米分辨率的光学影像进行可视化验证,并利用100米分辨率人口数据评估受灾人口。系统提供完整的技术实现,包括研究区加载、遥感数据处理、日期选择界面和洪水变化检测等功能模块,为灾害应急响应提供科学依据。
【即插即用模块】卷积篇 | TGRS 2025 | HLKConv:小核+空洞=大核,感受野一致,但更轻更准!
本文介绍了分层大核卷积模块HLKConv,该模块通过动态大核+空洞卷积实现高效感受野扩展,将超大核卷积分解为小核+空洞卷积(如53×53核用17×17+dilation=3实现),计算量仅为普通大核的1/10。模块采用双分支设计:基础卷积分支捕捉局部细节,大核空洞分支捕捉长距离关联,通过1×1卷积融合。实验表明HLKConv在红外小目标检测中优于传统大核卷积,适用于高分辨率视觉任务。代码实现了不同核尺寸的配置,输入输出特征维度保持不变,计算效率显著提升。
自建简单计算机CPU——软硬兼施
教材的一个独特之处是它的广泛性。无论您对学生构建的SAP(simple as possible)简单微处理器、6502、6800/6808、8080/8085/Z80、8086/8088感兴趣,这本教科书都能满足您的需求。关于微处理器的教科书有时很难理解。《Digital Computer Electronics (1993)》以易于理解和有趣的方式介绍微处理器的各个方面。使用这本教科书的唯一先决条件是了解二极管和晶体管。
WINCC7.3破解文件
WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!
Unity Android log view(Android Debug Bridge)
Android Debug Bridge
Devexpress16.2.6破解工具
Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具
精雕软件(JDpaint) 5.5 绿色版
精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版
Android Google XTS
GMS全称为Google Mobile Service,即谷歌移动服务。GMS是Google开发并推动Android的动力,是Google提供的Mobile Device上的一系列应用服务。
深度学习工具包 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');```[](https://bitdeli.com/free "Bitdeli Badge")
深挖C++:类和对象(中)
(先进后出)
跟我学c++中级篇—类型定义的方式
本文系统阐述了编程中类型定义的重要性及c++中的实现方式。重点对比了宏定义、typedef与modern using三种机制,指出using在可读性、灵活性和模板支持上的优势,推荐优先使用。同时提醒开发者注意别名滥用、类型歧义、错误信息冗长等问题,强调统一规范与合理设计。最终结论:在现代c++开发中,应以using为主,兼顾简洁性与可维护性,避免陷入命名混乱与编译困境。
【C/C++ 第一次跨越(下):移动语义与 noexcept——不改变行为的性能修复】
本文详解C++11移动语义在迁移至现代C++时的性能优化策略,强调“不改变行为”的前提下通过合理使用移动语义消除深拷贝开销。重点解析移动操作生成规则:析构函数、拷贝函数或const/引用成员会抑制移动构造;noexcept影响std::vector是否选择移动而非回退拷贝。提出“Rule of Zero”原则——用RAII封装资源,避免手动实现特殊成员函数,确保移动语义被正确调用,实现零开销移动与内存安全。
【C++】C++17的主要特性
C++17引入多项重要特性:结构化绑定简化多值返回与遍历;inline变量解决头文件中变量定义的ODR问题,支持类内初始化;if/switch初始化语句允许在条件中声明变量,提升代码简洁性;属性语法(如[[nodiscard]]、[[deprecated]])增强代码可读性与安全性;求值顺序明确化,提高程序可预测性。这些改进显著提升了代码的简洁性、安全性和可维护性。
【C++碎片化知识补充】C++ 里 int 也算对象?聊聊对象和变量的边界
盯着sessionId不就是个变量吗?变量凭什么能调用函数?后来才反应过来——它当然是对象。是我把对象这个词理解窄了。
【C++ 基础入门】C++11新特性(下):可变参数模板、lambda 表达式与包装器
C++11高阶特性(可变参数模板与参数包展开、emplace_back、lambda表达式与捕获列表、仿函数、std::function包装器)
1489



被折叠的 条评论
为什么被折叠?



