use std::collections::{VecDeque, HashSet}; const INF: usize = 1usize << 60; fn tree_diameter(paths: &Vec>) -> (usize, usize, usize) { fn calc(paths: &Vec>, start: usize) -> Vec { let n = paths.len(); let mut costs = vec![INF; n]; costs[start] = 0usize; let mut deq = VecDeque::new(); deq.push_back(start); while let Some(u) = deq.pop_front() { for &(v, cost) in paths[u].iter() { if costs[v] < INF { continue; } costs[v] = costs[v].min(costs[u] + cost); deq.push_back(v); } } costs } let n = paths.len(); let costs = calc(paths, 0); let idx = costs.into_iter().enumerate().max_by_key(|&(_, c)| c).unwrap().0; let costs = calc(paths, idx); let ridx = costs.into_iter().enumerate().max_by_key(|&(_, c)| c).unwrap(); // start_point, end_point, cost (idx, ridx.0, ridx.1) } fn get_leaves(cur: usize, paths: &Vec>) -> Vec { let n = paths.len(); let mut ret = vec![true; n]; let mut checked = vec![false; n]; checked[cur] = true; let mut deque = VecDeque::new(); deque.push_back(cur); while let Some(u) = deque.pop_front() { for &(v, _) in paths[u].iter() { if checked[v] { continue; } checked[v] = true; ret[u] = false; deque.push_back(v); } } ret[cur] = true; ret } fn get_dists(cur: usize, paths: &Vec>) -> Vec { let n = paths.len(); let mut ret = vec![INF; n]; ret[cur] = 0; let mut deque = VecDeque::new(); deque.push_back(cur); while let Some(u) = deque.pop_front() { for &(v, _) in paths[u].iter() { if ret[v] < INF { continue; } ret[v] = ret[u] + 1; deque.push_back(v); } } ret } fn main() { let mut n = String::new(); std::io::stdin().read_line(&mut n).ok(); let n: usize = n.trim().parse().unwrap(); let mut paths = vec![vec![]; n]; for _ in 0..n-1 { let mut ab = String::new(); std::io::stdin().read_line(&mut ab).ok(); let ab: Vec = ab.trim().split_whitespace().map(|s| s.parse().unwrap()).collect(); let a = ab[0]-1; let b = ab[1]-1; paths[a].push((b, 1)); paths[b].push((a, 1)); } let (left, right, _) = tree_diameter(&paths); let leaves = get_leaves(left, &paths); let l_dists = get_dists(left, &paths); let r_dists = get_dists(right, &paths); let mut result = HashSet::new(); for i in 0..n { if !leaves[i] { continue; } if i != left { result.insert(l_dists[i]); } if i != right { result.insert(r_dists[i]); } } if result.len() == 1 { println!("Yes"); } else { println!("No"); } }