首页 > 专题系列 > Java解POJ > POJ 2576 Tug of War [解题报告] Java
2013
11-11

POJ 2576 Tug of War [解题报告] Java

Tug of War

问题描述 :

A tug of war is to be arranged at the local office picnic. For the tug of war, the picnickers must be divided into two teams. Each person must be on one team or the other; the number of people on the two teams must not differ by more than 1; the total weight of the people on each team should be as nearly equal as possible.

输入:

The first line of input contains n the number of people at the picnic. n lines follow. The first line gives the weight of person 1; the second the weight of person 2; and so on. Each weight is an integer between 1 and 450. There are at most 100 people at the picnic.

输出:

Your output will be a single line containing 2 numbers: the total weight of the people on one team, and the total weight of the people on the other team. If these numbers differ, give the lesser first.

样例输入:

3
100
90
200

样例输出:

190 200

解题代码:

//* @author: [email protected]
import java.io.*;
import java.util.Arrays;
public class Main
{
	
 public static void main(String[] args) throws IOException
 {
  InputStreamReader is=new InputStreamReader(System.in);
  BufferedReader in=new BufferedReader(is);
  int a=Integer.parseInt(in.readLine());
  int total=0,l1=0,l2=0,i;
  int[] arr=new int[a];
  for(i=0;i< a;i++)
  {
   arr[i]=Integer.parseInt(in.readLine());
   total+=arr[i];
  }
  int u=a/2;
  int[] p1=new int[u];
  int[] p2=new int[a-u];
  Arrays.sort(arr);
  int sum1=0,sum2=0,u1,ans1=-1,ans2=-1;
  for(i=0;l1< u;i++)
   {
	p1[l1++]=arr[i];
	if(l1< u){
		p1[l1++]=arr[a-i-1];
		sum1+=arr[a-i-1];
	}
	sum1+=arr[i];
   }
   for(;l2< a-u;i++)
   {
	p2[l2++]=arr[i];
	sum2+=arr[i];
   }
   u1=Math.abs(sum1-sum2);
   ans1=sum1;
   ans2=sum2;
   for(i=0;i< 10000;i++)
   {
	int t1=(int) (Math.random()*l1);
	int t2=(int) (Math.random()*l2);
	sum1+=p2[t2]-p1[t1];
	sum2+=p1[t1]-p2[t2];
	int ww=p1[t1];
	p1[t1]=p2[t2];
	p2[t2]=ww;
	if(Math.abs(sum1-sum2)< u1)
	{
		u1=Math.abs(sum1-sum2);
		ans1=sum1;
		ans2=sum2;
	}
    }
    sum1=Math.min(ans1, ans2);
    sum2=Math.max(ans1, ans2);
    System.out.println(sum1+" "+sum2);
   }
}

  1. 算法是程序的灵魂,算法分简单和复杂,如果不搞大数据类,程序员了解一下简单点的算法也是可以的,但是会算法的一定要会编程才行,程序员不一定要会算法,利于自己项目需要的可以简单了解。