Problem:
Score : 100 points

Problem Statement

You are given a grid of N rows and M columns. The square at the i-th row and j-th column will be denoted as (i,j).
A nonnegative integer A_{i,j} is written for each square (i,j).

You choose some of the squares so that each row and column contains at most K chosen squares.
Under this constraint, calculate the maximum value of the sum of the integers written on the chosen squares.
Additionally, calculate a way to choose squares that acheives the maximum.

Constraints

1 \leq N \leq 50

1 \leq K \leq N

0 \leq A_{i,j} \leq 10^9

All values in Input are integer.

Input

Input is given from Standard Input in the following format:

N K
A_{1,1} A_{1,2} \cdots A_{1,N}
A_{2,1} A_{2,2} \cdots A_{2,N}
\vdots
A_{N,1} A_{N,2} \cdots A_{N,N}

Output

On the first line, print the maximum value of the sum of the integers written on the chosen squares.

On the next N lines, print a way that achieves the maximum.

Precisely, output the strings t_1,t_2,\cdots,t_N, that satisfies t_{i,j}=X if you choose (i,j) and t_{i,j}=. otherwise.

You may print any way to choose squares that maximizes the sum.

Sample Input 1

3 1
5 3 2
1 4 8
7 6 9

Sample Output 1

19
X..
..X
.X.

Sample Input 2

3 2
10 10 1
10 10 1
1 1 10

Sample Output 2

50
XX.
XX.
..X

Solution in Rust (1.42.0) (judge verdict: Accepted)

use min_cost_flow::McfGraph;
use std::io::*;
use utils::*;

pub fn main() {
    let i = stdin();
    let mut o = Vec::new();
    run(i.lock(), &mut o).unwrap();
    stdout().write_all(&o).unwrap();
}

pub fn run(i: impl BufRead, o: &mut impl Write) -> std::io::Result<()> {
    let mut i = CpReader::new(i);
    let (n, k) = i.read::<(usize, i64)>();
    let mut g = McfGraph::new(n * 2 + 2);
    let s = n * 2;
    let t = n * 2 + 1;
    let a_max = 1_000_000_000i64;

    let flow_limit = k * n as i64;

    g.add_edge(s, t, flow_limit, a_max);

    for i in 0..n {
        g.add_edge(s, i, k, 0);
        g.add_edge(n + i, t, k, 0);
    }

    for y in 0..n {
        let mut x = 0;
        for a in i.read_iter::<i64>(n) {
            g.add_edge(x, y + n, 1, a_max - a);
            x += 1;
        }
    }
    let (f, c) = g.flow_with_limit(s, t, flow_limit);
    writeln!(o, "{}", a_max * f - c)?;

    let mut rs = vec![vec![b'.'; n]; n];
    for edge in g.edges() {
        if edge.from == s || edge.to == t {
            continue;
        }
        let x = edge.from;
        let y = edge.to - n;
        if edge.flow != 0 {
            rs[y][x] = b'X';
        }
    }
    for r in rs {
        writeln!(o, "{}", std::str::from_utf8(&r).unwrap())?;
    }

    Ok(())
}

pub mod utils {
    use super::*;

    pub struct CpReader<R: BufRead> {
        r: R,
        b: Vec<u8>,
    }
    impl<R: BufRead> CpReader<R> {
        pub fn new(r: R) -> Self {
            CpReader {
                r: r,
                b: Vec::new(),
            }
        }
        pub fn read_word(&mut self) -> &[u8] {
            self.b.clear();
            loop {
                let b = self.r.fill_buf().unwrap();
                assert!(!b.is_empty());
                if let Some(p) = b.iter().position(|&x| x == b' ' || x == b'\n') {
                    self.b.extend_from_slice(&b[..p]);
                    self.r.consume(p + 1);
                    return &self.b;
                }
                self.b.extend_from_slice(b);
                let b_len = b.len();
                self.r.consume(b_len);
            }
        }
        pub fn read_word_str(&mut self) -> &str {
            unsafe { std::str::from_utf8_unchecked(self.read_word()) }
        }

        pub fn read_line(&mut self) -> &[u8] {
            self.b.clear();
            self.r.read_until(b'\n', &mut self.b).unwrap();
            if self.b.last() == Some(&b'\n') {
                &self.b[..self.b.len() - 1]
            } else {
                &self.b
            }
        }
        pub fn read_line_str(&mut self) -> &str {
            unsafe { std::str::from_utf8_unchecked(self.read_line()) }
        }

        pub fn read<T: CpIn>(&mut self) -> T {
            T::read_from(self)
        }

