[One question per day] Team competition (greedy, sorting)

Source of the topic
Niuke.com
Link: Team competition

Title description
Niuniu held a programming competition. There are 3*n players participating in the competition, and each player has a level value a_i. Now these players will be teamed up to form a total of n teams, that is, each team has 3 people . Niuniu found that the level of the team is equal to the second highest level of the team members.
For example:
the level value of
three players in a team is 3, 3, 3. Then the level value of the team is 3, and the level value of the three players in a team is 3, 2, and 3. Then the level value of the
team is 3, a team The level values ​​of the three players are 1, 5, 2. Then the level value of the team is 2.
In order to make the game more interesting, Niuniu wants to arrange the team to maximize the sum of the level values ​​of all the teams.
As shown in the example:
If Niuniu divides 6 players into two teams. If the plan is: team1:{1,2,5}, team2:{5,5,8}, the total level value at this time is 7, and if the plan is: team1:{2,5,8}, team2:{ 1,5,5}, at this time the sum of the level values ​​is 10. There is no scheme greater than the sum of 10, so 10 is output.

Enter description:

The first line of the input is a positive integer n (1 ≤ n ≤ 10^5). The
second line contains 3*n integers a_i (1 ≤ a_i ≤ 10^9), indicating the level of each contestant

Output description:

Output an integer representing the maximum sum of the level values ​​of all teams

Example:
Enter:

2
5 2 8 5 1 5

Output

10

Problem-solving ideas
The level value of the team is equal to the second highest level value among the team members, in order to solve the solution with the largest sum of level values ​​of all teams, that is to say, the second value of each team is as large as possible. So the actual value puts the maximum value to the far right and the minimum value to the far left.

The main idea of ​​this question is the greedy algorithm. The greedy algorithm is actually very simple, that is, every time you choose a value, you choose the most worry-free part that can be seen currently, so the greedy here is to ensure that the second value of each group is the largest that can be selected The value is fine. We try to take the largest value each time, but the largest number cannot be the median, so we should take the second largest in each group. for example:
Insert picture description here

Code display

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main()
{
    
    
	int n;
	while(cin>>n)
	{
    
    
		long long sum = 0;
		vector<int> a;
		a.resize(3*n);
		for(int i = 0;i < (3 * n);i++)
		{
    
    
			cin>>a[i];
		}
		std::sort(a.begin(),a.end());
		for(int i = n;i <=3 * n - 2;i += 2)
		{
    
    
			sum += a[i];
		}
		cout<<sum<<endl;
	}
}

Guess you like

Origin blog.csdn.net/zhao_leilei/article/details/110131060