-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2477. Minimum Fuel Cost to Report to the Capital.cpp
63 lines (62 loc) · 1.82 KB
/
2477. Minimum Fuel Cost to Report to the Capital.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
class Solution {
public:
// self, bfs
long long minimumFuelCost1(vector<vector<int>>& roads, int seats) {
int n = roads.size()+1; // no of nodes
vector<int> inDegree(n,0);
vector<vector<int>> adj(n);
for(auto& r:roads){
adj[r[0]].push_back(r[1]);
adj[r[1]].push_back(r[0]);
inDegree[r[0]]++;
inDegree[r[1]]++;
}
vector<int> seat(n,1);
queue<int> leafs;
for(int i=1;i<n;++i){ // ignore capital
if(inDegree[i]==1)
leafs.push(i);
}
long long fuel=0;
while(leafs.size() ){
auto node = leafs.front();
leafs.pop();
++fuel;
fuel += (seat[node]-1)/seats;
for(auto nei:adj[node]){
inDegree[nei]--;
seat[nei]+= seat[node];
if(nei !=0 && inDegree[nei]==1){ // ignore capital
leafs.push(nei);
}
}
}
return fuel;
}
// dfs
typedef long long ll;
long long minimumFuelCost(vector<vector<int>>& roads, int seats) {
int n = roads.size()+1;
//vector<int> inDegree(n,0);
vector<vector<int>> adj(n);
for(auto& r:roads){
adj[r[0]].push_back(r[1]);
adj[r[1]].push_back(r[0]);
//inDegree[r[0]]++;
//inDegree[r[1]]++;
}
ll fuel=0;
function<int(int,int)> dfs = [&](int node,int parent){
ll seat = 1;
for(auto child: adj[node]){
if(child!= parent)
seat += dfs(child,node);
}
if(node!=0)
fuel += ceil((double)seat/seats);
return seat;
};
dfs(0,-1);
return fuel;
}
};