UVA10308 Roads in the North
UVA 访问性不好,又因为多组数据,不知道为啥 TLE 了。但是在其他地方测是 AC 的。
方法:
随便找一点 ,用 dfs 找到距离 点最远一点 ,再 dfs 找到距离 最远点 ,则 到 的距离是树的直径。
代码:
#include <bits/stdc++.h>
using namespace std;
const int N = 1e4 + 5;
int maxn = 0, _place = 0;
struct Node
{
int v, w;
Node(int x, int y): v(x), w(y){}
};
vector<Node> G[N];
void dfs(int place, int fa, int cnt)
{
if (cnt > maxn)
{
maxn = cnt;
_place = place;
}
for (int i = 0; i < G[place].size(); i++)
{
int nx = G[place][i].v;
if (nx != fa)
{
dfs(nx, place, cnt + G[place][i].w);
}
}
}
int main()
{
int u, v, w;
while (scanf("%d %d %d", &u, &v, &w) != EOF)
{
G[u].push_back(Node(v, w));
G[v].push_back(Node(u, w));
}
dfs(u, 0, 0);
maxn = 0;
dfs(_place, 0, 0);
printf("%d\n", maxn);
return 0;
}

浙公网安备 33010602011771号