思路:dfs
使用unordered_map<int,vector> memo;创建图,然后使用dfs
class Solution {
public:
/**
* 树的直径
* @param n int整型 树的节点个数
* @param Tree_edge Interval类vector 树的边
* @param Edge_value int整型vector 边的权值
* @return int整型
*/
struct Edge{
int end;
int w;
Edge(int end_,int w_):end{end_},w{w_}{}
};
int dfs(unordered_map<int,vector<Edge>>& memo,int from,int pre){
int res=0;
int len=memo[from].size();
for(int i=0;i<len;i++){
if(memo[from][i].end!=pre)
res=max(res,dfs(memo,memo[from][i].end,from)+memo[from][i].w);
}
return res;
}
int solve(int n, vector<Interval>& Tree_edge, vector<int>& Edge_value) {
unordered_map<int,vector<Edge>> memo;
int res=0;
for(int i=0;i<Tree_edge.size();i++){
int start=Tree_edge[i].start;
int end=Tree_edge[i].end;
int w=Edge_value[i];
if(memo.find(start)==memo.end())
memo[start]=vector<Edge>{};
if(memo.find(end)==memo.end())
memo[end]=vector<Edge>{};
memo[start].push_back(Edge{end,w});
memo[end].push_back(Edge{start,w});
}
for(int i=0;i<n;i++){
res=max(res,dfs(memo,i,-1));
}
return res;
}
};