/* Leet code 2477: Minimum Fuel Cost to Report to the Capital. */ /* James S. Plank - Wed Apr 12 16:25:31 EDT 2023 */ #include #include #include #include #include #include #include #include #include #include #include using namespace std; class Solution { public: int Seats; vector < vector > Children; // For each node this is the node's children and its parent. vector Npeople; // This is the number of people that end up at a node vector Fuel; // This is how much fuel gets these people to the node long long minimumFuelCost(vector > &roads, int seats); void postorder(int node, int parent); }; void Solution::postorder(int node, int parent) { size_t i; /* Since this is a postorder traversal, start by visiting all of your children (skipping the parent, which is in the list of children). */ for (i = 0; i < Children[node].size(); i++) { if (Children[node][i] != parent) postorder(Children[node][i], node); } /* Now, for each child, add in the number of people from that child, and the amount of fuel that it takes those people to get from the child to the node. See "Extra Hint 2" about that last calculation. */ for (i = 0; i < Children[node].size(); i++) { if (Children[node][i] != parent) { Npeople[node] += Npeople[Children[node][i]]; Fuel[node] += Fuel[Children[node][i]]; Fuel[node] += (( Npeople[Children[node][i]] + Seats - 1 ) / Seats); } } } long long Solution::minimumFuelCost(vector > &roads, int seats) { int i; long long j; /* Initialize the variables */ Seats = seats; Npeople.resize(roads.size()+1, 1); Fuel.resize(roads.size()+1, 0); /* Initialize the list of children for each nodes (which includes the nodes' parents). */ Children.resize(roads.size()+1); for (i = 0; i < roads.size(); i++) { Children[roads[i][0]].push_back(roads[i][1]); Children[roads[i][1]].push_back(roads[i][0]); } postorder(0, -1); // Call this initially on node 0, with a parent of -1 return Fuel[0]; // The answer is the amount of fueld at node 0 at the end of the traversal. } int main() { vector p; vector < vector > roads; int seats; Solution s; /* Read in the edges, and then the seats. Create the roads vector from the edges. */ p.resize(2); while (cin >> seats) { if (cin >> p[1]) { p[0] = seats; roads.push_back(p); } } /* Print the solution */ cout << s.minimumFuelCost(roads, seats) << endl; return 0; }