Lintcode 1465:Order Of Tasks 贪婪算法

三星研究院上机题(Order of task) Thereare V tasks to do. Some task(s) can begin only after a particular task ends,which we will call precedence relation. A graph indicating precedence relationof tasks is given. In this graph, each ta... 阅读详情

1465 · Order Of Tasks

Algorithms

Medium

Description

Solution

Notes

Discuss

Leaderboard

Description

There are n different tasks, the execution time of tasks are t[], and the probability of success are p[]. When a task is completed or all tasks fail, the operation ends. Tasks are performed in a different order, and it is expected that the time to stop the action is generally different. Please find out the order in which the tasks are performed to minimize the expected end time of actions. If the expected end time of the two task sequences is the same, the lexicographic minimum order of tasks is returned.

  • 1≤n≤50,1≤ti​≤10,0≤pi​≤1
  • n is a positive integer, ti​ is a positive integer, pi​ is a floating-point number

Example

Example 1:


Input:n=1,t=[1],p=[1.0]
Output:1
Explanation:
The shortest expected action end time is 1.0*1+(1.0-1.0)*1=1.0

Example 2:

Input:n=2,t=[1,2],p=[0.3, 0.7]
Output:[2,1]
Explanation:
The shortest expected action end time is 0.7*2+(1.0-0.7)*0.3*(2+1

 解法1:贪婪法。因为我们要尽量把p越大,t越小的item摆到前面。
 

struct Node {
    int id, t;
    double p;
    Node(int index = 0, int time = 0, double prob = 0) : id(index), t(time), p(prob) {}
    bool operator < (const Node & n) {
        if (abs(p * n.t - n.p * t) < 1e-5) return id < n.id;
        return p * n.t > n.p * t;
    }
};

class Solution {
public:
    /**
     * @param n: The number of tasks
     * @param t: The time array t
     * @param p: The probability array p
     * @return: Return the order
     */
    vector<int> getOrder(int n, vector<int> &t, vector<double> &p) {
        vector<int> res;
        vector<Node> nodes(n);
        for (int i = 0; i < n; ++i) {
           nodes[i] = Node(i, t[i], p[i]);
        }
        sort(nodes.begin(), nodes.end());
        for (int i = 0; i < n; ++i) {
            res.push_back(nodes[i].id + 1);
        }
        return res;
    }
};

另一种写法如下:
 

struct Node {
    int id, t;
    double p;
    Node(int index = 0, int time = 0, double prob = 0) : id(index), t(time), p(prob) {}
};

struct compare {
    bool operator() (const Node & a, const Node & b) {
        if (abs(a.p * b.t - b.p * a.t) < 1e-5) return a.id < b.id;
        return a.p * b.t > b.p * a.t;
    }
} cmp;

class Solution {
public:
    /**
     * @param n: The number of tasks
     * @param t: The time array t
     * @param p: The probability array p
     * @return: Return the order
     */
    vector<int> getOrder(int n, vector<int> &t, vector<double> &p) {
        vector<int> res;
        vector<Node> nodes(n);
        for (int i = 0; i < n; ++i) {
           nodes[i] = Node(i, t[i], p[i]);
        }
        sort(nodes.begin(), nodes.end(), cmp);
        for (int i = 0; i < n; ++i) {
            res.push_back(nodes[i].id + 1);
        }
        return res;
    }
};

从原理到代码:拆解UniFormer中动态位置嵌入(DPE)的3D卷积实现 本文深入解析了UniFormer模型中动态位置嵌入(DPE)模块的3D卷积实现原理与代码。DPE通过一个轻量的3D深度可分离卷积,替代传统静态位置编码,使模型能自动学习视频数据的时空位置关系。文章对比了其与Swin Transformer相对位置偏置的优劣,并提供了PyTorch实现代码与高级定制方案,为视频理解任务提供了高效灵活的动态位置编码解决方案。 阅读详情

相关推荐

KEGG数据库与KAAS工具:基因功能注释的实用指南

本文提供了使用KEGG数据库与KAAS工具进行基因功能注释的完整实用指南。详细阐述了如何从准备基因或蛋白序列开始,通过KAAS服务器获取KEGG Orthology(KO)编号,并解读注释结果。文章进一步介绍了如何利用KOBAS工具进行通路富集分析,将定性观察转化为定量洞察,并分享了提高注释准确率、处理大数据集及使用API等避坑技巧与高阶方法,为基因组学、转录组学研究者奠定坚实的数据分析基础。

weixin_29292535的博客 390

Ordering Tasks---点任务(拓扑)

https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1246 John has n tasks to do. Unfortunately, the tasks are not independent and the executi...

嵩韵儿 357

别再死记硬背Payload了!深入理解Flask/Jinja2 SSTI的Python对象继承链与魔术方法

本文深入解析Flask/Jinja2 SSTI漏洞的底层原理,从Python对象模型出发,详细讲解如何通过魔术方法链实现RCE。文章揭示了Python对象继承链与魔术方法的精妙设计,提供了防御与绕过SSTI漏洞的实用技巧,帮助开发者深入理解漏洞本质并采取有效防护措施。

weixin_42525738的博客 356

Ordering Tasks

UVA - 10305  题目: John has n tasks to do. Unfortunately, the tasks are not independent and the execution of one task is only possible if other tasks have already been executed. Input The input wil...

qq_42759455的博客 273

Xilinx PL端DP显示接口开发实战(一)——环境搭建与硬件选型

本文详细介绍了Xilinx PL端DP显示接口开发的环境搭建与硬件选型实战经验。从Vivado和Vitis 2021.1版本的软件安装要点,到DP141和MCDP6000芯片的选型建议,再到DP1.4接口的RX/TX方向开发关键点,为开发者提供了全面的技术指导。文章还分享了IP核配置、BD原理图设计以及常见问题排查的实用技巧,帮助开发者高效完成Xilinx DP接口开发项目。

weixin_29250573的博客 174

调用D3D11硬解码和渲染VideoProcessor版本

在https://blog.youkuaiyun.com/robothn/article/details/78781321一文中使用shader来显示FFMPEG硬解码后的YUV420P,本文调用D3D11的videoprocessor来进行图像空间变换和尺寸变换,取得了较好的效果。 1.初始化D3D11设备、videodevice等数据结构 FFMPEG调用D3D11硬解码,获取其对应的device,videodevice。。。 FFMPEG使用av_hwdevice_find_type_by_name调用D3d11

zlyadvocate的博客 9285

Sicily: ordering task(算法逐层优化)

Description John has n tasks to do. Unfortunately, the tasks are not independent and the execution of one task is only possible if other tasks have already been executed. Input There are mu

linwh8的博客 630

【AI黑话日日新】什么是对比学习?

模型效果高度依赖大规模、高质量的人工标注数据。数据标注不仅成本高昂、周期漫长,在医疗、工业、小众垂类等场景中,甚至难以获取足量的标注样本,严重限制了模型的泛化能力与应用边界。自监督学习的出现,为解决这一问题提供了全新思路——无需人工标注标签,而是利用数据自身的结构与内在关联,构建自生成的监督信号完成模型预训练,再通过微调适配下游任务。在众多自监督学习方法中,对比学习(Contrastive Learning)

专注:太空算力、AI infra、异构调度、大模型成本工程 730

A Count Task

A Count Task Count is one of WNJXYK’s favorite tasks. Recently, he had a very long string and he wondered that how many substrings which contains exactly one kind of lowercase in this long string. B...

u013345179的博客 796

人工智能大语言模型微调技术:SFT 监督微调、LoRA 微调方法、P-tuning v2 微调方法、Freeze 监督微调方法

人工智能大语言模型微调技术:SFT 监督微调、LoRA 微调方法、P-tuning v2 微调方法、Freeze 监督微调方法

丨汀、的博客 4万+

WPS访问权限不足怎么解决??具体怎么操作?

🏆本文收录于 《全栈 Bug 调优(实战版)》 专栏。专栏聚焦真实项目中的各类疑难 Bug,从成因剖析 → 排查路径 → 解决方案 → 预防优化全链路拆解,形成一套可复用、可沉淀的实战知识体系。无论你是初入职场的开发者,还是负责复杂项目的资深工程师,都可以在这里构建一套属于自己的「问题诊断与性能调优」方法论,助你稳步进阶、放大技术价值。

**My Coding Family** 4171

Ordering Tasks From:UVA, 10305(拓扑排序)

题目大意: 用N份工作,M组关系,例如关系A,B表示要先完成B,才能完成A,让你输出一组工作完成的顺序。 解题思路: 拓扑排序。

Menglei Min 990

使用OpenCV从低对比度图像中提取圆形轮廓

希望本文能帮助您从低对比度图像中提取圆形轮在本文中,我们将探讨如何使用OpenCV库从低对比度图像中提取圆形轮廓。低对比度图像通常指的是图像中的亮度差异很小,导致物体边缘不够清晰的情况。在本文中,我们将探讨如何使用OpenCV库从低对比度图像中提取圆形轮廓。低对比度图像通常指的是图像中的亮度差异很小,导致物体边缘不够清晰的情况。通过预处理图像并应用Hough变换,我们能够在低对比度图像中准确地提取圆形轮廓。通过预处理图像并应用Hough变换,我们能够在低对比度图像中准确地提取圆形轮廓。

ByteWhiz的博客 350

UVaOJ10305---Ordering Tasks

10305 - Ordering Tasks Time limit: 3.000 seconds   John has n tasks to do. Unfortunately, the tasks are not independent and the execution of one task is only possible if other tasks have already

c随遇er安的专栏 583

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

uva 10305 Ordering Tasks(拓扑排序)

Ordering Tasks Input: standard input Output: standard output Time Limit: 1 second Memory Limit: 32 MB   John has n tasks to do. Unfortunately, the tasks are not independent and the execution of

不慌不忙、不急不躁 3244

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

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

视频隐私脱敏工程化:CSRT/KCF追踪算法在本地推理中的实现与边界

在短视频内容合规审查中,动态遮挡(Dynamic Masking)是高频且高耗时的环节。传统手动关键帧打码不仅效率低下,且在目标快速移动或遮挡时极易出现遮罩漂移。本文从计算机视觉工程角度,解析基于CSRT与KCF算法的目标追踪方案在视频隐私处理中的技术路径、性能权衡及落地实践。

Mysssone的博客 233

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

【算法拾光】链表 哈希表|K个一组翻转链表 + 两数之和

K个一组翻转链表需分段反转,借助哑节点与前驱指针维护连接,避免断链;两数之和利用哈希表实现O(1)查找,空间换时间,高效定位目标组合。前者考察链表指针操作,后者聚焦映射关系构建,均为面试高频题。

wuqingyigexiaoba的博客 318

把 KV Cache 压到 FP4:BitDecoding-FP4 的算法-系统协同设计复盘

长上下文推理卡在KV Cache的显存与带宽上,而现有FP4方案要么精度崩、要么速度废。这篇文章复盘BitDecoding-FP4如何用三个算法补丁加一个系统重构,在B300上把服务吞吐提升2.4–3.0倍,精度几乎不掉。

helloagent的博客 191

排序算法深度笔记(下):非比较类排序的线性突破与工程边界

排序算法时间复杂度额外空间复杂度稳定性是否基于比较选择排序O(N^2)(O(1))不稳定是冒泡排序O(N^2)(O(1))稳定是插入排序O(N^2)(O(1))稳定是归并排序O(N\log N)(O(N))稳定是快速排序O(N\log N)O(log N)不稳定是堆排序O(N\log N)O(1)不稳定是计数排序(O(N + M))O(M))稳定否基数排序O(N)稳定否桶排序平均O(N) / 最坏O(N^2)

