結果

問題 No.1094 木登り / Climbing tree
ユーザー nebocconebocco
提出日時 2021-03-17 19:16:09
言語 Rust
(1.77.0 + proconio)
結果
AC  
実行時間 636 ms / 2,000 ms
コード長 15,137 bytes
コンパイル時間 15,373 ms
コンパイル使用メモリ 378,924 KB
実行使用メモリ 65,936 KB
最終ジャッジ日時 2024-11-08 07:19:22
合計ジャッジ時間 28,822 ms
ジャッジサーバーID
(参考情報)
judge1 / judge2
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
5,248 KB
testcase_01 AC 604 ms
64,900 KB
testcase_02 AC 177 ms
61,076 KB
testcase_03 AC 26 ms
7,296 KB
testcase_04 AC 158 ms
27,984 KB
testcase_05 AC 381 ms
52,744 KB
testcase_06 AC 118 ms
24,488 KB
testcase_07 AC 487 ms
65,924 KB
testcase_08 AC 483 ms
65,808 KB
testcase_09 AC 483 ms
65,804 KB
testcase_10 AC 457 ms
65,780 KB
testcase_11 AC 530 ms
65,440 KB
testcase_12 AC 636 ms
65,396 KB
testcase_13 AC 549 ms
65,508 KB
testcase_14 AC 465 ms
65,508 KB
testcase_15 AC 52 ms
20,056 KB
testcase_16 AC 126 ms
52,112 KB
testcase_17 AC 82 ms
33,856 KB
testcase_18 AC 68 ms
26,956 KB
testcase_19 AC 109 ms
44,500 KB
testcase_20 AC 600 ms
65,404 KB
testcase_21 AC 91 ms
35,644 KB
testcase_22 AC 511 ms
65,936 KB
testcase_23 AC 492 ms
65,152 KB
testcase_24 AC 498 ms
65,016 KB
testcase_25 AC 492 ms
65,028 KB
testcase_26 AC 492 ms
65,156 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

fn main() {
	let mut io = IO::new();
    input!{ from io,
		n: usize,
		ed:[(Usize1, Usize1, i64); n-1],
		q: usize,
		query: [(Usize1, Usize1); q]
    }
	let mut hld = HeavyLightDecomposition::new(n);
	let mut g = UndirectedGraph::new(n);
	for &(u, v, c) in &ed {
		hld.add_edge(u, v);
		g.add_edge(u, v, c);
	}
	let (dist, _, _, _) = tree_dfs(&g, 0);
	hld.build(0);
	for &(u, v) in &query {
		let p = hld.lca(u, v);
		io.println(dist[u] + dist[v] - dist[p] * 2);
	}
}

// ------------ Heavy Light Decomposition start ------------

use std::ops::Range;

pub struct HeavyLightDecomposition {
	graph: Vec<Vec<usize>>,
	index: Vec<usize>, // 新しい頂点番号
	parent: Vec<usize>, // 親
	head: Vec<usize>, // 属するHeavy Pathの根
	range: Vec<usize>, // 部分木の開区間右端
}

impl HeavyLightDecomposition {
	pub fn new(n: usize) -> Self {
		Self {
			graph: vec![Vec::new(); n],
			index: Vec::new(),
			parent: Vec::new(),
			head: Vec::new(),
			range: Vec::new(),
		}
	}

	pub fn add_edge(&mut self, u: usize, v: usize) {
		self.graph[u].push(v);
		self.graph[v].push(u);
	}

	pub fn build(&mut self, root: usize)  {
		let graph = &mut self.graph;
		let n = graph.len();
		let mut index = vec![0; n];
		let mut parent = vec![n; n];
		let mut head = vec![root; n];
		let mut range = vec![0; n];
		let mut siz = vec![1; n];
		let mut st = Vec::new();
		st.push(root);
		while let Some(v) = st.pop() {
			if v < n {
				st.push(!v);
				if let Some(k) = graph[v].iter().position(|&u| u == parent[v]) {
					graph[v].swap_remove(k);
				}
				graph[v].iter().for_each(|&u| { parent[u] = v; st.push(u); });
			} else {
				let v = !v;
				for i in 0..graph[v].len() {
					let u = graph[v][i];
					siz[v] += siz[u];
					if siz[graph[v][0]] < siz[u] {
						graph[v].swap(0, i);
					}
				}
			}
		}
		st.push(root);
		let mut c = 0;
		while let Some(v) = st.pop() {
			if v < n {
				st.push(!v);
				index[v] = c; c += 1;
				for &u in graph[v].iter().skip(1) {
					head[u] = u;
					st.push(u);
				}
				if let Some(&u) = graph[v].get(0) {
					head[u] = head[v];
					st.push(u);
				}
			} else {
				range[!v] = c;
			}
		}
		self.index = index;
		self.parent = parent;
		self.head = head;
		self.range = range;
	}

