結果

問題 No.2390 Udon Coupon (Hard)
ユーザー 👑 Mizar
提出日時 2023-08-29 02:06:15
言語 Rust
(1.83.0 + proconio)
結果
AC  
実行時間 7 ms / 2,000 ms
コード長 2,645 bytes
コンパイル時間 15,077 ms
コンパイル使用メモリ 379,692 KB
実行使用メモリ 5,248 KB
最終ジャッジ日時 2024-12-30 20:17:29
合計ジャッジ時間 17,233 ms
ジャッジサーバーID
(参考情報)
judge2 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 47
権限があれば一括ダウンロードができます

ソースコード

diff #

// O((A_max)^2)解法
// 入力制約: 0 <= n <= 10^13, 0 < a_i < 2^15, 0 <= b_i, b_max * floor(n / a_min) <= 2^61
fn solve(n: u64, mut ab: [(u64, u64); 3]) -> u64 {
	let (a_min, a_max, _b_min, b_max) = ab.iter().fold((!0u64, 0u64, !0u64, 0u64), |(a_min, a_max, b_min, b_max), &(a, b)| (a.min(a_min), a.max(a_max), b.min(b_min), b.max(b_max)));
	assert!(n <= 1_0000_0000_0000);
	assert!(a_min > 0 && a_max < 2048 && b_max.saturating_mul(n / a_min) < (1u64 << 60));
	
	if ab[1].0 * ab[0].1 < ab[0].0 * ab[1].1 {
		ab.swap(0, 1);
	}
	if ab[2].0 * ab[0].1 < ab[0].0 * ab[2].1 {
		ab.swap(0, 2);
	}
	let [(a1, b1), (a2, b2), (a3, b3)] = ab;
	// a1inv = ceil(2^34 / a1) = floor((2^34 - 1) / a1) + 1
	// 2^32 / a1 <= a1inv < 2^32 / a1 + 1
	let a1inv = ((1u64 << 34) - 1) / a1 + 1;
	let (a1b2, a1b3) = (a1 * b2.max(1), a1 * b3.max(1));
	let a1a3 = a1 * a3;
	// w = max(floor(n / a1) - (a2 + a3), 0)
	let w = (n / a1).saturating_sub(a2 + a3);
	let (mut r, mut p, mut s) = (0, 0, n - w * a1);
	while p < a1b2 {
		let (mut q, mut t) = (0, s);
		if s < a1a3 {
			loop {
				// 準定数を除数とする除算の定数倍高速化
				// 0 < {a1,a2,a3} < 2^15, 0 <= t < 2000*(2*2000+1)
				// a1 * t < 2^34 --> quot = floor(ceil(2^34 / a1) * t / 2^34) = floor(t / a1)
				let quot = t * a1inv >> 34;
				debug_assert_eq!(t / a1, quot);
				r.chmax(quot * b1 + p + q);
				if let Some(d) = t.checked_sub(a3) {
					t = d;
					q += b3;
				} else {
					break;
				}
			}
		} else {
			while q < a1b3 {
				// 準定数を除数とする除算の定数倍高速化
				// 0 < {a1,a2,a3} < 2^15, 0 <= t < 2000*(2*2000+1)
				// a1 * t < 2^34 --> quot = floor(ceil(2^34 / a1) * t / 2^34) = floor(t / a1)
				let quot = t * a1inv >> 34;
				debug_assert_eq!(t / a1, quot);
				r.chmax(quot * b1 + p + q);
				t -= a3;
				q += b3;
			}
		}
		if let Some(d) = s.checked_sub(a2) {
			s = d;
			p += b2;
		} else {
			break;
		}
	}
	r + w * b1
}

fn main() {
	let mut stdinlock = std::io::stdin().lock();
	let mut lines = std::io::BufRead::lines(&mut stdinlock).map_while(Result::ok);
	let n = lines.next().unwrap().parse::<u64>().unwrap();
	let mut ab = [(0u64, 0u64); 3];
	for e in ab.iter_mut() {
		let s = lines.next().unwrap();
		let mut t = s.split_whitespace();
		*e = (
			t.next().unwrap().parse::<u64>().unwrap(),
			t.next().unwrap().parse::<u64>().unwrap(),
		);
	}
	println!("{}", solve(n, ab));
}

trait Change {
	fn chmax(&mut self, x: Self);
	fn chmin(&mut self, x: Self);
}
impl<T: PartialOrd> Change for T {
	fn chmax(&mut self, x: T) {
		if *self < x {
			*self = x;
		}
	}
	fn chmin(&mut self, x: T) {
		if *self > x {
			*self = x;
		}
	}
}
0