篮球比赛
标题:篮球比赛 | 时间限制:1秒 | 内存限制:65536K | 语言限制:不限
篮球(5V5)比赛中,每个球员拥有一个战斗力,每个队伍的所有球员战斗力之和为该队伍的总体战斗力。现有10个球员准备分为两队进行训练赛,教练希望2个队伍的战斗力差值能够尽可能的小,以达到最佳训练效果。给出10个球员的战斗力,如果你是教练,你该如何分队,才能达到最佳训练效果?请输出该分队方案下的最小战斗力差值。
import java.util.*; public class Main { static boolean[] isVisited; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String str = scanner.nextLine().trim(); String[] numStrArr = str.split(" "); int[] num = new int[numStrArr.length]; for (int i = 0; i < numStrArr.length; i++) { num[i] = Integer.parseInt(numStrArr[i]); } int sum = 0; isVisited = new boolean[10]; for (int k : num) { sum += k; } for (int min = 0; min <= sum; min++) { int target = (sum - min); if (target % 2 == 0) { if (dfs(target / 2, num, 0)) { System.out.println(min); break; } } } } private static boolean dfs(int target, int[] arr, int index) { int length = arr.length; if (index > 5 || target < 0) { return false; } if (index == 5 && target == 0) { return true; } for (int i = 0; i < length; i++) { if (isVisited[i]) { continue; } isVisited[i] = true; if (dfs(target - arr[i], arr, index + 1)) { return true; } isVisited[i] = false; } return false; } }
import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Scanner; public class Main { public static int minResult = Integer.MAX_VALUE; public static int sumResult = 0; public static void main(String[] args) { Scanner sc = new Scanner(System.in); String line = sc.nextLine(); sumResult = 0; String[] dataArray = line.split(" "); int[] numArray = new int[10]; for(int i=0;i<dataArray.length;i++){ numArray[i] = Integer.valueOf(dataArray[i]); sumResult += numArray[i]; } dnf(numArray,new ArrayList<>(),5,0,0); System.out.println(minResult); } public static void dnf(int[] numArray, List<Integer> processNum,int target,int k,int m){ if(k==target){ int tmpSumResult = 0; for(int i=0;i<processNum.size();i++){ tmpSumResult += processNum.get(i); } int tmpGap = Math.abs(sumResult - tmpSumResult-tmpSumResult); minResult = Math.min(minResult,tmpGap); }else{ for(int i =m;i<=numArray.length+k-target;i++){ processNum.add(numArray[i]); dnf(numArray,processNum,target,k+1,i+1); processNum.remove(processNum.size()-1); } } } }
package main import ( "bufio" "fmt" "math" "os" "sort" "strconv" "strings" ) var maxNum = 0 var res = 999999 func main() { input := bufio.NewScanner(os.Stdin) input.Scan() n:= strings.Split(input.Text(), " ") p:=make([]int,0,10) maxN := 0 for idx:=range n { tmp,_:=strconv.Atoi(n[idx]) p=append(p,tmp) maxN += tmp } maxNum = maxN sort.Ints(p) dfs(p,0,0,0) fmt.Println(res) } func dfs(p []int,num int,idx int,value int) { if idx == len(p) { return } if num == 6 { return } else { dfs(p,num,idx+1,value) value += p[idx] num ++ if num == 5 { dif := maxNum - value dif2 := value-dif dif3 := int(math.Abs(float64(dif2))) if dif3 < res { res = dif3 } return } dfs(p,num,idx+1,value) } }