NC24567. [USACO 2014 Jan B]Balanced Teams
描述
输入描述
Lines 1..12: Each line contains the skill level of a single cow.
输出描述
Line 1: The minimum possible value of S - s.
示例1
输入:
1 2 3 4 5 6 7 8 9 10 11 12
输出:
1
说明:
One possible solution is to divide the teams as follows: (12,1,7), (9,8,3),Java(javac 1.8) 解法, 执行用时: 132ms, 内存消耗: 14548K, 提交时间: 2019-11-29 10:05:11
import java.util.*; import java.io.*; public class Main { final public static int COWSPERTEAM = 3; final public static int NUMCOWS = 12; final public static int NOSOL = 10000000; public static void main(String[] args) throws Exception { Scanner stdin = new Scanner(System.in); int[] values = new int[NUMCOWS]; for (int i=0; i<NUMCOWS; i++) values[i] = stdin.nextInt(); stdin.close(); int[] teams = new int[NUMCOWS]; boolean[] used = new boolean[NUMCOWS]; int cost = recSolve(values, 0, teams, used); System.out.println(cost); } public static int recSolve(int[] values, int k, int[] teams, boolean[] used) { if (k == NUMCOWS) return eval(values, teams); int lowCow = 0; if (k > 0 && k%3 > 0) lowCow = teams[k-1]+1; else if (k > 0 && k%3 == 0) lowCow = teams[k-3]+1; int result = NOSOL; for (int i=lowCow; i<NUMCOWS; i++) { if (!used[i]) { teams[k] = i; used[i] = true; result = Math.min(result, recSolve(values, k+1, teams, used)); used[i] = false; } } return result; } public static int eval(int[] values, int[] teams) { int[] scores = new int[NUMCOWS/COWSPERTEAM]; for (int i=0; i<NUMCOWS; i++) scores[i/COWSPERTEAM] += values[teams[i]]; int res = 0; for (int i=0; i<scores.length; i++) for (int j=i+1; j<scores.length; j++) res = Math.max(res, Math.abs(scores[i]-scores[j])); return res; } }
C++11(clang++ 3.9) 解法, 执行用时: 15ms, 内存消耗: 596K, 提交时间: 2020-04-05 11:30:46
#include <bits/stdc++.h> #define M int(1e9) using namespace std; int a[13],o[13]={0,1,1,1,2,2,2,3,3,3,4,4,4},s[5]; int main() { //freopen("bteams.in","r",stdin); //freopen("bteams.out","w",stdout); for(int i=1;i<=12;i++) cin>>a[i]; sort(a+1,a+13); int ans=M; do { for(int i=1;i<=4;i++) s[i]=0; for(int i=1;i<=12;i++) s[o[i]]+=a[i]; int minn=M,maxn=0; for(int i=1;i<=4;i++) { minn=min(minn,s[i]); maxn=max(maxn,s[i]); } ans=min(ans,maxn-minn); }while(next_permutation(o+1,o+13)); cout<<ans; return 0; }
C++14(g++5.4) 解法, 执行用时: 41ms, 内存消耗: 384K, 提交时间: 2020-04-06 11:45:07
#include<stdio.h> #define fo(i,a,b) for(int i=a;i<=b;i++) #define fd(i,a,b) for(int i=a;i>=b;i--) #include<algorithm> using namespace std; int n=12,ans,a[15],bel[15],num[6],sum[6],te; void dfs(int now){ if (now>n){ fo(i,1,4) sum[i]=0; fo(i,1,n) sum[bel[i]]+=a[i]; sort(sum+1,sum+5); te=sum[4]-sum[1]; if (te<ans) ans=te; return; } fo(i,1,4) if (num[i]<3){ num[i]++; bel[now]=i; dfs(now+1); num[i]--; } } int main(){ ans=0x3fffffff; fo(i,1,n) scanf("%d",&a[i]); dfs(1); printf("%d\n",ans); }