Skip to content

Commit d4d8c47

Browse files
authored
Update 1066.Campus-Bikes-II.cpp
1 parent c395d6f commit d4d8c47

File tree

1 file changed

+32
-30
lines changed

1 file changed

+32
-30
lines changed
Lines changed: 32 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,46 @@
1+
typedef pair<int,int> PII;
2+
13
class Solution {
4+
int dist[10][10];
5+
int visited[1024];
26
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-
137
int assignBikes(vector<vector<int>>& workers, vector<vector<int>>& bikes)
148
{
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+
}
1720

18-
set<vector<int>>visited;
21+
priority_queue<PII, vector<PII>, greater<>>pq;
22+
pq.push({0, 0});
1923

20-
while (true)
24+
while (!pq.empty())
2125
{
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;
3331

32+
int i = __builtin_popcount(state);
33+
if (i==m) return cost;
34+
3435
for (int j=0; j<bikes.size(); j++)
3536
{
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+
}
4042
}
41-
43+
4244
return 0;
4345
}
4446
};

0 commit comments

Comments
 (0)