题目链接:传送门
看不下去的题面:
C
o
m
p
u
t
e
r
Computer
Computer
Problem Description
A school bought the first computer some time ago(so this computer’s id is 1). During the recent years the school bought N-1 new computers. Each new computer was connected to one of settled earlier. Managers of school are anxious about slow functioning of the net and want to know the maximum distance Si for which i-th computer needs to send signal (i.e. length of cable to the most distant computer). You need to provide this information.
Hint: the example input is corresponding to this graph. And from the graph, you can see that the computer 4 is farthest one from 1, so S1 = 3. Computer 4 and 5 are the farthest ones from 2, so S2 = 2. Computer 5 is the farthest one from 3, so S3 = 3. we also get S4 = 4, S5 = 4.
Input
Input file contains multiple test cases.in each case there is natural number N (N<=10000) in the first line, followed by (N-1) lines with descriptions of computers. i-th line contains two natural numbers - number of computer, to which i-th computer is connected and length of cable used for connection. Total length of cable does not exceed 10^9. Numbers in lines of input are separated by a space.
Output
For each case output N lines. i-th line must contain number Si for i-th computer (1<=i<=N).
Sample Input
5
1 1
2 1
3 1
1 1
Sample Output
3
2
3
4
4
题目大意:
给你一颗树,要你求从每个点能走的最远距离
树的直径?
不应该是树形dp专栏么
好麻烦啊
推荐一个树形dp做法:点这里
我的直径多好写
随便从一个点bfs找最长路
再从那个点找最长路,更新一下dis数组
再从那个点跑最长路,与第一次更新的dis数组作比较就好了
至此。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <complex>
#include <algorithm>
#include <climits>
#include <queue>
#include <map>
#include <vector>
#include <iomanip>
#define A 1000010
#define B 2010
#define ll long long
using namespace std;
struct node {
int next, to, dis;
}edge[A];
int head[A], num_edge;
void add_edge(int from, int to, int dis) {
edge[++num_edge].next = head[from];
edge[num_edge].to = to;
edge[num_edge].dis = dis;
head[from] = num_edge;
}
int dis[A], dis2[A], n, a, b, c;
int bfs(int s) {
int ans = s;
memset(dis, 0, sizeof dis);
queue<int> q;
q.push(s); dis[s] = 1;
while (!q.empty()) {
int fr = q.front(); q.pop();
for (int i = head[fr]; i; i = edge[i].next) {
int ca = edge[i].to;
if (dis[ca]) continue;
dis[ca] = dis[fr] + edge[i].dis;
q.push(ca);
if (dis[ca] > dis[ans]) ans = ca;
}
}
return ans;
}
int main() {
while (cin >> n) {
memset(head, 0, sizeof head); num_edge = 0;
for (int i = 2; i <= n; i++) {
scanf("%d%d", &a, &b);
add_edge(i, a, b);
add_edge(a, i, b);
}
memset(dis, 0, sizeof dis);
memset(dis2, 0, sizeof dis2);
int s = bfs(1);
int t = bfs(s);
for (int i = 1; i <= n; i++) dis2[i] = dis[i] - 1;
bfs(t);
for (int i = 1; i <= n; i++) dis2[i] = max(dis2[i], dis[i] - 1);
for (int i = 1; i <= n; i++) printf("%d\n", dis2[i]);
}
return 0;
}