题意:给出n个士兵,其中1号为指挥官,关系为树状结构,叶子为先锋,现在要在总花费小于等于m的情况切断所有的先锋与指挥官的联系,问最大的限制最小为多少。
析:很明显是一个树形DP,但是限制怎么求呢,就是通过二分,然后变成一个判定性问题,dp[i] 表示切断 以 i 的子树的最少花费不多少,当然是不超过限制的,这里就状态转移方程也是好写的dp[i] += min(dp[v], val) v 是u的子结点,val 是该边的值。
代码如下:
#pragma comment(linker, "/STACK:1024000000,1024000000") #include <cstdio> #include <string> #include <cstdlib> #include <cmath> #include <iostream> #include <cstring> #include <set> #include <queue> #include <algorithm> #include <vector> #include <map> #include <cctype> #include <cmath> #include <stack> #include <sstream> #include <list> #include <assert.h> #define debug() puts("++++"); #define gcd(a, b) __gcd(a, b) #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 #define fi first #define se second #define pb push_back #define sqr(x) ((x)*(x)) #define ms(a,b) memset(a, b, sizeof a) #define sz size() #define pu push_up #define pd push_down #define FOR(x,n) for(int i = (x); i < (n); ++i) #define freopenr freopen("in.txt", "r", stdin) #define freopenw freopen("out.txt", "w", stdout) using namespace std; typedef long long LL; typedef unsigned long long ULL; typedef pair<int, int> P; const int INF = 0x3f3f3f3f; const double inf = 1e20; const double PI = acos(-1.0); const double eps = 1e-8; const int maxn = 1000 + 5; const LL mod = 1e9 + 7; const int dr[] = {-1, 0, 1, 0}; const int dc[] = {0, 1, 0, -1}; const char *de[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"}; int n, m; const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; inline bool is_in(int r, int c) { return r > 0 && r <= n && c > 0 && c <= m; } struct Edge{ int to, val, next; }; Edge edge[maxn<<1]; int head[maxn], cnt; void addEdge(int u, int v, int val){ edge[cnt].val = val; edge[cnt].to = v; edge[cnt].next = head[u]; head[u] = cnt++; } int dp[maxn]; void dfs(int u, int fa, int mid){ dp[u] = 0; bool ok = true; for(int i = head[u]; ~i; i = edge[i].next){ int v = edge[i].to; if(v == fa) continue; ok = false; dfs(v, u, mid); if(dp[u] == INF) continue; if(edge[i].val <= mid) dp[u] += min(edge[i].val, dp[v]); else{ if(dp[v] == INF) dp[u] = INF; else dp[u] += dp[v]; } } if(ok) dp[u] = INF; } bool judge(int mid){ dfs(1, -1, mid); return dp[1] <= m; } int main(){ while(scanf("%d %d", &n, &m) == 2 && n+m){ ms(head, -1); cnt = 0; int mmax = -1; for(int i = 1; i < n; ++i){ int u, v, c; scanf("%d %d %d", &u, &v, &c); mmax = max(mmax, c); addEdge(u, v, c); addEdge(v, u, c); } int l = 1, r = mmax + 1; while(l < r){ int mid = l + r >> 1; if(judge(mid)) r = mid; else l = mid + 1; } printf("%d\n", l == mmax+1 ? -1 : l); } return 0; }