        pub fn read_vec<T: CpIn>(&mut self, n: usize) -> Vec<T> {
            (0..n).map(|_| self.read()).collect()
        }
        pub fn read_iter<'a, T: CpIn>(&'a mut self, n: usize) -> CpIter<'a, R, T> {
            CpIter {
                r: self,
                n: n,
                _pd: Default::default(),
            }
        }
    }
    pub struct CpIter<'a, R: BufRead + 'a, T> {
        r: &'a mut CpReader<R>,
        n: usize,
        _pd: std::marker::PhantomData<fn() -> T>,
    }
    impl<'a, R: BufRead, T: CpIn> Iterator for CpIter<'a, R, T> {
        type Item = T;
        fn next(&mut self) -> Option<T> {
            if self.n == 0 {
                None
            } else {
                self.n -= 1;
                Some(self.r.read())
            }
        }
        fn size_hint(&self) -> (usize, Option<usize>) {
            (self.n, Some(self.n))
        }
    }
    impl<'a, R: BufRead, T: CpIn> ExactSizeIterator for CpIter<'a, R, T> {}

    pub trait CpIn {
        fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self;
    }

    impl CpIn for u64 {
        fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self {
            read_u64_fast(&mut r.r)
        }
    }
    impl CpIn for i64 {
        fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self {
            read_i64_fast(&mut r.r)
        }
    }
    impl CpIn for char {
        fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self {
            let b = r.r.fill_buf().unwrap()[0] as char;
            r.r.consume(1);
            let s = r.r.fill_buf().unwrap()[0];
            assert!(s == b' ' || s == b'\n');
            r.r.consume(1);
            b
        }
    }

    macro_rules! cpin_tuple {
        ($($t:ident),*) => {
            impl<$($t: CpIn),*> CpIn for ($($t),*) {
                fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self {
                    ($($t::read_from(r)),*)
                }
            }
        };
    }

    macro_rules! cpin_cast {
        ($t_self:ty, $t_read:ty) => {
            impl CpIn for $t_self {
                fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self {
                    <$t_read>::read_from(r) as $t_self
                }
            }
        };
    }
    macro_rules! cpin_parse {
        ($t:ty) => {
            impl CpIn for $t {
                fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self {
                    r.read_word_str().parse().unwrap()
                }
            }
        };
    }
    cpin_cast!(usize, u64);
    cpin_cast!(u32, u64);
    cpin_cast!(u16, u64);
    cpin_cast!(i32, i64);
    cpin_cast!(i16, i64);
    cpin_cast!(i8, i64);

    cpin_parse!(f64);

    cpin_tuple!(T1, T2);
    cpin_tuple!(T1, T2, T3);
    cpin_tuple!(T1, T2, T3, T4);
    cpin_tuple!(T1, T2, T3, T4, T5);

    fn read_u64_fast<R: BufRead>(r: &mut R) -> u64 {
        let mut value = 0;
        loop {
            let buf = r.fill_buf().unwrap();
            assert!(!buf.is_empty());
            let mut idx = 0;
            while let Some(&c) = buf.get(idx) {
                if b'0' <= c && c <= b'9' {
                    value = value * 10 + (c - b'0') as u64;
                    idx += 1;
                } else {
                    r.consume(idx + 1);
                    return value;
                }
            }
            r.consume(idx);
        }
    }
    fn read_i64_fast<R: BufRead>(r: &mut R) -> i64 {
        let sign = match r.fill_buf().unwrap()[0] {
            b'+' => {
                r.consume(1);
                1
            }
            b'-' => {
                r.consume(1);
                -1
            }
            _ => 1,
        };
        read_u64_fast(r) as i64 * sign
    }
}
mod min_cost_flow {
    #![allow(dead_code)]
    use std::{
        cmp::min, cmp::Reverse, collections::BinaryHeap, fmt::Debug, ops::Add, ops::AddAssign,
        ops::Mul, ops::Neg, ops::Sub, ops::SubAssign,
    };

    use num::{zero, Bounded, Zero};

    pub struct McfGraph<Cap, Cost> {
        n: usize,
        pos: Vec<(usize, usize)>, // "edge id" to "EdgeData" table. ( if edge id is `x`, "EdgeData" is g[pos[x].0][pos[x].1] )
        g: Vec<Vec<EdgeData<Cap, Cost>>>,
    }

    #[derive(Clone)]
    struct EdgeData<Cap, Cost> {
        to: usize,
        rev: usize,
        cap: Cap,
        cost: Cost,
    }
    pub struct Edge<Cap, Cost> {
        pub from: usize,
        pub to: usize,
        pub cap: Cap,
        pub flow: Cap,
        pub cost: Cost,
    }

