@@ -18,24 +18,16 @@ struct state
18
18
{
19
19
int pos;
20
20
int cost;
21
- vi tickets;
22
- state (int p = 0 , int c = 0 , vi t = vector<int >(10 , 0 )){
23
- pos = p;
24
- cost = c;
25
- tickets = t;
26
- }
21
+ int tickets;
22
+ int nt;
23
+ state (int p, int c, int t, int n) : pos(p), cost(c), tickets(t), nt(n) {}
27
24
};
28
25
bool operator <(state a, state b){
29
26
return a.cost > b.cost ;
30
27
}
31
28
int num = 0 ;
32
29
class IslandFerries {
33
- int dfs (int s, vvi &M, vi &vis){
34
- num++;
35
- vis[s] = true ;
36
- for (int j = 0 ; j < 50 ; j++)
37
- if (!vis[j] && M[s][j] > 0 ) dfs (j, M, vis);
38
- }
30
+
39
31
public:
40
32
vector <int > costs (vector <string> legs, vector <string> prices) {
41
33
num = 0 ;
@@ -57,54 +49,38 @@ class IslandFerries{
57
49
}
58
50
59
51
vi vis (50 , 0 );
60
- dfs (0 , M, vis);
61
- cout<<" num = " <<num<<endl;
52
+ // cout<<"num = "<<num<<endl;
62
53
priority_queue<state> Q;
63
- state s;
64
- Q.push (s);
54
+ Q.push (state (0 , 0 , 0 , 0 ));
65
55
vi done (50 , -1 );
66
- int count = 0 ;
67
- set<pair<int , vi> > visited;
56
+ map<pi , int > best;
68
57
69
58
while (!Q.empty ()){
70
59
state p = Q.top ();
71
60
Q.pop ();
72
- int pos = p.pos , cost = p.cost ;
73
- vi tickets = p.tickets ;
61
+ int pos = p.pos , cost = p.cost , tickets = p.tickets , nt = p.nt ;
62
+ // cout<<pos<<" "<<cost<<" "<<tickets<<" "<<tickets<<endl;
63
+ pi t = make_pair (pos, tickets);
74
64
75
- if (visited. find ( make_pair (pos, tickets)) != visited. end () ) continue ;
76
- visited. insert ( make_pair (pos, tickets)) ;
65
+ if (best. count (t) != 0 && best[t] <= cost ) continue ;
66
+ best[t] = cost ;
77
67
78
- if (done[pos] == -1 ){
79
- done[pos] = cost;
80
- count++;
81
- if (count == num) break ;
82
- }
83
- int nt = 0 ;
84
- for (int t : tickets) if (t > 0 ) nt++;
68
+ if (done[pos] == -1 ) done[pos] = cost;
85
69
// buy more tickets if it is possible
86
- if (nt < 3 ){
70
+ if (nt < 3 )
87
71
for (int i = 0 ; i < m; i++)
88
- if (tickets[i] == 0 ){
89
- tickets[i] = P[pos][i];
90
- Q.push (state (pos, cost+P[pos][i], tickets));
91
- tickets[i] = 0 ;
92
- }
93
- }
72
+ if (!(tickets & (1 <<i)))
73
+ Q.push (state (pos, cost+P[pos][i], tickets|(1 <<i), nt+1 ));
94
74
95
75
// Go to some other island utilising any one of the tickets in kitty
96
76
for (int i = 0 ; i < m; i++)
97
- if (tickets[i] > 0 ){
77
+ if (tickets & ( 1 <<i) ){
98
78
// visit all islands to check if ferry i can help to go from pos to j
99
79
for (int j = 0 ; j < n; j++)
100
- if (M[pos][j] & (1 <<i)){
101
- int t = tickets[i];
102
- tickets[i] = 0 ;
103
- Q.push (state (j, cost, tickets));
104
- tickets[i] = t;
105
- }
80
+ if (M[pos][j] & (1 <<i))
81
+ Q.push (state (j, cost, tickets^(1 <<i), nt-1 ));
106
82
}
107
- }
83
+ }
108
84
return vi (done.begin ()+1 , done.begin ()+n);
109
85
}
110
86
0 commit comments