直接根據最短distance greedy作。less
用了優先隊列,C++ less<type> 是大的先,因此咱們能夠重載<符號,把邏輯反過來。spa
class Solution { public: struct dist_pair{ int dist; int worker; int bike; bool operator<(const dist_pair &a) const { if (dist!=a.dist) return dist>a.dist; else if (worker!=a.worker) return worker>a.worker; return bike>a.bike; } }; vector<int> assignBikes(vector<vector<int>>& workers, vector<vector<int>>& bikes) { priority_queue<dist_pair> q; for (int i=0;i<workers.size();++i){ for (int j=0;j<bikes.size();++j){ int d = abs(workers[i][0] - bikes[j][0]) + abs(workers[i][1] - bikes[j][1]); q.push({d,i,j}); } } vector<int> assign(workers.size(),-1); vector<bool> visitedBike(bikes.size(),false); while (!q.empty()){ auto [d,i,j] = q.top(); q.pop(); if(assign[i]==-1 && visitedBike[j]==false){ visitedBike[j] = true; assign[i] = j; } } return assign; } };
第二種寫法不用結構體,節省了空間複雜度,可是每次cmp的時候都要計算dist,可是時間會翻倍。code
這裏採用了 lambda funtion,注意 priority_queue 裏 lambda 的寫法。blog
class Solution { public: vector<int> assignBikes(vector<vector<int>>& workers, vector<vector<int>>& bikes) { auto cmp=[&](const pair<int,int> &a, const pair<int,int> &b){ int dist_a=dist(a.first,a.second,workers,bikes); int dist_b=dist(b.first,b.second,workers,bikes); if (dist_a!=dist_b) return dist_a>dist_b; if (a.first!=b.first) return a.first>b.first; return a.second>b.second; }; priority_queue<pair<int,int>,vector<pair<int,int>>,decltype(cmp)> q(cmp); for (int i=0;i<workers.size();++i) for (int j=0;j<bikes.size();++j) q.push({i,j}); vector<int> assign(workers.size(),-1); vector<bool> visitedBike(bikes.size(),false); while (!q.empty()){ auto [i,j] = q.top(); q.pop(); if(assign[i]==-1 && visitedBike[j]==false){ visitedBike[j] = true; assign[i] = j; } } return assign; } int dist(int i, int j, vector<vector<int>>& workers, vector<vector<int>>& bikes){ return abs(workers[i][0]-bikes[j][0])+abs(workers[i][1]-bikes[j][1]); } };
時間複雜度:mnlog(mn),由於有mn對pair。隊列