    impl<
            Cap: Copy
                + AddAssign
                + Add<Output = Cap>
                + Bounded
                + PartialEq
                + Ord
                + Zero
                + Sub<Output = Cap>
                + SubAssign
                + Debug,
            Cost: Copy
                + Bounded
                + Ord
                + Zero
                + AddAssign
                + Sub<Output = Cost>
                + SubAssign
                + Mul<Cap, Output = Cost>
                + Neg<Output = Cost>
                + Debug,
        > McfGraph<Cap, Cost>
    {
        pub fn new(n: usize) -> Self {
            Self {
                n,
                pos: Vec::new(),
                g: vec![Vec::new(); n],
            }
        }
        pub fn add_edge(&mut self, from: usize, to: usize, cap: Cap, cost: Cost) -> usize {
            debug_assert!(from < self.n);
            debug_assert!(to < self.n);
            let m = self.pos.len();
            self.pos.push((from, self.g[from].len()));
            let from_id = self.g[from].len();
            let mut to_id = self.g[to].len();
            if from == to {
                to_id += 1;
            }
            self.g[from].push(EdgeData {
                to,
                rev: to_id,
                cap,
                cost,
            });
            self.g[to].push(EdgeData {
                to: from,
                rev: from_id,
                cap: zero(),
                cost: -cost,
            });
            m
        }

        pub fn get_edge(&self, i: usize) -> Edge<Cap, Cost> {
            let m = self.pos.len();
            debug_assert!(i < m);
            let e = &self.g[self.pos[i].0][self.pos[i].1];
            let re = &self.g[e.to][e.rev];
            Edge {
                from: self.pos[i].0,
                to: e.to,
                cap: e.cap + re.cap,
                flow: re.cap,
                cost: e.cost,
            }
        }
        pub fn edges(&self) -> Vec<Edge<Cap, Cost>> {
            (0..self.pos.len()).map(|i| self.get_edge(i)).collect()
        }
        pub fn flow(&mut self, s: usize, t: usize) -> (Cap, Cost) {
            self.flow_with_limit(s, t, Cap::max_value())
        }

        pub fn flow_with_limit(&mut self, s: usize, t: usize, flow_limit: Cap) -> (Cap, Cost) {
            self.slope_with_limit(s, t, flow_limit).pop().unwrap()
        }
        pub fn slope(&mut self, s: usize, t: usize) -> Vec<(Cap, Cost)> {
            self.slope_with_limit(s, t, Cap::max_value())
        }

        pub fn slope_with_limit(
            &mut self,
            s: usize,
            t: usize,
            flow_limit: Cap,
        ) -> Vec<(Cap, Cost)> {
            debug_assert!(s < self.n);
            debug_assert!(t < self.n);
            debug_assert!(s != t);
            let mut dual: Vec<Cost> = vec![zero(); self.n];
            let mut dist: Vec<Cost> = vec![zero(); self.n];
            let mut pv = vec![usize::max_value(); self.n];
            let mut pe = vec![usize::max_value(); self.n];
            let mut vis = vec![false; self.n];

            let mut flow = zero();
            let mut cost = zero();
            let mut prev_cost_per_flow = None;
            let mut result = Vec::new();
            result.push((flow, cost));
            while flow < flow_limit {
                if !self.dual_ref(s, t, &mut dist, &mut dual, &mut pv, &mut pe, &mut vis) {
                    break;
                }
                let mut c = flow_limit - flow;
                let mut v = t;
                while v != s {
                    c = min(c, self.g[pv[v]][pe[v]].cap);
                    v = pv[v];
                }
                let mut v = t;
                while v != s {
                    let e = &mut self.g[pv[v]][pe[v]];
                    e.cap -= c;
                    let e_rev = e.rev;
                    self.g[v][e_rev].cap += c;
                    v = pv[v];
                }
                let d = -dual[s];
                flow += c;
                cost += d * c;
                if prev_cost_per_flow == Some(d) {
                    result.pop();
                }
                result.push((flow, cost));
                prev_cost_per_flow = Some(d);
            }
            result
        }

        fn dual_ref(
            &mut self,
            s: usize,
            t: usize,
            dist: &mut Vec<Cost>,
            dual: &mut Vec<Cost>,
            pv: &mut Vec<usize>,
            pe: &mut Vec<usize>,
            vis: &mut Vec<bool>,
        ) -> bool {
            #[derive(Ord, PartialOrd, Eq, PartialEq)]
            struct Q<Cost> {
                key: Reverse<Cost>,
                to: usize,
            }
            for x in dist.iter_mut() {
                *x = Cost::max_value();
            }
            for x in pv.iter_mut() {
                *x = usize::max_value();
            }
            for x in pe.iter_mut() {
                *x = usize::max_value();
            }
            for x in vis.iter_mut() {
                *x = false;
            }
            let mut que = BinaryHeap::new();
            dist[s] = zero();
            que.push(Q {
                key: Reverse(zero()),
                to: s,
            });
            while let Some(Q { key: _, to: v }) = que.pop() {
                if vis[v] {
                    continue;
                }
                vis[v] = true;
                if v == t {
                    break;
                }
                for i in 0..self.g[v].len() {
                    let e = &self.g[v][i];
                    if vis[e.to] || e.cap == zero() {
                        continue;
                    }
                    let cost = e.cost - dual[e.to] + dual[v];
                    if dist[e.to] - dist[v] > cost {
                        dist[e.to] = dist[v] + cost;
                        pv[e.to] = v;
                        pe[e.to] = i;
                        que.push(Q {
                            key: Reverse(dist[e.to]),
                            to: e.to,
                        });
                    }
                }
            }
            if !vis[t] {
                return false;
            }
            for v in 0..self.n {
                if !vis[v] {
                    continue;
                }
                dual[v] -= dist[t] - dist[v];
            }
            true
        }
    }
}