Just to remind, girls in Arpa's land are really nice.
Mehrdad wants to invite some Hoses to the palace for a dancing party. Each Hos has some weight wi and some beauty bi. Also each Hos may have some friends. Hoses are divided in some friendship groups. Two Hoses x and y are in the same friendship group if and only if there is a sequence of Hoses a1, a2, ..., ak such that ai and ai + 1 are friends for each 1 ≤ i < k, and a1 = x and ak = y.
Arpa allowed to use the amphitheater of palace to Mehrdad for this party. Arpa's amphitheater can hold at most w weight on it.
Mehrdad is so greedy that he wants to invite some Hoses such that sum of their weights is not greater than w and sum of their beauties is as large as possible. Along with that, from each friendship group he can either invite all Hoses, or no more than one. Otherwise, some Hoses will be hurt. Find for Mehrdad the maximum possible total beauty of Hoses he can invite so that no one gets hurt and the total weight doesn't exceed w.
Input
The first line contains integers n, m and w (1 ≤ n ≤ 1000, , 1 ≤ w ≤ 1000) — the number of Hoses, the number of pair of friends and the maximum total weight of those who are invited.
The second line contains n integers w1, w2, ..., wn (1 ≤ wi ≤ 1000) — the weights of the Hoses.
The third line contains n integers b1, b2, ..., bn (1 ≤ bi ≤ 106) — the beauties of the Hoses.
The next m lines contain pairs of friends, the i-th of them contains two integers xi and yi (1 ≤ xi, yi ≤ n, xi ≠ yi), meaning that Hoses xi and yi are friends. Note that friendship is bidirectional. All pairs (xi, yi) are distinct.
Output
Print the maximum possible total beauty of Hoses Mehrdad can invite so that no one gets hurt and the total weight doesn't exceed w.
Examples
Input
3 1 5
3 2 5
2 4 2
1 2
Output
6
Input
4 2 11
2 4 6 6
6 4 2 1
1 2
2 3
Output
7
Note
In the first sample there are two friendship groups: Hoses {1, 2} and Hos {3}. The best way is to choose all of Hoses in the first group, sum of their weights is equal to 5 and sum of their beauty is 6.
In the second sample there are two friendship groups: Hoses {1, 2, 3} and Hos {4}. Mehrdad can't invite all the Hoses from the first group because their total weight is 12 > 11, thus the best way is to choose the first Hos from the first group and the only one from the second group. The total weight will be 8, and the total beauty will be 7.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We are given n up to 1000, w up to 1000. There are m edges. Hoses (nodes) have weight w_i and beauty b_i. We need to select a subset of nodes such that total weight <= w, total beauty max, and with the constraint: within each connected component (friendship group), we can either select all nodes from that component, or at most one node from that component. In other words, if we select more than one node from a component, we must select all nodes from that component. Also we can select zero nodes from a component.
This is a variant of knapsack with groups but each group has two options: either take the sum of all weights and beauty of the whole component, or take at most one item from the component (like choosing any single node, but not more than one). Wait careful: The condition: "from each friendship group he can either invite all Hoses, or no more than one." That means there are two possibilities per group: either we take the entire component (all its nodes) as a whole (i.e., we must take all of them together) or we take at most one node from the component (so we can take one node, or none). So for each component, we have a set of possible selections: (1) take none: weight 0, beauty 0; (2) take exactly one node i (any i) with weight w_i, beauty b_i; (3) take all nodes in the component: total weight = sum_{i in comp} w_i, total beauty = sum_{i in comp} b_i. However, we cannot take a subset of size >1 that is not all nodes. So the possible selections are basically: a set of items (singles) plus a special "whole group" option that is different from just the sum of singles? Note that taking all nodes is not the same as taking each single one individually, because if we take each single one, that would be multiple selections from the same component, which is not allowed unless we take all. So the group constraints forbid mixing multiple singles. So we have to treat each component as a special knapsack where we can either pick exactly one of the items (or none), or pick the entire group as a whole. But note: picking the entire group includes the case of picking all items, which may be equivalent to picking each single? But that would be picking multiple singles, which is not allowed. So we must treat the whole-group option as a separate package that cannot be combined with any other item from that component. Also note: if the component has size 1, then picking that single node is also picking "all Hoses" (since it's the only one). But both options essentially lead to same selection: we can either take the single node as "all" or as "one". But they are the same effect, so we can treat as a single node group where the whole-group option is same as picking that node. But we must be careful not to double count. Usually such problems treat each component as having a list of items (the individual nodes) and also a group option (take all). But since if we take all, that selection includes the same nodes as taking each individually, but the constraint forbids mixing, we need to handle it as a 0-1 decision across the component.
One typical solution: For each component, compute total weight and total beauty. Then we can consider the component as a "super item" with weight = total weight, beauty = total beauty. However, we also have the option to take individual nodes. But taking individual nodes is like we can only take at most one. But we can treat each component as offering several "choices" that are mutually exclusive: either choose none, choose exactly one node (any of them), or choose the whole group. So this is like each component has a set of "options", each option has weight and beauty. The number of options per component is (size + 1), plus the none option which we can represent by not selecting anything. In knapsack DP we can treat each component as a group; we pick at most one option from each group. This becomes a group knapsack problem (also known as multi-choice knapsack). Since n <= 1000 and w <= 1000, we can do DP over weight, where for each component we consider its options and update DP.
But careful: if we treat each component as a group with its options (including the whole group option and each single node option), then note that the whole group option might be dominated by some single node option if it has less beauty per weight? But we must allow it because maybe taking all gives higher total beauty even though weight is larger. Also note that we cannot take both a single node and the whole group; they are mutually exclusive. So group knapsack is appropriate.
However, there might be an nuance: Suppose we take a single node from component A and also take a single node from component B, that's allowed because they are from different groups. So the DP across groups must consider selection of at most one option per group.
So the problem reduces to: Given up to n components (max n, but actually number of components <= n). For each component, we have a set of possible selections:
take nothing (weight 0, beauty 0)
take node i for each i in component: (w_i, b_i)
take all nodes: (sum_w, sum_b)
But wait: Could there be also possibility of taking no nodes (which is covered by the "none" option). Also, can we take all nodes but also maybe take additional nodes from the same component? No, because that would be selecting more than all. So it's fine.
Now number of components can be up to n (if each node isolated). Then total options sum over components is sum over (size + 1) which is n + number_of_components. That's O(n). That's manageable.
We need to compute DP for max beauty with weight capacity w. Standard group knapsack: DP[k][c] = max beauty using first k groups with total weight c. We can compress to 1D: for each group, we iterate capacity from w down to 0, and for each option in the group, if weight <= capacity, update dp[capacity] = max(dp[capacity], dp[capacity - weight] + beauty). However, careful: In group knapsack, you must ensure at most one option from each group. If we iterate capacity from w down to 0 and for each option we consider updating dp[cap] using dp[cap - weight] from the previous group state, then we might combine multiple options from the same group because after we update dp for one option, then when considering another option later, we might use the updated dp which already includes an option from same group. So we need to use a temporary array to store dp before processing the group, or process the group by iterating over capacities in reverse and for each capacity, compute the best among options using the previous dp values. Standard approach: For each group, we have a new_dp = dp copy (or we can update from a copy). We'll do: for each capacity from 0..w, new_dp[c] = dp[c] (i.e., not selecting any option from this group). Then for each option (weight, beauty) in the group, for each capacity c from weight to w: new_dp[c] = max(new_dp[c], dp[c - weight] + beauty). At the end, dp = new_dp. This ensures exactly one option from each group (or none). This runs in O(total_options * w) which is O((n + comps) * w) = O(n * w) = 1e6, fine.
But wait: The "none" option is essentially not selecting any node from the group. We already have that by initializing new_dp with dp (i.e., skipping the group). So we don't need an explicit option for none.
Now, is it correct that the only allowed selections per component are exactly one node or all nodes? Let's re-read problem statement: "from each friendship group he can either invite all Hoses, or no more than one." So it says: either invite all Hoses (the whole group) OR invite no more than one (so 0 or 1). That matches our interpretation. So the group options are:
if we decide to invite all: that yields sum of weights and beauty of the whole component.
if we decide to invite at most one: then we can choose any single node, or none. So we need to consider all possible single nodes.
But is there also possibility to invite none? Yes. So we include none via not selecting any option.
Thus the DP approach is correct.
Edge Cases: Component size 1: The "all" option is same as taking that single node. But if we include both as separate options, it's okay but it will double count same option; but it may cause issues? Actually, the group knapsack DP will treat both as options; they are two options with same weight and beauty. That's okay; it won't cause problem as picking either yields same result, but DP might choose it twice? No, because we only pick one option per group, so we either pick the single node option or the all option, but both lead to same outcome. So it's fine. But we could deduplicate to reduce work.
Now we need to find connected components given n up to 1000, m up to min( n*(n-1)/2, 10^5?). Actually constraint says m ≤ n(n-1)/2, but no explicit upper bound other than that. Since n ≤ 1000, m can be up to ~500k. But still manageable for DSU or DFS. Use DSU to group nodes.
Implementation steps:
Read n, m, W.
Read arrays w[1..n], b[1..n].
Initialize DSU of size n.
For each of m lines, read x, y, union(x-1, y-1).
After DSU, build component lists: For each node i, find its root, add i to that component's list.
For each component comp:
compute sum_w = sum of w_i over i in comp
compute sum_b = sum of b_i over i in comp
create a vector options for this component: for each node i in comp, add (w_i, b_i). Also add the "all" option: (sum_w, sum_b). But note: If we add the all option, we might double count size-1 components, but it's fine.
However, note that if we add the all option, we should consider that we can also achieve the all selection by picking each node individually? No, because that would be picking more than one node, which is not allowed. So it's a distinct option.
Also note: For components with size > 1, the "all" option might be better or worse. Good.
Now do DP: array dp of size W+1, initialized to 0 (or -inf for impossible but with 0 base). Use group knapsack:
For each component with its options:
new_dp = dp copy (or we can do dp array and use temporary copy to store previous state)
for each (weight, beauty) in options:
for cap from weight to W:
if dp[cap - weight] + beauty > new_dp[cap]:
new_dp[cap] = dp[cap - weight] + beauty
dp = new_dp
After all components, answer = max over cap dp[cap] (but dp[cap] already stores max beauty for exact capacity? Actually in our update we are maximizing for each capacity; dp[W] is max beauty with weight <= W? Not exactly, dp[cap] is max beauty using total weight exactly cap? In typical knapsack, dp[capacity] is max beauty for that exact capacity? Usually we want weight <= W, we can define dp[cap] as max beauty achievable with total weight exactly cap. Then answer = max(dp[0..W]). But we can also define dp[cap] as max beauty for weight at most cap, but easier is to keep dp as exact and take max. Alternatively we can update by allowing less weight. In group knapsack we can also maintain dp as maximum beauty for weight up to cap? Usually we fill dp with -inf except dp[0]=0, then after each group we get exact weights; then answer = max(dp[0..W]). That works.
But we can also do dp initially all 0, but careful: if we use dp[0] = 0, others 0, that implies we can achieve weight 0 with beauty 0, but other weights may be 0 initially which may be higher than -inf? Actually if we allow weight not exactly cap, we need to ensure we don't use invalid states. For simplicity, we can initialize dp with 0, and then during DP, we consider dp[cap - weight] + beauty. Since dp[cap - weight] might be 0 for some cap-weight that are unreachable (i.e., no combination exactly that weight) but if we haven't set dp for those exact sums, they might be 0 and we could erroneously add beauty to them, assuming we started from weight 0. But if we start with dp[0]=0 and all others 0, then for any cap, dp[cap] could be updated from dp[cap - weight] if dp[cap - weight] is 0, which might correspond to not using any previous groups (i.e., weight exactly cap - weight not necessarily achievable). However, in knapsack DP where we only add positive items, it's typical to initialize dp with -inf and dp[0]=0. Because if dp[cap - weight] is 0 for a state that is not actually achievable (e.g., cap - weight > 0 but we haven't yet found a combination for that weight), we might incorrectly combine. But is that a problem? Let's think: In standard 0/1 knapsack with dp array of size W+1 and all dp initially 0, we iterate items with weight w_i, for cap from W down to w_i: dp[cap] = max(dp[cap], dp[cap - w_i] + b_i). Starting with dp[0]=0 and all others 0, the dp array stores the maximum beauty for weight exactly cap? Actually in that classic version, dp[cap] represents the maximum beauty for a total weight exactly cap? Not exactly; it's often used for "maximum value with weight at most cap" if we treat dp[cap] as the max value we can get with capacity cap, and we allow not filling exactly. In that variant, we initialize dp[0..W] = 0, and for each item, we update dp[cap] = max(dp[cap], dp[cap - w_i] + b_i). This dp[cap] after all items yields the maximum beauty for total weight ≤ cap? Actually it's known that when dp is initialized to 0, the DP computes the maximum value for a total weight not exceeding the capacity, because you can always leave leftover capacity unused, and dp[cap] is the max value you can obtain with weight exactly cap? Hmm, I need to recall precisely.
Standard 0-1 knapsack (max value, weight constraint ≤ W) can be implemented with dp[0..W] initialized to 0, and then for each item (w, v), for c from W down to w: dp[c] = max(dp[c], dp[c-w] + v). At the end, the answer is dp[W]. Why does dp[W] give the answer? Because each dp[c] stores the maximum value achievable with total weight exactly c? Not exactly; let's test: Suppose we have one item with weight 2, value 5, W=5. Starting dp = [0,0,0,0,0,0]. Process item: for c=5 to2: dp[5] = max(dp[5], dp[3]+5) = max(0,0+5)=5. dp[4]=max(0, dp[2]+5)=5. dp[3]=max(0, dp[1]+5)=5. dp[2]=max(0, dp[0]+5)=5. So after, dp = [0,0,5,5,5,5]. dp[5] = 5. But can we achieve weight 5 exactly? We have only weight 2, so we cannot fill weight 5 exactly. Yet dp[5]=5, indicating that we can get value 5 with total weight not exceeding 5? Actually we can take the item (weight 2) and have leftover capacity 3. The DP as coded gives dp[5]=5 because it's using dp[3] which is 0 (since dp[3] before update was 0, but we treat dp[3] as achievable? dp[3] is 0 before, meaning we can achieve weight 3 with value 0 (by taking nothing). That's valid: taking nothing gives weight 0, not 3. However, the combination: take the item (weight 2) and then fill the rest with nothing results in total weight 2, not 5. But dp[5] uses dp[3] which is 0, implying we have a subset that weighs exactly 3? But we don't; but the dp[3] entry being 0 means that with weight exactly 3, the best value is 0? Actually if we haven't found a way to achieve weight 3 exactly, dp[3] should be -inf to indicate impossible. But we set it to 0 initially, so it treats "weight exactly 3 with value 0" as achievable, which is false. However, does this affect answer? Because in the end, dp[W] may be larger than true max if it uses impossible states. But standard 0-1 knapsack with dp initialized to 0 works because we only care about maximum value for weight at most W, not exactly W. Indeed, dp[c] after DP can be interpreted as the maximum value achievable with total weight ≤ c. Because the DP transition dp[c] = max(dp[c], dp[c-w] + v) effectively considers adding an item to a state that might not exactly weigh c-w, but dp[c-w] is the best value for weight at most c-w. The DP is actually solving the unbounded? Let's analyze: In the standard 0-1 knapsack, when we initialize dp with zeros, we are solving the "bounded" knapsack where we can take any subset, and the DP yields for each capacity c, the maximum value with total weight not exceeding c. Because the recurrence uses the maximum from previous capacity c-w (which itself is maximum for weight ≤ c-w). This works because if we have a solution with total weight ≤ c-w, we can add the item to get total weight ≤ c, and the DP will track the maximum value. At the end, dp[W] is the answer.
Thus for group knapsack with 0 initialization, the same concept holds: dp[c] will be maximum beauty achievable with total weight ≤ c. The recurrence: new_dp[c] = max(old_dp[c], old_dp[c - weight] + beauty) for each option. This works because old_dp[c - weight] is the best beauty for weight ≤ c - weight (from previous groups). Adding an item of weight gives weight ≤ c. So final dp[W] is answer. We don't need to take max over all capacities. But we must be cautious: For group knapsack, we need to use old_dp (from previous groups) to compute new_dp. With 0 initialization, dp[0..W] = 0 at start. This means we assume for any capacity, we can achieve weight 0 with value 0 (which is true: we can take nothing, weight 0 ≤ any capacity). That's fine. But could we incorrectly use a state where old_dp[c - weight] is positive but corresponds to weight not exactly c-weight? Actually old_dp[c - weight] is the max beauty for weight ≤ c - weight. So if we add an item of weight, the total weight becomes ≤ (c - weight) + weight = c. So it's valid. So yes, dp[c] after DP will be max beauty for total weight ≤ c.
Thus we can use dp of length W+1 initialized to 0. For each group, we create a new array new_dp = dp (copy). Then for each option (wt, bt), for cap from wt to W: new_dp[cap] = max(new_dp[cap], dp[cap - wt] + bt). Note we use dp (old) not new_dp for the update, because we want to combine exactly one option from this group with the previous groups. After processing all options, set dp = new_dp.
At the end, answer = dp[W].
But is this correct for group knapsack? Let's test simple: Two groups each with one item (like standard 0/1 knapsack). Standard 0/1 can be done with this group method if each group is a single item. For group knapsack with 0 init, our procedure: new_dp = old_dp. For each option, we update new_dp[cap] = max(new_dp[cap], old_dp[cap - wt] + bt). Since only one option, after group, dp = new_dp. That's exactly same as 0/1 knapsack but using old_dp for the update? Actually standard 0/1 knapsack updates in-place, but when using old_dp for reference and writing to new_dp, it's also correct and prevents using an item twice. So works.
Thus our DP complexity: For each group, we iterate over all options and for each option we iterate cap from wt to W. Total operations sum over options of (W - wt + 1) ≤ total_options * W. Since total_options is at most n + number_of_components (which <= n + n = 2n). So at most 2000 * 1000 = 2e6, fine.
But we need to ensure that "none" option is allowed: by not taking any option from the group, we keep old_dp values; that's implemented by copying old dp to new_dp at start.
Thus answer = dp[W].
Now test with given examples.
Example 1:
n=3,m=1,w=5.
weights: [3,2,5]; beauty: [2,4,2]; edges: 1-2.
Components: {1,2} and {3}. For component {1,2}:
options: single node1: (3,2), node2: (2,4), all: sum_w=3+2=5, sum_b=2+4=6.
component {3}: options: node3: (5,2), all: (5,2) (same).
Now DP:
dp init [0,0,0,0,0,0] (size 6, indices 0..5)
Group1:
new_dp = dp
For option (3,2): cap from 3 to5: new_dp[3] = max(0, dp[0]+2=2) =>2; cap4: dp[1]+2=0+2=2 =>2; cap5: dp[2]+2=0+2=2 =>2.
For option (2,4): cap2: dp[0]+4=4 => new_dp[2]=4; cap3: dp[1]+4=4 => new_dp[3]=max(2,4)=4; cap4: dp[2]+4=4 => new_dp[4]=max(2,4)=4; cap5: dp[3]+4=0? Wait dp[3] old is 0, so 0+4=4 => new_dp[5]=max(2,4)=4.
For option (5,6): cap5: dp[0]+6=6 => new_dp[5]=max(4,6)=6.
So after group1: dp = [0,0,4,4,4,6]
Group2:
options: node3: (5,2), all: (5,2) basically same.
new_dp = dp
For option (5,2): cap5: old dp[0]+2=2, but new_dp[5] is max(6, 2)=6 remains.
Also consider option (5,2) again? It's duplicate but fine.
So dp remains [0,0,4,4,4,6].
answer dp[5]=6. matches example.
Example 2:
n=4,m=2,w=11.
weights: [2,4,6,6]; beauty: [6,4,2,1]; edges:1-2,2-3.
Components: {1,2,3} and {4}. For component1:
sum_w=2+4+6=12, sum_b=6+4+2=12.
singles: (2,6), (4,4), (6,2)
all: (12,12)
component2: sum_w=6, sum_b=1; singles: (6,1); all: (6,1) same.
DP:
Initialize dp[0..11]=0.
Group1:
new_dp = dp.
Process (2,6):
cap2: dp[0]+6=6 => new_dp[2]=6
cap3: dp[1]+6=6 => new_dp[3]=6
cap4: dp[2]+6=0+6=6? Actually dp[2] old is 0 =>6 => new_dp[4]=6
cap5: dp[3]+6=0+6=6 => new_dp[5]=6
cap6: dp[4]+6=0+6=6 => new_dp[6]=6
cap7: dp[5]+6=0+6=6 => new_dp[7]=6
cap8: dp[6]+6=0+6=6 => new_dp[8]=6
cap9: dp[7]+6=0+6=6 => new_dp[9]=6
cap10: dp[8]+6=0+6=6 => new_dp[10]=6
cap11: dp[9]+6=0+6=6 => new_dp[11]=6
Process (4,4):
cap4: dp[0]+4=4, but new_dp[4] currently 6, so stays 6.
cap5: dp[1]+4=4 -> new_dp[5]=max(6,4)=6
cap6: dp[2]+4=0+4=4 -> new_dp[6]=max(6,4)=6
cap7: dp[3]+4=0+4=4 -> new_dp[7]=6
cap8: dp[4]+4=0+4=4 -> new_dp[8]=6
cap9: dp[5]+4=0+4=4 -> new_dp[9]=6
cap10: dp[6]+4=0+4=4 -> new_dp[10]=6
cap11: dp[7]+4=0+4=4 -> new_dp[11]=6
Process (6,2):
cap6: dp[0]+2=2 -> new_dp[6] stays 6
cap7: dp[1]+2=2 -> 6
cap8: dp[2]+2=2 ->6
cap9: dp[3]+2=2 ->6
cap10: dp[4]+2=2 ->6
cap11: dp[5]+2=2 ->6
Process all (12,12): but weight 12 > W (11) so skip.
So after group1, dp = [0,0,6,6,6,6,6,6,6,6,6,6]? Let's list indices 0..11:
index0:0,1:0,2:6,3:6,4:6,5:6,6:6,7:6,8:6,9:6,10:6,11:6.
That means after first group, we can achieve max beauty 6 with weight at least 2, up to 11? Actually dp[2]=6, dp[3]=6,... all 6. So best so far is 6.
Group2: component2: options: (6,1) and all (6,1)
new_dp = dp (so initially new_dp = dp).
Process (6,1):
cap6: old dp[0] +1 =1, new_dp[6] currently 6 => stays 6.
cap7: dp[1]+1=1 => new_dp[7]=6
cap8: dp[2]+1=6+1=7! Because old dp[2] = 6 (from previous groups). So new_dp[8] = max(6, 6+1=7) = 7.
cap9: dp[3]+1=6+1=7 => new_dp[9]=7
cap10: dp[4]+1=6+1=7 => new_dp[10]=7
cap11: dp[5]+1=6+1=7 => new_dp[11]=7
Process all same weight 6, same beauty, but duplicate won't change.
So after group2, dp becomes: indices 0..5: same? Actually new_dp[0..5] remain from old dp: 0,0,6,6,6,6? Wait we updated from cap6 onward, but earlier indices unchanged. Let's list:
0:0
1:0
2:6
3:6
4:6
5:6
6:6 (max(6, dp[0]+1=1) =>6)
7:6 (max(6, dp[1]+1=1) =>6)
8:7 (max(6, dp[2]+1=7) =>7)
9:7 (max(6, dp[3]+1=7) =>7)
10:7 (max(6, dp[4]+1=7) =>7)
11:7 (max(6, dp[5]+1=7) =>7)
Thus answer dp[11]=7. Matches example.
Works.
So algorithm is correct.
Potential pitfalls: The DSU: we need to map 0-indexed. Ensure we handle large input. Use fast I/O.
Edge Cases:
When a component's total weight > W, the all option cannot be taken. That's fine because we skip it if weight > W; but we could still include it in options, but loop will skip because cap from wt to W will have no iteration if wt > W; we could avoid adding it if sum_w > W to reduce operations, but it's fine.
When a component's total weight <= W, we include all option.
Note: Could there be a scenario where picking no nodes from a component is not optimal? But we include none as option by not selecting any option, which is handled by copying old dp.
Thus the solution is straightforward.
Now let's also consider if there is any nuance: The problem states "from each friendship group he can either invite all Hoses, or no more than one." This means if we want to invite multiple from a group, we must invite all of them. So our options are correct. But could there be a scenario where we invite all but also some additional from the same group? That would be inviting all (since all includes all). So it's covered.
Thus we can implement.
Now complexities: O(n * α(n)) for DSU, O(n + comps) for building groups, O(total_options * W) for DP. n up to 1000, w up to 1000, so fine.
Implementation details:
We'll store options as vector<pair<int, int>> for each component.
Or we can store them in a list.
Pseudo:
int n, m, W;
cin >> n >> m >> W;
vector w(n), b(n);
for i=0..n-1: cin >> w[i];
for i=0..n-1: cin >> b[i];
DSU dsu(n);
for each edge: read xi yi; dsu.unite(xi-1, yi-1);
vector<vector> components(n); // list per root
for i=0..n-1: components[dsu.find(i)].push_back(i);
vector<vector<pair<int,int>>> groups; // each group options
for each root r where components[r] not empty:
comp = components[r];
int sum_w = 0, sum_b = 0;
vector<pair<int,int>> opts;
for (int i : comp) {
sum_w += w[i];
sum_b += b[i];
opts.push_back({w[i], b[i]});
}
opts.push_back({sum_w, sum_b}); // all option
groups.push_back(opts);
// DP
vector dp(W+1, 0);
for (auto& opts : groups) {
vector new_dp = dp; // copy
for (auto& p : opts) {
int wt = p.first, bt = p.second;
if (wt > W) continue; // but can skip earlier
for (int cap = wt; cap <= W; ++cap) {
// use old dp[cap - wt] which is previous dp (not new)
new_dp[cap] = max(new_dp[cap], dp[cap - wt] + bt);
}
}
dp = move(new_dp);
}
cout << dp[W] << endl;
That's it.
Potential issue: In the inner loop, we refer to dp[cap - wt] (old dp). Since we are updating new_dp based on old dp, it's correct. However, we need to ensure that we don't accidentally also consider the case where we combine two options from same group because we might update new_dp and then later use it for another option? We are using dp, not new_dp, so it's safe.
Now the complexity: total_options = sum(size+1) = n + number_of_groups. That's at most 2000. So inner loops total iterations ≤ sum over options of (W - wt + 1) ≤ total_options * W = 2e6. Very small.
We can also optimize by not adding all options if they are dominated. But not needed.
One nuance: The "all" option might be dominated by a single node option if weight less and beauty higher? But not necessarily. For DP, we include all.
But wait: There is also possibility of inviting zero nodes from a group, which is covered. However, is it possible to achieve the "all" selection by also selecting a single node? That would be more than all, so no.
Thus solution is correct.
Now, what about constraints: w_i up to 1000, but sum of weights could be up to 1000? Actually total weight of all nodes could be up to n*1000 = 1e6, but W is at most 1000. So we only care about total weight up to W.
Now let's double-check the group DP logic with a more complex case: Suppose a component has 2 nodes: w1=2,b1=5; w2=3,b2=4; sum_w=5,sum_b=9. Options: (2,5),(3,4),(5,9). And we can choose none. Suppose we have DP after previous groups. With our DP, we will consider each option using old dp. That's fine.
But could there be a scenario where we might want to take none from a component but also take some nodes from it? No.
Thus solution is correct.
Now we should ensure that we correctly treat nodes that are isolated (no friends). They form components of size 1. Options: (w_i,b_i) and (w_i,b_i) again. That's okay.
Now we can code.
Time Complexity: O(n * α(n) + (n + groups) * W) = O(nW). Space O(n + W).
But careful: The groups may be up to n (1000). So DP array of size 1001 is small.
Case: group where all option weight > W, but some singles are within. Works.
Now confirm that DP with copying works as intended: For each group, we start new_dp as dp (old). For each option, we update new_dp based on old dp. This ensures that we only add one option from the group, because each update uses only the old dp (before any option from this group). However, suppose we have multiple options; we might update new_dp for multiple caps; but each update is independent and does not combine options because each is using old dp only. At the end, we set dp = new_dp. So we are picking at most one option: we could pick none (if new_dp remains old dp for all caps) or pick exactly one option (if we update). But could we pick more than one? For that we would need an update that uses new_dp (which already includes an option from this group) to add another option. Since we use old dp, that cannot happen. So at most one option per group.
But what about if we have multiple options with the same weight/beauty? That's fine, it's still at most one.
Thus correct.
Now final code: We'll implement DSU. Alternatively, we could use DFS to find components. Since n is small, we can use adjacency list and BFS/DFS.
But DSU is simpler.
Edge Cases: m may be 0, then each node is its own component.
Now, code.
Potential performance: We'll read input using scanf/printf or fast cin/cout.
Then after reading edges, we do dsu.unite(x-1, y-1).
Then we create a vector of vectors for components: vector<vector> comps(n); but we can also use map from root to list. Since n <= 1000, we can just create comps of size n and if comps[root] is empty initially, we push, etc.
After building comps, we create groups.
One more nuance: The "all" option might be same as picking a single node if component size is 1, but we can still add it; but it's duplicate. Could that cause any issue? No.
But note: For component size 1, if we add both the single and all option, we will have two identical options. This could cause the DP to effectively allow "selecting that node" but the group DP will consider both options. However, that doesn't cause a problem because they are both representing the same selection. But it could cause that we update new_dp twice for the same weight/beauty, which is wasted but fine.
We could deduplicate by only adding all option if component size > 1. But not necessary.
Now, we also need to ensure that when we add all option, we do not also add an option that represents taking all nodes individually (i.e., if component size > 1, the all option is distinct from any single option). So it's fine.
Now final answer: dp[W].
But wait: In the DP, we copied dp to new_dp, then for each option we update new_dp using old dp. At the end, dp = new_dp. This yields dp[W] as maximum beauty with total weight ≤ W. However, we need to double-check the correctness of using dp[cap - wt] from old dp, which stores the best beauty for weight ≤ cap - wt from previous groups. When we combine with an option of weight wt, total weight becomes ≤ (cap - wt) + wt = cap. So dp[cap - wt] is the best beauty from previous groups with weight at most cap - wt. Adding the option's beauty gives a valid selection with weight at most cap. So dp[cap] after update is the best over all selections that include at most one option from this group and any from previous groups. That's correct.
One subtlety: The none option is represented by simply not choosing any option, i.e., new_dp[cap] = old dp[cap] initially. That covers the case of not selecting from this group.
Thus DP works.
Now let's test more:
Case: component with two nodes: w1=1,b1=1; w2=1,b2=1; sum_w=2,b=2. W=2. Options: (1,1),(1,1),(2,2). DP:
init dp[0..2]=0
Group:
new_dp = dp
For (1,1): update cap1: dp0+1=1 -> new_dp[1]=1; cap2: dp1+1=0+1=1 -> new_dp[2]=1
For second (1,1): same updates; but new_dp[1] already 1, cap2: dp1+1 =0+1=1 => no change.
For (2,2): cap2: dp0+2=2 -> new_dp[2]=max(1,2)=2.
So dp after group: [0,1,2]. answer dp[2]=2. That's max beauty 2 by taking both nodes (all). Also we could take only one node for beauty 1, but 2 is better. Works.
Case: component with w1=1,b1=100; w2=1000,b2=1; sum_w=1001,b=101; W=1000. Options: (1,100), (1000,1), (1001,101) (skip because >W). So group: new_dp = dp. For (1,100): update cap1: 100 -> dp[1]=100; then also for cap2..1000? Actually for cap from 1 to 1000: dp[cap-1] + 100, but old dp[cap-1] are 0 for all, so it sets new_dp[cap] = 100 for all cap >=1. So new_dp becomes [0,100,100,...]. For (1000,1): cap1000: dp[0] + 1 = 1, so new_dp[1000] = max(100, 1)=100. So after group, dp[1000]=100. That's best: take the node with weight 1, beauty 100. Good.
Now consider two groups: group1 with nodes (1,100), group2 with (1000,1). Then DP: group1 yields dp[cap]=100 for all cap>=1. Then group2: new_dp = dp, then for (1000,1): cap1000: old dp[0] + 1 = 1? Wait old dp[0]=0, but old dp[1000-1000]? Actually we compute new_dp[1000] = max(old dp[1000] (100), old dp[0] + 1 = 1) => 100. So answer 100. But what about taking both nodes? That would be two groups, we can take one from each: that would be weight 1+1000=1001 > W, so not allowed. So correct.
Thus algorithm stands.
Now check memory: groups could store options list as vector<pair<int,int>>. That's fine.
Now we should also consider that w_i and b_i are up to 1000 and 1e6 respectively, beauty sum can be up to 1e9 maybe, so use int? But maximum beauty: n=1000, each b_i up to 1e6, sum up to 1e9, fits in 32-bit signed? 1e9 < 2^31-1, so int is fine. However, DP values can go up to sum of all b_i <= 1e9, so still fits in int. But we might do addition, still safe. But to be safe, use long long? The problem output may require up to 1e9, int is enough (2.147e9). But sum could be 10^9, but if all b_i=10^6, sum = 10^9, okay. However, if n=1000, b_i=10^6, sum=1e9 exactly. So int works. But we could use long long for safety. I'll use long long.
Now confirm constraints: n ≤ 1000, w ≤ 1000, but m is not given upper bound except that it is ≤ n(n-1)/2, which for n=1000 is about 500k, still fine.
Now implement DSU quickly.
Now let's consider if we need to consider the possibility that we may want to take all nodes from a component and also take one node from it? That's not allowed because taking all includes that node. So no.
Now let's test a scenario: component with 3 nodes: w1=2,b1=5; w2=2,b2=5; w3=2,b3=5; sum_w=6,b=15; W=5. Options: singles: (2,5) each, all: (6,15) skip because >W. So best is take at most one node, but can take only one, max beauty 5. But maybe we could take two? Not allowed. So answer 5. Our DP: group: new_dp = dp; process each (2,5) option. For each, it will set new_dp[cap] = max(old_dp[cap], old_dp[cap-2]+5). Since old_dp[cap-2] is 0 for all initially, after first (2,5), new_dp[2]=5, new_dp[3]=5? Actually for cap=2: dp[0]+5=5 -> new_dp[2]=5; cap=3: dp[1]+5=0+5=5 -> new_dp[3]=5; cap=4: dp[2]+5=0+5=5 -> new_dp[4]=5; cap=5: dp[3]+5=0+5=5 -> new_dp[5]=5. After second (2,5), we again use old dp, which is 0 everywhere except? But careful: We use old dp, not new_dp. So for second option, old dp[cap-2] is still 0 because old dp hasn't changed. So the second option doesn't change anything because we are maxing with 5 again. So after group, dp = [0,0,5,5,5,5] (but only weight 2+? Actually dp[3]=5? But weight exactly 3 cannot be achieved with a single item of weight 2? However, with the DP approach, dp[3] becomes 5 because it used old dp[1] which is 0, implying we take the item (weight 2) and have leftover capacity 1, so total weight <=3, and the actual weight is 2. So dp[3]=5 is fine. So answer dp[5]=5. Good.
Now if we had two groups each with a node weight 2, we could take both, total weight 4, beauty 10, if W=5. Our DP with group method would handle that.
Now consider a tricky case: component with size 2: w1=2,b1=3; w2=3,b2=5; sum_w=5,b=8; W=5. Options: (2,3),(3,5),(5,8). DP would consider:
initially dp=0
group: new_dp = dp
(2,3): set cap2:3, cap3:3, cap4:3, cap5:3
(3,5): set cap3: max(3, dp0+5=5) -> 5; cap4: max(3, dp1+5=5) ->5; cap5: max(3, dp2+5 =? dp2 old is 0? Actually old dp[2] is 0, so 0+5=5) ->5 (but we might later update)
Wait careful: After first option, we haven't updated new_dp for cap2,3,4,5? Actually we are using old dp, which is all zeros, to compute these updates. So (2,3) updates new_dp: cap2=3, cap3=3, cap4=3, cap5=3. Then (3,5) updates new_dp using old dp (still all zeros). So cap3: max(3,0+5=5) ->5; cap4: max(3,0+5=5) ->5; cap5: max(3,0+5=5) ->5. Then (5,8): cap5: max(5,0+8=8) ->8. So new_dp after group: cap0=0, cap1=0, cap2=3, cap3=5, cap4=5, cap5=8. So dp after group = [0,0,3,5,5,8]. That corresponds to: choose none =>0; choose node1 => weight2, beauty3; choose node2 => weight3, beauty5; choose all => weight5, beauty8. That's correct.
Now if we had capacity 4, answer would be dp[4]=5, which is either node2 (weight3, beauty5) or node1+??? Actually cannot take both, so max beauty is 5, correct.
Thus DP works.
Now let's think about the problem constraints: n up to 1000, w up to 1000. But sum of w_i could be up to 1e6, but we only care up to 1000. So DP is fine.
Now we could consider alternative: treat each component as a "knapsack group" where we can take at most one item from it, but also the whole group is an item. That's exactly what we do.
Now we must be careful: There's also possibility to take all nodes but also take an extra node from another component. That's allowed; DP handles that.
Thus solution is correct.
Now, we might also need to consider that we should not include the "all" option if it's weight > W because it's impossible. In DP, we can skip iteration if wt > W.
Now final code.
But before finalizing, consider if there is any scenario where the DP with 0 initialization could produce a value that is not achievable due to using unreachable previous states? Let's double-check: In standard 0/1 knapsack DP with 0 initialization, the DP's correctness for max value with weight ≤ capacity is well-known. Similarly for group knapsack with 0 init, it's also correct because we treat dp[c] as best value for weight at most c. The recurrence new_dp[c] = max(old_dp[c], old_dp[c-w] + v) is valid because if old_dp[c-w] is the best value for weight at most c-w, adding the item yields a solution with weight at most c, and we compare with not taking the item. So it's correct. And the base dp array after no groups is all zeros, which means with weight at most any capacity, the best beauty is 0 (by taking nothing). That's valid.
Now we need to ensure that the "at most" property holds: after processing groups, dp[c] might be larger than dp[c-1]? Actually it's non-decreasing because if you can achieve beauty X with weight ≤ c-1, you can also achieve it with weight ≤ c. So dp is monotonic non-decreasing. Our DP might not enforce monotonicity but it will be true because we only take max. But we don't rely on it.
Thus answer is dp[W].
Now code details:
We'll use vector<vector> comps(n); but after DSU we can create a map from root to index. Because we need to iterate over roots that have at least one member.
Simplify:
vector root_id(n, -1);
int groups_count = 0;
vector<vector> components; // list of nodes
for (int i = 0; i < n; i++) {
int r = dsu.find(i);
if (root_id[r] == -1) {
root_id[r] = groups_count++;
components.push_back({});
}
components[root_id[r]].push_back(i);
}
Then for each component in components, compute options.
Alternatively, we can store sums per root using map.
Now implement.
Now check for potential integer overflow: dp values up to sum of beauties up to 1e9, use int, but safe. Use long long for safety.
Now code.
We'll also include fast I/O.
Let's write final code.
But wait, there is another nuance: The problem states that if you invite all Hoses from a friendship group, you can't also invite any other Hoses from that group because that would be extra. But it's covered.
Now final code.
But before final answer, I want to think if there is any alternative interpretation: Could the phrase "no more than one" mean you can invite either zero or exactly one? Usually "no more than one" means zero or one. So we have that.
Now confirm with second example: They choose one from first group (Hos 1) and the only one from second group. That matches.
Now the problem constraints: w_i up to 1000, W up to 1000, b_i up to 10^6. DP using int is okay.
Now let's test on edge: n=1000, all isolated, all w_i=1, b_i=1, W=1000. Options each group: two options: (1,1) and (1,1). Our DP would process 1000 groups, each with one node, but also duplicate "all" option for size1 groups (which is same). That means each group has 2 options. However, we would be adding duplicate options, but it's fine. However, the DP complexity: total options = 1000*2 = 2000, times W=1000 = 2e6, fine.
Now consider that a component might have size up to 1000. Then options = size+1 = up to 1001. total_options = n + comps <= 2000. But if there is one giant component of size 1000, then options = 1001, which is fine.
Now check: For such large component, the DP inner loop will process each option, each takes up to W iterations. So at worst, total operations ~1001*1000 = 1e6, still fine.
Now code.
Now, I want to double-check the group DP implementation. We'll implement as:
vector dp(W+1, 0);
for (auto& opts : groups) {
vector new_dp = dp;
for (auto& [wt, bt] : opts) {
if (wt > W) continue;
for (int cap = wt; cap <= W; ++cap) {
new_dp[cap] = max(new_dp[cap], dp[cap - wt] + bt);
}
}
dp = move(new_dp);
}
Yes.
Now confirm that we need to use long long for dp. We'll define dp as long long.
Now also note: The "all" option may have weight <= W but beauty could be large. So it's fine.
Now final answer.
But wait, consider scenario: If a component has sum_w <= W, then the "all" option may dominate picking a single node. However, is it possible that picking all nodes yields higher beauty but also we could combine with other groups? That's fine.
Now think about possibility: Could it be beneficial to not pick any node from a component even though you could pick one? DP handles.
Thus finalize.
Now I'll write the code in C++.
Potential bug: When we create components via DSU, we need to be careful that we don't have leftover roots that are not used. But we can handle with map.
Implementation:
int n, m, W;
cin >> n >> m >> W;
vector w(n), b(n);
for (int i=0; i<n; i++) cin >> w[i];
for (int i=0; i<n; i++) cin >> b[i];
DSU dsu(n);
for (int i=0; i<m; i++) {
int x, y; cin >> x >> y; x--; y--;
dsu.unite(x, y);
}
// Build components
vector root_id(n, -1);
vector<vector> comps;
for (int i=0; i<n; i++) {
int r = dsu.find(i);
if (root_id[r] == -1) {
root_id[r] = comps.size();
comps.emplace_back();
}
comps[root_id[r]].push_back(i);
}
// Build group options
vector<vector<pair<int,int>>> groups;
for (auto& comp : comps) {
int sum_w = 0, sum_b = 0;
vector<pair<int,int>> opts;
for (int i : comp) {
sum_w += w[i];
sum_b += b[i];
opts.emplace_back(w[i], b[i]);
}
opts.emplace_back(sum_w, sum_b); // all option
groups.push_back(opts);
}
// DP
vector dp(W+1, 0);
for (auto& opts : groups) {
vector new_dp = dp;
for (auto& [wt, bt] : opts) {
if (wt > W) continue;
for (int cap = wt; cap <= W; ++cap) {
if (dp[cap - wt] + bt > new_dp[cap])
new_dp[cap] = dp[cap - wt] + bt;
}
}
dp = move(new_dp);
}
cout << dp[W] << endl;
Now test with examples.
Example 1:
Input:
3 1 5
3 2 5
2 4 2
1 2
Our code should output 6.
Example 2:
Output 7.
Now check with custom: n=1,m=0,w=0? But w>=1 per constraints. But if W=0? Actually constraint says 1 ≤ w (maximum total weight). So W>=1. So dp array length at least 1.
Now consider scenario: W=0? Not possible. So fine.
Now we might want to use faster I/O: ios_base::sync_with_stdio(false); cin.tie(nullptr); etc.
Now we need to implement DSU properly.
Let's write DSU:
struct DSU {
vector parent, size;
DSU(int n) : parent(n), size(n, 1) { iota(parent.begin(), parent.end(), 0); }
int find(int x) { return parent[x] == x ? x : parent[x] = find(parent[x]); }
void unite(int x, int y) {
x = find(x); y = find(y);
if (x == y) return;
if (size[x] < size[y]) swap(x, y);
parent[y] = x;
size[x] += size[y];
}
};
Yes.
Now compile and test.
Potential bug: The sum of beauties can be up to 1e9, but we are storing in long long just in case, but dp values are long long. For dp[cap - wt] + bt, we add bt (int) to long long, fine.
Now confirm that we are not using any memory heavy.
Now consider alternative approach: The group DP can be done in-place if we iterate capacities in reverse and iterate options in any order but using a temporary array to store old dp. Since we need old dp unchanged, copying is easier.
Copying dp array of size 1001 each group is trivial.
Now we are done.
Now let's verify one more scenario: If a component's total weight is exactly W, and all singles are also weight <= W, DP will consider all.
Now what if W is large, say 1000, and sum_w of a component is 2000, we skip all option due to weight > W, but singles may be selected. Fine.
Now double-check that we haven't missed something: Could it be that from a group we can invite all Hoses, but also invite additional Hoses from other groups? Yes, DP allows that.
Now confirm that the group's "all" option does not conflict with also taking individual nodes from that same group because DP only picks one option.
Thus final answer.
Now we will produce the final solution.
But wait: There is a nuance: The phrase "from each friendship group he can either invite all Hoses, or no more than one." Could it be interpreted as: For each group, if you invite any Hose from that group, you must either invite all of them, or just one (i.e., you cannot invite two unless you invite all). That is exactly our interpretation.
Thus the solution is correct.
Now I'll write the final answer in the required format.
Note: The problem originally is from Codeforces (Arpa's weak amphitheater?? Actually it's "Hoses"? Might be from "Arpa's weak amphitheater"? But here they are Hoses, probably a story. The solution is group knapsack.
Now we must output a single integer.
Now write final code.
One more thing: In the DP, when we update new_dp[cap], we use dp[cap - wt] + bt. dp[cap - wt] might be 0 even if we haven't used any group? That's fine because dp[0] = 0 is valid; for cap-wt>0, if dp[cap-wt] is 0 but that might correspond to not using any items from previous groups? Actually after processing some groups, dp[cap-wt] may be 0 because we haven't achieved that weight exactly? But dp is defined as max beauty for weight ≤ cap-wt. So dp[cap-wt] = 0 means the best we can do with weight ≤ cap-wt is 0 (i.e., take nothing). That is a valid state: we can take nothing from previous groups, then take this option, resulting in total weight ≤ cap, beauty = bt. This is valid. So it's fine.
Now I think everything is correct.
Now finalize. ```cpp
#include <bits/stdc++.h>
using namespace std;
struct DSU {
vector parent, sz;
DSU(int n) : parent(n), sz(n, 1) {
iota(parent.begin(), parent.end(), 0);
}
int find(int x) {
return parent[x] == x ? x : parent[x] = find(parent[x]);
}
void unite(int x, int y) {
x = find(x); y = find(y);
if (x == y) return;
if (sz[x] < sz[y]) swap(x, y);
parent[y] = x;
sz[x] += sz[y];
}
};
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
code
int n, m, W;
cin >> n >> m >> W;
vector<int> w(n), b(n);
for (int i = 0; i < n; ++i) cin >> w[i];
for (int i = 0; i < n; ++i) cin >> b[i];
DSU dsu(n);
for (int i = 0; i < m; ++i) {
int x, y;
cin >> x >> y;
--x; --y;
dsu.unite(x, y);
}
// build components
vector<int> root_id(n, -1);
vector<vector<int>> comps;
for (int i = 0; i < n; ++i) {
int r = dsu.find(i);
if (root_id[r] == -1) {
root_id[r] = comps.size();
comps.emplace_back();
}
comps[root_id[r]].push_back(i);
}
// options for each component
vector<vector<pair<int, int>>> groups;
for (const auto& comp : comps) {
int total_w = 0, total_b = 0;
vector<pair<int, int>> opts;
for (int i : comp) {
total_w += w[i];
total_b += b[i];
opts.emplace_back(w[i], b[i]); // single hose
}
opts.emplace_back(total_w, total_b); // whole group
groups.push_back(opts);
}
// group knapsack DP
vector<long long> dp(W + 1, 0);
for (const auto& opts : groups) {
vector<long long> new_dp = dp; // start by not taking any option
for (const auto& [wt, bt] : opts) {
if (wt > W) continue;
for (int cap = wt; cap <= W; ++cap) {
// use the state before this group (dp) to ensure at most one option
if (dp[cap - wt] + bt > new_dp[cap]) {
new_dp[cap] = dp[cap - wt] + bt;
}
}
}
dp = move(new_dp);
}
cout << dp[W] << '\n';
return 0;