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
| #include <cstdio> #include <algorithm> #include <cstring> #include <queue> #define MAXN 3005 #define INF 0x3f3f3f3f using namespace std;
int n, s, root, cnt, ans=INF, ecc, head[MAXN], dis[MAXN], pre[MAXN]; bool vis[MAXN];
struct Edge {int next, to, dis;} edge[MAXN*2];
void addedge(int from, int to, int dis) { edge[++cnt].next=head[from]; edge[cnt].to=to; edge[cnt].dis=dis; head[from]=cnt; }
void bfs(int root) { queue<int> q; vis[root]=true; q.push(root); while(!q.empty()) { int x=q.front(); q.pop(); for(int i=head[x]; i; i=edge[i].next) { int to=edge[i].to; if(vis[to]) continue; pre[to]=x; vis[to]=true; dis[to]=dis[x]+edge[i].dis; q.push(to); } } }
void getline() { int maxdis=0; bfs(1); for(int i=1; i<=n; i++) if(dis[i]>maxdis) maxdis=dis[i], root=i; memset(vis, 0, sizeof(vis)); memset(pre, 0, sizeof(pre)); memset(dis, 0, sizeof(dis)); bfs(root); maxdis=0; for(int i=1; i<=n; i++) if(dis[i]>maxdis) maxdis=dis[i], root=i; }
void dfs(int x, int fa, int dis) { ecc=max(ecc, dis); for(int i=head[x]; i; i=edge[i].next) { int to=edge[i].to; if(to==fa || vis[to]) continue; dfs(to, x, edge[i].dis+dis); } }
void solve() { for(int x=root; x; x=pre[x]) { int y=0, len=0; ecc=0; memset(vis, 0, sizeof(vis)); for(int i=x; i; i=pre[i]) { for(int j=head[i]; j; j=edge[j].next) if(edge[j].to==pre[i]) len+=edge[j].dis; y=i; vis[i]=true; if(len>s) break; } for(int i=x; ; i=pre[i]) { dfs(i, 0, 0); if(i==y) break; } ans=min(ans, ecc); } }
int main() { scanf("%d%d", &n, &s); for(int i=1; i<n; i++) { int x, y, z; scanf("%d%d%d", &x, &y, &z); addedge(x, y, z); addedge(y, x, z); } getline(); solve(); printf("%d\n", ans); }
|