借鉴于:http://blog.csdn.net/shuangde800/article/details/9732825
做了一题就可以把很多此类类型题给弄懂了,
该题的意思大概就是给你N个点M条边,求出每个点距离其他点的最远距离。
思路是把该无向图转换成有向图
如下图
定义f[i][0] 为i这棵子树上,距离i的最大距离
f[i][0]定义为,除了这课子树,树的其他点距离i点的最大距离
图中红色部分即为 f[4][0],黑色圈的部分为f[4][1],
那么最终的最远距离即为 max(f[i][0],f[i][1])
那么这样的数组怎么填充呢,
思路是: 先用一次dfs将所有点的子树距离该点的最大距离求出,即把f[i][0]求出
然后再用dfs1(第二个dfs)根据f[i][0]求f[i][1]
代码如下:
#include <cstdio>
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
//结构体
typedef struct edge
{
int to, cost;
edge(int to1, int cost1){to = to1;cost = cost1;}
}edge;
//常量
const int N_MAX = 10005;
//变量
int N;//N台机器
int used[N_MAX];
vector<edge> V[N_MAX];
int f[N_MAX][2];//0表示子树中的最大距离,1表示排除子树的最大距离
//函数
int dfs0(int n)//访问节点n
{
used[n] = 1;
f[n][0] = 0;
for(int i=0; i<V[n].size(); i++)
{
int to = V[n][i].to;
int cost = V[n][i].cost;
if(!used[to])
{
f[n][0] = max(f[n][0],dfs0(to)+cost);
}
}
return f[n][0];
}
void dfs1(int n)//访问n这个节点
{
used[n] = 1;
int max1 = 0,max2 = 0,v1 = -1,v2 = -1;
for(int i=0; i<V[n].size();i++)
{
int to = V[n][i].to;
int cost = V[n][i].cost;
if(used[to])continue;
if(f[to][0]+cost > max1)
{
max2 = max1;
max1 = f[to][0] + cost;
v2 = v1;
v1 = to;
}
else if(f[to][0] + cost >= max2)
{
max2 = f[to][0] + cost;
v2 = to;
}
}
if(n!=1)
{
if(f[n][1] > max1)
{
max2 = max1;
v2 = v1;
max1 = f[n][1];
v1 = -1;
}
else if(f[n][1] >= max2)
{
max2 = f[n][1];
v2 = -1;
}
}
for(int i=0; i<V[n].size(); i++)
{
int to = V[n][i].to;
int cost = V[n][i].cost;
if(used[to])continue;
if(v1 == to)
f[to][1] = max2 + cost;
else
f[to][1] = max1 + cost;
if(f[to][1] == 14)cout << "!"<<v1<<","<< to << "," << max1<<"."<< max2 << "!"<< endl;
dfs1(to);
}
}
int main()
{
while(scanf("%d", &N)!=EOF && N)
{
for(int i=1; i<=N; i++)
V[i].clear();
memset(used, 0,sizeof(used));
memset(f, 0, sizeof(f));
for(int i=2; i<=N; i++)
{
int to, cost;
scanf("%d%d", &to, &cost);
V[i].push_back(edge(to, cost));
V[to].push_back(edge(i, cost));
}
dfs0(1);
memset(used,0,sizeof(used));
dfs1(1);
for(int i=1; i<=N; i++)
printf("%d\n", max(f[i][0],f[i][1]));
}
}
在开始做该题时,因为一个简单的语句,导致debug了一天左右,一直找一直找,最终把网上的代码搬出来和我的对比,又用了freopen()代码,自己写了一些数据,将两个输出的文件进行比较,最终找到了问题,那一刻。。。
所以,写代码的时候,要趁清醒的时候写?我不知道为什么我晚上的时候脑子最清醒,但是比赛都是上午或下午啊!真是泪。