Team competition problem - Niu Ke (with Java source code)

Topic description:

Niuniu held a programming competition. There were 3*n players participating in the competition, and each player had a level value a_i. Now these players should be teamed up to form a total of n teams, that is, 3 people in each team. Niuniu The team's level value is found to be equal to the second-highest level of the team's players.
For example:
the level values ​​of three members of a team are 3, 3, and 3. Then the level value of the team is 3. The level value of the
three members of 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, and 2 respectively. Then the level value of the team is 2.
In order to make the game more interesting, Niuniu wants to arrange the teams so that the sum of the level values ​​of all teams is the largest.
As shown in the example:
If Niu Niu divides 6 players into two teams
If the plan is:
team1:{1,2,5}, team2:{5,5,8}, then the total level value is 7.
And If the plan is:
team1:{2,5,8}, team2:{1,5,5}, then the sum of the level values ​​is 10.
There is no plan greater than the sum of 10, so the output is 10

Topic Analysis:

Sort the array first. Take the first value and the last two values ​​and put them into a group,
so grouping we will definitely get a highest value and a value next to the highest value.
This is next to the highest value The value of is the data we need.

Example 1: 1 2 5 5 5 8

insert image description here

Example 2: 1 2 3 4 5 6 7 8 9

insert image description here

From the above example, we can find that a formula is derived. The subscript of the value we get is for array.length-2*(i+1)
example:
Example 1: The length of the array is 6, and the subscript of the data we get is 6-2*(0+1)=4, 6-2*(1+1)=2.
Example 2: The length of the array is 9, we The subscript of the obtained data is9-2*(0+1)=7, 9-2*(1+1)=5, 9-2*(2+1)=3.

code show as below:

import java util.*;
public class Main{
    
    
	public static void main(string[] args){
    
    
		Scanner sc=new Scanner(System.in);
		int n=sc.nextInt();
		//创建数组
		long[] array=new long[3*n];
		for(int i=0;i<(3*n);i++){
    
    
			//给数组输入值
			array[i]=sc.nextLong();
		}
		//先对数组进行排序
		Arrays.sort(array);
		//用来记录最后输出的结果
		long sum=0;
		for(int i=0;i<n;i++){
    
    
			//array.length-2*(i+1)就是我们所需要的第二高水平值的下标.
			sum+=array[array.length-(2*(i+1))];
		}
		System.out.println(sum);
	}
}

Guess you like

Origin blog.csdn.net/weixin_47278183/article/details/124407270