Roma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind.
Roma has a choice to buy exactly one of n different weapons and exactly one of m different armor sets. Weapon i has attack modifier a_i and is worth ca_i coins, and armor set j has defense modifier b_j and is worth cb_j coins.
After choosing his equipment Roma can proceed to defeat some monsters. There are p monsters he can try to defeat. Monster k has defense x_k, attack y_k and possesses z_k coins. Roma can defeat a monster if his weapon's attack modifier is larger than the monster's defense, and his armor set's defense modifier is larger than the monster's attack. That is, a monster k can be defeated with a weapon i and an armor set j if a_i > x_k and b_j > y_k. After defeating the monster, Roma takes all the coins from them. During the grind, Roma can defeat as many monsters as he likes. Monsters do not respawn, thus each monster can be defeated at most one.
Thanks to Roma's excessive donations, we can assume that he has an infinite amount of in-game currency and can afford any of the weapons and armor sets. Still, he wants to maximize the profit of the grind. The profit is defined as the total coins obtained from all defeated monsters minus the cost of his equipment. Note that Roma must purchase a weapon and an armor set even if he can not cover their cost with obtained coins.
Help Roma find the maximum profit of the grind.
Input
The first line contains three integers n, m, and p (1 ≤ n, m, p ≤ 2 ⋅ 10^5) — the number of available weapons, armor sets and monsters respectively.
The following n lines describe available weapons. The i-th of these lines contains two integers a_i and ca_i (1 ≤ a_i ≤ 10^6, 1 ≤ ca_i ≤ 10^9) — the attack modifier and the cost of the weapon i.
The following m lines describe available armor sets. The j-th of these lines contains two integers b_j and cb_j (1 ≤ b_j ≤ 10^6, 1 ≤ cb_j ≤ 10^9) — the defense modifier and the cost of the armor set j.
The following p lines describe monsters. The k-th of these lines contains three integers x_k, y_k, z_k (1 ≤ x_k, y_k ≤ 10^6, 1 ≤ z_k ≤ 10^3) — defense, attack and the number of coins of the monster k.
Output
Print a single integer — the maximum profit of the grind.
Example
Input
2 3 3
2 3
4 7
2 4
3 2
5 11
1 2 4
2 1 6
3 4 6
Output
1
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 weapons: each has attack modifier a_i and cost ca_i.
Given m armors: each has defense modifier b_j and cost cb_j.
Given p monsters: each has defense requirement x_k, attack requirement y_k, and reward z_k.
Roma chooses exactly one weapon and exactly one armor. Then he can defeat any subset of monsters such that for each defeated monster, a_i > x_k and b_j > y_k. So the chosen weapon and armor define a region in the monster (x,y) space: monsters with x < a_i and y < b_j are defeatable. Note: a_i and b_j are strictly greater than x and y respectively. So monster is defeatable if x < a_i and y < b_j (since all integers, a_i > x_k etc). Actually condition: a_i > x_k and b_j > y_k. So yes.
He can defeat any number of them, each at most once. So total reward from monsters is sum of z_k for all monsters with x_k < a_i and y_k < b_j. Profit = (sum of z_k) - ca_i - cb_j.
We need max over i, j of (sum_{k: x_k < a_i and y_k < b_j} z_k - ca_i - cb_j).
n,m,p up to 2e5. a_i and b_j up to 1e6, x,y up to 1e6, z_k up to 1000 (small, but many). So total reward sum could be large? p up to 2e5, each z up to 1e3 => total sum up to 2e8, fits in 32-bit signed? 2e8 < 2^31, but profit may be negative; ca_i and cb_j up to 1e9 each, so profit could be negative up to -2e9. But we'll use 64-bit.
Goal: compute max_{i,j} (f(a_i,b_j) - ca_i - cb_j) where f(A,B) = total reward from monsters with x < A and y < B.
We have to efficiently compute this.
We can think of the weapons and armors as points in (a_i, ca_i) and (b_j, cb_j). The function f(A,B) is like a 2D prefix sum over monsters. But we need to evaluate for many (A,B). Classic problem: given two sets, we want max of (pref(A,B) - costA(A) - costB(B)). This resembles "maximum over pairs of f(A,B) minus costs" where f is defined by sum of rewards of points that are dominated by (A,B) in terms of (x < A and y < B). One approach: sort weapons by a_i, sort armors by b_j, and process events.
We can treat monsters as points (x, y) with weight z. We want for each armor b_j, compute something? Or we can iterate over weapons and maintain some data structure for armors.
Given that both n,m up to 2e5, O(n*m) impossible. Need O((n+m+p) log something).
We can think of: For each weapon (a, ca), the set of monsters with x < a is those with x <= a-1. But note: a_i > x_k, so x_k <= a_i-1. Similarly for armor.
So we could compress coordinates of a_i, b_j, and monsters' x,y.
Standard solution: Sort weapons by attack a_i ascending. For each weapon, we want best armor j to pair with it: profit = reward_sum(x<a_i, y<b_j) - ca_i - cb_j. So if we precompute for each armor j a value g(b_j) = something like reward_sum for that armor's threshold minus its cost, we could update as we increase a_i.
But note: reward_sum(x<a_i, y<b_j) depends on both a_i and b_j. If we process weapons in increasing a, then as a increases, new monsters become available (those with x between previous a and current a). Those monsters can be added to a data structure over b (armor thresholds). Specifically, for a given b_j, adding a monster with (x_k, y_k, z_k) that satisfies x_k < current a_i (automatically because we add when a_i surpasses x_k) contributes to the sum for all armors with b_j > y_k. So it's like we have a 2D partial sum: we add monsters one by one (by x), and for each armor we need to know total reward from monsters with y < b_j. So if we maintain a Fenwick tree or segment tree over y-coordinate (compressed b values or y values), where we add z_k to position y_k (or to all positions > y_k? Actually we need for each armor b_j, sum of z_k for y_k < b_j. So if we add each monster's z_k to the point y_k, then the prefix sum up to b_j-1 gives the sum. Alternatively, we could add to all positions > y_k? But typical: we maintain BIT over y coordinates (discretized) where we add z_k at index of y_k (or after). Then the prefix sum up to (b_j - 1) gives sum_{monsters with y < b_j}. However careful: We only consider monsters already added (with x < current a_i). So we maintain a BIT that holds contributions of added monsters. For each armor b_j, we can query sum over y < b_j.
So for each weapon i (with attack a_i), we first add all monsters with x < a_i (that haven't been added yet) to the BIT: for each such monster, we add z_k at its y coordinate (so later queries for armor thresholds). Then we need for each armor j: profit_ij = (BIT.prefix(b_j-1)) - ca_i - cb_j. Since ca_i is constant for the weapon, we need max over j of (BIT.prefix(b_j-1) - cb_j) - ca_i.
Thus, for each weapon i, if we precompute value H(b) = (prefix sum up to b-1 from BIT) - cb for each armor b, and then take the maximum H(b) over armors, then profit_i = max_b H(b) - ca_i.
We need to update BIT as we increase a_i (by processing weapons in sorted order). However, H(b) depends on the BIT which changes as we add monsters. So we need a data structure that can maintain, for each armor b_j, the value val_j = current prefix sum for b_j minus cb_j, and support updates to the BIT (which are point updates on y: add z to a y coordinate) that affect val_j for all b_j with b_j > y_k (since prefix sum up to b_j-1 changes). Actually, after adding a monster at y_k with weight z, the prefix sum for any b_j > y_k increases by z. For b_j <= y_k, the prefix sum unchanged. So the effect on val_j is: for all j such that b_j > y_k, val_j += z. That's a range update over j sorted by b_j. So we need to maintain an array of val_j (for each armor) with range add operations (add z to all armors with b > y) and then query the maximum over j of val_j.
Since m can be up to 2e5, we can sort armors by b_j, and use a segment tree that supports range add and global max query. That's efficient.
Alternatively, we could maintain the BIT for prefix sum and for each weapon compute max over j by scanning all j? Not possible.
Thus approach:
Read weapons (a_i, ca_i). Sort weapons by a_i ascending.
Read armors (b_j, cb_j). We'll need to sort them by b_j as well, and maybe compress. We'll build a segment tree over the sorted list. But careful: The value for armor j depends on its b_j and its own cost cb_j. Initially, before any monsters added, prefix sum = 0, so val_j = -cb_j. So initial values in segment tree: for each armor j (sorted by b_j), set leaf value = -cb_j.
Read monsters (x_k, y_k, z_k). We'll sort monsters by x ascending.
Process weapons in increasing a_i. For each weapon i:
Add all monsters with x_k < a_i (i.e., those not yet added) to the data structure: For each such monster, do a range add on the segment tree: add z_k to all armors with b > y_k? Actually prefix sum up to b_j-1 increases by z_k if b_j > y_k. So yes, for all armors whose b_j > y_k, val_j += z_k. So we need to find the index in sorted armors list where b_j > y_k. Since armors sorted by b, we can binary search to find the first index with b > y_k, then range add from that index to end.
But careful: prefix sum up to b_j-1: for b_j exactly equal to some value, we need to consider strict inequality: monster is defeated if b_j > y_k. So for an armor with b_j, the condition for monster to be counted is y_k < b_j. So for a given monster (y_k), all armors with b_j > y_k will include it. So indeed, range add to indices where b_j > y_k. Equivalent to if we treat b_j sorted, and we find the first armor with b_j > y_k. However, what about armors with b_j == y_k? Since need b_j > y_k, those with b_j == y_k do NOT count the monster. So we should add only to indices where b_j > y_k. That's correct.
After adding all monsters with x < a_i, we query the segment tree for maximum value among all armors: max_val = max_j ( prefix_sum(b_j-1) - cb_j ). Then profit for this weapon = max_val - ca_i. Keep global maximum profit over all weapons.
Note: we must consider that we might also consider weapon without any monsters? That is fine; max_val might be negative (since -cb_j can be negative). So profit could be negative. But we want maximum profit; it could be negative if all options lose money, but the problem asks to maximize profit, and presumably could be negative? Probably answer could be negative? But we can also decide not to defeat any monsters? He must buy exactly one weapon and armor, but can defeat zero monsters. So profit = -ca_i - cb_j. That's captured by initial val_j = -cb_j and no monsters added, so max_val is max over -cb_j, then subtract ca_i. So negative values are considered.
Edge Cases: There might be multiple weapons with same a_i. We should process all weapons, and for each we need to have added monsters with x < a_i. If weapons have same a_i, we should ensure that monsters are added only once before processing the first of them, and then for subsequent weapons with same a_i, we don't add again. So typical: sort weapons ascending by a_i; maintain a pointer over sorted monsters (sorted by x). For each weapon in order, while monster pointer index < p and monster.x < a_i, add that monster. Note: condition: a_i > x_k. So if a_i == x_k, then not added because we need strict >. So we add while monster.x < a_i. That's correct.
What about armors with same b? That's fine; each has its own cb_j. Segment tree stores values per armor (by index in sorted order). Duplicate b's are fine; for range add, we consider each armor individually.
Now complexity: Sorting O(n log n + m log m + p log p). Segment tree over m elements supports range add and max query in O(log m). For each monster added, we do a range add. Total monsters added = p (each once). So total range adds = p, each O(log m). For each weapon (n), we query max O(log m). So total O((n + p) log m). Good.
But there is nuance: The range add is "add z to all indices where b_j > y_k". Since armors sorted by b, we need to find the first index with b > y_k. Using binary search on sorted b array (we can precompute list of sorted b values). Since we have to do this for each monster, binary search O(log m). So each monster addition: binary search + range add = O(log m). That's fine.
We need to be careful about indexing: Let armor list sorted by b_j (ascending). For a given y_k, we find the smallest index idx such that b_j > y_k. Then do range add on [idx, m-1]. But careful: If no such armor (i.e., all b_j <= y_k), then no range add needed. And if idx == 0, then all get added.
Segment tree implementation: we need to support range addition and query of max. This is standard lazy propagation or a Fenwick tree with max? Fenwick can't easily do range add and global max? It can do range add and then query point values, but we need max over all points after many range adds. There is a trick: we can use a BIT to maintain differences and then compute each point's value by prefix sum, but to get max over all points we need to either iterate all (bad) or use a segment tree with lazy. So segment tree with lazy range add and max is appropriate.
Alternatively, we could use a BIT and maintain a multiset? Another approach: Since updates are only range add to suffix, we could maintain a Fenwick tree for the prefix sums of z added for each y, and for each armor j, compute prefix sum up to b_j-1 on the fly. Then the value for armor j is something like queryBIT(b_j-1) - cb_j. But then to get max over j we would need to compute that for each j for each weapon? Not efficient. So segment tree is the way.
But we can also reverse: Process armors similarly, but symmetric.
Hence, plan:
Read n,m,p.
Read weapons: store (a_i, ca_i). Sort weapons by a_i.
Read armors: store (b_j, cb_j). Sort armors by b_j. Create arrays B (sorted b) and C (corresponding cb) in that order.
Build segment tree over m leaves: leaf value = -cb_j.
Read monsters: store (x_k, y_k, z_k). Sort monsters by x.
Initialize monster pointer = 0.
Initialize ans = -inf (e.g., -1e18).
For each weapon i in sorted order:
While monster_ptr < p and monsters[monster_ptr].x < a_i:
y = monsters[monster_ptr].y; z = monsters[monster_ptr].z;
// find first index where B[idx] > y
idx = lower_bound(B.begin(), B.end(), y+1) ??? Actually we need first b_j > y. Since B sorted ascending, we want the first element greater than y. So we can use std::upper_bound(B.begin(), B.end(), y) which returns first > y. That's correct. So idx = upper_bound(B.begin(), B.end(), y) - B.begin(); // index from 0 to m.
If idx < m: segment_tree.range_add(idx, m-1, z);
monster_ptr++;
After adding all monsters with x < a_i, query segment_tree.get_max() -> max_val.
profit_i = max_val - ca_i.
ans = max(ans, profit_i).
After processing all weapons, output ans.
Edge Cases: What about weapons with a_i that are less than all monster x? Then no monsters added, max_val is just max over -cb_j. So profit = max(-cb_j) - ca_i. That's valid.
What about armor with b_j very small? The range add only applies to those with b_j > y_k. So small b_j might never get added, so they stay negative.
Now we need to be careful about large numbers: Use 64-bit integers.
Now, is there any other nuance? The problem says "Roma can defeat a monster if his weapon's attack modifier is larger than the monster's defense, and his armor set's defense modifier is larger than the monster's attack." That's strictly greater. So indeed a_i > x_k and b_j > y_k. Our condition x < a_i, y < b_j. So for adding monsters when processing weapon with a_i, we add monsters with x < a_i. Good.
Now about sorting monsters by x: We need to add monsters as soon as weapon's a becomes larger than x. Since we process weapons in ascending a, we add monsters in ascending x. That's fine.
Now about the range add: For a monster with y = y_k, the contribution to prefix sum for an armor with b_j is if y_k < b_j. So exactly b_j > y_k. So we add z to all armors with b_j > y_k. That's correct.
But wait: In our process, for a given weapon a_i, we add all monsters with x < a_i. Then for a particular armor b_j, the total reward from monsters is sum over those added monsters that also satisfy y < b_j. Since we only add monsters with x < a_i, and then for each armor we consider the prefix sum based on y only. However, the condition for monster to be counted for that armor is y < b_j, which we ensure by the range add to those armors with b_j > y. But note: Our range add adds z to all armors with b_j > y, but that means for an armor with b_j <= y, it does not get added. So after processing all monsters, the value for armor j = (sum of z over all added monsters with y < b_j) - cb_j. That's exactly the reward sum for that weapon's a_i condition. So it's consistent.
Now, important: The segment tree stores for each armor j the value = sum_{monsters added so far (with x < current a_i)} (z if y < b_j else 0) - cb_j. So indeed, after we finish adding monsters for the current weapon, the value for armor j is exactly the total reward for that weapon+armor pair. So the max over j gives the best armor for this weapon. Then subtract ca_i. Great.
Thus the algorithm should produce correct answer.
But we must also consider possibility of monsters with same x and y, but that doesn't matter.
Now we need to implement segment tree with lazy propagation for range add and max query. We'll store values as long long (int64). Number of operations up to 2e5, safe.
Now process weapons sorted by a: first weapon (2,3). Need to add monsters with x < 2: those with x=1 only. Monster (1,2,4): y=2, z=4. Find first b > 2: b values [2,3,5]; upper_bound(2) -> first >2 is 3 at index1. So range add idx1..2 (+4). After addition, leaf values: idx0: -4, idx1: -2+4=2, idx2: -11+4=-7. Max = 2. Profit = 2 - ca_i=2-3=-1. ans = max(-inf, -1) = -1.
Next weapon (4,7). Add remaining monsters with x < 4: monsters with x=2 and x=3 (since x<4: x=2 and x=3). Process one by one:
Monster (2,1,6): y=1, z=6. upper_bound(1) on b: first >1 is b=2 at index0. So range add [0,2] +6. Update: idx0: -4+6=2, idx1: 2+6=8, idx2: -7+6=-1. (Actually careful: previously idx1=2, idx2=-7, idx0=-4. After +6: idx0=2, idx1=8, idx2=-1.)
Monster (3,4,6): y=4, z=6. upper_bound(4) -> first >4 is b=5 at index2. So range add [2,2] +6. Update: idx2: -1+6=5. Now values: idx0=2, idx1=8, idx2=5. Max = 8. Profit = 8 - ca_i (7) = 1. ans = max(-1, 1) = 1. Output 1 matches.
Works.
Now we must also consider if there are weapons with a_i that are same as previous? For a weapon with same a, we should have same set of monsters added, so we can process them sequentially without adding new monsters in between. Since we process in sorted order, if multiple weapons have same a, after processing the first weapon we will have added all monsters with x < a. For the next weapon with same a, the while condition (monsters.x < a) will be false because we already advanced past all monsters with x < a (since we added them earlier). So it will just query the same BIT and compute profit. That's correct.
Now about armors: There might be multiple armors with same b. In range add, for b_j > y, those with b_j equal to y are not included. So if b == y, they don't get added. That's correct.
Now about coordinate compression: b values up to 1e6, but m up to 2e5, we can just sort the armor list and use indices. No need for compression beyond that.
Now about segment tree implementation: We'll need to store size maybe next power of two. Use 1-indexed or 0-indexed. We'll implement classic.
Pseudo:
struct SegTree {
int n;
vector tree, lazy;
void build(const vector& init) {
n = init.size();
tree.assign(4n, 0);
lazy.assign(4n, 0);
build(1,0,n-1,init);
}
void build(int node, int l, int r, const vector& init) {
if(l==r) { tree[node]=init[l]; return; }
int mid=(l+r)/2;
build(node2,l,mid,init);
build(node2+1,mid+1,r,init);
tree[node]=max(tree[node2],tree[node2+1]);
}
void push(int node) {
if(lazy[node]!=0) {
tree[node2] += lazy[node];
lazy[node2] += lazy[node];
tree[node2+1] += lazy[node];
lazy[node2+1] += lazy[node];
lazy[node]=0;
}
}
void range_add(int ql, int qr, long long val) { update(1,0,n-1,ql,qr,val); }
void update(int node, int l, int r, int ql, int qr, long long val) {
if(ql<=l && r<=qr) {
tree[node] += val;
lazy[node] += val;
return;
}
push(node);
int mid=(l+r)/2;
if(ql<=mid) update(node2, l, mid, ql, qr, val);
if(qr>mid) update(node2+1, mid+1, r, ql, qr, val);
tree[node] = max(tree[node2], tree[node2+1]);
}
long long query_max() { return tree[1]; } // entire range max
};
But note: We need to query max over all indices; indeed root gives max over whole array.
Now we need to store initial values: for each armor sorted by b, leaf = -cb_j.
Edge Cases: m may be 0? But constraints say m ≥ 1. So okay.
Now let's think about potential pitfalls:
The condition for monsters: a_i > x_k and b_j > y_k. Since we use x < a_i and y < b_j. That's correct.
Monsters can have same x,y etc.
The segment tree might need to handle large range addition values: z up to 1000, total sum up to 2e8, plus negative costs up to 1e9, so values around -1e9 to 2e8, fits in 64-bit. But we use long long.
The answer might be negative? For instance, if all weapon+armor costs are high and monsters give little. In that case we might need to output negative number. In problem statement, they didn't say profit can't be negative. So we should initialize ans to something like -1e18. Also note that max profit could be negative; we must compute it.
Are there any constraints about multiple weapons/armors with same a/b? Works.
Is there any scenario where using a weapon with a very high attack but low cost? Already considered.
Now we must also consider that we could possibly choose to defeat no monsters, but we still must buy equipment. That's captured.
Now let's consider if there are monsters with x or y values that are very high, bigger than all weapons or armors. Then they will never be added for any weapon (if a_i <= max x) but might be added for weapons with a_i > x. So okay.
Now consider if there are no monsters? p=0. Then we never add any. For each weapon, max_val = max_j(-cb_j). So profit_i = max_j(-cb_j) - ca_i. The best overall profit is max over i of ( -ca_i + max_j(-cb_j) ) = (max_i -ca_i) + max_j(-cb_j). Equivalent to - (min_i ca_i + min_j cb_j). So the answer is negative of sum of minimal costs? Actually max over -ca_i = -min ca_i, so ans = -min ca_i - min cb_j. That matches expectation: buy cheapest weapon and cheapest armor to minimize loss, profit negative. But wait: Is it allowed to buy any combination? Yes exactly one of each. So profit = -ca_i - cb_j. So maximum profit is - (min_i ca_i + min_j cb_j). Our algorithm: weapons sorted, no monsters added. For each weapon i, max_val = max_j(-cb_j) which is - min_j cb_j? Actually max over -cb_j is negative of the minimum cb_j? Because -cb_j is larger when cb_j is smaller. So max_j(-cb_j) = - (min cb_j). So profit_i = - (min cb_j) - ca_i. Then max_i profit_i = - (min cb_j) - min_i ca_i. So correct.
Now about handling weapons with a_i that are less than all x of monsters: They get zero monsters added, but the max_val is computed based on current BIT (which has no additions) so correct.
Now about weapon with a_i larger than all monster x: After processing all monsters, we will have added all monsters. So for the largest a_i, the segment tree will have all monster contributions applied. Then max_val is computed correctly.
Now overall algorithm seems solid.
But is there any nuance about the ordering of adding monsters? We add monsters with x < a_i. However, suppose there are monsters with x exactly equal to a_i? Not added because need strict >. So they are added only when a_i > x. That's right.
Now what about monsters with y exactly equal to b_j? Should not be counted. Our range add uses upper_bound(y) which adds to b_j > y. So if b_j == y, not added, correct.
Now we must be careful that we use upper_bound on the sorted array of b values. Since we need first index where b > y, using std::upper_bound on B vector works.
Now segment tree: range_add on [idx, m-1]. If idx == m, then no addition.
Now about the case when there are no armors? But m>=1.
Now we need to consider the possibility that the best profit involves not defeating any monster but maybe buying a more expensive armor? Actually profit = -ca_i - cb_j, so we want to minimize sum of costs. So indeed the best combination for no monsters is the cheapest weapon and cheapest armor. Our algorithm would capture that because for the weapon with minimum ca_i, the profit_i = max_j(-cb_j) - ca_i = -(min_j cb_j) - ca_i. That's the best. But what if there is a weapon that is not the cheapest, but because it allows monsters, yields higher profit? That's fine. Our algorithm considers all.
Now we need to ensure that we don't miss combinations where the weapon's a_i is less than some monster's x, but the armor's b_j is high, enabling monsters that are only constrained by a_i? Actually to defeat a monster, both conditions must hold. So if a_i is too low, that monster cannot be defeated regardless of armor. So correct.
Now what about the opposite: weapon high, armor low? Then monsters with high y are not defeatable. So correct.
Now we should also consider that maybe we don't need to consider all weapons? Could we just consider the ones that are "dominant"? For instance, if we have weapon i with higher attack and lower cost than weapon j, then weapon i dominates j because for any armor, profit_i >= profit_j (since more monsters maybe? Actually more attack can only increase the set of monsters (since x<a_i includes those with x<a_j if a_i > a_j) and cost is lower, so profit_i >= profit_j). But we don't need to do this optimization because we process all weapons; O(n log m) is fine.
But there is a nuance: For weapon i with a_i, the set of monsters that can be added is x < a_i. If we have weapon i with larger a_i but also larger ca_i, it might not dominate. So need to consider all.
Now about the segment tree: The values stored are per armor. But we might have many armors (2e5). The segment tree with 4*m nodes is fine.
Now we should think about memory and speed. All good.
Now we must also ensure we use fast I/O because input size large. Use scanf/printf or cin with sync.
Now we can code.
Potential tricky part: The segment tree query is only global max. However, do we ever need to query only a subset? Not in this approach. So we can just keep root value.
But is the root value always the maximum over the whole range? Yes, after updates, we maintain it.
Now we should also consider that the initial values might be negative; the segment tree root after building should be correct.
Now we need to think about the order of processing weapons: Could there be weapons with a_i that are not sorted ascending? We'll sort.
Now the algorithm:
Input.
Store weapons: vector<pair<int, int>> weapons; // a, ca
Sort weapons by a.
Store armors: vector<pair<int, int>> armors; // b, cb
Sort armors by b.
Create vector B (size m) for b values, and vector initVals (size m) for -cb.
Build segtree with initVals.
Store monsters: vector<tuple<int,int,int>> or struct.
Sort monsters by x.
Initialize pointer = 0.
Initialize ans = -1e18 (or LLONG_MIN).
For each weapon in sorted order:
while (ptr < p && monster.x < weapon.a):
auto [x,y,z] = monsters[ptr];
int idx = upper_bound(B.begin(), B.end(), y) - B.begin();
if (idx < m) seg.range_add(idx, m-1, z);
ptr++;
long long bestArmor = seg.query_max(); // max over j of (sum_z - cb_j)
long long profit = bestArmor - weapon.ca;
if (profit > ans) ans = profit;
Print ans.
Now consider if there are weapons with same a; as mentioned, fine.
Now test on some edge cases.
Edge case: All monsters have y large, beyond all armors b_j? Then for each monster, idx = upper_bound(y) might be m (no armor qualifies). So no updates. So profit only based on costs.
Edge case: All monsters have y small, then many updates to all armors. Works.
Edge case: Armor with b very small, may never get updates, but its -cb might be large (if cheap). That can be best if all monsters are not giving much.
Now verify correctness for a simple scenario: n=1,m=1,p=0. Weapon (a, ca), Armor (b, cb). profit = -ca - cb. Our algorithm: initVals = [-cb]. seg.root = -cb. Process weapon: no monsters, bestArmor = -cb, profit = -cb - ca = -(ca+cb). ans = that. correct.
Now scenario with p>0 but weapon's a < all monster.x: Then no monsters added. Same as above.
Now scenario where armor's b > all monster.y: Then each monster will update all armors? Actually if monster.y < min(b) then idx = 0, updates all armors. So all armors get same reward addition. But if some armors have lower b but still > all y? Actually if min b > all y, then for each monster, idx = 0, all armors get added. So all armors get same total reward sum. Then best armor is the one with smallest cb (i.e., largest -cb). So algorithm picks cheapest armor. Good.
Now scenario where armor's b is exactly some monster.y: that monster not counted for that armor. That's correct.
Now we need to think about potential integer overflow in segment tree: Use long long.
Now we also need to consider that p can be up to 2e5, and for each monster we do a binary search and range add. So 2e5 * log m (around 18) fine.
Now some optimizations: We could pre-sort armors and store B array.
Now confirm that we are not missing any monster contributions: For a given weapon a_i, after adding monsters with x < a_i, the segment tree contains contributions from exactly those monsters. So for each armor j, the stored value is sum over monsters with x < a_i and y < b_j minus cb_j. So max over j yields best armor for that weapon.
Now consider whether we need to consider that after adding monsters for a particular a_i, the segment tree values are changed permanently, meaning that for later weapons with larger a, the segment tree accumulates more monsters. That's correct because the reward for larger a includes more monsters. So we are reusing the segment tree.
Now consider the possibility of negative z? No, z >=1.
Now is there any scenario where we might need to also consider not defeating a monster even if it's eligible? But since monsters give positive coins, it's always beneficial to defeat all eligible monsters because there is no cost to defeat them. So Roma will always defeat all monsters that satisfy conditions. So the total reward is sum of all such monsters. So our approach of adding all monsters when eligible is correct.
Now test with random small cases to validate with brute force. But in analysis, we trust.
Now think about potential alternative: maybe we need to consider that Roma might not defeat all eligible monsters? No reason to skip because they give coins and no cost.
Now ensure we handle the case where weapon a_i is less than some monster x, but we still could defeat monsters with lower x? Yes we add only those with x < a_i, so that's correct.
Now also ensure that we treat a_i, b_j, x_k, y_k all up to 1e6, so sorting and binary search within those ranges is fine.
Now memory: segtree with 4*m ~ 800k, fine.
Now we can code.
But wait: There is one more nuance: The segment tree stores values for each armor j, but the range add affects all armors with b_j > y. However, note that for an armor j, the reward sum is over monsters with y < b_j. But when we add a monster, we add to all armors with b_j > y. But what about an armor with b_j exactly equal to y+something? Fine. But what about the scenario where multiple monsters have the same y? We add each separately, each adds to all b_j > y. So net effect is sum of z for all monsters with that y and less x conditions. That's correct.
Now check: When we add a monster, we add z to all armors with b > y. But the reward for an armor with b should be sum of z for monsters with y < b. So if we add z to all armors with b > y, then for an armor with b, the total reward becomes sum over monsters with y such that y < b? Actually, if we do suffix range add for each monster (add to b > y), then for a given armor b_j, its total reward = sum of z over all monsters added such that y_k < b_j. Because each monster with y_k adds to this armor only if b_j > y_k, i.e., y_k < b_j. So yes. So the suffix add is correct.
Now check with example: Monster y=2, b values [2,3,5]. For b=2 (equal), not added. For b=3, added. For b=5, added. So reward for b=2 includes only monsters with y <2; for b=3 includes y<3; etc. That's exactly the prefix sum over y when sorted.
Now the segment tree does range add on suffix starting from index where b > y. That's correct.
Now what about monsters with y that is larger than the maximum b? Then idx = upper_bound(y) returns m (since no b > y). So no add. That's correct: such monsters never contribute to any armor.
Now final step: answer might be negative; print as integer.
Now think about potential pitfalls: The segment tree might need to support large number of range adds. We must ensure lazy propagation doesn't cause stack overflow due to recursion depth. Recursion depth is log m, safe. But we can implement iterative segment tree with lazy? Simpler recursive is fine. However, with 2e5 elements, recursion depth for segment tree functions is O(log m) ~ 18, so fine. Number of recursive calls: each update touches O(log m) nodes; for 2e5 updates, total calls ~ 2e5 * 2log m ~ 7.2e6, fine. In C++ recursion overhead moderate but okay. Alternatively, we could implement iterative segment tree with lazy propagation using a segment tree on size 2^ceil(log2(m)). But I'll stick with recursive for simplicity, but need to be careful with recursion limit? Usually no, but if we implement a recursive function that goes depth up to 2log2(200000) ~ 18, it's fine. However, the recursion is for each node visited, not deep recursion; but we may call recursion many times but depth small. So fine.
Now let's double-check the sorting of weapons: We should sort by a_i. But there might be weapons with same a_i but different ca_i. They are all processed. The order among them doesn't matter because they share the same set of monsters (since a_i same). So we can process them all after adding monsters with x < a_i. However, if there are multiple weapons with same a, we must ensure that for the first weapon we add monsters with x < a, and for subsequent weapons with same a, we do not add monsters again. That works because while condition checks x < a_i, and after processing the first weapon, monster_ptr is at the first monster with x >= a_i (since all with x < a_i are added). For subsequent weapons with same a_i, condition x < a_i is still false for those monsters (since x >= a_i). So no further adds. So each monster added exactly once.
Now consider if there is a monster with x equal to a_i. It will not be added for any weapon with a_i. But if later weapon has a higher a > x, it will be added. So correct.
Now about the segment tree query: For each weapon we query the maximum value over all armors. That's O(log m). Good.
Now about initial answer: We could set ans = -1e18. But also we could compute some initial value: maybe ans = max_j(-cb_j) - min_i ca_i? But we'll just compute in loop.
Now consider if there are no weapons? n>=1.
Now implement.
Now I want to think if there is any alternative that might be more efficient? This is fine.
Now I recall a known problem: "CF 1380F? Actually this is Codeforces problem "Roma and Prefix Sums"? I'm not sure. But it resembles a problem from Codeforces Round #626? Possibly "World of Darkraft" problem? Actually I recall a Codeforces problem titled "Roma and Game with Monsters" or "World of Darkraft". I think it's Codeforces Round #138? Wait, there is a problem "World of Darkraft - 2"? Actually I recall a problem "Roma and Killing Monsters" but not sure. But the solution described is exactly as above: sort weapons, maintain segment tree over armors, add monsters as x increases.
Add monsters with x<5: monster (3,4,7): y=4, z=7. upper_bound(4) on B=[6,10] gives first >4 is 6 at idx0. So add [0,1] +7 => values: idx0: -4+7=3, idx1: -8+7=-1. max=3.
profit = 3 - 10 = -7. ans=-7.
Next weapon (8,5):
Add remaining monsters with x<8: monster (6,5,3): y=5, z=3. upper_bound(5) on B: first >5 is 6 at idx0. add [0,1] +3 => idx0:3+3=6, idx1:-1+3=2. max=6.
profit = 6-5=1. ans=1.
Now brute force: Evaluate all combos:
Weapon 5, armor6: monsters: x<5 and y<6? (3,4) yes, (6,5) x=6 not <5 => only first: reward=7 - costs 10+4= -7.
Weapon5, armor10: monsters: x<5 and y<10 => first monster qualifies, second not (x=6) => reward 7 -10-8= -11.
Weapon8, armor6: monsters: x<8 and y<6 => both? first: (3,4) y=4<6 qualifies. second: (6,5) y=5<6 qualifies, both: reward 7+3=10 - costs 5+4=1 => profit=1.
Weapon8, armor10: both qualify => reward 10 - costs 5+8= -3? Actually reward 10, cost 13 => -3. So max=1. matches.
Now test where multiple weapons with same a: Suppose n=2 both a=5, costs 10 and 12. Then for both weapons, after adding monsters for a=5, segment tree values same. Profit1 = max_val -10, profit2 = max_val-12. So we pick cheaper if same attack. That makes sense.
Now test where multiple armors with same b: Suppose m=2 both b=6, costs 4 and 6. Sort B: both 6, but we need to keep them as separate entries. Their order relative to each other might be arbitrary. Range add for a monster with y=5: upper_bound(5) on B=[6,6] gives first >5 is index0, then add from index0 to end includes both. So both get the same reward addition. Their values differ by -cb. So the cheaper one will have higher value. So max picks cheaper. Works.
Now test case where b_j values are not distinct and range add should not affect those with b == y. That's handled by upper_bound.
Now test scenario where some armor has b less than some monster y but still gets update from other monsters. That's fine.
Now we must also think about the maximum possible answer: p=2e5, each z=1000 => total reward 2e8, ca and cb up to 1e9, so profit up to 2e8 - 2e9 = -1.8e9, could be negative but also could be positive if cheap equipment and many monsters. So ans within range -2e9 to 2e8. Use long long.
Now implementation details:
We'll define structures:
struct Weapon { int a, ca; };
struct Armor { int b, cb; };
struct Monster { int x, y, z; };
Read input. Since p up to 2e5, we can use scanf or fast cin.
Sort weapons by a.
Sort armors by b; after sorting, create vector B(m), vector init(m).
For i from 0 to m-1: B[i] = armors[i].b; init[i] = -armors[i].cb.
Build segtree with init.
Sort monsters by x.
Then iterate.
Segment tree implementation:
class SegTree {
public:
int n;
vector tree, lazy;
SegTree(int _n, const vector& arr) {
n = _n;
tree.resize(4n);
lazy.resize(4n, 0);
build(1, 0, n-1, arr);
}
void build(int node, int l, int r, const vector& arr) {
if (l == r) {
tree[node] = arr[l];
return;
}
int mid = (l+r)/2;
build(node2, l, mid, arr);
build(node2+1, mid+1, r, arr);
tree[node] = max(tree[node2], tree[node2+1]);
}
void push(int node) {
if (lazy[node] != 0) {
tree[node2] += lazy[node];
lazy[node2] += lazy[node];
tree[node2+1] += lazy[node];
lazy[node2+1] += lazy[node];
lazy[node] = 0;
}
}
void range_add(int ql, int qr, long long val) {
if (ql > qr) return;
update(1, 0, n-1, ql, qr, val);
}
void update(int node, int l, int r, int ql, int qr, long long val) {
if (ql <= l && r <= qr) {
tree[node] += val;
lazy[node] += val;
return;
}
push(node);
int mid = (l+r)/2;
if (ql <= mid) update(node2, l, mid, ql, qr, val);
if (qr > mid) update(node2+1, mid+1, r, ql, qr, val);
tree[node] = max(tree[node2], tree[node2+1]);
}
long long query_max() {
return tree[1];
}
};
Now careful: The build recursion depth is log2(n) for each call, but it's fine.
Alternatively, we could use a Fenwick tree that maintains difference array and then query each point? But we need max over points after range adds. Not directly.
Segment tree with lazy is fine.
Now potential issue: When building tree, we need to ensure tree[1] holds global max. Works.
Now also need to consider that we might need to query after each weapon, which is O(1) (just root). So we just call query_max().
Now large input: Use scanf/printf.
Now test with sample.
Now potential overflow: sum of z can be up to 2e8, but we may add to segment tree values up to that plus costs up to 1e9, so tree values up to ~2e8 - 1e9? Actually -cb up to -1, plus additions up to 2e8, so final values maybe around -1e9 to +2e8. That fits in 64-bit.
Now we also need to consider that the answer might be negative and we output it as integer.
Now we must consider that weapons and armors have attributes up to 1e6, but monsters also up to 1e6. Sorting by those is fine.
Now think about the possibility of large m and many monsters with y values that cause many range adds to the suffix. That's fine.
Now complexity: O((n + p) log m). n, p up to 2e5, so about 4e5 * log(2e5) ~ 4e5*18 = 7.2e6 operations, plus overhead, should be fine.
Now check if we also need to consider that after we add a monster, the segment tree updates may cause O(log m) per update.
Now consider that we might need to consider both weapons and armors symmetrically; but our approach is fine.
Now about the ordering: What if we process weapons in descending order? Could also work. But ascending is typical.
Now think about corner case: If there is a monster with y = 0? But constraints: y >= 1. So y is positive.
Now think about the case where b_j can be 1. Then for a monster with y=0 (not possible) but with y=1, upper_bound(1) on b values: if b_j = 1, then b_j > 1? false because 1 > 1 false. So first >1 is if there is b=2 or larger. So armor with b=1 won't get monster with y=1. That's correct: need b > y, so if b=1, y=1 not counted.
Now one more nuance: The condition for monster is a_i > x_k and b_j > y_k. So if a_i = 2 and x_k = 1, ok. If a_i = 2 and x_k = 2, not ok. So x < a_i.
Now we used strict less-than for x and y.
Now everything seems consistent.
Now let's write final code.
But wait, there is a potential subtlety: The segment tree stores values for each armor based on the current set of monsters added. However, when we add a monster, we add its z to all armors with b > y. But what about the condition for the armor's reward: it should be sum over monsters with y < b_j. But note: The monsters added have x < current a_i. But later when we process a larger a_i, we add more monsters. So for a given armor, after adding those new monsters, the reward sum becomes sum over all monsters with x < current a_i and y < b_j. That's correct.
Now consider if we have two weapons with different a, say a1 < a2. For the larger a2, the segment tree contains contributions from all monsters with x < a2. For the smaller a1, we only had contributions from x < a1. So for each weapon, the segment tree state corresponds exactly to the set of monsters that are eligible given its a. So it's perfect.
Now we should also consider if there might be any advantage to skipping some monsters even if eligible? No.
Now confirm that the segment tree's global max correctly identifies the best armor for the current weapon. Since each leaf corresponds to an armor's profit contribution without weapon cost. The weapon cost is subtracted later. So yes.
Now just implement.
Now I realize that we must be careful about the data types: Use long long (int64). In C++, int is 32-bit, which may not hold sums up to 2e9? Actually 2e9 fits in signed 32-bit (2^31-1 = 2.147e9), but to be safe, use long long.
Now code.
Pseudo-code:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
struct Weapon {
int a, ca;
};
struct Armor {
int b, cb;
};
struct Monster {
int x, y, z;
};
int main() {
int n, m, p;
scanf("%d %d %d", &n, &m, &p);
vector weapons(n);
for (int i=0; i<n; ++i) scanf("%d %d", &weapons[i].a, &weapons[i].ca);
vector armors(m);
for (int i=0; i<m; ++i) scanf("%d %d", &armors[i].b, &armors[i].cb);
vector monsters(p);
for (int i=0; i<p; ++i) scanf("%d %d %d", &monsters[i].x, &monsters[i].y, &monsters[i].z);
code
sort(weapons.begin(), weapons.end(), cmpWeapon);
sort(armors.begin(), armors.end(), cmpArmor);
sort(monsters.begin(), monsters.end(), cmpMonster);
// build initial values for segment tree
vector<ll> init(m);
vector<int> B(m);
for (int i=0; i<m; ++i) {
B[i] = armors[i].b;
init[i] = -armors[i].cb; // negative cost
}
SegTree seg(m, init);
int mon_idx = 0;
ll ans = -1e18; // large negative
for (const Weapon& w : weapons) {
// add monsters with x < w.a
while (mon_idx < p && monsters[mon_idx].x < w.a) {
int y = monsters[mon_idx].y;
int z = monsters[mon_idx].z;
// find first index with b > y
int idx = upper_bound(B.begin(), B.end(), y) - B.begin();
if (idx < m) {
seg.range_add(idx, m-1, z);
}
mon_idx++;
}
ll bestArmor = seg.query_max();
ll profit = bestArmor - w.ca;
if (profit > ans) ans = profit;
}
printf("%lld\n", ans);
return 0;
}
Now we should double-check the type of answer: It may be negative, so we should output as integer.
Now test with sample.
Now confirm with edge case: m=1. Then B has one element, init = [-cb]. Segment tree works. Range add: idx = upper_bound(B, y) - B.begin(). If B[0] > y then idx=0, add to [0,0] else idx=1 (since no element > y) then no add. Query_max returns updated leaf value. Works.
Now test with n=1,m=1,p=1: weapon (5,10), armor (5,5), monster (3,4,6). For weapon a=5, monster x=3 <5: add monster y=4, z=6. B=[5]; upper_bound(4) -> first >4 is index0, add to leaf: init -5 +6 = 1. bestArmor=1, profit=1-10=-9. But brute: weapon a=5 >3, armor b=5 >4? Actually b=5 >4 => true, so monster qualifies, reward 6, costs 10+5=15, profit -9. Works.
Now test with case where monster y equals armor b: weapon (5,10), armor (5,5), monster (3,5,6). y=5, b=5, condition b > y? 5 >5 false, so monster not counted. In our algorithm: B=[5]; upper_bound(5) returns index? Since upper_bound returns first >5, none => idx=1, no add. bestArmor = -5, profit = -5-10 = -15. Correct.
Now test with duplicate b: m=2: armors (5,5) and (5,7). Sorted order: both b=5, but they are distinct. For a monster y=4, upper_bound(4) returns first >4; both b=5 >4, so idx=0, add to [0,1] -> both get +z. So value = -5+z and -7+z. Max = -5+z (if z positive). That's correct: both armors can defeat the monster, but cheaper armor gives better profit.
Now test with weapon a values that are not increasing? We sorted, so fine.
Now about the segment tree: Need to ensure that when n=2e5 and m=2e5, recursion depth for building is O(log m) but building calls recursively for each node, which is O(m). That's fine.
Now consider potential performance issue with using recursion for each update; but total updates 2e5, each update calls O(log m) nodes, recursion depth O(log m), fine.
Now we should also consider that the problem may require output 64-bit integer. Use %lld or %I64d? Usually %lld works.
Now finalize.
But there might be an alternative approach: using "sweep line" and "segment tree beats"? Not needed.
Now before finalizing, let's think if we missed any detail: The profit is defined as total coins from all defeated monsters minus cost of equipment. Roma can defeat as many monsters as he likes. Since all coins are positive, he would defeat all monsters that satisfy conditions. So we assume all such monsters are defeated. Good.
Now one more nuance: The problem states: "Roma can defeat a monster if his weapon's attack modifier is larger than the monster's defense, and his armor set's defense modifier is larger than the monster's attack." That is strictly larger. Our condition uses strict >. In our algorithm, we add monsters with x < a_i and y < b_j, which is equivalent to a_i > x_k and b_j > y_k. So fine.
Now consider if a_i or b_j are 1 and monster's x or y is 0 (not possible because min 1). So okay.
Now also note that a_i, b_j, x_k, y_k can be up to 1e6, so they fit in int.
Now we must ensure that while sorting weapons, we consider a_i as sorting key. For weapons with same a, the order does not matter.
Now confirm that we use all weapons. Yes.
Now potential bug: In the while loop, we check monsters[mon_idx].x < w.a. But note: We previously sorted monsters by x. But if there are multiple monsters with the same x, and weapon a_i equals that x, they should not be added. The condition x < a_i ensures they are not added. So if a_i equals x, those monsters are not added. If later weapon has a greater a, they will be added. So correct.
Now check scenario: There is a monster with x = 0? Not possible.
Now final answer.
Now let's think about memory: vector etc.
Now we are ready.
But there is an important subtlety: The segment tree range_add is on suffix of armors sorted by b. However, what if the armor list is sorted by b, but we need to apply updates to only those armors that satisfy b > y. That is indeed suffix from first index where b > y. But if there are multiple armors with same b, and some of them have b exactly equal to y, they should not be updated. Our upper_bound returns first index with b > y, so any armor with b == y will be before that index (since they are not > y). So they are excluded. That's correct.
Now check with example: B = [2,2,3] and y=2. Upper_bound returns first >2, i.e., index of 3 (2). So range add from 2 to end; leaves indices 0 and 1 (both b=2) not updated. Good.
Now we also need to consider that the segment tree stores values per armor; if there are multiple armors with same b but different cb, they are separate leaves.
Now overall algorithm seems correct.
Now we can code.
But we also need to consider that we might need to use 64-bit for the sum of z in segment tree. In update, we add z (int) to long long.
Now I'll implement.
Potential optimization: Instead of building a full segment tree with lazy, we could use a BIT and a max segment tree that maintains a value that is BIT query prefix? Wait, we need to maintain for each armor j: value = sum_{monsters added} (z if y < b_j) - cb_j. As we add monsters, we need to add z to all j with b_j > y. That's a range update on suffix. So we need a data structure that supports range add and point query? No, we need max over all points. So segment tree with range add and max query is straightforward.
Another alternative: Use a Fenwick tree to store the cumulative adds per armor? Actually we could maintain an array diff and then compute each point as prefix sums? Let's think: For each armor j, after many monsters added, the total reward = sum_{monsters} z * [y_k < b_j]. That's equivalent to: if we sort monsters by y, we could maintain prefix sum; but monsters are added dynamically by x, not by y. However, we could pre-sort monsters by y, but we need to update only those added so far. Could maintain a BIT over y coordinate, but then for each armor we need to compute prefix sum up to b_j-1. That would be O(log m) per armor per query, which is too much. But since we only need max over armors, we could maintain a segment tree that stores for each b value the current prefix sum up to that b minus cost? Actually the function f(b) = (prefix sum up to b-1) - cost(b). As we add a monster at y, the prefix sums for all b > y increase by z. So f(b) gets +z for b > y. So it's the same.
Thus segment tree is appropriate.
Now I recall that this problem is known as "World of Darkraft" from Codeforces #138? Actually it's CF 1380D? Not sure. But I've seen similar solutions.
Now we should also consider that the weapon's attack a_i can be up to 1e6, and we sort weapons. However, there could be weapons with very large a_i, but that's fine.
Now think about boundary conditions for the while loop: Since we sorted weapons ascending, the monsters are also sorted ascending by x. For each weapon, we add all monsters with x < a_i. This works even if there are weapons with a_i that are smaller than the smallest monster x: then no monsters added.
Now what about weapons with a_i extremely large, larger than all monster x: we add all monsters eventually. Good.
Now complexity is fine.
Now coding details:
Use vector for monsters? Possibly simpler: define struct.
Use scanf/printf.
Use long long for answer.
Now test with sample: Should output 1.
Now also test with some random small cases to confirm. Let's manually test a few.
Case 2: n=1,m=1,p=1: monster (5,5,30). weapon (10,10), armor (10,20). Condition: a=10 >5, b=10>5 => yes. reward=30, costs=30, profit=0. Our code: init = [-20]. Process weapon: add monster y=5,z=30. B=[10]; upper_bound(5) -> first >5 is index0 => add to [0,0] +30 => leaf becomes 10? Actually -20+30=10. bestArmor=10. profit=10-10=0. Correct.
Case 3: n=1,m=2: armors (5,10) and (6,5). weapon (4,2). monster (3,5,10). Condition: a=4>3, b must be >5 to defeat. Armor1 b=5, not >5; armor2 b=6 >5 => only armor2 can defeat. reward=10. Profit with armor2 = 10-5-2=3. Armor1 profit = -10-2=-12. So max=3. Our code: weapons sorted: (4,2). init: sorted armors by b: (5,10) idx0, (6,5) idx1 -> init = [-10,-5]. B=[5,6]. Process weapon: add monster y=5, z=10. upper_bound(5) on B returns first >5 -> b=6 at idx1. range_add idx1..1 +10 => values: idx0 -10, idx1 -5+10=5. bestArmor=5. profit=5-2=3. correct.
Now check scenario where we need to consider that we could have both a_i and b_j high but costs high, maybe not best.
Now think about the possibility that some armor has b extremely high but cost also high, making it not optimal.
Segment tree will consider all.
Now I think it's correct.
Now we can produce final answer.
But let's double-check the complexity: p up to 2e5, each addition does binary search O(log m) and segtree update O(log m). So O(p log m). n up to 2e5, each query O(1) (since root). So total O((n+p) log m) which is fine.
Now I'll write the code accordingly.
However, there is a subtle bug: The segment tree's query_max returns the maximum value over the entire array, but we must ensure that after adding monsters, the values for some armor might be undefined? No.
Now but think about a potential edge: When we build segment tree with initial values -cb_j, the max might be negative. When we add monsters, it increases. But what if we add a monster that should not affect some armors because b_j <= y? That's handled.
Now I realize that we might need to treat the case when there are no armors? But constraints m>=1.
Now just implement.
Now I'll also test with a case where there are many weapons and many monsters to ensure no overflow.
Now let's also consider the possibility of using int for a_i, b_j, x, y, but for B we need int. Fine.
Now about the segment tree's lazy propagation: I'll implement as described.
Now about overflow in recursion: depth is small.
Now code.
Wait: In the segment tree, we need to ensure that tree and lazy are vector<long long>. lazy can be long long. In push, we need to propagate lazy value to children.
Now we should also consider that range_add might be called with ql > qr (if idx == m). We handle by checking if idx < m.
Now about building: we can also build iteratively. But I'll stick with recursive.
Now confirm that the segment tree query is O(1) as we just take root. That's fine.
Now final code.
But there is one more nuance: The problem says "Roma has a choice to buy exactly one of n different weapons and exactly one of m different armor sets." So he must buy exactly one weapon and one armor. Our algorithm considers all combinations.
Now we need to ensure that we don't accidentally skip the case where he chooses a weapon and armor but defeats no monsters: This is included when segment tree has only initial values.
Now answer may be negative. In many CF problems, they require to output a number, negative is allowed.
Now we should output a single integer.
Now test with a custom case where all profits are negative, and see if we get correct.
Now test with p=1: monster (10,10,100). weapons and armors all small. For any weapon, monster x=10, so need a_i>10, none. So no monster added. So same as above. Works.
Now test with p=1: monster (3,3,100), weapons (5,10) and (4,5), armors (5,10) and (4,5). Brute: For weapon 5, armor5: both >3? 5>3 and 5>3 => reward 100, costs 20 => profit 80. weapon5, armor4: b=4>3 => reward 100, costs 5+10? weapon5(10)+armor4(5)=15? Actually armor4 cost 5? wait armors: (5,10) cost10, (4,5) cost5. So weapon5,armor4: 100 - (10+5)=85. weapon4,armor5: a=4>3, b=5>3 => reward 100, costs (5+10)=15 => profit 85. weapon4,armor4: reward 100, costs (5+5)=10 => profit 90. So max=90. Our algorithm: weapons sorted: (4,5) first, then (5,10). Armors sorted by b: (4,5) idx0, (5,10) idx1. init = [-5,-10]. Process weapon (4,5): add monsters with x<4: none because monster x=3 <4? Actually x=3 <4, so add. Monster y=3, z=100. upper_bound(3) on B [4,5] => first >3 is index0. range_add [0,1] +100 => values: idx0=95, idx1=90. bestArmor = max(95,90)=95. profit = 95 - ca(5) = 90. ans=90. Next weapon (5,10): add remaining monsters? monster already added, pointer now p, no more adds. bestArmor= still max(95,90)=95? Actually wait after previous weapon, segment tree state: values 95 and 90. For weapon (5,10), the segment tree still same (since no new monsters). That's correct because for weapon a=5, the eligible monsters are still only the one (x=3). So bestArmor =95. profit = 95 - 10 =85. ans remains 90. So answer 90, correct.
Now test with two monsters and weapon/armor combinations: This algorithm seems solid.
Now potential issue: The segment tree's values after processing the first weapon remain for the second weapon. That's correct because we never reset; we just continue adding monsters as a increases. But in the example above, a_i increased, but no new monsters added (since only one monster), so segment tree unchanged. That's correct. But what about the scenario where a_i increases and new monsters become available? Then we add them, and segment tree values increase accordingly. So for the larger a_i, we have more monsters, so values are higher. So profit for larger a_i may be higher or lower depending on cost. So all good.
Now consider that the segment tree's values for a particular armor j after processing all weapons will be the sum of all monsters with x < max_a (if we processed all weapons). But we don't need that after all weapons.
Now also consider that the order of weapons sorted by a ensures that when we process a weapon with a certain a, the segment tree already includes all monsters with x less than that a. That's correct.
Now what about weapon with a_i that is the smallest? We add monsters with x < a_i (none if a_i <= min x). Then query. Good.
Now I think it's correct.
Now we need to ensure that we consider all weapons. Indeed we loop over all.
Now about the segment tree's maximum: Could there be a situation where the maximum is from an armor that has b_j that is extremely high but cost high, but after some updates it becomes max. That's fine.
Now we also might think about potential integer overflow in init values when we compute -cb_j: cb_j up to 1e9, so -1e9 fits in 64-bit.
Now all good.
Now let's implement.
Now about the input: The problem statement might have large input, so use scanf/printf for speed.
Now consider that using vector<long long> and recursion might be okay.
Now final code.
But I recall that there might be a more efficient method: using a BIT and then for each weapon, we could compute max over j by scanning a segment tree built on the armors' b values. That's exactly what we do.
Now I'll code now.
Potential bug: In the segment tree's push, we should propagate lazy to children before recursing. In update, we push before going down.
Now check that tree and lazy are sized 4*n. For n up to 200k, 800k nodes, each 8 bytes => ~6.4 MB for tree + 6.4 MB for lazy = ~12.8 MB, plus other vectors, total under memory limits (256 MB). So fine.
Now to be safe, we can use int for n,m,p; long long for other.
Now implement.
Now double-check the use of upper_bound. It requires the vector to be sorted ascending, which it is.
Now we need to include for sort, lower_bound, upper_bound.
Now after coding, test with sample.
Now run mental test with a scenario where there are many armors and many monsters to ensure no off-by-one.
Edge: y can be up to 1e6, but B contains b_j up to 1e6. upper_bound works.
Now consider if there is an armor with b=1e6 and a monster with y=1e6: then b > y? 1e6 > 1e6 false, so not added. upper_bound(1e6) on B that contains 1e6 returns index after the last element (since it returns first > 1e6, and all elements <=1e6). So idx=m, no add. Correct.
Now if armor b=1e6+1? Not possible because max 1e6.
Now one more nuance: The weapon's a_i and armor's b_j can be up to 1e6, but monster's x and y also up to 1e6. So no overflow.
Now code.
Potential improvement: We could compress the y-values of monsters? Not needed.
Now I think it's done.
Now I'll produce final answer. ```cpp
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
struct Weapon {
int a, ca;
};
struct Armor {
int b, cb;
};
struct Monster {
int x, y, z;
};
// Segment tree with range add and global max query
class SegTree {
public:
int n;
vector tree, lazy;
SegTree(int _n, const vector& arr) {
n = _n;
tree.resize(4 * n);
lazy.resize(4 * n, 0);
build(1, 0, n-1, arr);
}
void build(int node, int l, int r, const vector& arr) {
if (l == r) {
tree[node] = arr[l];
return;
}
int mid = (l + r) / 2;
build(node2, l, mid, arr);
build(node2+1, mid+1, r, arr);
tree[node] = max(tree[node2], tree[node2+1]);
}
void push(int node) {
if (lazy[node] != 0) {
tree[node2] += lazy[node];
lazy[node2] += lazy[node];
tree[node2+1] += lazy[node];
lazy[node2+1] += lazy[node];
lazy[node] = 0;
}
}
void range_add(int ql, int qr, ll val) {
if (ql > qr) return;
update(1, 0, n-1, ql, qr, val);
}
void update(int node, int l, int r, int ql, int qr, ll val) {
if (ql <= l && r <= qr) {
tree[node] += val;
lazy[node] += val;
return;
}
push(node);
int mid = (l + r) / 2;
if (ql <= mid) update(node2, l, mid, ql, qr, val);
if (qr > mid) update(node2+1, mid+1, r, ql, qr, val);
tree[node] = max(tree[node2], tree[node2+1]);
}
ll query_max() {
return tree[1];
}
};
int main() {
int n, m, p;
scanf("%d%d%d", &n, &m, &p);
vector weapons(n);
for (int i = 0; i < n; ++i) {
scanf("%d%d", &weapons[i].a, &weapons[i].ca);
}
vector armors(m);
for (int i = 0; i < m; ++i) {
scanf("%d%d", &armors[i].b, &armors[i].cb);
}
vector monsters(p);
for (int i = 0; i < p; ++i) {
scanf("%d%d%d", &monsters[i].x, &monsters[i].y, &monsters[i].z);
}
code
sort(weapons.begin(), weapons.end(), cmpWeapon);
sort(armors.begin(), armors.end(), cmpArmor);
sort(monsters.begin(), monsters.end(), cmpMonster);
// Prepare initial values for segment tree (reward 0 - armor cost)
vector<int> B(m);
vector<ll> init(m);
for (int i = 0; i < m; ++i) {
B[i] = armors[i].b;
init[i] = -armors[i].cb;
}
SegTree seg(m, init);
int mon_idx = 0;
ll ans = -1e18; // sufficiently small
for (const Weapon& w : weapons) {
// Add all monsters with x < w.a
while (mon_idx < p && monsters[mon_idx].x < w.a) {
int y = monsters[mon_idx].y;
int z = monsters[mon_idx].z;
// first armor with b > y
int idx = upper_bound(B.begin(), B.end(), y) - B.begin();
if (idx < m) {
seg.range_add(idx, m-1, z);
}
++mon_idx;
}
ll bestArmor = seg.query_max();
ll profit = bestArmor - w.ca;
if (profit > ans) ans = profit;
}
printf("%lld\n", ans);
return 0;