Daily question --- 2477. Minimum fuel consumption to reach the capital

Chained forward star solution 

The core point is that I run dfs twice. The first time is to find out how many leaf nodes there are for each node?

Because we can think of it as starting from the current node to the root node of the current node, then we need to know the number of leaf nodes of the current node, that is, we let the leaf nodes (representatives) of the current node come to the current node set first, then this is a sub-problem

So for sub-problem solutions, we can memorize search or use recursive features

This question is solved using the memory search method

f[i], represents how many people will eventually gather at point i

dp[i], represents the minimum amount of fuel required to train at point i

class Solution {
public:
    int h[510000], ne[510000], e[510000], idx;
    bool st[110000] = {0};
    long long dp[110000] = {0};

    long long dfs1(int u, int seats, vector<long long>& f) {
        st[u] = true;
        for (int i = h[u]; i != -1; i = ne[i]) {
            int b = e[i];
            if (st[b]) continue;

            long long cnt = dfs1(b, seats, f);
            f[u] = f[u] + cnt;
        }
        return f[u];
    }

    long long dfs2(int u, int seats, vector<long long>& f) {
        st[u] = true;
        for (int i = h[u]; i != -1; i = ne[i]) {
            int b = e[i];
            if (st[b]) continue;

            dfs2(b, seats, f);
            dp[u] = dp[u] + (f[b] / seats) + ((f[b] % seats == 0) ? 0 : 1) + dp[b];
        }

        return dp[u];
    }

    void add(int a, int b) {
        e[idx] = b, ne[idx] = h[a], h[a] = idx++;
    }

    long long minimumFuelCost(vector<vector<int>>& roads, int seats) {
        vector<long long> f(110000, 1);
        f[0] = 0;
        memset(h, -1, sizeof(h));

        for (auto& e : roads) {
            int a = e[0];
            int b = e[1];
            add(a, b), add(b, a);
        }

        memset(st, 0, sizeof(st));
        dfs1(0, seats, f);

        memset(st, 0, sizeof(st));
        dfs2(0, seats, f);

        return dp[0];
    }
};

Guess you like

Origin blog.csdn.net/txh1873749380/article/details/134997510