# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
537615 | dantoh000 | Paths (RMI21_paths) | C++14 | 102 ms | 15628 KiB |
This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
#define fi first
#define se second
using namespace std;
typedef long long ll;
typedef pair<int,int> ii;
int n,k;
vector<ii> G[100005];
ll d[100005];
int p[100005][18];
int dep[100005];
int d1 = 0;
int d2 = 0;
ll md = 0;
void dfs(int u){
for (auto v : G[u]){
if (v.fi == p[u][0]) continue;
d[v.fi] = d[u]+v.se;
dep[v.fi] = dep[u]+1;
p[v.fi][0] = u;
dfs(v.fi);
}
}
int lca(int a, int b){
if (dep[a] > dep[b]) swap(a,b);
int DD = dep[b] - dep[a];
for (int k = 0; k < 18; k++){
if (DD>>k&1){
b = p[b][k];
}
}
if (a == b) return a;
for (int k = 17; k >= 0; k--){
if (p[a][k] != -1 && p[a][k] != p[b][k]){
a = p[a][k];
b = p[b][k];
}
}
assert(p[a][0] == p[b][0]);
return p[a][0];
}
ll dist(int a, int b){
return d[a] + d[b] - 2*d[lca(a,b)];
}
int main(){
scanf("%d%d",&n,&k);
for (int i = 1 ; i < n; i++){
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
G[a].push_back({b,c});
G[b].push_back({a,c});
}
memset(p,-1,sizeof(p));
p[1][0] = -1;
dfs(1);
for (int k = 1; k < 18; k++){
for (int i = 1; i <=n ;i ++ ){
if (p[i][k-1] != -1) p[i][k] = p[p[i][k-1]][k-1];
}
}
for (int i = 1; i <= n; i++){
if (d1 == 0 || d[d1] < d[i]) d1 = i;
}
for (int i = 1; i <= n; i++){
ll nd = dist(d1, i);
if (md < nd){
d2 = i;
md = nd;
}
}
for (int i = 1; i <= n; i++){
printf("%d\n",max(dist(i,d1), dist(i,d2)));
}
}
Compilation message (stderr)
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |