题意:在一棵带权树上要切断若干条边使得根节点与所有叶子结点都不联通,且花费不能超过m。问你切掉边中最大的权值最小的是多少。
思路:二分最大权值,验证答案。每次选择当前结点下面一条边或者是当前子树多有叶子结点不连通的最小值。叶子结点的只为INF(这里被坑了无数次!!!最大值不能太大每次累加起来就越界了,我错了10次有木有)。
代码如下:
1 /************************************************** 2 * Author : xiaohao Z 3 * Blog : http://www.cnblogs.com/shu-xiaohao/ 4 * Last modified : 2014-04-03 21:35 5 * Filename : hdu_3586.cpp 6 * Description : 7 * ************************************************/ 8 9 #include <iostream> 10 #include <cstdio> 11 #include <cstring> 12 #include <cstdlib> 13 #include <cmath> 14 #include <algorithm> 15 #include <queue> 16 #include <stack> 17 #include <vector> 18 #include <set> 19 #include <map> 20 #define MP(a, b) make_pair(a, b) 21 #define PB(a) push_back(a) 22 23 using namespace std; 24 typedef long long ll; 25 typedef pair<int, int> pii; 26 typedef pair<unsigned int,unsigned int> puu; 27 typedef pair<int, double> pid; 28 typedef pair<ll, int> pli; 29 typedef pair<int, ll> pil; 30 31 const int INF = 1000001; 32 const double eps = 1E-6; 33 const int LEN = 1010; 34 int n, m; 35 vector<pii> Map[LEN]; 36 37 int dfs(int v, int f, int mid){ 38 int ret = 0; 39 for(int i=0; i<Map[v].size(); i++){ 40 int ch = Map[v][i].first, val = Map[v][i].second; 41 if(ch != f){ 42 int get = dfs(ch, v, mid); 43 if(val < get && val <= mid) get = val; 44 ret += get; 45 } 46 } 47 if(ret == 0) return INF; 48 return ret; 49 } 50 51 int main() 52 { 53 // freopen("in.txt", "r", stdin); 54 55 ios::sync_with_stdio(false); 56 int a, b, c; 57 while(cin >> n >> m){ 58 if(!n && !m) break; 59 for(int i=0; i<LEN; i++) Map[i].clear(); 60 for(int i=0; i<n-1; i++){ 61 cin >> a >> b >> c; 62 Map[a].PB(MP(b, c)); 63 Map[b].PB(MP(a, c)); 64 } 65 int l = 0, r = 1000; 66 if(n == 1) cout << "0" << endl; 67 else if(dfs(1, -1, r) > m) cout << "-1" << endl; 68 else { 69 while(l < r){ 70 int mid = (l+r)/2; 71 if(dfs(1, -1, mid) <= m) r = mid; 72 else l = mid+1; 73 } 74 cout << l << endl; 75 } 76 } 77 return 0; 78 }