题目链接:
[HDU 3848]CC On The Tree[dfs]
题意分析:
求树上任意两个叶子结点之间距离的最小值。
解题思路:
考虑从树上任意一个非叶子结点开始dfs遍历,求出距离该点最短和次短的两个叶子节点,更新答案:ans = min(ans, 最短 + 次短)。如果每一个都这样求很容易就超时了,可以发现,之前的结果可以接着用,比如新结点遍历到了之前已经遍历过的结点,那么只要返回到这个结点最近的叶子结点距离即可,即返回最短,整个是个递归的子结构。
个人感受:
20天前WA的题,坚信自己的算法是对的。今天重新拿出来,原来是少判断了可能越界的情况= =我真是醉了!!!1h debug!!!
具体代码如下:
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int INF = 0x7f7f7f7f;
const int MAXN = 1e4 + 111;
struct Edge{
int to, w;
Edge(int _to, int _w):to(_to), w(_w){}
};
vector<vector<Edge> > G;
int ans;
int dfs(int u, int fa)
{
if (G[u].size() <= 1) return 0;
vector<int> temp; //存储所有的子状态
for (int i = 0; i < G[u].size(); ++i) {
if (G[u][i].to == fa) continue;
temp.push_back(dfs(G[u][i].to, u) + G[u][i].w);
}
sort(temp.begin(), temp.end());
// 就是这里!!!!!本地运行越界也无所谓,真是醉了,然而去掉这句就WA
if (temp.size() > 1){
ans = min(ans, temp[0] + temp[1]);
}
return temp[0];
}
int main()
{
int n, u, v, w;
while (~scanf("%d", &n) && n)
{
G.clear();
G.resize(n + 2);
ans = INF;
for (int i = 0; i < n - 1; ++i) {
scanf("%d%d%d", &u, &v, &w);
G[u].push_back(Edge(v, w));
G[v].push_back(Edge(u, w));
}
for (int i = 1; i <= n; ++i) {
if (G[i].size() > 1) {
dfs(i, -1);
break;
}
}
if (n == 2) ans = w;
printf("%d\n", ans);
}
return 0;
}