|
| 1 | +typedef pair<int,int> PII; |
| 2 | + |
1 | 3 | class Solution { |
| 4 | + int dist[10][10]; |
| 5 | + int visited[1024]; |
2 | 6 | public: |
3 | | - int dis(vector<vector<int>>& workers, vector<vector<int>>& bikes, int i, int j) |
4 | | - { |
5 | | - int x1=workers[i][0]; |
6 | | - int y1=workers[i][1]; |
7 | | - int x2=bikes[j][0]; |
8 | | - int y2=bikes[j][1]; |
9 | | - return abs(x1-x2)+abs(y1-y2); |
10 | | - } |
11 | | - |
12 | | - |
13 | 7 | int assignBikes(vector<vector<int>>& workers, vector<vector<int>>& bikes) |
14 | 8 | { |
15 | | - set<vector<int>>Set; |
16 | | - Set.insert({0,0,0}); |
| 9 | + int m = workers.size(); |
| 10 | + int n = bikes.size(); |
| 11 | + for (int i=0; i<m; i++) |
| 12 | + for (int j=0; j<n; j++) |
| 13 | + { |
| 14 | + int x1=workers[i][0]; |
| 15 | + int y1=workers[i][1]; |
| 16 | + int x2=bikes[j][0]; |
| 17 | + int y2=bikes[j][1]; |
| 18 | + dist[i][j] = abs(x1-x2)+abs(y1-y2); |
| 19 | + } |
17 | 20 |
|
18 | | - set<vector<int>>visited; |
| 21 | + priority_queue<PII, vector<PII>, greater<>>pq; |
| 22 | + pq.push({0, 0}); |
19 | 23 |
|
20 | | - while (true) |
| 24 | + while (!pq.empty()) |
21 | 25 | { |
22 | | - int cost = (*Set.begin())[0]; |
23 | | - int i = (*Set.begin())[1]; |
24 | | - int taken = (*Set.begin())[2]; |
25 | | - Set.erase(Set.begin()); |
26 | | - |
27 | | - if (i==workers.size()) |
28 | | - return cost; |
29 | | - |
30 | | - if (visited.find({i,taken})!=visited.end()) |
31 | | - continue; |
32 | | - visited.insert({i,taken}); |
| 26 | + auto [cost, state] = pq.top(); |
| 27 | + pq.pop(); |
| 28 | + |
| 29 | + if (visited[state]) continue; |
| 30 | + visited[state] = 1; |
33 | 31 |
|
| 32 | + int i = __builtin_popcount(state); |
| 33 | + if (i==m) return cost; |
| 34 | + |
34 | 35 | for (int j=0; j<bikes.size(); j++) |
35 | 36 | { |
36 | | - if ((taken&(1<<j)) !=0) |
37 | | - continue; |
38 | | - Set.insert({cost+dis(workers, bikes, i,j), i+1, taken+(1<<j)}); |
39 | | - } |
| 37 | + if ((state>>j)&1) continue; |
| 38 | + int newState = state+(1<<j); |
| 39 | + if (visited[newState]) continue; |
| 40 | + pq.push({cost+dist[i][j], newState}); |
| 41 | + } |
40 | 42 | } |
41 | | - |
| 43 | + |
42 | 44 | return 0; |
43 | 45 | } |
44 | 46 | }; |
0 commit comments