	pub fn lca(&self, mut u: usize, mut v: usize) -> usize {
		let parent = &self.parent;
		let head = &self.head;
		let index = &self.index;

		while head[u] != head[v] {
			if index[u] < index[v] {
				v = parent[head[v]];
			} else {
				u = parent[head[u]];
			}
		}
		if index[u] < index[v] {
			u
		} else {
			v
		}
	}

	fn for_each(&self, mut u: usize, mut v: usize, b: usize) -> (Vec<Range<usize>>, Vec<Range<usize>>) {
		let parent = &self.parent;
		let head = &self.head;
		let index = &self.index;

		let mut up = Vec::new();
		let mut down = Vec::new();
		while head[u] != head[v] {
			if index[u] < index[v] {
				let h = head[v];
				down.push(index[h]..index[v] + 1);
				v = parent[h];
			} else {
				let h = head[u];
				up.push(index[h]..index[u] + 1);
				u = parent[h];
			}
		}
		if index[u] < index[v] {
			down.push(index[u] + b .. index[v] + 1);
		} else if index[v] + b < index[u] + 1 {
			up.push(index[v] + b .. index[u] + 1);
		}

		down.reverse();
		(up, down)
	}

	pub fn id(&self, v: usize) -> usize {
		self.index[v]
	}

	pub fn for_each_vertex(&self, u: usize, v: usize) -> (Vec<Range<usize>>, Vec<Range<usize>>) {
		self.for_each(u, v, 0)
	}
	pub fn for_each_edge(&self, u: usize, v: usize) -> (Vec<Range<usize>>, Vec<Range<usize>>) {
		self.for_each(u, v, 1)
	}
	pub fn subtree_range(&self, v: usize) -> Range<usize> {
		self.index[v]..self.range[v]
	}
}

// ------------ Heavy Light Decomposition end ------------

// ------------ Graph impl start ------------

pub trait Cost:
    Element
    + Clone + Copy + std::fmt::Display
    + Eq + Ord
    + Zero + One
    + Add<Output = Self> + AddAssign
    + Sub<Output = Self>
    + Neg<Output = Self>
{
    const MAX: Self;
}

#[derive(Copy, Clone)]
pub struct Edge<C = Void> {
    // pub from: usize,
    pub to: usize,
    pub cost: C,
    pub id: usize
}

pub struct UndirectedGraph<C>(pub Vec<Vec<Edge<C>>>, pub usize);
pub struct DirectedGraph<C>{
    pub forward: Vec<Vec<Edge<C>>>,
    pub backward: Vec<Vec<Edge<C>>>,
    pub count: usize,
}

pub trait Graph<C: Element> {
    fn new(size: usize) -> Self;
    fn size(&self) -> usize;
    fn add_edge(&mut self, u: usize, v: usize, cost: C);
    fn edges_from(&self, v: usize) -> std::slice::Iter<Edge<C>>;
}

impl<C: Element> Graph<C> for UndirectedGraph<C> {
    fn new(size: usize) -> Self {
        Self(vec![Vec::<Edge<C>>::new(); size], 0)
    }

    fn size(&self) -> usize {
        self.0.len()
    }

    fn add_edge(&mut self, u: usize, v: usize, cost: C) {
        self.0[u].push(Edge{ to: v, cost: cost.clone(), id: self.1 });
        self.0[v].push(Edge{ to: u, cost: cost.clone(), id: self.1 });
        self.1 += 1;
    }

    fn edges_from(&self, v: usize) -> std::slice::Iter<Edge<C>> {
        self.0[v].iter()
    }
}

