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;
}
};