一堆糖分给两个小朋友,要求人分到的糖果数最多相差一,分到的糖的质量相差最小,糖的数据不超过2,最后按照从小到大的顺序输出。
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Scanner;
public class Main{
public static int n,m,i,tem,flag,num;
public static int [] c={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
public static Double result;
public static int min=(int) 1e10;
public static int res,add;
public static void main(String []args)
{
Scanner in=new Scanner(System.in);
n=in.nextInt();
Main op=new Main();
add=0;
for(i=0;i<n;i++)
{
c[i]=in.nextInt();
add+=c[i];
}
Arrays.sort(c);
num=c.length/2;
op.dfs(c,0,0,0);
System.out.println(Math.min(res, add-res)+" "+Math.max(res, add-res));
in.close();
}
public int dfs(int [] c,int weight,int start,int cnt)
{
if(cnt==num)
{
return 0;
}
else
{
if(Math.abs(weight*2-add)<min)
{
min=Math.abs(weight*2-add);
res=weight;
}
if(start<c.length)
{
dfs(c,weight,start+1,cnt);
dfs(c,weight+c[start],start+1,cnt+1);
}
}
return 5;
}
}
使用dfs对分糖问题的解答的Java程序
最新推荐文章于 2024-02-19 15:57:31 发布