impl<C: Element> Graph<C> for DirectedGraph<C> {
    fn new(size: usize) -> Self {
        Self {
            forward: vec![Vec::<Edge<C>>::new(); size],
            backward: vec![Vec::<Edge<C>>::new(); size],
            count: 0
        }
    }

    fn size(&self) -> usize {
        self.forward.len()
    }

    fn add_edge(&mut self, u: usize, v: usize, cost: C) {
        self.forward[u].push(Edge{ to: v, cost: cost.clone(), id: self.count });
        self.backward[v].push(Edge{ to: u, cost: cost.clone(), id: self.count });
        self.count += 1;
    }

    fn edges_from(&self, v: usize) -> std::slice::Iter<Edge<C>> {
        self.forward[v].iter()
    }
}

impl<C: Element> DirectedGraph<C> {
    pub fn edges_to(&self, u: usize) -> std::slice::Iter<Edge<C>> {
        self.backward[u].iter()
    }

    pub fn reverse(&self) -> Self {
        Self {
            forward: self.backward.clone(),
            backward: self.forward.clone(),
            count: self.count,
        }
    }
}

macro_rules! impl_cost {
    ($($T:ident,)*) => {
        $(
            impl Cost for $T { const MAX: Self = std::$T::MAX; }
        )*
    };
}

impl_cost! {
    i8, i16, i32, i64, i128, isize,
}

#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Void();

impl std::fmt::Display for Void {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "")
    }
}

impl Zero for Void {
    fn zero() -> Self { Void() }
    fn is_zero(&self) -> bool { true }
}

impl One for Void {
    fn one() -> Self { Void() }
    fn is_one(&self) -> bool { true }
}

impl Add for Void {
    type Output = Self;
    fn add(self, _: Self) -> Self { Void() }
}

impl AddAssign for Void {
    fn add_assign(&mut self, _: Self) {}
}

impl Sub for Void {
    type Output = Self;
    fn sub(self, _: Self) -> Self { Void() }
}

impl Neg for Void {
    type Output = Self;
    fn neg(self) -> Self { Void() }
}

impl Cost for Void { const MAX: Self = Void(); }

// ------------ Graph impl end ------------


// ------------ algebraic traits start ------------
use std::marker::Sized;
use std::ops::*;

/// 元
pub trait Element: Sized + Clone + PartialEq {}
impl<T: Sized + Clone + PartialEq> Element for T {}

/// 結合性
pub trait Associative: Magma {}

/// マグマ
pub trait Magma: Element + Add<Output=Self> {}
impl<T: Element + Add<Output=Self>> Magma for T {}

/// 半群
pub trait SemiGroup: Magma + Associative {}
impl<T: Magma + Associative> SemiGroup for T {}

/// モノイド
pub trait Monoid: SemiGroup + Zero {}
impl<T: SemiGroup + Zero> Monoid for T {}

pub trait ComMonoid: Monoid + AddAssign {}
impl<T: Monoid + AddAssign> ComMonoid for T {}

/// 群
pub trait Group: Monoid + Neg<Output=Self> {}
impl<T: Monoid + Neg<Output=Self>> Group for T {}

pub trait ComGroup: Group + ComMonoid {}
impl<T: Group + ComMonoid> ComGroup for T {}

/// 半環
pub trait SemiRing: ComMonoid + Mul<Output=Self> + One {}
impl<T: ComMonoid + Mul<Output=Self> + One> SemiRing for T {}

/// 環
pub trait Ring: ComGroup + SemiRing {}
impl<T: ComGroup + SemiRing> Ring for T {}

pub trait ComRing: Ring + MulAssign {}
impl<T: Ring + MulAssign> ComRing for T {}

/// 体
pub trait Field: ComRing + Div<Output=Self> + DivAssign {}
impl<T: ComRing + Div<Output=Self> + DivAssign> Field for T {}

/// 加法単元
pub trait Zero: Element {
    fn zero() -> Self;
    fn is_zero(&self) -> bool {
        *self == Self::zero()
    }
}

/// 乗法単元
pub trait One: Element {
    fn one() -> Self;
    fn is_one(&self) -> bool {
        *self == Self::one()
    }
}

