結果
| 問題 | No.5026 Spectrum Router |
| コンテスト | |
| ユーザー |
👑 terry_u16
|
| 提出日時 | 2026-11-23 22:56:03 |
| 言語 | Rust (1.99.1 + proconio + num + itertools + ACL) |
| 結果 |
AC
不安定
|
| 実行時間 | 1,980 ms / 2,000 ms |
| + 132µs | |
| コード長 | 110,879 bytes |
| 記録 | |
| コンパイル時間 | 3,224 ms |
| コンパイル使用メモリ | 241,640 KB |
| 実行使用メモリ | 9,904 KB |
| スコア | 1,501,751 |
| 最終ジャッジ日時 | 2026-11-23 23:04:25 |
| 合計ジャッジ時間 | 108,463 ms |
|
ジャッジサーバーID (参考情報) |
judge5_0 / judge4_0 |
| 純コード判定しない問題か言語 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| other | AC * 50 |
ソースコード
pub mod library {
//! ヒューリスティック問題向けの共通ライブラリ。
pub mod annealing {
//! 焼きなましライブラリ
#![macro_use]
use super::rand_yuki::Pcg64Mcg;
use super::rand_yuki::Rng as _;
use itertools::{Itertools, izip};
use std::{
cell::RefCell,
fmt::{Debug, Display},
rc::Rc,
time::{Duration, Instant},
};
pub type AnnealingRng = Pcg64Mcg;
/// 焼きなましの状態
pub trait State: Clone {
type Env;
type Score: Score;
/// 生スコア(大きいほど良い)
fn score(&self, env: &Self::Env) -> Self::Score;
}
pub trait Score {
/// 焼きなまし用スコア(大きいほど良い)
/// デフォルトでは生スコアをそのまま返す
#[allow(unused_variables)]
fn annealing_score(&self, progress: f64) -> f64 {
self.raw_score()
}
/// 生スコア
fn raw_score(&self) -> f64;
}
/// 単一の値からなるスコア
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct SingleScore(pub f64);
impl Score for SingleScore {
fn raw_score(&self) -> f64 {
self.0
}
}
/// 焼きなましの近傍
///
/// * 受理パターンの流れ: `preprocess()` -> `eval()` -> `postprocess()`
/// * 却下パターンの流れ: `preprocess()` -> `eval()` -> `rollback()`
pub trait Neighbor: Sized {
type Env;
type State: State<Env = Self::Env>;
fn generate(
env: &Self::Env,
state: &Self::State,
rng: &mut AnnealingRng,
progress: f64,
) -> Option<Self>;
/// `eval()` 前の変形操作を行う
fn preprocess(&mut self, env: &Self::Env, state: &mut Self::State);
/// 変形後の状態の評価を行う
///
/// # Arguments
///
/// * `env` - 環境
/// * `state` - 状態
/// * `progress` - 焼きなましの進捗([0, 1]の範囲をとる)
/// * `threshold` - 近傍採用の閾値。新しいスコアがこの値を下回る場合はrejectされる
///
/// # Returns
///
/// 現在の状態のスコア。スコアが `threshold` を下回ることが明らかな場合は `None` を返すことで評価の打ち切りを行うことができる。
///
/// 評価の打ち切りについては[焼きなまし法での評価関数の打ち切り](https://qiita.com/not522/items/cd20b87157d15850d31c)を参照。
#[allow(unused_variables)]
fn eval(
&mut self,
env: &Self::Env,
state: &Self::State,
progress: f64,
threshold: f64,
) -> Option<<Self::State as State>::Score> {
Some(state.score(env))
}
/// `eval()` 後の変形操作を行う(2-optの区間reverse処理など)
fn postprocess(self, env: &Self::Env, state: &mut Self::State);
/// `preprocess()` で変形した `state` をロールバックする
fn rollback(self, env: &Self::Env, state: &mut Self::State);
}
pub trait NeighborDelegator: Sized {
type Env;
type State: State<Env = Self::Env>;
fn get_neighbor_weights() -> Vec<f64>;
fn get_neighbor_names() -> &'static [&'static str];
fn step(context: &mut AnnealingContext<Self::Env, Self::State>, neighbor_index: usize);
}
/// 近傍の委譲をするstructを生成するマクロ
///
/// `delegator_name` は生成するstructの名前、`env` は環境の型、`state` は状態の型を指定する。
/// 各近傍は `variant => weight` の形式で指定する。`variant` は `Neighbor` を実装した型名。
/// 生成されるstructは `NeighborDelegator` を実装する。
/// `weight` はその近傍が選ばれる確率の重みを表す。焼きなまし実行時に遅延評価されるため、`weight` は定数である必要はない。
///
/// # Usage
///
/// ```ignore
/// use crate::neighbors;
/// use crate::library::annealing::{run_annealing, SimdSelector};
/// use std::time::Duration;
///
/// // Env・State、およびNeighborを実装した各近傍の型を別途定義する。
/// neighbors! {
/// Neighbors, Env, State, [
/// TwoOpt => 1.0,
/// Swap => 2.0,
/// Insert => 0.5,
/// ]
/// }
///
/// let (state, stats) = run_annealing::<Neighbors, SimdSelector, 128>(&input, state, 1e1, 1e-1, Duration::from_millis(1000), 42);
/// ```
#[macro_export]
macro_rules! neighbors {
(
$delegator_name:ident, $env:ty, $state:ty, [
$( $variant:ident => $weight:expr ),+ $(,)?
]
) => {
use $crate::library::annealing::Neighbor as _;
// step()内のmatch式で使用するNEIGHBOR_INDEXを定義する
$crate::neighbors! {
@index 0; $($variant),+
}
// 本体
$crate::neighbors! {
@body
$delegator_name, $env, $state, [
$( $variant => $weight ),+
]
}
};
(
@body
$delegator_name:ident, $env:ty, $state:ty, [
$( $variant:ident => $weight:expr ),+ $(,)?
]
) => {
struct $delegator_name;
impl $delegator_name {
thread_local!(static WEIGHTS: std::cell::RefCell<Vec<Box<dyn FnMut() -> f64>>> = std::cell::RefCell::new(vec![$(Box::new(|| $weight), )+]));
const NAMES: &'static [&'static str] = &[$(stringify!($variant), )+];
}
impl $crate::library::annealing::NeighborDelegator for $delegator_name
{
type Env = $env;
type State = $state;
fn get_neighbor_weights() -> Vec<f64> {
// 重みの設定を遅延させる
Self::WEIGHTS.with(|weights| {
weights.borrow_mut().iter_mut().map(|f| f()).collect()
})
}
fn get_neighbor_names() -> &'static [&'static str] {
Self::NAMES
}
fn step(context: &mut $crate::library::annealing::AnnealingContext<Self::Env, Self::State>, neighbor_index: usize) {
match neighbor_index {
$($variant::NEIGHBOR_INDEX => {
let Some(neighbor) = $variant::generate(context.env, &context.state, &mut context.rng, context.progress) else {
return;
};
context.step(neighbor, neighbor_index)
}),*,
_ => panic!("Invalid neighbor index: {}", neighbor_index),
}
}
}
};
// 近傍にNEIGHBOR_INDEXを定義する補助マクロ
// バリアントが複数残っているとき
(@index $idx:expr; $head:ident, $($tail:ident),+) => {
impl $head {
const NEIGHBOR_INDEX: usize = $idx;
}
$crate::neighbors! {
@index ($idx + 1); $($tail),+
}
};
// 最後のバリアント
(@index $idx:expr; $last:ident) => {
impl $last {
const NEIGHBOR_INDEX: usize = $idx;
}
};
}
/// 近傍選択のためのトレイト
pub trait NeighborSelector {
fn new(weights: Vec<f64>) -> Self;
fn select(&self, rng: &mut AnnealingRng) -> usize;
}
/// SIMD命令を使用した近傍選択
///
/// 候補となる近傍は8個までという制限があるが高速
pub struct SimdSelector {
prefix_sum: std::arch::x86_64::__m256,
}
impl SimdSelector {
#[target_feature(enable = "bmi1,avx")]
unsafe fn select_simd(&self, rng: &mut AnnealingRng) -> usize {
// SIMD命令を使用して、重みの中からランダムな値以上の最初のインデックスを選択する
// 8要素同時に比較してからtrue/falseのビットを取得し、tzcntで最初のtrueのインデックスを返す
let x = rng.random::<f32>();
let x = std::arch::x86_64::_mm256_set1_ps(x);
let cmp = std::arch::x86_64::_mm256_cmp_ps(
self.prefix_sum,
x,
std::arch::x86_64::_CMP_GE_OQ,
);
let flag = std::arch::x86_64::_mm256_movemask_ps(cmp);
std::arch::x86_64::_tzcnt_u32(flag as u32) as usize
}
}
impl NeighborSelector for SimdSelector {
fn new(weights: Vec<f64>) -> Self {
assert!(!weights.is_empty(), "Weights must not be empty");
assert!(
weights.len() <= 8,
"SimdSelector requires weights of length 8 or less"
);
assert!(
weights.iter().all(|&w| w >= 0.0),
"Weights must be non-negative"
);
let mut prefix_sum = [0.0; 8];
for i in 0..weights.len() {
prefix_sum[i] = weights[i] as f32;
}
for i in 1..prefix_sum.len() {
prefix_sum[i] += prefix_sum[i - 1];
}
let sum = prefix_sum[7];
assert!(sum > 0.0, "Weights must not all be zero");
for v in prefix_sum.iter_mut() {
*v /= sum; // 正規化
}
let prefix_sum = unsafe { std::arch::x86_64::_mm256_loadu_ps(prefix_sum.as_ptr()) };
Self { prefix_sum }
}
fn select(&self, rng: &mut AnnealingRng) -> usize {
unsafe { self.select_simd(rng) }
}
}
/// 焼きなましの統計データ
#[derive(Debug, Clone)]
pub struct AnnealingStatistics {
all_iter: usize,
valid_iter: usize,
accepted_count: usize,
updated_count: usize,
init_score: f64,
final_score: f64,
selected: Vec<u64>,
accepted: Vec<u64>,
neighbor_names: &'static [&'static str],
}
impl AnnealingStatistics {
fn new(init_score: f64, neighbor_names: &'static [&'static str]) -> Self {
Self {
all_iter: 0,
valid_iter: 0,
accepted_count: 0,
updated_count: 0,
init_score,
final_score: init_score,
selected: vec![0; neighbor_names.len()],
accepted: vec![0; neighbor_names.len()],
neighbor_names,
}
}
fn select(&mut self, neighbor_index: usize) {
self.valid_iter += 1;
self.selected[neighbor_index] += 1;
}
fn accept(&mut self, neighbor_index: usize) {
self.accepted_count += 1;
self.accepted[neighbor_index] += 1;
}
}
impl Display for AnnealingStatistics {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(f, "===== annealing =====")?;
writeln!(f, "init score : {}", self.init_score)?;
writeln!(f, "score : {}", self.final_score)?;
writeln!(f, "all iter : {}", self.all_iter)?;
writeln!(f, "valid iter : {}", self.valid_iter)?;
writeln!(f, "accepted : {}", self.accepted_count)?;
writeln!(f, "updated : {}", self.updated_count)?;
for (name, &selected, &accepted) in
izip!(self.neighbor_names, &self.selected, &self.accepted)
{
let percent = accepted as f64 / selected as f64 * 100.0;
writeln!(f, "{name:11}: {accepted} / {selected} ({percent:.2}%)")?;
}
Ok(())
}
}
/// 焼きなましを実行する関数
///
/// `N` は `NeighborDelegator` を実装した型。`neighbors!` マクロで生成できる。
/// `S` は `NeighborSelector` を実装した近傍選択器。
/// `I` は焼きなましの進捗を更新する間隔を指定する。例えば `I = 1024` とすると、1024回に1回の頻度で進捗を更新する。
///
/// 初期状態と受理した状態のうち、`annealing_score(1.0)` が最大の状態と統計を返す。
/// 統計のスコア表示には `raw_score()` を用いる。
///
/// # Usage
///
/// ```
/// use crate::library::annealing::{
/// run_annealing, AnnealingStatistics, NeighborDelegator, SimdSelector,
/// };
/// use std::time::Duration;
///
/// fn solve<N: NeighborDelegator>(env: &N::Env, state: N::State)
/// -> (N::State, AnnealingStatistics)
/// {
/// run_annealing::<N, SimdSelector, 128>(
/// env, state, 1e1, 1e-1, Duration::from_millis(1000), 42,
/// )
/// }
/// ```
pub fn run_annealing<N: NeighborDelegator, S: NeighborSelector, const I: usize>(
env: &N::Env,
state: N::State,
start_temp: f64,
end_temp: f64,
duration: Duration,
seed: u128,
) -> (N::State, AnnealingStatistics) {
let threshold_generator = ThresholdGenerator::get_singleton();
let mut threshold_generator = threshold_generator.borrow_mut();
let mut context =
AnnealingContext::new::<N>(env, state, &mut threshold_generator, start_temp, seed);
context
.threshold_generator
.set_pos(context.rng.random_range(0..ThresholdGenerator::LEN));
let selector = S::new(N::get_neighbor_weights());
let since = Instant::now();
let duration_inv = 1.0 / duration.as_secs_f64();
loop {
if context.stats.all_iter % I == 0 {
context.progress = since.elapsed().as_secs_f64() * duration_inv;
context.temperature =
start_temp.powf(1.0 - context.progress) * end_temp.powf(context.progress);
if context.progress >= 1.0 {
break;
}
}
context.stats.all_iter += 1;
let neighbor_index = selector.select(&mut context.rng);
N::step(&mut context, neighbor_index);
}
context.stats.final_score = context.best_state.score(env).raw_score();
(context.best_state, context.stats)
}
pub struct AnnealingContext<'a, E, S: State<Env = E>> {
pub env: &'a E,
pub state: S,
pub best_state: S,
pub current_score: S::Score,
pub best_score: f64,
pub stats: AnnealingStatistics,
pub progress: f64,
pub temperature: f64,
pub rng: AnnealingRng,
threshold_generator: &'a mut ThresholdGenerator,
}
impl<'a, E, S: State<Env = E>> AnnealingContext<'a, E, S> {
fn new<N: NeighborDelegator>(
env: &'a E,
state: S,
threshold_generator: &'a mut ThresholdGenerator,
temperature: f64,
seed: u128,
) -> Self {
let best_state = state.clone();
let current_score = state.score(env);
let best_score = current_score.annealing_score(1.0);
let stats =
AnnealingStatistics::new(current_score.raw_score(), N::get_neighbor_names());
let progress = 0.0;
let rng = AnnealingRng::new(seed);
Self {
env,
state,
best_state,
current_score,
best_score,
stats,
progress,
temperature,
rng,
threshold_generator,
}
}
pub fn step<N: Neighbor<Env = E, State = S>>(
&mut self,
mut neighbor: N,
neighbor_index: usize,
) {
self.stats.select(neighbor_index);
neighbor.preprocess(self.env, &mut self.state);
// スコア計算
let threshold = self.threshold_generator.next(
self.current_score.annealing_score(self.progress),
self.temperature,
);
let Some(new_score) =
neighbor.eval(self.env, &self.state, self.progress, threshold)
else {
// 明らかに閾値に届かない場合はreject
neighbor.rollback(self.env, &mut self.state);
return;
};
if new_score.annealing_score(self.progress) >= threshold {
self.stats.accept(neighbor_index);
self.current_score = new_score;
neighbor.postprocess(self.env, &mut self.state);
let new_score = self.current_score.annealing_score(1.0);
if self.best_score < new_score {
self.best_score = new_score;
self.best_state = self.state.clone();
self.stats.updated_count += 1;
}
} else {
neighbor.rollback(self.env, &mut self.state);
}
}
}
/// 焼きなましにおける評価関数の打ち切り基準となる次の閾値を返す構造体
///
/// 参考: [焼きなまし法での評価関数の打ち切り](https://qiita.com/not522/items/cd20b87157d15850d31c)
struct ThresholdGenerator {
iter: usize,
log_randoms: Vec<f64>,
}
impl ThresholdGenerator {
const LEN: usize = 1 << 16;
thread_local! {
static THRESHOLD_GENERATOR: Rc<RefCell<ThresholdGenerator>> = Rc::new(RefCell::new(ThresholdGenerator::new(42)));
}
fn new(seed: u128) -> Self {
let mut rng = Pcg64Mcg::new(seed);
let log_randoms = (0..Self::LEN)
.map(|_| rng.random_range(0.0f64..1.0).ln())
.collect_vec();
Self {
iter: 0,
log_randoms,
}
}
/// 評価関数の打ち切り基準となる次の閾値を返す
fn next(&mut self, prev_score: f64, temperature: f64) -> f64 {
let threshold = prev_score + temperature * self.log_randoms[self.iter % Self::LEN];
self.iter += 1;
threshold
}
fn set_pos(&mut self, pos: usize) {
self.iter = pos % Self::LEN;
}
fn get_singleton() -> Rc<RefCell<Self>> {
Self::THRESHOLD_GENERATOR.with(|cell| cell.clone())
}
}
}
pub mod data_structures {
use std::slice::Iter;
macro_rules! define_index_set {
($name:ident, $int:ty) => {
/// `[0, n)` の整数集合。追加・削除・所属判定はO(1)。
///
/// 値と位置を同じ整数型で保持し、位置の最大値を不在の番兵に使う。
/// `n`は整数型の最大値以下。反復順序は削除によって変わる。
#[derive(Debug, Clone)]
pub struct $name {
values: Vec<$int>,
positions: Vec<$int>,
}
impl $name {
pub fn new(n: usize) -> Self {
assert!(n <= <$int>::MAX as usize, "IndexSet universe is too large");
Self {
values: Vec::new(),
positions: vec![<$int>::MAX; n],
}
}
pub fn add(&mut self, value: $int) {
let pos = &mut self.positions[value as usize];
if *pos == <$int>::MAX {
*pos = self.values.len() as $int;
self.values.push(value);
}
}
pub fn remove(&mut self, value: $int) {
let index = self.positions[value as usize];
if index != <$int>::MAX {
let last = *self.values.last().unwrap();
self.values[index as usize] = last;
self.values.pop();
self.positions[last as usize] = index;
self.positions[value as usize] = <$int>::MAX;
}
}
pub fn contains(&self, value: $int) -> bool {
self.positions[value as usize] != <$int>::MAX
}
pub fn len(&self) -> usize {
self.values.len()
}
pub fn is_empty(&self) -> bool {
self.values.is_empty()
}
pub fn iter(&self) -> Iter<'_, $int> {
self.values.iter()
}
pub fn as_slice(&self) -> &[$int] {
&self.values
}
}
};
}
define_index_set!(IndexSet32, u32);
define_index_set!(IndexSet16, u16);
/// u32版の整数集合。省メモリなu16版は[`IndexSet16`]。
///
/// ```
/// use cp_lib_rs::data_structures::{IndexSet, IndexSet16};
/// let mut set = IndexSet::new(100);
/// set.add(42u32);
/// assert_eq!(set.as_slice(), &[42u32]);
/// let mut small = IndexSet16::new(100);
/// small.add(42u16);
/// assert!(small.contains(42));
/// ```
pub type IndexSet = IndexSet32;
}
pub mod geometry {
//! i32整数座標を使う2次元幾何。
mod kd_tree {
use super::{KD_COORD_LIMIT, squared_distance, validate_point};
use std::collections::BinaryHeap;
const NONE: usize = usize::MAX;
#[derive(Debug, Clone)]
struct Node {
id: usize,
children: [usize; 2],
min: [i32; 2],
max: [i32; 2],
}
/// 静的な2次元KD-tree。座標はi32、距離はユークリッド距離。
///
/// 入力順のIDを維持し、同じ座標の点も別IDとして保持する。点の追加・移動・削除は
/// 再構築で行う。問い合わせ点自体も入力に含まれていれば検索結果に含む。
/// 各座標は±10^9以内に制限し、距離の二乗をi64で返す。
/// 範囲外の入力点・問い合わせ点、負の半径はpanicする。
///
/// 構築O(N log N)、メモリO(N)。各検索は境界箱で枝刈りするが、最悪では全点を見る。
/// k近傍は最悪O(N log(k+1) + k log(k+1))(kはN以下に切り詰める)。
///
/// ```
/// use crate::library::geometry::KdTree;
/// let tree = KdTree::new(vec![[0, 0], [3, 4], [10, 0]]);
/// assert_eq!(tree.nearest([2, 3]), Some((1, 2))); // (点ID, 距離の二乗)
/// assert_eq!(tree.k_nearest([0, 0], 2), vec![(0, 0), (1, 25)]);
/// let mut ids = tree.within_radius([0, 0], 5);
/// ids.sort_unstable();
/// assert_eq!(ids, vec![0, 1]); // 境界上の点も含む
/// ```
#[derive(Debug, Clone)]
pub struct KdTree {
points: Vec<[i32; 2]>,
nodes: Vec<Node>,
root: usize,
}
impl KdTree {
pub fn new(points: Vec<[i32; 2]>) -> Self {
points
.iter()
.copied()
.for_each(|p| validate_point(p, KD_COORD_LIMIT));
let mut ids: Vec<_> = (0..points.len()).collect();
let mut tree = Self {
nodes: Vec::with_capacity(points.len()),
points,
root: NONE,
};
tree.root = tree.build(&mut ids, 0);
tree
}
pub fn len(&self) -> usize {
self.points.len()
}
pub fn is_empty(&self) -> bool {
self.points.is_empty()
}
/// 入力順の点列。
pub fn points(&self) -> &[[i32; 2]] {
&self.points
}
fn build(&mut self, ids: &mut [usize], axis: usize) -> usize {
if ids.is_empty() {
return NONE;
}
let mid = ids.len() / 2;
ids.select_nth_unstable_by_key(mid, |&i| (self.points[i][axis], i));
let id = ids[mid];
let index = self.nodes.len();
self.nodes.push(Node {
id,
children: [NONE; 2],
min: self.points[id],
max: self.points[id],
});
let l = self.build(&mut ids[..mid], 1 - axis);
let r = self.build(&mut ids[mid + 1..], 1 - axis);
self.nodes[index].children = [l, r];
for child in [l, r] {
if child == NONE {
continue;
}
for axis in 0..2 {
self.nodes[index].min[axis] =
self.nodes[index].min[axis].min(self.nodes[child].min[axis]);
self.nodes[index].max[axis] =
self.nodes[index].max[axis].max(self.nodes[child].max[axis]);
}
}
index
}
fn lower_bound(&self, node: usize, query: [i32; 2]) -> i64 {
if node == NONE {
return i64::MAX;
}
let n = &self.nodes[node];
let closest = [
query[0].clamp(n.min[0], n.max[0]),
query[1].clamp(n.min[1], n.max[1]),
];
squared_distance(query, closest)
}
fn ordered_children(&self, node: usize, query: [i32; 2]) -> [(usize, i64); 2] {
let [l, r] = self.nodes[node].children;
let a = (l, self.lower_bound(l, query));
let b = (r, self.lower_bound(r, query));
if a.1 <= b.1 { [a, b] } else { [b, a] }
}
/// 最近傍の(点ID, 距離の二乗)。空ならNone。同距離では小さいIDを優先する。
/// ヒープや結果Vecの確保は行わない。
pub fn nearest(&self, query: [i32; 2]) -> Option<(usize, i64)> {
validate_point(query, KD_COORD_LIMIT);
if self.is_empty() {
return None;
}
let mut best = (i64::MAX, usize::MAX);
self.search_nearest(self.root, query, &mut best);
Some((best.1, best.0))
}
fn search_nearest(&self, node: usize, query: [i32; 2], best: &mut (i64, usize)) {
let id = self.nodes[node].id;
*best = (*best).min((squared_distance(query, self.points[id]), id));
for (child, bound) in self.ordered_children(node, query) {
if child != NONE && bound <= best.0 {
self.search_nearest(child, query, best);
}
}
}
/// 最大k点の(点ID, 距離の二乗)を、距離・IDの昇順で返す。k=0なら空。
pub fn k_nearest(&self, query: [i32; 2], k: usize) -> Vec<(usize, i64)> {
validate_point(query, KD_COORD_LIMIT);
let k = k.min(self.len());
if k == 0 {
return Vec::new();
}
let mut heap = BinaryHeap::with_capacity(k);
self.search_k(self.root, query, k, &mut heap);
heap.into_sorted_vec()
.into_iter()
.map(|(d, id)| (id, d))
.collect()
}
fn search_k(
&self,
node: usize,
query: [i32; 2],
k: usize,
heap: &mut BinaryHeap<(i64, usize)>,
) {
let id = self.nodes[node].id;
let value = (squared_distance(query, self.points[id]), id);
if heap.len() < k {
heap.push(value);
} else if value < *heap.peek().unwrap() {
*heap.peek_mut().unwrap() = value;
}
for (child, bound) in self.ordered_children(node, query) {
if child != NONE && (heap.len() < k || bound <= heap.peek().unwrap().0) {
self.search_k(child, query, k, heap);
}
}
}
/// 半径radius以内の点ID。境界を含む。結果の順序は未規定。
pub fn within_radius(&self, query: [i32; 2], radius: i32) -> Vec<usize> {
let mut result = Vec::new();
self.within_radius_each(query, radius, |id| result.push(id));
result
}
/// 結果のVecを確保せず、半径内の点IDをコールバックに渡す。
pub fn within_radius_each(
&self,
query: [i32; 2],
radius: i32,
mut visit: impl FnMut(usize),
) {
validate_point(query, KD_COORD_LIMIT);
assert!(radius >= 0, "radius must be non-negative");
if self.root != NONE {
self.search_radius(self.root, query, i64::from(radius).pow(2), &mut visit);
}
}
fn search_radius(
&self,
node: usize,
query: [i32; 2],
radius2: i64,
visit: &mut impl FnMut(usize),
) {
if self.lower_bound(node, query) > radius2 {
return;
}
let id = self.nodes[node].id;
if squared_distance(query, self.points[id]) <= radius2 {
visit(id);
}
for child in self.nodes[node].children {
if child != NONE {
self.search_radius(child, query, radius2, visit);
}
}
}
}
}
pub use kd_tree::KdTree;
mod delaunay {
//! 分割統治とquad-edgeによるDelaunay三角形分割。
//!
//! トポロジー操作・マージ手順はKACTL FastDelaunay.hを参考にRustへ移植。
//! <https://github.com/kth-competitive-programming/kactl/blob/main/content/geometry/FastDelaunay.h>
//! 原実装: Philippe Legault, <https://github.com/Bathlamos/delaunay-triangulation/>
//! 整数の厳密判定・入力ID・重複点処理・面の列挙はこの実装で追加。
//
// Copyright (c) 2016 Philippe Legault
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
use super::{DELAUNAY_COORD_LIMIT, validate_point};
/// i32整数座標の静的な2次元Delaunay三角形分割。
///
/// 分割統治によりO(N log N)時間、O(N)メモリ。入力順の点IDを返す。
/// 外接円の内部に他の点がない三角形を生成する(円周上の点は許す)。
/// 各座標を±10^9以内に制限する(範囲外はpanic)。向きはi64、外接円判定の
/// 積と和だけi128で厳密に計算する。浮動小数点・多倍長整数は使わない。
///
/// - 同一座標は最小の入力IDにまとめる。[`Self::representatives`]で対応を返す。
/// - 全点が共線なら三角形は空、辺は座標順の隣接点を結ぶ鎖になる。
/// - 0点・1点なら辺も三角形も空。
/// - 共円などで分割が一意でない場合は、そのうち1つを決定的に返す。
///
/// ```
/// use crate::library::geometry::Delaunay;
/// let triangulation = Delaunay::new(&[[0, 0], [4, 0], [0, 3]]);
/// assert_eq!(triangulation.triangles().len(), 1);
/// assert_eq!(triangulation.edges(), &[[0, 1], [0, 2], [1, 2]]);
/// ```
///
/// # ユークリッドMSTの候補辺にする
///
/// 辺の長さを丸めないユークリッド距離なら、この辺集合からMSTを求められる。
/// 距離の二乗でソートしてよい。障害物迂回など別の辺コストでは保証されない。
/// 重複点も全て接続する場合は、代表点と重複点の間に距離0の辺を補う。
///
/// ```
/// use ac_library::Dsu;
/// use crate::library::geometry::Delaunay;
/// let points = [[0i32, 0], [3, 0], [0, 4], [0, 0]];
/// let dt = Delaunay::new(&points);
/// let mut edges: Vec<_> = dt.edges().iter().map(|&[u, v]| {
/// let dx = i64::from(points[u][0]) - i64::from(points[v][0]);
/// let dy = i64::from(points[u][1]) - i64::from(points[v][1]);
/// ((dx * dx + dy * dy) as i64, u, v)
/// }).collect();
/// for (id, &representative) in dt.representatives().iter().enumerate() {
/// if id != representative { edges.push((0, id, representative)); }
/// }
/// edges.sort_unstable();
/// let mut dsu = Dsu::new(points.len());
/// let mut mst = Vec::new();
/// for (_, u, v) in edges {
/// if !dsu.same(u, v) {
/// dsu.merge(u, v);
/// mst.push((u, v));
/// }
/// }
/// assert_eq!(mst.len(), points.len() - 1);
/// ```
#[derive(Debug, Clone)]
pub struct Delaunay {
triangles: Vec<[usize; 3]>,
edges: Vec<[usize; 2]>,
representatives: Vec<usize>,
}
impl Delaunay {
pub fn new(points: &[[i32; 2]]) -> Self {
points
.iter()
.copied()
.for_each(|p| validate_point(p, DELAUNAY_COORD_LIMIT));
let mut ids: Vec<_> = (0..points.len()).collect();
ids.sort_unstable_by_key(|&i| (points[i], i));
let mut representatives = vec![0; points.len()];
let mut unique: Vec<usize> = Vec::with_capacity(ids.len());
for id in ids {
if unique.last().is_none_or(|&last| points[last] != points[id]) {
unique.push(id);
}
representatives[id] = *unique.last().unwrap();
}
let mut result = Self {
triangles: Vec::new(),
edges: Vec::new(),
representatives,
};
if unique.len() < 2 {
return result;
}
let mut mesh = Mesh {
points,
quads: Vec::new(),
free: Vec::new(),
};
mesh.build(&unique);
for q in &mesh.quads {
if q.alive {
let [u, v] = q.vertices;
result.edges.push([u.min(v), u.max(v)]);
}
}
result.edges.sort_unstable();
let mut seen = vec![[false; 2]; mesh.quads.len()];
for block in 0..mesh.quads.len() {
if !mesh.quads[block].alive {
continue;
}
for direction in [0, 2] {
if seen[block][direction / 2] {
continue;
}
let start = block * 4 + direction;
let mut edge = start;
let mut vertices = [0; 3];
let mut count = 0;
loop {
seen[edge / 4][(edge % 4) / 2] = true;
if count < 3 {
vertices[count] = mesh.origin(edge);
}
count += 1;
edge = mesh.left_next(edge);
if edge == start {
break;
}
}
// 外側の面は時計回り。共線の場合も除外する。
if count == 3
&& orient(
points[vertices[0]],
points[vertices[1]],
points[vertices[2]],
) > 0
{
let min_pos = (0..3).min_by_key(|&i| vertices[i]).unwrap();
vertices.rotate_left(min_pos);
result.triangles.push(vertices);
}
}
}
result.triangles.sort_unstable();
result
}
/// 入力点IDによる反時計回りの三角形。最小IDを先頭にし、辞書順に並べる。
pub fn triangles(&self) -> &[[usize; 3]] {
&self.triangles
}
/// 重複のない無向辺。各辺はu<v、一覧は辞書順。重複座標の点は代表IDのみ使う。
pub fn edges(&self) -> &[[usize; 2]] {
&self.edges
}
/// 各入力点と同じ座標の、最小の入力ID。代表点自身は自身のIDになる。
pub fn representatives(&self) -> &[usize] {
&self.representatives
}
}
fn orient(a: [i32; 2], b: [i32; 2], c: [i32; 2]) -> i64 {
let bx = i64::from(b[0]) - i64::from(a[0]);
let by = i64::from(b[1]) - i64::from(a[1]);
let cx = i64::from(c[0]) - i64::from(a[0]);
let cy = i64::from(c[1]) - i64::from(a[1]);
bx * cy - by * cx
}
/// a,b,cが反時計回りなら、pが外接円の厳密な内部にあるか。
fn in_circle(a: [i32; 2], b: [i32; 2], c: [i32; 2], p: [i32; 2]) -> bool {
let norm = |v: [i32; 2]| i64::from(v[0]).pow(2) + i64::from(v[1]).pow(2);
let p2 = norm(p);
// 座標上限B=10^9。ノルム差は最大2B^2、orientは最大8B^2でi64内。
// 積と和はi128へ拡張する。3項の絶対値の和は最大48B^4 = 4.8e37 < i128::MAX。
// pからの相対座標のノルムではなく、原点からのノルム差で範囲を抑える。
i128::from(orient(p, a, b)) * i128::from(norm(c) - p2)
+ i128::from(orient(p, b, c)) * i128::from(norm(a) - p2)
+ i128::from(orient(p, c, a)) * i128::from(norm(b) - p2)
> 0
}
// 1つの無向辺に4つの有向quad-edgeを割り当てる。0,2は実頂点、1,3は双対側。
struct Quad {
next: [usize; 4],
vertices: [usize; 2],
alive: bool,
}
struct Mesh<'a> {
points: &'a [[i32; 2]],
quads: Vec<Quad>,
free: Vec<usize>,
}
fn rot(e: usize) -> usize {
(e & !3) | ((e + 1) & 3)
}
fn symmetric(e: usize) -> usize {
e ^ 2
}
impl Mesh<'_> {
fn origin(&self, e: usize) -> usize {
self.quads[e / 4].vertices[(e % 4) / 2]
}
fn destination(&self, e: usize) -> usize {
self.origin(symmetric(e))
}
fn next(&self, e: usize) -> usize {
self.quads[e / 4].next[e % 4]
}
fn set_next(&mut self, e: usize, next: usize) {
self.quads[e / 4].next[e % 4] = next;
}
fn previous(&self, e: usize) -> usize {
rot(self.next(rot(e)))
}
fn left_next(&self, e: usize) -> usize {
self.previous(symmetric(e))
}
fn make_edge(&mut self, from: usize, to: usize) -> usize {
let block = self.free.pop().unwrap_or_else(|| {
self.quads.push(Quad {
next: [0; 4],
vertices: [0; 2],
alive: false,
});
self.quads.len() - 1
});
let e = block * 4;
self.quads[block] = Quad {
next: [e, e + 3, e + 2, e + 1],
vertices: [from, to],
alive: true,
};
e
}
fn splice(&mut self, a: usize, b: usize) {
let alpha = rot(self.next(a));
let beta = rot(self.next(b));
let an = self.next(alpha);
let bn = self.next(beta);
self.set_next(alpha, bn);
self.set_next(beta, an);
let an = self.next(a);
let bn = self.next(b);
self.set_next(a, bn);
self.set_next(b, an);
}
fn connect(&mut self, a: usize, b: usize) -> usize {
let e = self.make_edge(self.destination(a), self.origin(b));
self.splice(e, self.left_next(a));
self.splice(symmetric(e), b);
e
}
fn delete(&mut self, e: usize) {
self.splice(e, self.previous(e));
self.splice(symmetric(e), self.previous(symmetric(e)));
self.quads[e / 4].alive = false;
self.free.push(e / 4);
}
fn side(&self, point: usize, edge: usize) -> i64 {
orient(
self.points[self.origin(edge)],
self.points[self.destination(edge)],
self.points[point],
)
}
fn circle(&self, a: usize, b: usize, c: usize, p: usize) -> bool {
in_circle(
self.points[a],
self.points[b],
self.points[c],
self.points[p],
)
}
// 座標順の点列を分割し、左右の外側に沿う有向辺を返す。
fn build(&mut self, ids: &[usize]) -> (usize, usize) {
if ids.len() == 2 {
let a = self.make_edge(ids[0], ids[1]);
return (a, symmetric(a));
}
if ids.len() == 3 {
let a = self.make_edge(ids[0], ids[1]);
let b = self.make_edge(ids[1], ids[2]);
self.splice(symmetric(a), b);
let side = orient(
self.points[ids[0]],
self.points[ids[1]],
self.points[ids[2]],
);
if side == 0 {
return (a, symmetric(b));
}
let c = self.connect(b, a);
return if side > 0 {
(a, symmetric(b))
} else {
(symmetric(c), c)
};
}
let mid = ids.len() / 2;
let (mut outer_left, mut inner_left) = self.build(&ids[..mid]);
let (mut inner_right, mut outer_right) = self.build(&ids[mid..]);
loop {
if self.side(self.origin(inner_right), inner_left) > 0 {
inner_left = self.left_next(inner_left);
} else if self.side(self.origin(inner_left), inner_right) < 0 {
inner_right = self.next(symmetric(inner_right));
} else {
break;
}
}
let mut base = self.connect(symmetric(inner_right), inner_left);
if self.origin(inner_left) == self.origin(outer_left) {
outer_left = symmetric(base);
}
if self.origin(inner_right) == self.origin(outer_right) {
outer_right = base;
}
loop {
let mut left = self.next(symmetric(base));
if self.side(self.destination(left), base) < 0 {
while self.circle(
self.destination(base),
self.origin(base),
self.destination(left),
self.destination(self.next(left)),
) {
let next = self.next(left);
self.delete(left);
left = next;
}
}
let mut right = self.previous(base);
if self.side(self.destination(right), base) < 0 {
while self.circle(
self.destination(base),
self.origin(base),
self.destination(right),
self.destination(self.previous(right)),
) {
let next = self.previous(right);
self.delete(right);
right = next;
}
}
let left_valid = self.side(self.destination(left), base) < 0;
let right_valid = self.side(self.destination(right), base) < 0;
if !left_valid && !right_valid {
break;
}
if !left_valid
|| (right_valid
&& self.circle(
self.destination(left),
self.origin(left),
self.origin(right),
self.destination(right),
))
{
base = self.connect(right, symmetric(base));
} else {
base = self.connect(symmetric(base), symmetric(left));
}
}
(outer_left, outer_right)
}
}
}
pub use delaunay::Delaunay;
/// KD-treeで受け付ける各座標の絶対値の上限。
pub const KD_COORD_LIMIT: i32 = 1_000_000_000;
/// Delaunayの外接円判定をi128で正確に計算できる各座標の絶対値の上限。
pub const DELAUNAY_COORD_LIMIT: i32 = 1_000_000_000;
fn validate_point(p: [i32; 2], limit: i32) {
assert!(
p.into_iter().all(|x| (-limit..=limit).contains(&x)),
"coordinates must be in -{limit}..={limit}"
);
}
/// 検証済み座標の距離二乗。各差は最大2e9、和は最大8e18でi64に収まる。
fn squared_distance(a: [i32; 2], b: [i32; 2]) -> i64 {
let dx = i64::from(a[0]) - i64::from(b[0]);
let dy = i64::from(a[1]) - i64::from(b[1]);
dx * dx + dy * dy
}
}
pub mod graph {
use std::ops::Index;
/// 隣接リスト形式のグラフを行圧縮したグラフ
///
/// # Examples
///
/// ```
/// use cp_lib_rs::graph::{RowCompressedGraph, UnweightedEdge};
/// use itertools::Itertools;
///
/// let nodes = vec!["hoge", "fuga", "piyo"];
/// let edges = vec![
/// (1, UnweightedEdge::new(2)),
/// (2, UnweightedEdge::new(0)),
/// (0, UnweightedEdge::new(1)),
/// ];
/// let graph = RowCompressedGraph::new(3, nodes, edges);
///
/// assert_eq!(graph.len(), 3);
/// assert_eq!(graph.nodes()[0], "hoge");
/// assert_eq!(graph[0].iter().sorted().copied().collect_vec(), [UnweightedEdge::new(1)]);
/// ```
#[derive(Debug, Clone)]
pub struct RowCompressedGraph<V, E> {
nodes: Vec<V>,
edges: Vec<E>,
pos: Vec<usize>,
len: usize,
}
impl<V, E> RowCompressedGraph<V, E> {
pub fn new(n: usize, nodes: Vec<V>, edges: Vec<(usize, E)>) -> Self {
assert!(nodes.len() == n);
let mut raw_edges = edges;
raw_edges.sort_unstable_by_key(|(u, _)| *u);
let mut edges = Vec::with_capacity(raw_edges.len());
let mut pos = vec![0; n + 1];
let mut index = 0;
for (i, (u, e)) in raw_edges.into_iter().enumerate() {
assert!(u < n);
while index < u {
index += 1;
pos[index] = i;
}
edges.push(e);
}
pos[index + 1..].fill(edges.len());
Self {
nodes,
edges,
pos,
len: n,
}
}
#[allow(clippy::len_without_is_empty)]
pub fn len(&self) -> usize {
self.len
}
pub fn nodes(&self) -> &[V] {
&self.nodes
}
pub fn nodes_mut(&mut self) -> &mut [V] {
&mut self.nodes
}
}
impl<E> RowCompressedGraph<(), E> {
pub fn new_edges(n: usize, edges: Vec<(usize, E)>) -> Self {
Self::new(n, vec![(); n], edges)
}
}
impl<V, E> Index<usize> for RowCompressedGraph<V, E> {
type Output = [E];
fn index(&self, index: usize) -> &Self::Output {
let start = self.pos[index];
let end = self.pos[index + 1];
&self.edges[start..end]
}
}
pub trait EdgeTo {
fn to(&self) -> usize;
}
pub trait EdgeWeight<T>: EdgeTo {
fn weight(&self) -> &T;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct UnweightedEdge {
to: usize,
}
impl UnweightedEdge {
pub fn new(to: usize) -> Self {
Self { to }
}
}
impl EdgeTo for UnweightedEdge {
fn to(&self) -> usize {
self.to
}
}
#[derive(Debug, Clone, Copy)]
pub struct WeightedEdge<T> {
to: usize,
weight: T,
}
impl<T> WeightedEdge<T> {
pub fn new(to: usize, weight: T) -> Self {
Self { to, weight }
}
}
impl<T> EdgeTo for WeightedEdge<T> {
fn to(&self) -> usize {
self.to
}
}
impl<T> EdgeWeight<T> for WeightedEdge<T> {
fn weight(&self) -> &T {
&self.weight
}
}
}
pub mod grid {
use std::{
fmt::Display,
ops::{
Add, AddAssign, Div, DivAssign, Index, IndexMut, Mul, MulAssign, Neg, Sub,
SubAssign,
},
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct Coord {
row: u8,
col: u8,
}
impl Coord {
pub const fn new(row: usize, col: usize) -> Self {
Self {
row: row as u8,
col: col as u8,
}
}
pub const fn row(&self) -> usize {
self.row as usize
}
pub const fn col(&self) -> usize {
self.col as usize
}
pub fn in_map(&self, size: usize) -> bool {
self.row < size as u8 && self.col < size as u8
}
pub const fn to_index(&self, size: usize) -> CoordIndex {
CoordIndex(self.row as usize * size + self.col as usize)
}
pub const fn dist(&self, other: &Self) -> usize {
Self::dist_1d(self.row, other.row) + Self::dist_1d(self.col, other.col)
}
const fn dist_1d(x0: u8, x1: u8) -> usize {
x0.abs_diff(x1) as usize
}
}
impl Display for Coord {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "({}, {})", self.row, self.col)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct CoordIndex(pub usize);
impl CoordIndex {
pub const fn to_coord(&self, size: usize) -> Coord {
Coord::new(self.0 / size, self.0 % size)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct CoordDiff {
dr: i8,
dc: i8,
}
impl CoordDiff {
pub const fn new(dr: i32, dc: i32) -> Self {
Self {
dr: dr as i8,
dc: dc as i8,
}
}
pub const fn invert(&self) -> Self {
Self {
dr: -self.dr,
dc: -self.dc,
}
}
pub const fn dr(&self) -> i32 {
self.dr as i32
}
pub const fn dc(&self) -> i32 {
self.dc as i32
}
}
impl Display for CoordDiff {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "({}, {})", self.dr, self.dc)
}
}
impl Add<CoordDiff> for Coord {
type Output = Coord;
fn add(self, rhs: CoordDiff) -> Self::Output {
Coord {
row: self.row.wrapping_add(rhs.dr as u8),
col: self.col.wrapping_add(rhs.dc as u8),
}
}
}
impl AddAssign<CoordDiff> for Coord {
fn add_assign(&mut self, rhs: CoordDiff) {
self.row = self.row.wrapping_add(rhs.dr as u8);
self.col = self.col.wrapping_add(rhs.dc as u8);
}
}
impl Add<CoordDiff> for CoordDiff {
type Output = CoordDiff;
fn add(self, rhs: CoordDiff) -> Self::Output {
CoordDiff {
dr: self.dr + rhs.dr,
dc: self.dc + rhs.dc,
}
}
}
impl Add<Coord> for CoordDiff {
type Output = Coord;
fn add(self, rhs: Coord) -> Self::Output {
rhs + self
}
}
impl Sub<CoordDiff> for Coord {
type Output = Coord;
fn sub(self, rhs: CoordDiff) -> Self::Output {
Coord {
row: self.row.wrapping_sub(rhs.dr as u8),
col: self.col.wrapping_sub(rhs.dc as u8),
}
}
}
impl SubAssign<CoordDiff> for Coord {
fn sub_assign(&mut self, rhs: CoordDiff) {
*self = *self - rhs;
}
}
// Differences outside the i8 range wrap, as in CoordDiff::new.
impl Sub<Coord> for Coord {
type Output = CoordDiff;
fn sub(self, rhs: Coord) -> Self::Output {
CoordDiff::new(
self.row as i32 - rhs.row as i32,
self.col as i32 - rhs.col as i32,
)
}
}
impl Sub<CoordDiff> for CoordDiff {
type Output = CoordDiff;
fn sub(self, rhs: CoordDiff) -> Self::Output {
CoordDiff {
dr: self.dr - rhs.dr,
dc: self.dc - rhs.dc,
}
}
}
impl SubAssign<CoordDiff> for CoordDiff {
fn sub_assign(&mut self, rhs: CoordDiff) {
*self = *self - rhs;
}
}
// Scalar operations use i32 arithmetic, then narrow as in CoordDiff::new.
impl Mul<i32> for CoordDiff {
type Output = CoordDiff;
fn mul(self, rhs: i32) -> Self::Output {
CoordDiff::new(self.dr() * rhs, self.dc() * rhs)
}
}
impl Mul<CoordDiff> for i32 {
type Output = CoordDiff;
fn mul(self, rhs: CoordDiff) -> Self::Output {
rhs * self
}
}
impl MulAssign<i32> for CoordDiff {
fn mul_assign(&mut self, rhs: i32) {
*self = *self * rhs;
}
}
impl Div<i32> for CoordDiff {
type Output = CoordDiff;
fn div(self, rhs: i32) -> Self::Output {
CoordDiff::new(self.dr() / rhs, self.dc() / rhs)
}
}
impl DivAssign<i32> for CoordDiff {
fn div_assign(&mut self, rhs: i32) {
*self = *self / rhs;
}
}
impl AddAssign<CoordDiff> for CoordDiff {
fn add_assign(&mut self, rhs: CoordDiff) {
self.dr += rhs.dr;
self.dc += rhs.dc;
}
}
impl Neg for CoordDiff {
type Output = Self;
fn neg(self) -> Self::Output {
Self {
dr: -self.dr,
dc: -self.dc,
}
}
}
pub const ADJACENTS: [CoordDiff; 4] = [
CoordDiff::new(-1, 0),
CoordDiff::new(0, 1),
CoordDiff::new(1, 0),
CoordDiff::new(0, -1),
];
pub const U: usize = 0;
pub const R: usize = 1;
pub const D: usize = 2;
pub const L: usize = 3;
pub const DIRECTIONS: [char; 4] = ['U', 'R', 'D', 'L'];
#[derive(Debug, Clone)]
pub struct Map2d<T> {
size: usize,
map: Vec<T>,
}
impl<T> Map2d<T> {
pub fn new(map: Vec<T>, size: usize) -> Self {
debug_assert!(size * size == map.len());
Self { size, map }
}
pub fn from_fn(mut f: impl FnMut(Coord) -> T, size: usize) -> Self {
let mut map = Vec::with_capacity(size * size);
for row in 0..size {
for col in 0..size {
map.push(f(Coord::new(row, col)));
}
}
Self { size, map }
}
pub fn iter(&self) -> impl Iterator<Item = &T> {
self.map.iter()
}
}
impl<T: Default + Clone> Map2d<T> {
pub fn with_default(size: usize) -> Self {
let map = vec![T::default(); size * size];
Self { size, map }
}
}
impl<T> Index<Coord> for Map2d<T> {
type Output = T;
#[inline]
fn index(&self, coordinate: Coord) -> &Self::Output {
&self.map[coordinate.to_index(self.size).0]
}
}
impl<T> IndexMut<Coord> for Map2d<T> {
#[inline]
fn index_mut(&mut self, coordinate: Coord) -> &mut Self::Output {
&mut self.map[coordinate.to_index(self.size).0]
}
}
impl<T> Index<&Coord> for Map2d<T> {
type Output = T;
#[inline]
fn index(&self, coordinate: &Coord) -> &Self::Output {
&self.map[coordinate.to_index(self.size).0]
}
}
impl<T> IndexMut<&Coord> for Map2d<T> {
#[inline]
fn index_mut(&mut self, coordinate: &Coord) -> &mut Self::Output {
&mut self.map[coordinate.to_index(self.size).0]
}
}
impl<T> Index<usize> for Map2d<T> {
type Output = [T];
#[inline]
fn index(&self, row: usize) -> &Self::Output {
let begin = row * self.size;
let end = begin + self.size;
&self.map[begin..end]
}
}
impl<T> IndexMut<usize> for Map2d<T> {
#[inline]
fn index_mut(&mut self, row: usize) -> &mut Self::Output {
let begin = row * self.size;
let end = begin + self.size;
&mut self.map[begin..end]
}
}
impl<T> Index<CoordIndex> for Map2d<T> {
type Output = T;
#[inline]
fn index(&self, index: CoordIndex) -> &Self::Output {
&self.map[index.0]
}
}
impl<T> IndexMut<CoordIndex> for Map2d<T> {
#[inline]
fn index_mut(&mut self, index: CoordIndex) -> &mut Self::Output {
&mut self.map[index.0]
}
}
#[derive(Debug, Clone)]
pub struct ConstMap2d<T, const N: usize, const LEN: usize> {
map: [T; LEN],
}
impl<T, const N: usize, const LEN: usize> ConstMap2d<T, N, LEN> {
pub fn new(map: Vec<T>) -> Self {
assert_eq!(LEN, N * N);
assert_eq!(map.len(), LEN);
let Ok(map) = map.try_into() else {
unreachable!("長さ検証済みのVecから配列への変換に失敗しました。");
};
Self { map }
}
pub fn from_fn(mut f: impl FnMut(Coord) -> T) -> Self {
assert_eq!(LEN, N * N);
let map = std::array::from_fn(|index| f(Coord::new(index / N, index % N)));
Self { map }
}
pub fn iter(&self) -> impl Iterator<Item = &T> {
self.map.iter()
}
}
impl<T: Default, const N: usize, const LEN: usize> ConstMap2d<T, N, LEN> {
pub fn with_default() -> Self {
assert_eq!(LEN, N * N);
let map = std::array::from_fn(|_| T::default());
Self { map }
}
}
impl<T, const N: usize, const LEN: usize> Index<Coord> for ConstMap2d<T, N, LEN> {
type Output = T;
#[inline]
fn index(&self, coordinate: Coord) -> &Self::Output {
&self.map[coordinate.to_index(N).0]
}
}
impl<T, const N: usize, const LEN: usize> IndexMut<Coord> for ConstMap2d<T, N, LEN> {
#[inline]
fn index_mut(&mut self, coordinate: Coord) -> &mut Self::Output {
&mut self.map[coordinate.to_index(N).0]
}
}
impl<T, const N: usize, const LEN: usize> Index<&Coord> for ConstMap2d<T, N, LEN> {
type Output = T;
#[inline]
fn index(&self, coordinate: &Coord) -> &Self::Output {
&self.map[coordinate.to_index(N).0]
}
}
impl<T, const N: usize, const LEN: usize> IndexMut<&Coord> for ConstMap2d<T, N, LEN> {
#[inline]
fn index_mut(&mut self, coordinate: &Coord) -> &mut Self::Output {
&mut self.map[coordinate.to_index(N).0]
}
}
impl<T, const N: usize, const LEN: usize> Index<usize> for ConstMap2d<T, N, LEN> {
type Output = [T];
#[inline]
fn index(&self, row: usize) -> &Self::Output {
let begin = row * N;
let end = begin + N;
&self.map[begin..end]
}
}
impl<T, const N: usize, const LEN: usize> IndexMut<usize> for ConstMap2d<T, N, LEN> {
#[inline]
fn index_mut(&mut self, row: usize) -> &mut Self::Output {
let begin = row * N;
let end = begin + N;
&mut self.map[begin..end]
}
}
impl<T, const N: usize, const LEN: usize> Index<CoordIndex> for ConstMap2d<T, N, LEN> {
type Output = T;
#[inline]
fn index(&self, index: CoordIndex) -> &Self::Output {
&self.map[index.0]
}
}
impl<T, const N: usize, const LEN: usize> IndexMut<CoordIndex> for ConstMap2d<T, N, LEN> {
#[inline]
fn index_mut(&mut self, index: CoordIndex) -> &mut Self::Output {
&mut self.map[index.0]
}
}
}
pub mod modint {
use ac_library::modint::ModIntBase;
pub struct Comb<T: ModIntBase> {
fact: Vec<T>,
inv_fact: Vec<T>,
}
impl<T: ModIntBase> Comb<T> {
pub fn new(n: usize) -> Self {
let mut fact = vec![T::raw(1); n + 1];
let mut inv_fact = vec![T::raw(1); n + 1];
for i in 1..=n {
fact[i] = fact[i - 1] * T::raw(i as u32);
}
inv_fact[n] = fact[n].inv();
for i in (0..n).rev() {
inv_fact[i] = inv_fact[i + 1] * T::raw((i + 1) as u32);
}
Self { fact, inv_fact }
}
pub fn fact(&self, n: usize) -> T {
assert!(n < self.fact.len());
self.fact[n]
}
pub fn inv_fact(&self, n: usize) -> T {
assert!(n < self.inv_fact.len());
self.inv_fact[n]
}
pub fn comb(&self, n: usize, k: usize) -> T {
assert!(n < self.fact.len() && k <= n);
self.fact[n] * self.inv_fact[k] * self.inv_fact[n - k]
}
pub fn perm(&self, n: usize, k: usize) -> T {
assert!(n < self.fact.len() && k <= n);
self.fact[n] * self.inv_fact[n - k]
}
}
}
pub mod rand_yuki {
//! yukicoder 向けの外部依存なし乱数モジュール。rand 0.9 の主要な API に対応。
//! Pcg64Mcg のシードと生の出力は rand_pcg 0.9 互換。範囲抽選などの結果は変わり得る。
use std::ops::{Range, RangeInclusive};
#[derive(Clone)]
pub struct Pcg64Mcg(u128);
impl Pcg64Mcg {
pub fn new(state: u128) -> Self {
Self(state | 1)
}
}
pub trait SeedableRng: Sized {
type Seed;
fn from_seed(seed: Self::Seed) -> Self;
fn seed_from_u64(seed: u64) -> Self;
}
impl SeedableRng for Pcg64Mcg {
type Seed = [u8; 16];
fn from_seed(seed: Self::Seed) -> Self {
Self::new(u128::from_le_bytes(seed))
}
fn seed_from_u64(mut seed: u64) -> Self {
// rand_core と同じ PCG32 で 64 bit のシードを展開する。
let mut state = 0;
for shift in [0, 32, 64, 96] {
seed = seed
.wrapping_mul(6364136223846793005)
.wrapping_add(11634580027462260723);
let word = (((seed >> 18) ^ seed) >> 27) as u32;
state |= u128::from(word.rotate_right((seed >> 59) as u32)) << shift;
}
Self::new(state)
}
}
pub trait RngCore {
fn next_u64(&mut self) -> u64;
#[inline]
fn next_u32(&mut self) -> u32 {
self.next_u64() as u32
}
}
impl RngCore for Pcg64Mcg {
#[inline]
fn next_u64(&mut self) -> u64 {
self.0 = self
.0
.wrapping_mul(0x2360_ed05_1fc6_5da4_4385_df64_9fcc_f645);
((self.0 as u64) ^ ((self.0 >> 64) as u64)).rotate_right((self.0 >> 122) as u32)
}
}
pub trait Rng: RngCore {
#[inline]
fn random<T: RandomValue>(&mut self) -> T {
T::draw(self)
}
#[inline]
fn random_range<T, S: SampleRange<T>>(&mut self, range: S) -> T {
range.draw(self)
}
#[inline]
fn random_bool(&mut self, p: f64) -> bool {
assert!((0.0..=1.0).contains(&p), "probability must be in [0, 1]");
p == 1.0 || self.next_u64() < (p * 18446744073709551616.0) as u64
}
}
impl<R: RngCore + ?Sized> Rng for R {}
pub trait RandomValue {
fn draw(rng: &mut (impl Rng + ?Sized)) -> Self;
}
pub trait SampleRange<T> {
fn draw(self, rng: &mut (impl Rng + ?Sized)) -> T;
}
trait Uniform: Sized + PartialOrd {
fn draw_range(
rng: &mut (impl Rng + ?Sized),
lo: Self,
hi: Self,
inclusive: bool,
) -> Self;
}
impl<T: Uniform> SampleRange<T> for Range<T> {
#[inline]
fn draw(self, rng: &mut (impl Rng + ?Sized)) -> T {
assert!(self.start < self.end, "empty range");
T::draw_range(rng, self.start, self.end, false)
}
}
impl<T: Uniform> SampleRange<T> for RangeInclusive<T> {
#[inline]
fn draw(self, rng: &mut (impl Rng + ?Sized)) -> T {
assert!(!self.is_empty(), "empty range");
let (lo, hi) = self.into_inner();
T::draw_range(rng, lo, hi, true)
}
}
// Lemire 法。剰余による補正は下位 64 bit が幅を下回るときだけ必要。
#[inline]
fn below(rng: &mut (impl Rng + ?Sized), width: u64) -> u64 {
let mut product = u128::from(rng.next_u64()) * u128::from(width);
if (product as u64) < width {
let threshold = width.wrapping_neg() % width;
while (product as u64) < threshold {
product = u128::from(rng.next_u64()) * u128::from(width);
}
}
(product >> 64) as u64
}
macro_rules! integers {
($next:ident; $($t:ty),+) => {$(
impl RandomValue for $t {
#[inline]
fn draw(rng: &mut (impl Rng + ?Sized)) -> Self {
rng.$next() as Self
}
}
impl Uniform for $t {
#[inline]
fn draw_range(rng: &mut (impl Rng + ?Sized), lo: Self, hi: Self, inclusive: bool) -> Self {
let width = (hi as u64).wrapping_sub(lo as u64).wrapping_add(u64::from(inclusive));
// 幅が 2^64 のときは生の乱数を使う。
let offset = if width == 0 { rng.next_u64() } else { below(rng, width) };
lo.wrapping_add(offset as Self)
}
}
)+};
}
integers!(next_u32; u8, u16, u32, i8, i16, i32);
integers!(next_u64; u64, usize, i64, isize);
impl RandomValue for bool {
#[inline]
fn draw(rng: &mut (impl Rng + ?Sized)) -> Self {
(rng.next_u32() as i32) < 0
}
}
macro_rules! floats {
($t:ty, $next:ident, $shift:expr, $scale:expr) => {
impl RandomValue for $t {
#[inline]
fn draw(rng: &mut (impl Rng + ?Sized)) -> Self {
(rng.$next() >> $shift) as Self * $scale
}
}
impl Uniform for $t {
#[inline]
fn draw_range(
rng: &mut (impl Rng + ?Sized),
lo: Self,
hi: Self,
inclusive: bool,
) -> Self {
let width = hi - lo;
assert!(width.is_finite(), "range width must be finite");
let unit = rng.random::<Self>();
if inclusive {
(lo + width * (unit / (1.0 - $scale))).min(hi)
} else {
(lo + width * unit).min(hi.next_down())
}
}
}
};
}
floats!(f32, next_u32, 8, 1.0 / 16777216.0);
floats!(f64, next_u64, 11, 1.0 / 9007199254740992.0);
pub mod seq {
use super::Rng;
pub trait IndexedRandom {
type Output;
fn choose(&self, rng: &mut (impl Rng + ?Sized)) -> Option<&Self::Output>;
}
pub trait IndexedMutRandom: IndexedRandom {
fn choose_mut(
&mut self,
rng: &mut (impl Rng + ?Sized),
) -> Option<&mut Self::Output>;
}
pub trait SliceRandom: IndexedMutRandom {
fn shuffle(&mut self, rng: &mut (impl Rng + ?Sized));
/// 選んだ要素と残りの要素を返す。選ぶ個数はスライス長で打ち切る。
fn partial_shuffle(
&mut self,
rng: &mut (impl Rng + ?Sized),
amount: usize,
) -> (&mut [Self::Output], &mut [Self::Output]);
}
impl<T> IndexedRandom for [T] {
type Output = T;
fn choose(&self, rng: &mut (impl Rng + ?Sized)) -> Option<&T> {
(!self.is_empty()).then(|| &self[rng.random_range(0..self.len())])
}
}
impl<T> IndexedMutRandom for [T] {
fn choose_mut(&mut self, rng: &mut (impl Rng + ?Sized)) -> Option<&mut T> {
(!self.is_empty()).then(|| {
let i = rng.random_range(0..self.len());
&mut self[i]
})
}
}
impl<T> SliceRandom for [T] {
fn shuffle(&mut self, rng: &mut (impl Rng + ?Sized)) {
self.partial_shuffle(rng, self.len());
}
fn partial_shuffle(
&mut self,
rng: &mut (impl Rng + ?Sized),
amount: usize,
) -> (&mut [T], &mut [T]) {
let split = self.len().saturating_sub(amount);
for i in (split.max(1)..self.len()).rev() {
self.swap(i, rng.random_range(0..=i));
}
let (rest, chosen) = self.split_at_mut(split);
(chosen, rest)
}
}
}
pub mod prelude {
pub use super::seq::{IndexedMutRandom, IndexedRandom, SliceRandom};
pub use super::{Rng, RngCore, SeedableRng};
}
}
pub mod random {
use super::rand_yuki::Rng;
use num::{FromPrimitive, PrimInt};
use std::ops::{Range, RangeInclusive};
/// 高速な乱数生成の拡張トレイト
pub trait RandExtension {
fn fast_gen_range_u64x1<T: PrimInt + FromPrimitive, R: BoundedRange<T>>(
&mut self,
range: R,
) -> T;
fn fast_gen_range_u32x1<T: PrimInt + FromPrimitive, R: BoundedRange<T>>(
&mut self,
range: R,
) -> T;
fn fast_gen_range_u32x2<
T0: PrimInt + FromPrimitive,
T1: PrimInt + FromPrimitive,
R0: BoundedRange<T0>,
R1: BoundedRange<T1>,
>(
&mut self,
range0: R0,
range1: R1,
) -> (T0, T1);
fn fast_gen_range_u16x1<T: PrimInt + FromPrimitive, R: BoundedRange<T>>(
&mut self,
range: R,
) -> T;
fn fast_gen_range_u16x2<
T0: PrimInt + FromPrimitive,
T1: PrimInt + FromPrimitive,
R0: BoundedRange<T0>,
R1: BoundedRange<T1>,
>(
&mut self,
range0: R0,
range1: R1,
) -> (T0, T1);
fn fast_gen_range_u16x3<
T0: PrimInt + FromPrimitive,
T1: PrimInt + FromPrimitive,
T2: PrimInt + FromPrimitive,
R0: BoundedRange<T0>,
R1: BoundedRange<T1>,
R2: BoundedRange<T2>,
>(
&mut self,
range0: R0,
range1: R1,
range2: R2,
) -> (T0, T1, T2);
fn fast_gen_range_u16x4<
T0: PrimInt + FromPrimitive,
T1: PrimInt + FromPrimitive,
T2: PrimInt + FromPrimitive,
T3: PrimInt + FromPrimitive,
R0: BoundedRange<T0>,
R1: BoundedRange<T1>,
R2: BoundedRange<T2>,
R3: BoundedRange<T3>,
>(
&mut self,
range0: R0,
range1: R1,
range2: R2,
range3: R3,
) -> (T0, T1, T2, T3);
}
impl<G: Rng> RandExtension for G {
fn fast_gen_range_u64x1<T: PrimInt + FromPrimitive, R: BoundedRange<T>>(
&mut self,
range: R,
) -> T {
let rand_value = self.next_u64();
gen_range_u64(range, rand_value)
}
fn fast_gen_range_u32x1<T: PrimInt + FromPrimitive, R: BoundedRange<T>>(
&mut self,
range: R,
) -> T {
let rand_value = self.next_u64();
gen_range_u32(range, rand_value as u32)
}
fn fast_gen_range_u32x2<
T0: PrimInt + FromPrimitive,
T1: PrimInt + FromPrimitive,
R0: BoundedRange<T0>,
R1: BoundedRange<T1>,
>(
&mut self,
range0: R0,
range1: R1,
) -> (T0, T1) {
let rand_value = self.next_u64();
let v0 = gen_range_u32(range0, rand_value as u32);
let v1 = gen_range_u32(range1, (rand_value >> 32) as u32);
(v0, v1)
}
fn fast_gen_range_u16x1<T: PrimInt + FromPrimitive, R: BoundedRange<T>>(
&mut self,
range: R,
) -> T {
let rand_value = self.next_u64();
gen_range_u16(range, rand_value as u16)
}
fn fast_gen_range_u16x2<
T0: PrimInt + FromPrimitive,
T1: PrimInt + FromPrimitive,
R0: BoundedRange<T0>,
R1: BoundedRange<T1>,
>(
&mut self,
range0: R0,
range1: R1,
) -> (T0, T1) {
let rand_value = self.next_u64();
let v0 = gen_range_u16(range0, rand_value as u16);
let v1 = gen_range_u16(range1, (rand_value >> 16) as u16);
(v0, v1)
}
fn fast_gen_range_u16x3<
T0: PrimInt + FromPrimitive,
T1: PrimInt + FromPrimitive,
T2: PrimInt + FromPrimitive,
R0: BoundedRange<T0>,
R1: BoundedRange<T1>,
R2: BoundedRange<T2>,
>(
&mut self,
range0: R0,
range1: R1,
range2: R2,
) -> (T0, T1, T2) {
let rand_value = self.next_u64();
let v0 = gen_range_u16(range0, rand_value as u16);
let v1 = gen_range_u16(range1, (rand_value >> 16) as u16);
let v2 = gen_range_u16(range2, (rand_value >> 32) as u16);
(v0, v1, v2)
}
fn fast_gen_range_u16x4<
T0: PrimInt + FromPrimitive,
T1: PrimInt + FromPrimitive,
T2: PrimInt + FromPrimitive,
T3: PrimInt + FromPrimitive,
R0: BoundedRange<T0>,
R1: BoundedRange<T1>,
R2: BoundedRange<T2>,
R3: BoundedRange<T3>,
>(
&mut self,
range0: R0,
range1: R1,
range2: R2,
range3: R3,
) -> (T0, T1, T2, T3) {
let rand_value = self.next_u64();
let v0 = gen_range_u16(range0, rand_value as u16);
let v1 = gen_range_u16(range1, (rand_value >> 16) as u16);
let v2 = gen_range_u16(range2, (rand_value >> 32) as u16);
let v3 = gen_range_u16(range3, (rand_value >> 48) as u16);
(v0, v1, v2, v3)
}
}
fn gen_range_u64<T: PrimInt + FromPrimitive, R: BoundedRange<T>>(
range: R,
rand_value: u64,
) -> T {
assert!(!range.is_empty(), "cannot sample empty range");
let width = range.width().to_u64().expect("width must fit in u64");
let start = range.start();
let value = (((width as u128) * (rand_value as u128)) >> 64) as u64;
T::from_u64(value).expect("value must fit in T") + start
}
fn gen_range_u32<T: PrimInt + FromPrimitive, R: BoundedRange<T>>(
range: R,
rand_value: u32,
) -> T {
assert!(!range.is_empty(), "cannot sample empty range");
let width = range.width().to_u32().expect("width must fit in u32");
let start = range.start();
let value = (((width as u64) * (rand_value as u64)) >> 32) as u32;
T::from_u32(value).expect("value must fit in T") + start
}
fn gen_range_u16<T: PrimInt + FromPrimitive, R: BoundedRange<T>>(
range: R,
rand_value: u16,
) -> T {
assert!(!range.is_empty(), "cannot sample empty range");
let width = range.width().to_u16().expect("width must fit in u16");
let start = range.start();
let value = (((width as u32) * (rand_value as u32)) >> 16) as u16;
T::from_u16(value).expect("value must fit in T") + start
}
pub trait BoundedRange<T> {
fn start(&self) -> T;
fn width(&self) -> T;
fn is_empty(&self) -> bool;
}
impl<T: PrimInt> BoundedRange<T> for Range<T> {
fn start(&self) -> T {
self.start
}
fn width(&self) -> T {
self.end - self.start
}
fn is_empty(&self) -> bool {
self.start >= self.end
}
}
impl<T: PrimInt> BoundedRange<T> for RangeInclusive<T> {
fn start(&self) -> T {
*self.start()
}
fn width(&self) -> T {
*self.end() - *self.start() + T::one()
}
fn is_empty(&self) -> bool {
self.start() > self.end()
}
}
}
pub mod util {
//! よく使われるユーティリティ関数をまとめたモジュール
use std::{
fmt::Display,
io::{self, BufWriter, Write as _},
};
use num::PrimInt;
/// 最小値と最大値を更新するトレイト
///
/// # Examples
///
/// ```
/// use cp_lib_rs::util::ChangeMinMax;
///
/// let mut x = 10;
/// assert!(x.change_min(3));
/// assert_eq!(x, 3);
/// ```
pub trait ChangeMinMax {
fn change_min(&mut self, v: Self) -> bool;
fn change_max(&mut self, v: Self) -> bool;
}
impl<T: PartialOrd> ChangeMinMax for T {
fn change_min(&mut self, v: T) -> bool {
*self > v && {
*self = v;
true
}
}
fn change_max(&mut self, v: T) -> bool {
*self < v && {
*self = v;
true
}
}
}
/// 条件に従ってYes/Noを出力する
///
/// # Examples
///
/// ```
/// use cp_lib_rs::yesno;
///
/// let n = 3;
/// yesno!(3 % 2 == 0)
/// ```
#[macro_export]
macro_rules! yesno {
($p:expr) => {
if $p {
println!("Yes");
} else {
println!("No");
}
};
}
/// 標準出力・標準エラー出力に出力するトレイト
///
/// # Examples
///
/// ```
/// use cp_lib_rs::util::PrintLine as _;
///
/// let x = 5;
/// x.println();
/// x.eprintln();
///
/// let y = [1, 2, 3];
/// y.println();
/// y.eprintln();
/// ```
pub trait PrintLine {
fn println(&self);
fn eprintln(&self);
}
/// 単体値版
impl<T: Display> PrintLine for T {
fn println(&self) {
println!("{self}");
}
fn eprintln(&self) {
eprintln!("{self}");
}
}
/// スライス版
impl<T: Display> PrintLine for [T] {
fn println(&self) {
let stdout = io::stdout();
let mut out = BufWriter::new(stdout.lock());
let mut first = true;
for x in self {
if !first {
out.write_all(b" ").unwrap();
}
write!(out, "{x}").unwrap();
first = false;
}
out.write_all(b"\n").unwrap();
// drop(out)でflush
}
fn eprintln(&self) {
let stderr = io::stderr();
let mut out = BufWriter::new(stderr.lock());
let mut first = true;
for x in self {
if !first {
out.write_all(b" ").unwrap();
}
write!(out, "{x}").unwrap();
first = false;
}
out.write_all(b"\n").unwrap();
}
}
/// 多次元配列を作成する
///
/// # Examples
///
/// ```
/// use cp_lib_rs::mat;
///
/// let a = mat![0; 4; 3];
/// assert_eq!(a, vec![vec![0; 3]; 4]);
/// ```
#[macro_export]
macro_rules! mat {
($($e:expr),*) => { vec![$($e),*] };
($($e:expr,)*) => { vec![$($e),*] };
($e:expr; $d:expr) => { vec![$e; $d] };
($e:expr; $d:expr $(; $ds:expr)+) => { vec![mat![$e $(; $ds)*]; $d] };
}
/// 整数の二分探索を行う
///
/// # Examples
///
/// ```
/// use cp_lib_rs::util::binary_search;
///
/// let result = binary_search(0, 10, |x| x * x <= 5);
/// assert_eq!(result, 2);
/// ```
pub fn binary_search<T: PrimInt>(ok: T, ng: T, f: impl Fn(T) -> bool) -> T {
let mut ok = ok;
let mut ng = ng;
while ok.max(ng) - ok.min(ng) > T::one() {
let mid = (ok + ng) / (T::one() << 1);
if f(mid) {
ok = mid;
} else {
ng = mid;
}
}
ok
}
}
}
mod problem {
use proconio::input;
use std::{array, fmt::Display};
use crate::library::grid::{ADJACENTS, Coord, D, L, Map2d, R, U};
#[derive(Debug, Clone)]
pub struct Input {
pub a: [usize; Self::PORT_COUNT],
pub graph: Map2d<[Coord; 4]>,
}
impl Input {
pub const MAP_SIZE: usize = 64;
pub const PORT_COUNT: usize = Self::MAP_SIZE * 4;
pub fn read() -> Self {
input! {
n: usize,
a: [usize; Self::PORT_COUNT],
}
assert_eq!(n, Self::MAP_SIZE);
let a = array::from_fn(|i| a[i] - 1);
let mut graph = Map2d::from_fn(|_| [Coord::new(!0, !0); 4], Input::MAP_SIZE);
for row in 0..Self::MAP_SIZE {
for col in 0..Self::MAP_SIZE {
let pos = Coord::new(row, col);
for dir in 0..4 {
let next = pos + ADJACENTS[dir];
if next.in_map(Input::MAP_SIZE) {
graph[pos][dir] = next;
}
}
}
}
Self { a, graph }
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Mirror {
#[default]
None,
Slash,
Backslash,
}
impl Mirror {
const NONE_DIR: [usize; 4] = [U, R, D, L];
const SLASH_DIR: [usize; 4] = [R, U, L, D];
const BACKSLASH_DIR: [usize; 4] = [L, D, R, U];
pub fn change_dir(&self, dir: usize) -> usize {
match self {
Self::None => Self::NONE_DIR[dir],
Self::Slash => Self::SLASH_DIR[dir],
Self::Backslash => Self::BACKSLASH_DIR[dir],
}
}
pub fn is_mirror(&self) -> bool {
!matches!(self, Self::None)
}
}
impl Display for Mirror {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::None => write!(f, "0"),
Self::Slash => write!(f, "1"),
Self::Backslash => write!(f, "2"),
}
}
}
#[derive(Debug, Clone)]
pub struct Output {
map: Map2d<Mirror>,
}
impl Output {
pub fn new(map: Map2d<Mirror>) -> Self {
Self { map }
}
}
impl Display for Output {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for row in 0..Input::MAP_SIZE {
for col in 0..Input::MAP_SIZE {
write!(f, "{}", self.map[row][col])?;
}
writeln!(f)?;
}
Ok(())
}
}
}
mod solver {
pub mod annealing_solver {
use std::time::Duration;
use ac_library::FenwickTree;
use crate::{
library::{
annealing::{self, SimdSelector},
data_structures::IndexSet16,
grid::{Coord, D, L, Map2d, R, U},
random::RandExtension,
},
neighbors,
problem::{Input, Mirror, Output},
};
pub fn solve(input: &Input) -> Output {
let env = Env::new(input.clone());
let state = State::new(&env);
let (state, stats) = annealing::run_annealing::<Neighbors, SimdSelector, 16>(
&env,
state,
3e1,
1e0,
Duration::from_millis(1990),
42,
);
eprintln!("{}", stats);
Output::new(state.map)
}
neighbors! {
Neighbors,
Env,
State,
[
AddMirror => 10.0,
RemoveMirror => 1.0,
]
}
struct Env {
input: Input,
in_positions: [(Coord, usize); Input::PORT_COUNT],
out_ports: Map2d<[Option<usize>; 4]>,
}
impl Env {
fn new(input: Input) -> Self {
let mut in_positions = [(Coord::new(0, 0), 0); Input::PORT_COUNT];
let mut out_ports: Map2d<[Option<usize>; 4]> = Map2d::with_default(Input::MAP_SIZE);
for index in 0..Input::PORT_COUNT {
let (pos, dir) = if index < Input::MAP_SIZE {
(Coord::new(0, index), D)
} else if index < 2 * Input::MAP_SIZE {
(Coord::new(index - Input::MAP_SIZE, Input::MAP_SIZE - 1), L)
} else if index < 3 * Input::MAP_SIZE {
(
Coord::new(Input::MAP_SIZE - 1, 3 * Input::MAP_SIZE - 1 - index),
U,
)
} else {
(Coord::new(4 * Input::MAP_SIZE - 1 - index, 0), R)
};
in_positions[index] = (pos, dir);
}
for index in 0..Input::PORT_COUNT {
let (pos, dir) = if index < Input::MAP_SIZE {
(Coord::new(0, index), U)
} else if index < 2 * Input::MAP_SIZE {
(Coord::new(index - Input::MAP_SIZE, Input::MAP_SIZE - 1), R)
} else if index < 3 * Input::MAP_SIZE {
(
Coord::new(Input::MAP_SIZE - 1, 3 * Input::MAP_SIZE - 1 - index),
D,
)
} else {
(Coord::new(4 * Input::MAP_SIZE - 1 - index, 0), L)
};
out_ports[pos][dir] = Some(index);
}
Self {
input,
in_positions,
out_ports,
}
}
}
#[derive(Debug, Clone)]
struct State {
map: Map2d<Mirror>,
outputs: [usize; Input::PORT_COUNT],
ray: Map2d<[usize; 4]>,
empty_cells: IndexSet16,
mirror_cells: IndexSet16,
mirrors: i32,
ray_len: i32,
}
impl State {
const NO_RAY: usize = !0;
fn new(env: &Env) -> Self {
let map = Map2d::with_default(Input::MAP_SIZE);
let outputs = [0; Input::PORT_COUNT];
let ray = Map2d::from_fn(|_| [Self::NO_RAY; 4], Input::MAP_SIZE);
let mut empty_cells = IndexSet16::new(Input::MAP_SIZE * Input::MAP_SIZE);
for index in 0..Input::MAP_SIZE * Input::MAP_SIZE {
empty_cells.add(index as u16);
}
let mirror_cells = IndexSet16::new(Input::MAP_SIZE * Input::MAP_SIZE);
let mut output = Self {
map,
outputs,
empty_cells,
mirror_cells,
ray,
mirrors: 0,
ray_len: 0,
};
for port_index in 0..Input::PORT_COUNT {
output.trace_ray(env, port_index);
}
output
}
fn trace_ray(&mut self, env: &Env, port_index: usize) {
let (mut pos, mut dir) = env.in_positions[port_index];
loop {
dir = self.map[pos].change_dir(dir);
self.ray[pos][dir] = port_index;
self.ray_len += 1;
if let Some(index) = env.out_ports[pos][dir] {
self.outputs[index] = port_index;
break;
}
pos = env.input.graph[pos][dir];
}
}
fn erase_ray(&mut self, env: &Env, port_index: usize) {
let (mut pos, mut dir) = env.in_positions[port_index];
loop {
dir = self.map[pos].change_dir(dir);
self.ray[pos][dir] = Self::NO_RAY;
self.ray_len -= 1;
if let Some(index) = env.out_ports[pos][dir] {
self.outputs[index] = Self::NO_RAY;
break;
}
pos = env.input.graph[pos][dir];
}
}
fn calc_score(&self, env: &Env) -> Score {
let mut bit = FenwickTree::new(Input::PORT_COUNT, 0i32);
let mut inv = 0;
for &output in self.outputs.iter().rev() {
let v = env.input.a[output];
inv += bit.accum(v);
bit.add(v, 1);
}
Score::new(inv, self.mirrors, self.ray_len)
}
}
impl annealing::State for State {
type Env = Env;
type Score = Score;
fn score(&self, env: &Self::Env) -> Self::Score {
self.calc_score(env)
}
}
struct Score {
raw_score: i32,
mirror_penalty: i32,
len_penalty: i32,
}
impl Score {
fn new(inv: i32, mirrors: i32, ray_len: i32) -> Self {
let raw_score = (Input::PORT_COUNT * (Input::PORT_COUNT - 1) / 2) as i32 - inv;
Self {
raw_score,
mirror_penalty: mirrors,
len_penalty: ray_len,
}
}
}
impl annealing::Score for Score {
fn raw_score(&self) -> f64 {
self.raw_score as f64
}
fn annealing_score(&self, progress: f64) -> f64 {
let t = 1.0 - progress;
let mirror_penalty = self.mirror_penalty as f64 * 100.0 * t * t * t;
let len_penalty = 0.5 * self.len_penalty as f64 * t * t * t;
self.raw_score() - mirror_penalty - len_penalty
}
}
struct AddMirror {
pos: Coord,
old_mirror: Mirror,
new_mirror: Mirror,
rays: Vec<usize>,
}
impl annealing::Neighbor for AddMirror {
type Env = Env;
type State = State;
fn generate(
_env: &Self::Env,
state: &Self::State,
rng: &mut annealing::AnnealingRng,
_progress: f64,
) -> Option<Self> {
if state.empty_cells.len() == 0 {
return None;
}
let index = state.empty_cells.as_slice()
[rng.fast_gen_range_u16x1(0..state.empty_cells.len()) as usize];
let pos = Coord::new(
index as usize / Input::MAP_SIZE,
index as usize % Input::MAP_SIZE,
);
let old_mirror = state.map[pos];
let new_mirror = match rng.fast_gen_range_u16x1(0..2) {
0 => Mirror::Slash,
1 => Mirror::Backslash,
_ => unreachable!(),
};
let mut rays = vec![];
for dir in 0..4 {
let r = state.ray[pos][dir];
if r != State::NO_RAY {
rays.push(r);
}
}
rays.sort_unstable();
rays.dedup();
Some(Self {
pos,
old_mirror,
new_mirror,
rays,
})
}
fn preprocess(&mut self, env: &Self::Env, state: &mut Self::State) {
for &ray in &self.rays {
state.erase_ray(env, ray);
}
state.map[self.pos] = self.new_mirror;
state.mirrors +=
self.new_mirror.is_mirror() as i32 - self.old_mirror.is_mirror() as i32;
state
.empty_cells
.remove(self.pos.to_index(Input::MAP_SIZE).0 as u16);
state
.mirror_cells
.add(self.pos.to_index(Input::MAP_SIZE).0 as u16);
for &ray in &self.rays {
state.trace_ray(env, ray);
}
}
fn postprocess(self, _env: &Self::Env, _state: &mut Self::State) {
// do nothing
}
fn rollback(self, env: &Self::Env, state: &mut Self::State) {
for &ray in &self.rays {
state.erase_ray(env, ray);
}
state.map[self.pos] = self.old_mirror;
state.mirrors +=
self.old_mirror.is_mirror() as i32 - self.new_mirror.is_mirror() as i32;
state
.mirror_cells
.remove(self.pos.to_index(Input::MAP_SIZE).0 as u16);
state
.empty_cells
.add(self.pos.to_index(Input::MAP_SIZE).0 as u16);
for &ray in &self.rays {
state.trace_ray(env, ray);
}
}
}
struct RemoveMirror {
pos: Coord,
old_mirror: Mirror,
new_mirror: Mirror,
rays: Vec<usize>,
}
impl annealing::Neighbor for RemoveMirror {
type Env = Env;
type State = State;
fn generate(
_env: &Self::Env,
state: &Self::State,
rng: &mut annealing::AnnealingRng,
_progress: f64,
) -> Option<Self> {
if state.mirror_cells.len() == 0 {
return None;
}
let index = state.mirror_cells.as_slice()
[rng.fast_gen_range_u16x1(0..state.mirror_cells.len()) as usize];
let pos = Coord::new(
index as usize / Input::MAP_SIZE,
index as usize % Input::MAP_SIZE,
);
let old_mirror = state.map[pos];
let new_mirror = Mirror::None;
let mut rays = vec![];
for dir in 0..4 {
let r = state.ray[pos][dir];
if r != State::NO_RAY {
rays.push(r);
}
}
rays.sort_unstable();
rays.dedup();
Some(Self {
pos,
old_mirror,
new_mirror,
rays,
})
}
fn preprocess(&mut self, env: &Self::Env, state: &mut Self::State) {
for &ray in &self.rays {
state.erase_ray(env, ray);
}
state.map[self.pos] = self.new_mirror;
state.mirrors +=
self.new_mirror.is_mirror() as i32 - self.old_mirror.is_mirror() as i32;
state
.mirror_cells
.remove(self.pos.to_index(Input::MAP_SIZE).0 as u16);
state
.empty_cells
.add(self.pos.to_index(Input::MAP_SIZE).0 as u16);
for &ray in &self.rays {
state.trace_ray(env, ray);
}
}
fn postprocess(self, _env: &Self::Env, _state: &mut Self::State) {
// do nothing
}
fn rollback(self, env: &Self::Env, state: &mut Self::State) {
for &ray in &self.rays {
state.erase_ray(env, ray);
}
state.map[self.pos] = self.old_mirror;
state.mirrors +=
self.old_mirror.is_mirror() as i32 - self.new_mirror.is_mirror() as i32;
state
.empty_cells
.remove(self.pos.to_index(Input::MAP_SIZE).0 as u16);
state
.mirror_cells
.add(self.pos.to_index(Input::MAP_SIZE).0 as u16);
for &ray in &self.rays {
state.trace_ray(env, ray);
}
}
}
}
}
use crate::problem::Input;
fn main() {
let input = Input::read();
let output = solver::annealing_solver::solve(&input);
print!("{}", output);
}
terry_u16