篮球队员5V5分组战力差最小
生活随笔
收集整理的這篇文章主要介紹了
篮球队员5V5分组战力差最小
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
解法1:
依次把隊員中最接近平均值的隊員找出來,放都兩隊中,放入規(guī)則:A組,B組人數(shù)相同且總戰(zhàn)力較小;或者人數(shù)較少的那一組優(yōu)先放入
package com.hanzheng.algorithm;import java.util.ArrayList; import java.util.Collections; import java.util.List;public class BasketballPlayer {public static List<Integer> nums = new ArrayList<>();public static void main(String[] args) {int[] players = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};int sum = 0;for (int i = 0; i < players.length; i++) {nums.add(players[i]);sum += players[i];}Collections.sort(nums);List<Integer> A = new ArrayList<>();int countA = 0;List<Integer> B = new ArrayList<>();int countB = 0;while (nums.size() > 0) {int index = findMostNearAverage(sum / nums.size());if (A.size() > B.size() || (A.size() == B.size() && countA > countB)) {B.add(nums.get(index));countB += nums.get(index);} else {A.add(nums.get(index));countA += nums.get(index);}nums.remove(index);}System.out.println(Math.abs(sum - countA * 2));}private static int findMostNearAverage(int average) {int index = 0;int minDelta = Integer.MAX_VALUE;for (int i = 0; i < nums.size(); i++) {if (Math.abs(average - nums.get(i)) < minDelta) {minDelta = Math.abs(average - nums.get(i));index = i;}}return index;}}
解法2:
把從10個人里選五個的全排列都列出來,求戰(zhàn)力平均值和總?cè)藬?shù)戰(zhàn)力平均值差值的最小值
package com.hanzheng.algorithm;import java.util.ArrayList; import java.util.List;public class BasketballPlayer2 {// 五個隊員的全部組合static List<List<Integer>> player = new ArrayList<>();public static void main(String[] args) {int[] arr = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};int total = 0;for (int i = 0; i < arr.length; i++) {total += arr[i];}permutation(arr, 5);int midDelta = Integer.MAX_VALUE;for (int i = 0; i < player.size(); i++) {int sum = calcPlayerSum(player.get(i));int delta = Math.abs(total - 2 * sum);midDelta = Math.min(midDelta, delta);}System.out.println(midDelta);}private static int calcPlayerSum(List<Integer> player) {int sum = 0;for (int i = 0; i < player.size(); i++) {sum += player.get(i);}return sum;}private static void permutation(int[] arr, int selectCount) {List<Integer> track = new ArrayList<>();backtrack(arr, selectCount, track);}private static void backtrack(int[] arr, int selectCount, List<Integer> track) {if (track.size() == selectCount) {player.add(new ArrayList<>(track));return;}for (int i = 0; i < arr.length; i++) {if (track.contains(arr[i])) {continue;}track.add(arr[i]);backtrack(arr, selectCount, track);track.remove(track.size() - 1);}} }
總結(jié)
以上是生活随笔為你收集整理的篮球队员5V5分组战力差最小的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MATLAB画图符号标注
- 下一篇: 测试测试