简体   繁体   中英

Finding the heaviest path of an undirected graph

I am trying to solve a particular problem but i cannot find any suitable solution. I'll explain ... I have a graph where each node has a numeric value. Starting from a node of my choice, I have to find the path where the sum of the node values is the heaviest. The peculiarity of this problem, however, is that I can only cross the same bridge once BUT it is possible to pass several times on the same node.

to be even more precise, if I have a graph of this type

在此处输入图片说明

Starting from the node 1, the solution I should get would be this : 1->2->0->1->4 with a total weight of 23.

I tried to apply known algorithms such as Dijkstra or Prime but I don't think they are the right solution. I couldn't find much on the internet. Is anyone able to provide me with any explanation or suggestions? Could thinking about coloring the arches and not the knots lead me to a solution in your opinion? A thousand thanks

I solved the problem using a dfs variant like this:

int dfs(vector<vector<int> >& g,
        int* cost, int u, int pre){
    vis[u] = true;
    dp[u] = cost[u];
    bool check = 1;
    int cur = cost[u];
    for (auto& x : g[u]) {
        if (vis[x] && x != pre) {
            check = 0;
        }
        else if (!vis[x]) {
            check &= dfs(g, cost, x, u);
            cur = max(cur, cost[u] + dp[x]);
        }
    }
    dp[u] = cur;
    if (!check) {
        canTake += cost[u];
        path.push_back(u);
    }
    else {
        best = max(best, dp[u]);
        last_node = u;
    }
    return check;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM