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
|
#include <iostream> #include <cstdio> #include <cstring> using namespace std; typedef long long ll; typedef pair <int,int> pii; #define DEBUG(x) cout << #x << " = " << x << "\n" template <typename T> inline bool read(T &x) { int f = 1,c = getchar();x = 0; while (!isdigit(c)) {if (c == 45)f = -1;c = getchar();} while (isdigit(c))x = (x<<3)+(x<<1)+(c^48),c = getchar(); return x *= f,true; } template <typename T,typename... Args> inline bool read(T &x,Args &...args) { return read(x) && read(args...); }
namespace run { const int maxn = 3e5+10; struct Edge {int nxt,to,w;}edge[maxn<<1]; int begn[maxn],e; inline void add(int x,int y,int z) { edge[++e] = (Edge){begn[x],y,z};begn[x] = e; return; } struct DP { ll f; int num; DP (ll F = 0,int Num = 0) {f = F;num = Num;} bool operator < (const DP &rhs) const { return (f ^ rhs.f) ? f < rhs.f : num < rhs.num; } }I,f[maxn][3]; DP operator + (DP x,DP y) {return DP(x.f+y.f,x.num+y.num);} inline void dfs(int x,int fa) { f[x][0] = f[x][1] = DP(0,0);f[x][2] = I; for (int i = begn[x];i;i = edge[i].nxt) { int y = edge[i].to; if (y ^ fa) { dfs(y,x); DP tmp = DP(edge[i].w,0); f[x][2] = max(f[x][2],max(f[x][1]+tmp+f[y][1]+I,f[x][2]+f[y][0])); f[x][1] = max(f[x][1],max(f[x][0]+f[y][1]+tmp,f[x][1]+f[y][0])); f[x][0] = max(f[x][0],f[x][0]+f[y][0]); } } f[x][0] = max(f[x][0],max(f[x][1]+I,f[x][2])); return; } int n,K; ll ans; inline bool main() { read(n,K);++K; for (int i = 1,x,y,z;i < n;++i)read(x,y,z),add(x,y,z),add(y,x,z); int l = -1e8,r = 1e8; while (l < r) { int mid = ((l+r)>>1)+1; I = DP(-mid,1); dfs(1,0); if (f[1][0].num >= K)l = mid,ans = f[1][0].f+1ll*mid*K; else r = mid-1; if (f[1][0].num == K)break; } printf("%lld\n",ans); cerr<<1.0*clock()/CLOCKS_PER_SEC<<"\n"; return 0; } }
#define demonlover int main() { #ifdef demonlover freopen("luogu4383.in","r",stdin); freopen("luogu4383.out","w",stdout); #endif return run :: main(); }
|