2401_87069538的博客 594

优选算法:分治-归并排序

交易逆序对的总数

Wangshijie1015的博客 122

算法日常・每日刷题--<动态规划>42

本题为“不相交的线”,与最长公共子序列问题相似。使用动态规划求解:定义 dp[i][j] 表示 nums1[0:i] 与 nums2[0:j] 的最大不相交连线数。若元素相等,则继承左上值加1;否则取上方或左方最大值。最终返回 dp[m][n],即两数组的最大不相交连线数。时间复杂度 O(mn),空间复杂度 O(mn)。

2503_92261635的博客 22

408 算法 06|堆与 Top-K:最小的 10 个数,到底该用数组还是堆

2022(42) 找 100 万个数里最小的 10 个,官方给了"10 元素有序数组"和"大根堆"两种答案。我把两种都实现并数了比较次数:k=10 时两者几乎打平,k=10000 时堆少 111 倍。另附 2021(42) 计数排序的比较次数与稳定性实测。

m0_56226131的博客 353

C语言程序设计题|有序数组插入数字冒泡排序

题目要求将一个数插入有序数组末尾,并用冒泡排序实现整体升序。代码先将输入数存入数组最后位置,再通过双重循环进行冒泡排序,每轮将较大元素向后移动,最终输出11个升序元素。该方法虽时间复杂度为O(n²),但符合题目要求,逻辑清晰,适合初学者理解排序原理。

