use std::io::*; use std::str::FromStr; use std::cmp::{min, max}; fn read() -> T { let stdin = stdin(); let stdin_lock = stdin.lock(); let s = stdin_lock .bytes() .map(|c| c.unwrap() as char) .skip_while(|c| c.is_whitespace()) .take_while(|c| !c.is_whitespace()) .collect::(); s.parse::().ok().unwrap() } fn main() { let n: usize = read(); let m: usize = read(); let mut uf = UnionFind::new(n); for _ in 0..m { let a: usize = read::() - 1; let b: usize = read::() - 1; uf.union(a, b); } for i in 0..n { println!("{}", uf.root(i) + 1); } } struct UnionFind { par: Vec, rank: Vec, groups: usize, cnt: Vec, } impl UnionFind { fn new(n: usize) -> UnionFind { UnionFind { par: (0..n).map(|i| i).collect(), rank: vec![0; n], groups: n, cnt: vec![1; n], } } fn same(&mut self, a: usize, b: usize) -> bool { self.root(a) == self.root(b) } fn root(&mut self, a: usize) -> usize { if self.par[a] == a { a } else { let par = self.par[a]; self.par[a] = self.root(par); self.par[a] } } fn union(&mut self, a: usize, b: usize) { let x = self.root(a); let y = self.root(b); if x == y { return; } self.groups -= 1; if self.cnt[x] < self.cnt[y] { self.par[x] = y; self.cnt[y] += self.cnt[x]; } else if self.cnt[x] == self.cnt[y] { self.par[max(x, y)] = self.par[min(x, y)]; self.cnt[min(x, y)] += self.cnt[max(x, y)]; } else { self.par[y] = x; self.cnt[x] += self.cnt[y]; } // if self.rank[x] < self.rank[y] { // self.par[x] = y; // } else { // self.par[y] = x; // if self.rank[x] == self.rank[y] { // self.rank[x] += 1; // } // } } }