1 条题解
-
0
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 10, M = 1e6+10; vector< pair<int, int> > G[N]; int n, k; int siz[N], all, rt, rtmaxsiz; int dis1[N], dis2[N], cnt, ans, mi[M]; bool del[N]; void getroot(int x, int xfa) { siz[x] = 1; int xmaxsiz = 0; for (auto i:G[x]) if (i.first != xfa && !del[i.first]){ getroot(i.first, x); siz[x] += siz[i.first]; xmaxsiz = max(xmaxsiz, siz[i.first]); } xmaxsiz = max(xmaxsiz, all - siz[x]); if (xmaxsiz < rtmaxsiz) rtmaxsiz = xmaxsiz, rt = x; } void getdis(int x, int xfa, int d1, int d2) { if(d1>k) return; dis1[++cnt]=d1; dis2[cnt]=d2; for (auto i:G[x]) if (i.first != xfa && !del[i.first]) getdis(i.first, x, d1+i.second, d2+1); } void calc(int x) { mi[0]=0; cnt=0; for(auto i:G[x]) if(!del[i.first]){ int oldcnt=cnt;getdis(i.first, x, i.second, 1); for(int j=oldcnt+1;j<=cnt;j++) ans=min(ans,mi[k-dis1[j]]+dis2[j]); for(int j=oldcnt+1;j<=cnt;j++) mi[dis1[j]]=min(mi[dis1[j]],dis2[j]); } for(int i=1;i<=cnt;i++) mi[dis1[i]]=0x3f3f3f3f; } void divide(int x) { del[x] = true; calc(x); for (auto i:G[x]) if (!del[i.first]){ all=rtmaxsiz=siz[i.first];getroot(i.first, x);getroot(rt, x); divide(rt); } } int main() { ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); cin >> n >>k; for(int i=1;i<=n;i++) G[i].clear(); for (int i = 1, x, y, w; i < n; i++) { cin >> x >> y >> w;x++;y++; G[x].push_back({y, w}); G[y].push_back({x, w}); } all=rtmaxsiz=n;getroot(1, 0);getroot(rt,0); memset(mi,0x3f,sizeof mi);memset(del,0,sizeof del); ans = n;divide(rt); if(ans>=n) cout << -1 ; else cout << ans ; return 0; }
- 1
信息
- ID
- 4264
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 8
- 标签
- 递交数
- 52
- 已通过
- 9
- 上传者