macro_rules! impl_integer {
    ($($T:ty,)*) => {
        $(
            impl Associative for $T {}

            impl Zero for $T {
                fn zero() -> Self { 0 }
                fn is_zero(&self) -> bool { *self == 0 }
            }

            impl<'a> Zero for &'a $T {
                fn zero() -> Self { &0 }
                fn is_zero(&self) -> bool { *self == &0 }
            }

            impl One for $T {
                fn one() -> Self { 1 }
                fn is_one(&self) -> bool { *self == 1 }
            }

            impl<'a> One for &'a $T {
                fn one() -> Self { &1 }
                fn is_one(&self) -> bool { *self == &1 }
            }
        )*
    };
}

impl_integer! {
    i8, i16, i32, i64, i128, isize,
    u8, u16, u32, u64, u128, usize,
}
// ------------ algebraic traits end ------------


pub fn tree_dfs<C: Cost, G: Graph<C>>(g: &G, root: usize)
-> (Vec<C>, Vec<Option<usize>>, Vec<usize>, Vec<usize>)
{
    let n = g.size();
    let mut euler = Vec::with_capacity(n);
	let mut dist = vec![C::MAX; n];
	dist[root] = C::zero();
    let mut par = vec![None; n];
    let mut size = vec![1; n];
    let mut q = vec![root];
    while let Some(v) = q.pop() {
        euler.push(v);
        for e in g.edges_from(v) {
            if par[v] == Some(e.to) { continue; }
            par[e.to] = Some(v);
            dist[e.to] = dist[v] + e.cost;
            q.push(e.to);
        }
    }
    for &v in euler.iter().skip(1).rev() {
        size[par[v].unwrap()] += size[v];
    }
    (dist, par, size, euler)
}


// ------------ io module start ------------
use std::io::{stdout, BufWriter, Read, StdoutLock, Write};

pub struct IO {
	iter: std::str::SplitAsciiWhitespace<'static>,
	buf: BufWriter<StdoutLock<'static>>,
}

impl IO {
	pub fn new() -> Self {
		let mut input = String::new();
		std::io::stdin().read_to_string(&mut input).unwrap();
		let input = Box::leak(input.into_boxed_str());
		let out = Box::new(stdout());
		IO {
			iter: input.split_ascii_whitespace(),
			buf: BufWriter::new(Box::leak(out).lock()),
		}
	}
	fn scan_str(&mut self) -> &'static str {
		self.iter.next().unwrap()
	}
	pub fn scan<T: Scan>(&mut self) -> <T as Scan>::Output {
		<T as Scan>::scan(self)
	}
	pub fn scan_vec<T: Scan>(&mut self, n: usize) -> Vec<<T as Scan>::Output> {
		(0..n).map(|_| self.scan::<T>()).collect()
	}
	pub fn print<T: Print>(&mut self, x: T) {
		<T as Print>::print(self, x);
	}
	pub fn println<T: Print>(&mut self, x: T) {
		self.print(x);
		self.print("\n");
	}
	pub fn iterln<T: Print, I: Iterator<Item = T>>(&mut self, mut iter: I, delim: &str) {
		if let Some(v) = iter.next() {
			self.print(v);
			for v in iter {
				self.print(delim);
				self.print(v);
			}
		}
		self.print("\n");
	}
	pub fn flush(&mut self) {
		self.buf.flush().unwrap();
	}
}

impl Default for IO {
	fn default() -> Self {
		Self::new()
	}
}

pub trait Scan {
	type Output;
	fn scan(io: &mut IO) -> Self::Output;
}

macro_rules! impl_scan {
	($($t:tt),*) => {
		$(
			impl Scan for $t {
				type Output = Self;
				fn scan(s: &mut IO) -> Self::Output {
					s.scan_str().parse().unwrap()
				}
			}
		)*
	};
}

impl_scan!(i16, i32, i64, isize, u16, u32, u64, usize, String, f32, f64);

impl Scan for char {
	type Output = char;
	fn scan(s: &mut IO) -> Self::Output {
		s.scan_str().chars().next().unwrap()
	}
}

pub enum Bytes {}
impl Scan for Bytes {
	type Output = &'static [u8];
	fn scan(s: &mut IO) -> Self::Output {
		s.scan_str().as_bytes()
	}
}

