#include "dreaming.h"
#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> pii;
const int MAXN = 1e5 + 10;
vector<pii> adj[MAXN];
int n, distante;
int dist[MAXN];
pii pai[MAXN];
bool mrk_1[MAXN], mrk_2[MAXN];
vector<int> curr;
int diam;
void dfs(int v) {
mrk_2[v] = true;
mrk_1[v] = true;
curr.push_back(v);
if (dist[distante] < dist[v]) {
distante = v;
}
for (auto [w, nc]: adj[v]) {
if (pai[v].first == w) continue;
pai[w] = {v, nc};
dist[w] = dist[v] + nc;
dfs(w);
}
}
int compute_radius() {
int v = distante;
vector<int> all_c;
int tot = 0;
while (v != -1) {
tot += pai[v].second;
all_c.push_back(pai[v].second);
v = pai[v].first;
}
int l = 0, r = tot;
int resp = tot;
for (int x: all_c) {
l += x;
r -= x;
resp = min(resp, max(l, r));
}
return resp;
}
int find_radius(int v) {
curr.clear();
distante = v;
pai[v] = {-1, 0};
dist[v] = 0;
dfs(v);
for (int x: curr) {
mrk_1[x] = false;
}
pai[distante] = {-1, 0};
dist[distante] = 0;
dfs(distante);
diam = max(diam, dist[distante]);
return compute_radius();
}
int travelTime(int N, int M, int L, int A[], int B[], int T[]) {
n = N;
for (int i = 0; i < n; i++) {
pai[i] = {-1, 0};
}
for (int i = 0; i < M; i++) {
adj[A[i]].push_back({B[i], T[i]});
adj[B[i]].push_back({A[i], T[i]});
}
if (M == N - 1) {
find_radius(0);
return diam;
}
multiset<int> rs;
for (int root = 0; root < n; root++) {
if (mrk_2[root]) continue;
int r = find_radius(root);
rs.insert(r);
}
auto it = rs.rbegin();
int large_r = *it;
it++;
int large_r_2 = *it;
return max(diam, large_r + large_r_2 + L);
}
# | 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... |