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;
}
};
这篇博客讨论了一种算法问题,即如何通过排序任务来最小化预期的行动结束时间。给定n个任务,每个任务有不同的执行时间和成功概率,目标是找到最佳的任务执行顺序,使得在所有任务完成或失败时,期望的结束时间最短。博客中提供了两种解决方案,都是基于比较任务的加权执行时间来排序任务。一种是使用结构体和比较运算符,另一种是使用自定义比较函数。这两种方法都能得到预期时间相同时的字典序最小的任务顺序。
3339

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



