Huawei OD computer-based test algorithm questions: MVP battle

Table of contents

Question part

Interpretation and analysis

Code


Question part

topic MVP battle
difficulty easy
Question description In the StarCraft Basketball Tournament, the powerful cosmic team hopes that everyone can get the MVP.
The condition for MVP is that the top scorers in a single game can tie, so Team Universe decided to put as many players on the field as possible during the game, and let all scoring players score the same amount.
However, every minute of the game can only be scored by one person.
Enter description The first line of input is a number t, which represents the number of scoring minutes (1 <= t <= 50).
The second line contains t numbers, representing the score p per minute (1 <= p <= 50).
Output description The players who output points are the ones with the least MVP points at the time of MVP.
Additional information none
------------------------------------------------------
Example
Example 1
enter 9
5 2 1 5 2 1 5 2 1
output 6
illustrate Example explanation: A total of 4 people scored, each with 6 points:
5 + 1
5 + 1
5 + 1
2 + 2 + 2


Interpretation and analysis

Question interpretation :

Enter a series of numbers to represent the players' scores, and distribute these scores to as many players as possible, ensuring that the sum of each player's scores is equal. Find the average score when the maximum number of people is equally distributed.

In other words, it is to divide a specified set of numbers into several groups (the number of groups is not determined, and the number of numbers in each group is not fixed) so that the sum of the numbers in each group is equal. Find the minimum value of this sum. The sum is the smallest, which means the number of groups divided into is the largest.

n numbers are given in the question, and the n numbers are required to be divided into m groups to ensure that the sum of the numbers in each group in the m groups is equal, that is, the sum of the numbers in each group is equal to n/m (Note: n/m is taken as all).

Please note: the number of numbers in each group is not fixed and may vary.

Analysis and ideas :

Although the difficulty of this question is marked as "easy", the ideas and methods are not that easy.

The best I can think of is dynamic programming, trying to put n numbers into different groups. Assuming that the largest value among n numbers is max, then the value range of the number of groups is [1, n / max].

We use a recursive approach to try to put a certain number into a group, and then use recursion to try to put the remaining numbers into a certain group to exhaust all possible situations.

Start trying from the number of groups (n / max rounded). If the grouping conditions are met , the number of groups at this time is the maximum number of groups. Return the sum of the numbers in each group at this time and exit the program. If it is not satisfied, the number of groups is decremented by 1, and the attempt continues until the number of groups is 1.
The conditions for grouping are: the sum of the numbers in each group is equal, and all numbers belong to a certain group.

There will definitely be a result to this question in the end. In the worst case, all numbers are in the same group. What it means in the title is that there is only one MVP player, and this player takes all the points.

This algorithm uses recursion and traverses the possible number of groups. In each grouping, exhausting all the numbers and putting them into each group requires a time complexity of O(  n^{2}) and a space complexity of O(n).


Code

Java code

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;


/**
 * MVP争夺战
 * 
 * @since 2023.09.11
 * @version 0.1
 * @author Frank
 *
 */
public class MVPCompetition {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		while (sc.hasNext()) {
			String input = sc.nextLine();
			int count = Integer.parseInt( input );
			input = sc.nextLine();
			String[] numbers = input.split( " " );
			processMVPCompetition( numbers );
		}
	}
	
	private static void processMVPCompetition( String numbers[] )
	{
		int sum = 0;
		int maxNum = 0;
		List<Integer> numList = new ArrayList<Integer>();
		for( int i = 0; i < numbers.length; i ++ )
		{
			int tmpNum = Integer.parseInt( numbers[i] );
			if( tmpNum > maxNum )
			{
				maxNum = tmpNum;
			}
			sum += tmpNum;
			numList.add( tmpNum );
		}
		
		int maxMVPCnt = sum / maxNum;
		for( int i = maxMVPCnt; i >= 1; i --)
		{
			if( sum % i != 0 )
			{
				continue;
			}
			int aveScroe = sum / i;
			
			int[] tmpSum = new int[ i ];
			for( int j = 0; j < tmpSum.length; j ++ )
			{
				tmpSum[j] = 0;
			}
			int ret = processAverageScroe( aveScroe, tmpSum, numList );
			if( ret != -1 )
			{
				System.out.println( ret );
				return;
			}
		}
		
	}

	private static int processAverageScroe( int score, int[] tmpSum, List<Integer> numbers)
	{
		int ret = -1;

		int tmpNum = numbers.get( 0 );
		numbers.remove( 0 );
		
		for( int i = 0; i < tmpSum.length; i ++ )
		{
			if( tmpNum + tmpSum[i] > score )
			{
				continue;
			}
			
			tmpSum[i] = tmpSum[i] + tmpNum;
			boolean meet = isArrayAllScore( score, tmpSum, numbers );
			if( meet )
			{
				return score;
			}
			ret = processAverageScroe( score, tmpSum, numbers);
			if( ret != -1 )
			{
				return ret;
			}
			tmpSum[i] = tmpSum[i] - tmpNum;
		}
		
		numbers.add( 0, tmpNum );
		return ret;		
	}
	
	private static boolean isArrayAllScore( int score, int[] tmpSum, List<Integer> numbers )
	{
		boolean ret = true;
		if( numbers.size() > 0 )
		{
			return false;
		}
		for( int i = 0; i < tmpSum.length; i ++ )
		{
			if( tmpSum[i] != score )
			{
				return false;
			}
		}
		return ret;
	}

}

JavaScript code

const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;
void async function() {
    while (line = await readline()) {
        // count 可以忽略
        var count = parseInt(line);
        line = await readline();
        var numberArr = line.split(" ");
        processMVPCompetition(numberArr);
    }
}();

function processMVPCompetition(numbers) {
    var sum = 0;
    var maxNum = 0;
    var numList = new Array();
    for (var i = 0; i < numbers.length; i++) {
        var tmpNum = parseInt(numbers[i]);
        if (tmpNum > maxNum) {
            maxNum = tmpNum;
        }
        sum += tmpNum;
        numList.push(tmpNum);
    }

    var maxMVPCnt = parseInt( sum / maxNum );
    for (var i = maxMVPCnt; i >= 1; i--) {

        if (sum % i != 0) {
            continue;
        }
        var aveScroe = sum / i;

        var tmpSum = new Array();
        for (var j = 0; j < i; j++) {
            tmpSum[j] = 0;
        }

        var ret = processAverageScroe(aveScroe, tmpSum, numList);
        if (ret != -1) {
            console.log(ret);
            return;
        }
    }

}

function processAverageScroe( score, tmpSum, numbers) {
    var ret = -1;

    var tmpNum = numbers.shift(0);
    for (var i = 0; i < tmpSum.length; i++) {
        if (tmpNum + tmpSum[i] > score) {
            continue;
        }
        tmpSum[i] = tmpSum[i] + tmpNum;
        var meet = isArrayAllScore(score, tmpSum, numbers);
        if (meet) {
            return score;
        }
        ret = processAverageScroe(score, tmpSum, numbers);
        if (ret != -1) {
            return ret;
        }
        tmpSum[i] = tmpSum[i] - tmpNum;
    }

    numbers.unshift( tmpNum );
    return ret;
}

function isArrayAllScore(score, tmpSum, numbers) {
    var ret = true;
    if (numbers.length > 0) {
        return false;
    }
    for (var i = 0; i < tmpSum.length; i++) {
        if (tmpSum[i] != score) {
            return false;
        }
    }
    return ret;
}

(over)

Guess you like

Origin blog.csdn.net/ZiJinShi/article/details/132807904