题意是给一棵树,求树中任意两点间的距离的最大值。其本质就是:求树的直径。
最短路径部分,可以用迪杰斯特拉实现。可以加优先队列优化一下,但是这里数据不大可以随便搞,快速读入并没有时间优化效果。
1493228 | 2015-01-02 13:37:59 | Accepted | 3517 | C++ | 1.7K | 0'00.11" | 980K |
0'00.11" | 980K |
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <utility>
#include <queue>
using namespace std;
const int MAX = 2048;
struct Edge {
int to;
int len;
};
vector<Edge> G[MAX];
bool vis[MAX];
int mincost[MAX];
const int INF = 0xfffffff;
int n;
//求from到其它所有点的距离(最短路)中的最大值和距离最大的点
pair<int, int> djistra(int from) {
fill(mincost, mincost + n + 1, INF);
memset(vis, false, sizeof(vis));
mincost[from] = 0;
pair<int, int> ans = make_pair(from, 0);
while (true) {
int v = -1;
for (int u = 1; u <= n; ++u) {
if (!vis[u] && (v == -1 || mincost[u] < mincost[v])) {
v = u;
}
}
if (v == -1) break;
vis[v] = true;
if (ans.second < mincost[v]) {
ans.first = v;
ans.second = mincost[v];
}
for (int u = 0; u < G[v].size(); ++u) {
if (mincost[G[v][u].to] > mincost[v] + G[v][u].len) {
mincost[G[v][u].to] = mincost[v] + G[v][u].len;
}
}
}//while
return ans;
}
inline int read() {
char ch;
while ((ch = getchar()) < '0' || ch > '9');
int x = ch - '0';
while ((ch = getchar()) >= '0' && ch <= '9') {
x = (x << 3) + (x << 1) + ch - '0';
}
return x;
}
int main() {
int T;
T = read();
//scanf(" %d", &T);
while (T--) {
n = read();
//scanf(" %d", &n);
for (int i = 1; i <= n; ++i) G[i].clear();
int s, t, c;
for (int i = 1; i < n; ++i) {
s = read();
t = read();
c = read();
//scanf(" %d %d %d", &s, &t, &c);
G[s].push_back((struct Edge){t, c});
G[t].push_back((struct Edge){s, c});
}
pair<int, int> a = djistra(1);
printf("%d\n", djistra(a.first).second);
}//while
return 0;
}