1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
| const int maxn = 500000 + 10; const int maxm = 1000000 + 5; const int inf = 0x3f3f3f3f; int head[maxn], ver[maxm], edges[maxm], ne[maxm], tot = 1; int n, s;
void add(int x, int y, int z) { ver[++tot] = y; edges[tot] = z; ne[tot] = head[x]; head[x] = tot; }
int vis[maxn], pre[maxn], d[maxn]; void bfs(int u, int &pos) { memset(vis, 0, sizeof vis); memset(pre, 0, sizeof pre); memset(d, 0, sizeof d); vis[u] = 1; d[u] = 0; queue<int> q; q.push(u);
while (!q.empty()) { int x = q.front(); q.pop(); for (int i = head[x]; i; i = ne[i]) { int y = ver[i]; if (vis[y]) continue; vis[y] = 1; d[y] = d[x] + edges[i]; pre[y] = x; if (d[y] > d[pos]) pos = y; q.push(y); } } }
typedef pair<int, int> PII; vector<PII> a;
int D[maxn]; int bfs_max(int u) { vis[u] = 1; queue<int> q; q.push(u);
int res = 0; while (!q.empty()) { int x = q.front(); q.pop(); for (int i = head[x]; i; i = ne[i]) { int y = ver[i]; if (vis[y]) continue; vis[y] = 1; d[y] = d[x] + edges[i]; if (d[y] > res) res = d[y]; q.push(y); } } return res; }
void diameter() { int p = 0; bfs(1, p); int q = 0; bfs(p, q);
while (q) { a.push_back({q, d[q]}); q = pre[q]; } reverse(a.begin(), a.end());
// mark diameter memset(vis, 0, sizeof vis); for (auto x : a) vis[x.first] = 1;
// get max dist out diameter memset(d, 0, sizeof d); for (auto x : a) D[x.first] = bfs_max(x.first); // for (int i = 1; i <= n; i++) printf("%d\n", D[i]); }
void solve() { int q[maxn], l = 1, r = 0, ans = inf; for (int i = 0, j = 0; i < a.size(); i++) { while (a[i].second - a[j].second > s) j++; assert(j <= i);
int res = max(a[j].second - a[0].second, a.back().second - a[i].second); while (l <= r && q[l] < j) l++; res = max(res, D[a[q[l]].first]); ans = min(ans, res); while (l <= r && D[a[q[r]].first] <= D[a[i].first]) r--; q[++r] = i; } printf("%d\n", ans); }
int main() { freopen("input.txt", "r", stdin); scanf("%d%d", &n, &s); for (int i = 0; i < n-1; i++) { int a, b, c; scanf("%d%d%d", &a, &b, &c); add(a, b, c); add(b, a, c); }
// then diameter diameter();
// solve solve(); }
|