forked from derekhh/HackerRank
-
Notifications
You must be signed in to change notification settings - Fork 0
/
a-knapsack-problem.cpp
90 lines (81 loc) · 1.6 KB
/
a-knapsack-problem.cpp
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
85
86
87
88
89
90
//a-knapsack-problem.cpp
//A Knapsack Problem
//Weekly Challenges - Week 15
//Author: derekhh
//May 29, 2015
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<map>
#include<vector>
using namespace std;
vector<vector<int>> e;
const int MAXN = 2001;
int s[MAXN], v[MAXN], m, ans;
map<int, int> dp[MAXN], f;
void dfs(int root, int parent)
{
for (int i = 0; i < (int)e[root].size(); i++)
if (e[root][i] != parent)
dfs(e[root][i], root);
dp[root].clear();
f.clear();
if (s[root] <= m)
{
dp[root][s[root]] = v[root];
f[s[root]] = v[root];
}
for (int i = 0; i < (int)e[root].size(); i++)
{
if (e[root][i] == parent) continue;
for (auto j = dp[root].begin(); j != dp[root].end(); j++)
{
for (auto k = dp[e[root][i]].begin(); k != dp[e[root][i]].end(); k++)
{
if (j->first + k->first > m) break;
f[j->first + k->first] = max(f[j->first + k->first], j->second + k->second);
}
}
for (auto j = f.begin(); j != f.end(); j++)
{
while (true)
{
auto temp = j;
temp++;
if (temp == f.end() || temp->second > j->second)
break;
f.erase(temp);
}
}
dp[root] = f;
}
if (dp[root].size())
ans = max(ans, dp[root].rbegin()->second);
}
int main()
{
int t;
scanf("%d", &t);
while (t--)
{
ans = 0;
int n;
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++)
scanf("%d", &s[i]);
for (int i = 1; i <= n; i++)
scanf("%d", &v[i]);
e.clear();
e.resize(n + 1);
for (int i = 0; i < n - 1; i++)
{
int a, b;
scanf("%d%d", &a, &b);
e[a].push_back(b);
e[b].push_back(a);
}
dfs(1, 0);
printf("%d\n", ans);
}
return 0;
}