P18022 [GCPC 2026] Junior Joining
Description
Arya, the Commander of Gil'ead, has received $2 \cdot n$ new recruits.
Since the Gil'ead City Protectorate Council has mandated more patrols,
she intends to pair them into $n$ pairs to patrol the area.
To maximize the effectiveness of a patrol pair in the modern era, it should consist of one shield bearer and one spear carrier.
Each recruit $i$ has shield-defense skill $d_i$, and spear-attack skill $a_i$.
While skilled usage of their respective tool is important, one should never neglect the effectiveness of strong synergy.
Because of long-standing rivalries between cities, strong bonds have formed within each city.
With enough discipline, Arya is sure that there will not be any bad blood within a pair,
but if both are from the same city, they will synergize exceptionally well.
The total fighting strength of a pair is the sum of the shield-defense skill of one,
the spear-attack skill of the other, and if both recruits are from the same city $c$, also a synergy bonus of $c$.
Determine the maximum sum of fighting strength over all pairs that Arya can achieve with optimal pairing.
Input Format
The input consists of:
- One line with an integer $n$ ($1\leq n \leq 10^5$), half the number of new recruits.
- $2 \cdot n$ lines, the $i$th of which contains three integers $d_i$, $a_i$, and $c_i$ ($1 \leq d_i, a_i, c_i \leq 10^6$), the shield-defense skill, spear-attack skill, and the home city of the $i$th recruit.
Output Format
Output the maximum achievable sum of fighting strength over all pairs.
Explanation/Hint
#### Explanation of Sample 1
There are only two recruits so they are paired together.
Recruit $1$ is assigned the shield, recruit $2$ the spear.
As they are not from the same city, only their skill is counted $4 + 2 = 6$.
#### Explanation of Sample 2
Recruit $3$ (shield) is paired with recruit $1$ (spear).
As they are both from city $5$, they have $5$ bonus strength from synergy ($5 + 2 + 5 = 12$ total).
Recruit $2$ (shield) and recruit $4$ (spear) are paired, resulting in a fighting strength of $6$.
#### Explanation of Sample 3
One possible pairing is the following:
recruit $3$ (shield) with $1$ (spear), and recruit $4$ (shield) with $2$ (spear).