题目
错误代码(18过15)
#include <bits/stdc++.h>
using namespace std;
const int N = 1e4+10, M = N << 1;
const int null = -0x3f3f3f3f;
int h[N], e[M], ne[M], w[M], idx;
int v[N];
int maxx;
int res;
int twice;
void add(int a, int b, int c)
{
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++;
}
void dfs(int f, int u, int cnt)
{
bool has_son = false;
for(int k = h[u]; ~k; k = ne[k])
{
int j = e[k];
if(j == f) continue;
else
{
dfs(u, j, cnt + w[k]);
has_son = true;
}
}
if(!has_son && cnt > maxx) maxx = cnt, twice = u;
return;
}
int main()
{
int n;
cin >> n;
memset(h, -1, sizeof h);
for(int i = 1; i < n; i++)
{
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
add(b, a, c);
}
maxx = null;
dfs(0, 3, 0);
maxx = null;
dfs(0, twice, 0);
res = maxx;
cout << res;
return 0;
}
原因
存在负权边,不能用两次dfs的结论得到树的最长路径
为了求最长路径的叶子节点产生的对于两种dfs的感想
void dfs(int f, int u, int cnt)
{
bool has_son = false;
for(int k = h[u]; ~k; k = ne[k])
{
int j = e[k];
if(j == f) continue;
else
{
dfs(u, j, cnt + w[k]);
has_son = true;
}
}
if(!has_son && cnt > maxx) maxx = cnt, twice = u;
return;
}
这种dfs要求在递归终点就可以得到结果进行判优,同时进行记录递归终点,这就要求增加参数,要增加对于递归终点的判断。如果要得到路径,那得维护数组。总归容易记录,比较白盒。
int dfs(int f, int u)
{
int maxb = null;
bool has_son = false;
for(int k = h[u]; ~k; k = ne[k])
{
int j = e[k];
if(j == f) continue;
else
{
maxb = max(maxb, dfs(u, j) + w[k]);
has_son = true;
}
}
if(!has_son) return 0;
else return maxb;
}
这种dfs不需要判断递归终点,且层层返回,这就要求返回的是从当前深度考虑到底部的最优值,需要比较,得到最终返回值。对于递归终点、递归路径,是黑盒的。