2301_81429079的博客 750

408 算法 04|主元素与三元组最小距离:两种“扫描时做决定“的思路

2013(41) 的主元素用摩尔投票一遍选出候选,但真正的考点是"选完必须验票";2020(41) 的三元组最小距离,三指针每次只挪最小的那个,靠的是 D=2×(max−min) 这个恒等式。两套完整 C 代码加真实输出,附官方评分档位表。

m0_56226131的博客 414

牛客周赛165C题(前后缀性质,递推,排序,枚举)

题目大意:给定长度为 `n` 的数组,选择 `k ∈ [1,n]`,将前 `k` 个元素整体翻转,后面的元素不变。要求操作后的整个数组非递减,统计满足条件的 `k` 的数量。题目链接:https://ac.nowcoder.com/acm/contest/141721/C。时间复杂度:O(nlogn)

2501_94316951的博客 172

【数据结构-3】算法美学之降复杂度

在while循环的循环体内,首先用临时变量保存最后一个位置的数据,再通过for循环把所有元素往后移动一位,最后把tmp中保存的值放到下标为0的位置上去。方法二的思路是:创建新数组,让原数组中后k个数据移动到新数组中前面的位置,让原数组中前numsSize-k个数据移动到新数组中后面的位置,这。这段代码的思路是:三次逆置,第一次逆置前numsSize-k个数据,第二次逆置后k个数据,最后整体逆置。这篇博文分享一道解法不一的算法题,求解过程的目的在于降低算法的时间复杂度,题源力扣。,属于空间换时间的操作。

weixin_44218929的博客 89
上一篇: LintCode 1573: Legal String
下一篇: LintCode 1464:The K-th Combination (subset变种)
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值