Problem:
Score : 600 points

Problem Statement

We have a tree with N vertices. The vertices are numbered 1 to N, and the i-th edge connects Vertex a_i and Vertex b_i.

Takahashi loves the number 3. He is seeking a permutation p_1, p_2, \ldots , p_N of integers from 1 to N satisfying the following condition:

For every pair of vertices (i, j), if the distance between Vertex i and Vertex j is 3, the sum or product of p_i and p_j is a multiple of 3.

Here the distance between Vertex i and Vertex j is the number of edges contained in the shortest path from Vertex i to Vertex j.

Help Takahashi by finding a permutation that satisfies the condition.

Constraints

2\leq N\leq 2\times 10^5

1\leq a_i, b_i \leq N

The given graph is a tree.

Input

Input is given from Standard Input in the following format:

N
a_1 b_1
a_2 b_2
\vdots
a_{N-1} b_{N-1}

Output

If no permutation satisfies the condition, print -1.

Otherwise, print a permutation satisfying the condition, with space in between.
If there are multiple solutions, you can print any of them.

Sample Input 1

5
1 2
1 3
3 4
3 5

Sample Output 1

1 2 5 4 3

The distance between two vertices is 3 for the two pairs (2, 4) and (2, 5).

p_2 + p_4 = 6

p_2\times p_5 = 6

Thus, this permutation satisfies the condition.

Solution in Rust (1.15.1) (judge verdict: Wrong Answer)

/// Segment Tree for range queries
pub struct SegmentTree<T, F> {
    seg: Vec<T>,
    n: usize,
    f: F,
    initial_value: T,
}

impl<T: Copy, F> SegmentTree<T, F>
where
    F: Fn(T, T) -> T,
{
    pub fn new(size: usize, initial_value: T, f: F) -> SegmentTree<T, F> {
        let mut m = 1;
        while m <= size {
            m <<= 1;
        }
        SegmentTree {
            seg: vec![initial_value; m * 2],
            n: m,
            f: f,
            initial_value: initial_value,
        }
    }

    pub fn update(&mut self, k: usize, value: T) {
        let mut k = k;
        k += self.n - 1;
        self.seg[k] = value;
        while k > 0 {
            k = (k - 1) >> 1;
            self.seg[k] = (self.f)(self.seg[k * 2 + 1], self.seg[k * 2 + 2]);
        }
    }

    /// Get the minimum value in the array in the range [a, b)
    ///
    /// # Panics
    ///
    /// Panics if `a >= b`.
    pub fn query(&self, a: usize, b: usize) -> T {
        assert!(a < b);
        self.query_range(a, b, 0, 0, self.n)
    }

    fn query_range(&self, a: usize, b: usize, k: usize, l: usize, r: usize) -> T {
        if r <= a || b <= l {
            self.initial_value
        } else if a <= l && r <= b {
            self.seg[k]
        } else {
            let x = self.query_range(a, b, k * 2 + 1, l, (l + r) >> 1);
            let y = self.query_range(a, b, k * 2 + 2, (l + r) >> 1, r);
            (self.f)(x, y)
        }
    }
}

#[cfg(test)]
mod test {

    use super::*;
    use rand::Rng;
    use std::cmp;
    use std::i64::MAX;

    #[test]
    fn random_array() {
        let n = 1000;
        let arr = (0..n)
            .map(|_| {
                return rand::thread_rng().gen::<i64>();
            })
            .collect::<Vec<_>>();

        let mut seg = SegmentTree::new(n, MAX, |a, b| cmp::min(a, b));
        for i in 0..n {
            let mut minimum = MAX;
            for j in 0..(i + 1) {
                minimum = cmp::min(minimum, arr[j]);
            }
            seg.update(i, arr[i]);
            assert_eq!(seg.query(0, n), minimum);
            assert_eq!(seg.query(0, i + 1), minimum);
        }
    }

