Hatena::Grouptopcoder

hama_DU@TopCoderへの道

2011-03-15div2hard 三本勝負(SRM491, 493, 497)

SRM491 div2 第三問(1000pt) BottlesOnShelf

|  SRM491 div2 第三問(1000pt) BottlesOnShelf - hama_DU@TopCoderへの道 を含むブックマーク はてなブックマーク -  SRM491 div2 第三問(1000pt) BottlesOnShelf - hama_DU@TopCoderへの道

http://www.topcoder.com/stat?c=problem_statement&pm=11008

ビットDP。頑張って自力でここまで書いた。

だがTLEする。降参


public class BottlesOnShelf {
	public long gcd(long a, long b) {
		long r = a % b;
		if (r == 0) {
			return b;
		}
		return gcd(b, r);
	}

	public long lcm(long a, long b) {
		return a * b / gcd(a, b);
	}

	public int getNumBroken(int N, int[] left, int[] right, int[] damage) {
		int M = left.length;
		int bits = (1 << M);

		int[] dp = new int[bits];
		long[] dp_min = new long[bits];
		long[] dp_max = new long[bits];
		long[] dp_lcm = new long[bits];
		dp_min[0] = 1;
		dp_max[0] = N;
		dp_lcm[0] = 1;

		for (int i = 0 ; i < bits ; i++) {
			int count = Integer.bitCount(i);
			if (count >= 1) {
				for (int j = (i - 1) & i ; j > 0 ; j = (j - 1) & i) {
					int ct = Integer.bitCount(j);
					dp[i] += dp[j] * (((count - ct) % 2 == 1) ? 1 : -1);
				}
				int max_i_1 = (i - 1) & i;
				long lcm = dp_lcm[max_i_1];
				long min = dp_min[max_i_1];
				long max = dp_max[max_i_1];
				if (min == -1) {
					dp_min[i] = -1;
					continue;
				} else {
					for (int x = 0 ; x < M ; x++) {
						int ptn = 1 << x;
						if ((max_i_1 & ptn) != 0) {
							continue;
						}
						if ((i & ptn) >= 1) {
							if (right[x] < min || max < left[x]) {
								min = -1;
								break;
							}
							lcm = lcm(lcm, damage[x]);
							if (min < left[x]) {
								min = left[x];
							}
							if (right[x] < max) {
								max = right[x];
							}
							break;
						}
					}
					dp_lcm[i] = lcm;
					dp_min[i] = min;
					dp_max[i] = max;
					if (min != -1) {
						if (min % lcm != 0) {
							min += (lcm - min % lcm);
						}
						max -= max % lcm;
						dp[i] += ((max - min) / lcm + 1) * ((count % 2 == 1) ? 1 : -1);
					}
				}
			}
		}
		return dp[(1<<M)-1];
	}
}