POJ 3273 二分

题意:给定一个序列,划分成m个子串,求一个数x使得每个子串的和都小于x
思路:二分,l是整个序列中的最大值,r是子列和,看看能不能划分成m个;
判断是否能划分成m个:从头开始,累加 知道和大于当前mid,组数+1并且从当前位置继续累加。 最后如果组数大于m则表示不能划分 应把界限变大。


import java.util.Scanner;

public class Main {
	final static int maxn = 100005;
	static int a[] = new int[maxn];
	static int n;
	static int m;

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		while(scanner.hasNext()){
			n = scanner.nextInt();
			m = scanner.nextInt();

			int minn =0, sum = 0;
			for (int i = 0; i < n; i++) {
				a[i] = scanner.nextInt();
				minn = Math.max(minn, a[i]);
				sum += a[i];
			}
			int l = minn, r = sum, ans = maxn, mid = 0;
			while (l <= r) {
				mid = (l + r) >> 1;
				// System.out.println(mid);
				if (check(mid)) {
					l = mid + 1;
				} else
					r = mid - 1;
			}
			System.out.println(mid);
		}
	}

	public static boolean check(int x) {
		int sum = 0;
		int group = 1;

		for (int i = 0; i < n; i++) {
			if (sum + a[i] <= x) {
				sum += a[i];
			} else {
				sum = a[i];
				group++;
			}
		}

		if (group > m)
			return true;
		else
			return false;
	}
}

你可能感兴趣的:(思维)