【问题标题】:How to optimize this graph/tree problem counting distance between two nodes in C++?如何优化 C++ 中两个节点之间的这个图/树问题计数距离?
【发布时间】:2021-09-04 21:27:28
【问题描述】:

问题是求树中两个节点之间的距离之和

输入:6 [[0,1],[0,2],[2,3],[2,4],[2,5]]

显示节点

输出:[8,12,6,10,10,10]

说明:树如上图。

我们可以看到 dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5)

等于 1 + 1 + 2 + 2 + 2 = 8。

因此,answer[0] = 8,依此类推。

这是我的代码,我已经解决了,但这给出了 TLE 并且无法优化此解决方案

如何优化这个图形问题。

class Solution {
public:
    vector<int> sumOfDistancesInTree(int n, vector<vector<int>>& edges) {
        vector<int> g[n];
        map<pair<int,int>,int> m;

        for(auto i:edges){
            g[i[0]].push_back(i[1]);
            g[i[1]].push_back(i[0]);
        }

        for(int i=0;i<n;i++){ 
            queue<int> q;
            q.push(i);
            vector<bool> vis(n,0);
            vis[i]=1;
            int incr=1;
            while(!q.empty()){
                int k=q.size();
                while(k--){
                    int t=q.front();q.pop();
                    for(int j=0;j<g[t].size();j++){
                        if(!vis[g[t][j]] && g[t][j]!=i){
                            m[{i,g[t][j]}]+=incr;
                            q.push(g[t][j]);
                            vis[g[t][j]]=1;
                        }
                    }
                }
                incr++;
            }
        }
        vector<int> res(n,0);
        for(auto i:m){
            res[i.first.first]+=i.second;
        }
        return res;
    }
};

【问题讨论】:

    标签: c++ caching graph dynamic-programming


    【解决方案1】:

    正如我所见,您正在为每个节点使用 bfs 来查找距离。
    您可以做的是使用动态编程
    请按照以下步骤解决问题

    1. 初始化一个向量 dp 以存储从每个节点 i 到树的所有叶节点的距离总和。
    2. 初始化一个向量叶子,以存储节点 i 的子树中叶子节点的计数,以 1 为根节点。
    3. 求节点 i 到所有叶节点的距离总和 i 的子树将 1 视为根节点,使用修改后的 深度优先搜索算法。
    Let node a be the parent of node i
    
    leaves[a] += leaves[i] ;
    dp[a] += dp[i] + leaves[i] 
    
    1. 使用重新生根技术找到剩余的距离 树的叶子不在节点 i 的子树中。到 计算这些距离,使用另一个修改过的深度优先搜索 (DFS)算法来查找和添加叶子的距离之和 节点到节点 i。
    Let a be the parent node and i be the child node, then
    Let the number of leaf nodes outside the sub-tree i that are present in the sub-tree a be L
    
    L = leaves[a] – leaves[i] ;
    dp[i] += ( dp[a] – dp[i] ) + ( L – leaves[i] ) ;
    leaves[i] += L ;
    

    【讨论】:

      猜你喜欢
      • 2019-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-26
      相关资源
      最近更新 更多