本来以为很简单的一题,结果因为自己的马虎WA了一上午...
#include <iostream>
#include <stdio.h>
#include <memory.h>
#include <vector>
using namespace std;
struct info
{
int child;//父节点的第一个子节点
int distance;//父节点到此节点child的距离
info(int child,int distance)
{
this->child = child;
this->distance = distance;
}
info(){}
};
int max_num;
bool visited[10005];
vector<info> data[10005];//如data[i],存放的是与i有通路的所有节点编号
void dfs(int father,int result)
{
for(int i = 0;i < data[father].size();i++)
{
if(!visited[data[father][i].child])//没被访问过
{
visited[data[father][i].child] = true;
result += data[father][i].distance;
if(result > max_num)
max_num = result;
dfs(data[father][i].child,result);
result -= data[father][i].distance;//遍历到最后一层时,要返回到最后一个节点的上一层
visited[data[father][i].child] = false;
}
}
}
int main()
{
int n,k;
int father,child,distance;
while(cin >> n >> k)
{
// cin >> k;
memset(visited,false,sizeof(visited));
//info temp;
max_num = 0;
for(int i = 1;i < n;i++)
{
scanf("%d %d %d",&father,&child,&distance);
//cin >> father >> child >> distance;
//temp.child = child;
//temp.distance = distance;
data[father-1].push_back(info(child-1,distance));
//temp.child = father;//因为是双向节点,所有两点互为父节点
data[child-1].push_back(info(father-1,distance));
}
visited[k-1] = true;
dfs(k-1,0);
//printf("%d\n",max_num);
cout << max_num << endl;
for(int i = 0;i < n;i++)
data[i].clear();
}
return 0;
}