Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
campus-bikes.cpp 1.41 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2019-06-03 02:09 +08:00 . Update campus-bikes.cpp
// Time: O((w * b) * log(w * b))
// Space: O(w * b)
class Solution {
public:
vector<int> assignBikes(vector<vector<int>>& workers, vector<vector<int>>& bikes) {
using P = vector<int>;
vector<vector<P>> distances(workers.size());
for (int i = 0; i < workers.size(); ++i) {
for (int j = 0; j < bikes.size(); ++j) {
distances[i].push_back({manhattan(workers[i], bikes[j]), i, j});
}
sort(distances[i].begin(), distances[i].end(), greater<P>());
}
vector<int> result(workers.size());
unordered_set<int> lookup;
priority_queue<P, vector<P>, greater<P>> min_heap;
for (int i = 0; i < workers.size(); ++i) {
min_heap.emplace(distances[i].back());
distances[i].pop_back();
}
while (lookup.size() < workers.size()) {
const auto worker = min_heap.top()[1];
const auto bike = min_heap.top()[2];
min_heap.pop();
if (!lookup.count(bike)) {
result[worker] = bike;
lookup.emplace(bike);
} else {
min_heap.emplace(distances[worker].back());
distances[worker].pop_back();
}
}
return result;
}
private:
int manhattan(const vector<int>& p1, const vector<int>& p2) {
return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1]);
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助