Files
CodeObject/storage/jungol/rs/completed/14024.rs

56 lines
1.4 KiB
Rust

use std::{
cmp::min, io::{read_to_string, stdin, stdout, Write},
};
fn main() {
let temp = read_to_string(stdin()).unwrap();
let mut iter = temp
.split_ascii_whitespace()
.map(|x| x.parse::<usize>().unwrap());
let (n, m, q) = (
iter.next().unwrap(),
iter.next().unwrap(),
iter.next().unwrap(),
);
let mut lock = stdout().lock();
let mut bfs = (0..m).map(|_| iter.next().unwrap()).collect::<Vec<_>>();
bfs.sort();
let dist = |a: usize, b: usize| -> usize {
let d = if a > b { a - b } else { b - a };
min(d, 2 * n - d)
};
for _ in 0..q {
let (mut x, mut y) = (iter.next().unwrap(), iter.next().unwrap());
if x > y {
(x, y) = (y, x);
}
let delta = y - x;
let mut r = min(delta, 2 * n - delta);
let (px, py) = (x % n, y % n);
let ix = bfs.partition_point(|&k| k < px);
let iy = bfs.partition_point(|&k| k < py);
let cands = [(ix + m - 1) % m, ix % m, (iy + m - 1) % m, iy % m];
for &cand in &cands {
let k = bfs[cand];
let u = k;
let v = k + n;
let d1 = dist(x, u) + dist(v, y) + 1;
let d2 = dist(x, v) + dist(u, y) + 1;
r = min(r, d1);
r = min(r, d2);
}
writeln!(lock, "{}", r).unwrap();
}
}