    #[test]
    fn random_array_online_update() {
        let n = 1000;

        let mut arr = vec![MAX; n];
        let mut seg = SegmentTree::new(n, MAX, |a, b| cmp::min(a, b));

        for _ in 0..n {
            let value = rand::thread_rng().gen::<i64>();
            let k = rand::thread_rng().gen_range(0, n);
            seg.update(k, value);

            arr[k] = value;
            let mut minimum = MAX;
            for i in 0..n {
                minimum = cmp::min(minimum, arr[i]);
            }
            assert_eq!(seg.query(0, n), minimum);
        }
    }
}
const MAX_N: usize = 200010;

fn dfs3(
    pos: usize,
    pre: Option<usize>,
    cost: usize,
    edges: &[Vec<usize>],
    candidates: &mut Vec<usize>,
) {
    if cost > 3 {
        return;
    }
    if cost == 3 {
        candidates.push(pos);
    }

    for &nxt in edges[pos].iter() {
        if let Some(prev) = pre {
            if prev == nxt {
                continue;
            }
        }
        dfs3(nxt, Some(pos), cost + 1, edges, candidates);
    }
}
fn solve() {
    let s = std::io::stdin();
    let mut sc = Scanner { stdin: s.lock() };
    let n: usize = sc.read();
    let mut edges: Vec<Vec<usize>> = vec![vec![]; MAX_N];
    let ab: Vec<(usize, usize)> = (0..n - 1)
        .map(|_| {
            let a: usize = sc.read();
            let b: usize = sc.read();
            (a - 1, b - 1)
        })
        .collect();

    for &(a, b) in ab.iter() {
        edges[a].push(b);
        edges[b].push(a);
    }
    let mut pair3 = vec![];
    for x in 0..n {
        let mut candidates = vec![];
        dfs3(x, None, 0, &edges, &mut candidates);
        candidates.sort();
        candidates.dedup();
        for &y in candidates.iter() {
            pair3.push((x, y));
        }
    }
    //no pair3
    if pair3.is_empty() {
        for i in 0..n {
            print!("{} ", i + 1);
        }
        return;
    }
    let mut degrees = vec![0; MAX_N];
    let mut edges3: Vec<Vec<usize>> = vec![vec![]; MAX_N];
    for &(a, b) in pair3.iter() {
        if a < b {
            degrees[a] += 1;
            degrees[b] += 1;
            edges3[a].push(b);
            edges3[b].push(a);
        }
    }
    let mut seg = SegmentTree::new(MAX_N, (0, 0), |a, b| std::cmp::max(a, b));
    // for i in 0..n {
    //     println!("{} {}", i, degrees[i]);
    // }
    for i in 0..n {
        seg.update(i, (degrees[i], i));
    }
    let mut cnts = vec![0; 3];
    for i in 1..n + 1 {
        cnts[i % 3] += 1;
    }
    //println!("{:?}", pair3);
    let mut colors = vec![None; MAX_N];
    loop {
        let (deg, idx): (usize, usize) = seg.query(0, n);
        if deg == 0 {
            break;
        }
        if colors[idx].is_none() {
            if cnts[0] > 0 {
                colors[idx] = Some(0);
                cnts[0] -= 1;
            } else {
                if cnts[1] >= cnts[2] {
                    colors[idx] = Some(2);
                    if cnts[2] == 0 {
                        println!("-1");
                        return;
                    }
                    cnts[2] -= 1;
                } else {
                    colors[idx] = Some(1);
                    if cnts[1] == 0 {
                        println!("-1");
                        return;
                    }
                    cnts[1] -= 1;
                }
            }
        }
        degrees[idx] = 0;
        seg.update(idx, (0, idx));
        let color = colors[idx].unwrap();
        //println!("{}, {}", idx, color);
        // for i in 0..n {
        //     println!("deg: {}", degrees[i]);
        // }
        if color == 0 {
            for &x in edges3[idx].iter() {
                if colors[x].is_none() {
                    degrees[x] -= 1;
                    seg.update(x, (degrees[x], x));
                }
            }
        } else if color == 1 {
            for &x in edges3[idx].iter() {
                if colors[x].is_none() {
                    degrees[x] -= 1;
                    colors[x] = Some(2);
                    if cnts[2] == 0 {
                        println!("-1");
                        return;
                    }
                    cnts[2] -= 1;
                    seg.update(x, (degrees[x], x));
                }
            }
        } else {
            for &x in edges3[idx].iter() {
                if colors[x].is_none() {
                    degrees[x] -= 1;
                    colors[x] = Some(1);
                    if cnts[1] == 0 {
                        println!("-1");
                        return;
                    }
                    cnts[1] -= 1;
                    seg.update(x, (degrees[x], x));
                }
            }
        }
    }
    let mut indices = vec![std::collections::VecDeque::new(); 3];
    for x in 1..n + 1 {
        indices[x % 3].push_back(x - 1);
    }

    let mut results = vec![0; MAX_N];
    for i in 0..n {
        if let Some(color) = colors[i] {
            if let Some(value) = indices[color].pop_front() {
                results[i] = value;
            } else {
                println!("-1");
                return;
            }
        }
    }
    for i in 0..n {
        if colors[i].is_none() {
            for c in 0..3 {
                if let Some(value) = indices[c].pop_front() {
                    results[i] = value;
                    break;
                }
            }
        }
    }
    for i in 0..n {
        print!("{} ", results[i] + 1);
    }
}

