Testing...

拔河比赛_暴力破解算法_递归破解

package com.qianfeng.bahe;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;

class Person {
	private int no;
	private int weight;

	public Person(int no, int weight) {
		super();
		this.no = no;
		this.setWeight(weight);
	}

	@Override
	public boolean equals(Object obj) {
		if (obj == this) {
			return true;
		} else {
			if (obj instanceof Person) {
				Person p = (Person) obj;
				if (p.no == this.no) {
					return true;
				}

			}

		}
		return false;
	}

	public int getWeight() {
		return weight;
	}

	public void setWeight(int weight) {
		this.weight = weight;
	}

	@Override
	public String toString() {
		return "Person [no=" + no + ", weight=" + weight + "]";
	}

}

public class BaHe {
	private static int sum;
	public static int min;

	public static void main(String[] args) {

		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		Person[] a = new Person[n];
		byte bb = 28;
		for (int i = 0; i < a.length; i++) {
			a[i] = new Person(i, in.nextInt());
		}
		BaHe.sum = 0;
		for (int i = 0; i < a.length; i++) {
			BaHe.sum += a[i].getWeight();
		}
		min = BaHe.sum;
		// 这是仅仅考虑体重相差最小的做法 如果要人数相差不能大于1那么按下面的佐
		// for (int i = 1; i <= a.length; i++) {
		// // int b[] = new int[i];不能判断是否重复使用一个人
		// // HashMap<Integer, Integer> b = new HashMap<Integer, Integer>();//
		// // 不能在指定位置更换元素
		// // 我们需要一个不能存储重复元素的list
		// List<Person> b = new ArrayList<Person>();
		// for (int j = 0; j < i; j++) {
		// b.add(null);
		// }
		// // System.out.println(b.size());
		// getMin(b, a, i);
		//
		// }

		if (n % 2 == 0 && n > 2) {
			for (int i = n / 2 - 1; i <= n / 2; i++) {
				List<Person> b = new ArrayList<Person>();
				for (int j = 0; j < i; j++) {
					b.add(null);
				}
				getMin(b, a, i);
			}
		} else {
			List<Person> b = new ArrayList<Person>();
			for (int j = 0; j < n / 2; j++) {
				b.add(null);
			}
			getMin(b, a, n / 2);
		}
		min = min > sum - min ? sum - min : min;
		System.out.println(BaHe.min);
		System.out.println(BaHe.sum - BaHe.min);
	}

	public static void getMin(List b, Person[] a, int n) {

		if (n == 0) {
			min = computeMin(b);
			// System.out.println("__________________________________");
		} else {
			for (int i = 0; i < a.length; i++) {
				if (!b.contains(a[i])) {
					b.set(n - 1, a[i]);
					getMin(b, a, n - 1);
				} else {
					continue;
				}
			}
		}

	}

	public static int computeMin(List b) {
		double mid = sum / 2.0;

		int sumt = 0;
		for (Iterator<Person> it = b.iterator(); it.hasNext();) {
			sumt += it.next().getWeight();
		}
		min = Math.abs(min - mid) > Math.abs(mid - sumt) ? sumt : min;
		// System.out.println(b);
		return min;

	}
}

 

//主要关注完全不知道要有多少层循环的递归算法

posted on 2013-08-08 23:27  左思  阅读(464)  评论(0)    收藏  举报

导航

Testing...