pub enum Chars {}
impl Scan for Chars {
	type Output = Vec<char>;
	fn scan(s: &mut IO) -> Self::Output {
		s.scan_str().chars().collect()
	}
}

pub enum Usize1 {}
impl Scan for Usize1 {
	type Output = usize;
	fn scan(s: &mut IO) -> Self::Output {
		s.scan::<usize>().wrapping_sub(1)
	}
}

impl<T: Scan, U: Scan> Scan for (T, U) {
	type Output = (T::Output, U::Output);
	fn scan(s: &mut IO) -> Self::Output {
		(T::scan(s), U::scan(s))
	}
}

impl<T: Scan, U: Scan, V: Scan> Scan for (T, U, V) {
	type Output = (T::Output, U::Output, V::Output);
	fn scan(s: &mut IO) -> Self::Output {
		(T::scan(s), U::scan(s), V::scan(s))
	}
}

impl<T: Scan, U: Scan, V: Scan, W: Scan> Scan for (T, U, V, W) {
	type Output = (T::Output, U::Output, V::Output, W::Output);
	fn scan(s: &mut IO) -> Self::Output {
		(T::scan(s), U::scan(s), V::scan(s), W::scan(s))
	}
}

pub trait Print {
	fn print(w: &mut IO, x: Self);
}

macro_rules! impl_print_int {
	($($t:ty),*) => {
		$(
			impl Print for $t {
				fn print(w: &mut IO, x: Self) {
					w.buf.write_all(x.to_string().as_bytes()).unwrap();
				}
			}
		)*
	};
}

impl_print_int!(i16, i32, i64, isize, u16, u32, u64, usize, f32, f64);

impl Print for u8 {
	fn print(w: &mut IO, x: Self) {
		w.buf.write_all(&[x]).unwrap();
	}
}

impl Print for &[u8] {
	fn print(w: &mut IO, x: Self) {
		w.buf.write_all(x).unwrap();
	}
}

impl Print for &str {
	fn print(w: &mut IO, x: Self) {
		w.print(x.as_bytes());
	}
}

impl Print for String {
	fn print(w: &mut IO, x: Self) {
		w.print(x.as_bytes());
	}
}

impl<T: Print, U: Print> Print for (T, U) {
	fn print(w: &mut IO, (x, y): Self) {
		w.print(x);
		w.print(" ");
		w.print(y);
	}
}

impl<T: Print, U: Print, V: Print> Print for (T, U, V) {
	fn print(w: &mut IO, (x, y, z): Self) {
		w.print(x);
		w.print(" ");
		w.print(y);
		w.print(" ");
		w.print(z);
	}
}

mod neboccoio_macro {
	#[macro_export]
	macro_rules! input {
		(@start $io:tt @read @rest) => {};

		(@start $io:tt @read @rest, $($rest: tt)*) => {
			input!(@start $io @read @rest $($rest)*)
		};

		(@start $io:tt @read @rest mut $($rest:tt)*) => {
			input!(@start $io @read @mut [mut] @rest $($rest)*)
		};

		(@start $io:tt @read @rest $($rest:tt)*) => {
			input!(@start $io @read @mut [] @rest $($rest)*)
		};

		(@start $io:tt @read @mut [$($mut:tt)?] @rest $var:tt: [[$kind:tt; $len1:expr]; $len2:expr] $($rest:tt)*) => {
			let $($mut)* $var = (0..$len2).map(|_| $io.scan_vec::<$kind>($len1)).collect::<Vec<Vec<$kind>>>();
			input!(@start $io @read @rest $($rest)*)
		};

		(@start $io:tt @read @mut [$($mut:tt)?] @rest $var:tt: [$kind:tt; $len:expr] $($rest:tt)*) => {
			let $($mut)* $var = $io.scan_vec::<$kind>($len);
			input!(@start $io @read @rest $($rest)*)
		};

		(@start $io:tt @read @mut [$($mut:tt)?] @rest $var:tt: $kind:tt $($rest:tt)*) => {
			let $($mut)* $var = $io.scan::<$kind>();
			input!(@start $io @read @rest $($rest)*)
		};

		(from $io:tt $($rest:tt)*) => {
			input!(@start $io @read @rest $($rest)*)
		};
	}
}

// ------------ io module end ------------
0