fn main() {
    std::thread::Builder::new()
        .stack_size(64 * 1024 * 1024) // 64MB
        .spawn(|| solve())
        .unwrap()
        .join()
        .unwrap();
}
pub mod utils {
    const DYX: [(isize, isize); 8] = [
        (0, 1),   //right
        (1, 0),   //down
        (0, -1),  //left
        (-1, 0),  //top
        (1, 1),   //down right
        (-1, 1),  //top right
        (1, -1),  //down left
        (-1, -1), //top left
    ];

    pub fn try_adj(y: usize, x: usize, dir: usize, h: usize, w: usize) -> Option<(usize, usize)> {
        let ny = y as isize + DYX[dir].0;
        let nx = x as isize + DYX[dir].1;
        if ny >= 0 && nx >= 0 {
            let ny = ny as usize;
            let nx = nx as usize;
            if ny < h && nx < w {
                Some((ny, nx))
            } else {
                None
            }
        } else {
            None
        }
    }
}

//snippet from kenkoooo
pub struct Scanner<R> {
    stdin: R,
}

impl<R: std::io::Read> Scanner<R> {
    pub fn read<T: std::str::FromStr>(&mut self) -> T {
        use std::io::Read;
        let buf = self
            .stdin
            .by_ref()
            .bytes()
            .map(|b| b.unwrap())
            .skip_while(|&b| b == b' ' || b == b'\n' || b == b'\r')
            .take_while(|&b| b != b' ' && b != b'\n' && b != b'\r')
            .collect::<Vec<_>>();
        unsafe { std::str::from_utf8_unchecked(&buf) }
            .parse()
            .ok()
            .expect("Parse error.")
    }
    pub fn read_line(&mut self) -> String {
        use std::io::Read;
        let buf = self
            .stdin
            .by_ref()
            .bytes()
            .map(|b| b.unwrap())
            .skip_while(|&b| b == b'\n' || b == b'\r')
            .take_while(|&b| b != b'\n' && b != b'\r')
            .collect::<Vec<_>>();
        unsafe { std::str::from_utf8_unchecked(&buf) }
            .parse()
            .ok()
            .expect("Parse error.")
    }
    pub fn vec<T: std::str::FromStr>(&mut self, n: usize) -> Vec<T> {
        (0..n).map(|_| self.read()).collect()
    }

    pub fn chars(&mut self) -> Vec<char> {
        self.read::<String>().chars().collect()
    }
}