#![allow(unused_imports)] #![allow(non_snake_case)] use std::cmp::*; use std::collections::*; use std::io::Write; #[allow(unused_macros)] macro_rules! debug { ($($e:expr),*) => { #[cfg(debug_assertions)] $({ let (e, mut err) = (stringify!($e), std::io::stderr()); writeln!(err, "{} = {:?}", e, $e).unwrap() })* }; } fn main() { let n = read::(); let mut products = vec![]; for i in 0..n { let v = read_vec::(); products.push((v[0], v[1])); } let mut edges: Vec = Vec::new(); for (i, &p) in products.iter().enumerate() { if i != 0 { edges.push(Edge { from: i, to: i + 1, cost: p.1, }); } edges.push(Edge { from: 0, to: i + 1, cost: p.0, }); } println!( "{}", products.iter().map(|x| x.0).sum::() + kruskal(&edges, n + 1) ); } fn read() -> T { let mut s = String::new(); std::io::stdin().read_line(&mut s).ok(); s.trim().parse().ok().unwrap() } fn read_vec() -> Vec { read::() .split_whitespace() .map(|e| e.parse().ok().unwrap()) .collect() } use std::cmp::Ordering; #[derive(Debug, Clone)] struct Edge { from: usize, to: usize, cost: i64, } impl PartialEq for Edge { fn eq(&self, other: &Edge) -> bool { self.cost == other.cost } } impl Eq for Edge {} impl Ord for Edge { fn cmp(&self, other: &Self) -> Ordering { self.cost.cmp(&other.cost) } } impl PartialOrd for Edge { fn partial_cmp(&self, other: &Edge) -> Option { Some(self.cost.cmp(&other.cost)) } } struct UnionFindTree { parent_or_size: Vec, } impl UnionFindTree { fn new(size: usize) -> UnionFindTree { UnionFindTree { parent_or_size: vec![-1; size], } } fn find(&self, index: usize) -> usize { let mut index = index; while self.parent_or_size[index] >= 0 { index = self.parent_or_size[index] as usize; } index } fn same(&self, x: usize, y: usize) -> bool { self.find(x) == self.find(y) } fn unite(&mut self, index0: usize, index1: usize) -> bool { let a = self.find(index0); let b = self.find(index1); if a == b { false } else { if self.parent_or_size[a] < self.parent_or_size[b] { self.parent_or_size[a] += self.parent_or_size[b]; self.parent_or_size[b] = a as isize; } else { self.parent_or_size[b] += self.parent_or_size[a]; self.parent_or_size[a] = b as isize; } true } } } fn kruskal(edges: &Vec, num_apexes: usize) -> i64 { let mut edges = edges.clone(); let mut res = 0; edges.sort(); let mut unf = UnionFindTree::new(num_apexes); for e in edges { if !unf.same(e.to, e.from) { unf.unite(e.to, e.from); res += e.cost; } } res }