857. 雇佣 K 名工人的最低成本
代码实现(自解)
class Solution {
public:
double mincostToHireWorkers(vector<int>& quality, vector<int>& wage, int k) {
int n = quality.size();
vector<int> h(n, 0);
iota(h.begin(), h.end(), 0);
sort(h.begin(), h.end(), [&](int& a, int& b) {
return quality[a] * wage[b] > quality[b] * wage[a];
});
double res = 1e9;
double totalq = 0.0;
priority_queue<int, vector<int>, less<int>> q;
for (int i = 0; i < k - 1; i++) {
totalq += quality[h[i]];
q.push(quality[h[i]]);
}
for (int i = k - 1; i < n; i++) {
int idx = h[i];
totalq += quality[idx];
q.push(quality[idx]);
double totalc = ((double) wage[idx] / quality[idx]) * totalq;
res = min(res, totalc);
totalq -= q.top();
q.pop();
}
return res;
}
};
1376. 通知所有员工所需的时间
代码实现(自解)
class Solution {
public:
int numOfMinutes(int n, int headID, vector<int>& manager, vector<int>& informTime) {
map<int, vector<int>> myMap;
int ans = 0;
for (int i = 0; i < n; i++) {
if (i == headID) continue;
myMap[manager[i]].push_back(i);
}
queue<pair<int, int>> myQueue;
myQueue.push({headID, 0});
while (!myQueue.empty()) {
const auto [ID, time] = myQueue.front();
myQueue.pop();
const auto& arr = myMap[ID];
for (const auto& id : arr) {
myQueue.push({id, time + informTime[ID]});
ans = max(ans, time + informTime[ID]);
}
}
return ans;
}
};
802. 找到最终的安全状态
代码实现(自解)
class Solution {
public:
vector<int> eventualSafeNodes(vector<vector<int>>& graph) {
map<int, vector<int>> father;
vector<int> deleteNum(graph.size());
vector<int> ans;
queue<int> myQueue;
for (int i = 0; i < graph.size(); i++) {
auto arr = graph[i];
if (graph[i].empty()) {
ans.push_back(i);
myQueue.push(i);
continue;
}
for (auto j : arr) {
father[j].push_back(i);
}
}
while (!myQueue.empty()) {
int node = myQueue.front();
myQueue.pop();
auto fa = father[node];
for (auto f : fa) {
deleteNum[f]++;
if (deleteNum[f] == graph[f].size()) {
ans.push_back(f);
myQueue.push(f);
}
}
}
sort(ans.begin(), ans.end());
return ans;
}
};