1. 程式人生 > >#2478. 「九省聯考 2018」林克卡特樹

#2478. 「九省聯考 2018」林克卡特樹

這題挺考思路的…我這種渣渣就是做不來.
大佬blog
想了半天,然後看題解了半天…思路還是看大佬的吧.
c++程式碼如下:

#include<bits/stdc++.h>
#define rep(i,x,y) for(register int i = x ; i <= y; ++ i)
#define repd(i,x,y) for(register int i = x ; i >= y; -- i)
using namespace std;
typedef long long ll;
template<typename T>inline void
read(T&x) { x = 0;char c;int sign = 1; do { c = getchar(); if(c == '-') sign = -1; }while(!isdigit(c)); do { x = x * 10 + c - '0'; c = getchar(); }while(isdigit(c)); x *= sign; } const ll inf = 1e12;const int N = 3e5+50; int n,k;ll K; int head[N],to[N << 1],nxt[N << 1],w[N << 1
],tot; inline void add(int x,int y,int val) { w[tot] = val; to[tot] = y; nxt[tot] = head[x]; head[x] = tot++; } #define PI pair<ll,int> #define mk make_pair PI f[N][3],t[3]; PI operator + (PI a,PI b) { return mk(a.first + b.first,a.second + b.second); } PI max(PI a,PI b) { if
(a.first > b.first) return a; else if(a.first == b.first && a.second < b.second) return a; return b; } inline void chkmax(PI&a,PI b,int w,int op) { b.first += w - K * op;b.second += op; a = max(a,b); } inline void update(int x,int y,int w) { t[0] = f[x][0]; t[1] = f[x][1]; t[2] = f[x][2]; chkmax(f[x][2],t[1] + f[y][1],w,-1); chkmax(f[x][2],t[1] + f[y][0],w,0); chkmax(f[x][2],t[2] + f[y][2],0,0); chkmax(f[x][1],t[0] + f[y][0],w,1); chkmax(f[x][1],t[0] + f[y][1],w,0); chkmax(f[x][1],t[1] + f[y][2],0,0); chkmax(f[x][0],t[0] + f[y][2],0,0); } void dfs(int x,int fa) { f[x][0] = mk(0,0); f[x][1] = mk(-inf,0); f[x][2] = mk(-inf,0); for(register int i = head[x];~i;i = nxt[i]) if(to[i] != fa){ dfs(to[i],x); update(x,to[i],w[i]); } f[x][2] = max(f[x][2],f[x][1]); f[x][2] = max(f[x][2],f[x][0]); f[x][2] = max(f[x][2],mk(f[x][0].first-K,f[x][0].second+1)); } inline bool check(ll x) { K = x; dfs(1,1); return f[1][2].second <= k; } int main() { memset(head,-1,sizeof head); read(n); read(k);++k; rep(i,2,n) { int u,v,w; read(u); read(v); read(w); add(u,v,w); add(v,u,w); } ll l = -inf,r = inf,mid,ans=0; while(l <= r) { if(check(mid = l + r>> 1)) ans = f[1][2].first + k * K,r = mid - 1; else l = mid + 1; } cout << ans << endl; return 0; }