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)

pub trait Zero: PartialEq + Sized {
    fn zero() -> Self;
    #[inline]
    fn is_zero(&self) -> bool {
        self == &Self::zero()
    }
}
pub trait One: PartialEq + Sized {
    fn one() -> Self;
    #[inline]
    fn is_one(&self) -> bool {
        self == &Self::one()
    }
}
macro_rules !zero_one_impls {($({$Trait :ident $method :ident $($t :ty ) *,$e :expr } ) *) =>{$($(impl $Trait for $t {#[inline ] fn $method () ->Self {$e } } ) *) *} ;}
zero_one_impls !({Zero zero u8 u16 u32 u64 usize i8 i16 i32 i64 isize u128 i128 ,0 } {Zero zero f32 f64 ,0. } {One one u8 u16 u32 u64 usize i8 i16 i32 i64 isize u128 i128 ,1 } {One one f32 f64 ,1. } );
pub trait IterScan: Sized {
    type Output;
    fn scan<'a, I: Iterator<Item = &'a str>>(iter: &mut I) -> Option<Self::Output>;
}
pub trait MarkedIterScan: Sized {
    type Output;
    fn mscan<'a, I: Iterator<Item = &'a str>>(self, iter: &mut I) -> Option<Self::Output>;
}
#[derive(Clone, Debug)]
pub struct Scanner<'a> {
    iter: std::str::SplitAsciiWhitespace<'a>,
}
mod scanner_impls {
    use super::*;
    impl<'a> Scanner<'a> {
        #[inline]
        pub fn new(s: &'a str) -> Self {
            let iter = s.split_ascii_whitespace();
            Self { iter }
        }
        #[inline]
        pub fn scan<T: IterScan>(&mut self) -> <T as IterScan>::Output {
            <T as IterScan>::scan(&mut self.iter).expect("scan error")
        }
        #[inline]
        pub fn mscan<T: MarkedIterScan>(&mut self, marker: T) -> <T as MarkedIterScan>::Output {
            marker.mscan(&mut self.iter).expect("scan error")
        }
        #[inline]
        pub fn scan_vec<T: IterScan>(&mut self, size: usize) -> Vec<<T as IterScan>::Output> {
            (0..size)
                .map(|_| <T as IterScan>::scan(&mut self.iter).expect("scan error"))
                .collect()
        }
        #[inline]
        pub fn iter<'b, T: IterScan>(&'b mut self) -> ScannerIter<'a, 'b, T> {
            ScannerIter {
                inner: self,
                _marker: std::marker::PhantomData,
            }
        }
    }
    macro_rules !iter_scan_impls {($($t :ty ) *) =>{$(impl IterScan for $t {type Output =Self ;#[inline ] fn scan <'a ,I :Iterator <Item =&'a str >>(iter :&mut I ) ->Option <Self >{iter .next () ?.parse ::<$t >() .ok () } } ) *} ;}
    iter_scan_impls !(char u8 u16 u32 u64 usize i8 i16 i32 i64 isize f32 f64 u128 i128 String );
    macro_rules !iter_scan_tuple_impl {($($T :ident ) *) =>{impl <$($T :IterScan ) ,*>IterScan for ($($T ,) *) {type Output =($(<$T as IterScan >::Output ,) *) ;#[inline ] fn scan <'a ,It :Iterator <Item =&'a str >>(_iter :&mut It ) ->Option <Self ::Output >{Some (($(<$T as IterScan >::scan (_iter ) ?,) *) ) } } } ;}
    iter_scan_tuple_impl!();
    iter_scan_tuple_impl!(A);
    iter_scan_tuple_impl !(A B );
    iter_scan_tuple_impl !(A B C );
    iter_scan_tuple_impl !(A B C D );
    iter_scan_tuple_impl !(A B C D E );
    iter_scan_tuple_impl !(A B C D E F );
    iter_scan_tuple_impl !(A B C D E F G );
    iter_scan_tuple_impl !(A B C D E F G H );
    iter_scan_tuple_impl !(A B C D E F G H I );
    iter_scan_tuple_impl !(A B C D E F G H I J );
    iter_scan_tuple_impl !(A B C D E F G H I J K );
    pub struct ScannerIter<'a, 'b, T> {
        inner: &'b mut Scanner<'a>,
        _marker: std::marker::PhantomData<fn() -> T>,
    }
    impl<'a, 'b, T: IterScan> Iterator for ScannerIter<'a, 'b, T> {
        type Item = <T as IterScan>::Output;
        #[inline]
        fn next(&mut self) -> Option<Self::Item> {
            <T as IterScan>::scan(&mut self.inner.iter)
        }
    }
}
pub mod marker {
    use super::*;
    use std::{iter::FromIterator, marker::PhantomData};
    #[derive(Debug, Copy, Clone)]
    pub struct Usize1;
    impl IterScan for Usize1 {
        type Output = usize;
        #[inline]
        fn scan<'a, I: Iterator<Item = &'a str>>(iter: &mut I) -> Option<Self::Output> {
            Some(<usize as IterScan>::scan(iter)?.checked_sub(1)?)
        }
    }
    #[derive(Debug, Copy, Clone)]
    pub struct Chars;
    impl IterScan for Chars {
        type Output = Vec<char>;
        #[inline]
        fn scan<'a, I: Iterator<Item = &'a str>>(iter: &mut I) -> Option<Self::Output> {
            Some(iter.next()?.chars().collect())
        }
    }
    #[derive(Debug, Copy, Clone)]
    pub struct CharsWithBase(pub char);
    impl MarkedIterScan for CharsWithBase {
        type Output = Vec<usize>;
        #[inline]
        fn mscan<'a, I: Iterator<Item = &'a str>>(self, iter: &mut I) -> Option<Self::Output> {
            Some(
                iter.next()?
                    .chars()
                    .map(|c| (c as u8 - self.0 as u8) as usize)
                    .collect(),
            )
        }
    }
    #[derive(Debug, Copy, Clone)]
    pub struct Collect<T: IterScan, B: FromIterator<<T as IterScan>::Output>> {
        size: usize,
        _marker: PhantomData<fn() -> (T, B)>,
    }
    impl<T: IterScan, B: FromIterator<<T as IterScan>::Output>> Collect<T, B> {
        pub fn new(size: usize) -> Self {
            Self {
                size,
                _marker: PhantomData,
            }
        }
    }
    impl<T: IterScan, B: FromIterator<<T as IterScan>::Output>> MarkedIterScan for Collect<T, B> {
        type Output = B;
        #[inline]
        fn mscan<'a, I: Iterator<Item = &'a str>>(self, iter: &mut I) -> Option<Self::Output> {
            Some(
                (0..self.size)
                    .map(|_| <T as IterScan>::scan(iter).expect("scan error"))
                    .collect::<B>(),
            )
        }
    }
}
#[macro_export]
macro_rules !min {($e :expr ) =>{$e } ;($e :expr ,$($es :expr ) ,+) =>{std ::cmp ::min ($e ,min !($($es ) ,+) ) } ;}
#[macro_export]
macro_rules !chmin {($dst :expr ,$($src :expr ) ,+) =>{{let x =std ::cmp ::min ($dst ,min !($($src ) ,+) ) ;$dst =x ;} } ;}
#[macro_export]
macro_rules !max {($e :expr ) =>{$e } ;($e :expr ,$($es :expr ) ,+) =>{std ::cmp ::max ($e ,max !($($es ) ,+) ) } ;}
#[macro_export]
macro_rules !chmax {($dst :expr ,$($src :expr ) ,+) =>{{let x =std ::cmp ::max ($dst ,max !($($src ) ,+) ) ;$dst =x ;} } ;}
pub use sparse_graph::{
    Adjacency, BidirectionalGraphScanner, BidirectionalSparseGraph, DirectedGraphScanner,
    DirectedSparseGraph, SparseGraph, TreeGraphScanner, UndirectedGraphScanner,
    UndirectedSparseGraph,
};
pub mod sparse_graph {
    use super::*;
    #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash)]
    pub struct DirectedEdge;
    #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash)]
    pub struct UndirectedEdge;
    #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash)]
    pub struct BidirectionalEdge;
    #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash)]
    pub struct Adjacency {
        pub id: usize,
        pub to: usize,
    }
    impl Adjacency {
        pub fn new(id: usize, to: usize) -> Adjacency {
            Adjacency { id, to }
        }
    }
    /// Static Sparse Graph represented as Compressed Sparse Row.
    #[derive(Debug, Clone)]
    pub struct SparseGraph<D> {
        vsize: usize,
        pub start: Vec<usize>,
        pub elist: Vec<Adjacency>,
        pub edges: Vec<(usize, usize)>,
        _marker: std::marker::PhantomData<fn() -> D>,
    }
    impl<D> SparseGraph<D> {
        /// Return the number of vertices.
        pub fn vertices_size(&self) -> usize {
            self.vsize
        }
        /// Return the number of edges.
        pub fn edges_size(&self) -> usize {
            self.edges.len()
        }
        /// Return an iterator over graph vertices.
        pub fn vertices(&self) -> std::ops::Range<usize> {
            0..self.vertices_size()
        }
        /// Return a slice of adjacency vertices.
        pub fn adjacencies(&self, v: usize) -> std::slice::Iter<'_, Adjacency> {
            self.elist[self.start[v]..self.start[v + 1]].iter()
        }
    }
    pub trait SparseGraphConstruction: Sized {
        fn construct_graph(vsize: usize, edges: Vec<(usize, usize)>) -> SparseGraph<Self>;
    }
    impl<D: SparseGraphConstruction> SparseGraph<D> {
        /// Construct graph from edges.
        pub fn from_edges(vsize: usize, edges: Vec<(usize, usize)>) -> Self {
            D::construct_graph(vsize, edges)
        }
    }
    impl SparseGraphConstruction for DirectedEdge {
        fn construct_graph(vsize: usize, edges: Vec<(usize, usize)>) -> SparseGraph<Self> {
            let mut start = vec![0; vsize + 1];
            let mut elist = Vec::with_capacity(edges.len());
            unsafe { elist.set_len(edges.len()) }
            for (from, _) in edges.iter().cloned() {
                start[from] += 1;
            }
            for i in 1..=vsize {
                start[i] += start[i - 1];
            }
            for (id, (from, to)) in edges.iter().cloned().enumerate() {
                start[from] -= 1;
                elist[start[from]] = Adjacency::new(id, to);
            }
            SparseGraph {
                vsize,
                start,
                elist,
                edges,
                _marker: std::marker::PhantomData,
            }
        }
    }
    impl SparseGraphConstruction for UndirectedEdge {
        fn construct_graph(vsize: usize, edges: Vec<(usize, usize)>) -> SparseGraph<Self> {
            let mut start = vec![0; vsize + 1];
            let mut elist = Vec::with_capacity(edges.len() * 2);
            unsafe { elist.set_len(edges.len() * 2) }
            for (from, to) in edges.iter().cloned() {
                start[to] += 1;
                start[from] += 1;
            }
            for i in 1..=vsize {
                start[i] += start[i - 1];
            }
            for (id, (from, to)) in edges.iter().cloned().enumerate() {
                start[from] -= 1;
                elist[start[from]] = Adjacency::new(id, to);
                start[to] -= 1;
                elist[start[to]] = Adjacency::new(id, from);
            }
            SparseGraph {
                vsize,
                start,
                elist,
                edges,
                _marker: std::marker::PhantomData,
            }
        }
    }
    impl SparseGraphConstruction for BidirectionalEdge {
        fn construct_graph(vsize: usize, edges: Vec<(usize, usize)>) -> SparseGraph<Self> {
            let mut start = vec![0; vsize + 1];
            let mut elist = Vec::with_capacity(edges.len() * 2);
            unsafe { elist.set_len(edges.len() * 2) }
            for (from, to) in edges.iter().cloned() {
                start[to] += 1;
                start[from] += 1;
            }
            for i in 1..=vsize {
                start[i] += start[i - 1];
            }
            for (id, (from, to)) in edges.iter().cloned().enumerate() {
                start[from] -= 1;
                elist[start[from]] = Adjacency::new(id * 2, to);
                start[to] -= 1;
                elist[start[to]] = Adjacency::new(id * 2 + 1, from);
            }
            SparseGraph {
                vsize,
                start,
                elist,
                edges,
                _marker: std::marker::PhantomData,
            }
        }
    }
    pub type DirectedSparseGraph = SparseGraph<DirectedEdge>;
    pub type UndirectedSparseGraph = SparseGraph<UndirectedEdge>;
    pub type BidirectionalSparseGraph = SparseGraph<BidirectionalEdge>;
    pub struct SparseGraphScanner<U: IterScan<Output = usize>, T: IterScan, D> {
        vsize: usize,
        esize: usize,
        _marker: std::marker::PhantomData<fn() -> (U, T, D)>,
    }
    impl<U: IterScan<Output = usize>, T: IterScan, D> SparseGraphScanner<U, T, D> {
        pub fn new(vsize: usize, esize: usize) -> Self {
            Self {
                vsize,
                esize,
                _marker: std::marker::PhantomData,
            }
        }
    }
    impl<U: IterScan<Output = usize>, T: IterScan, D: SparseGraphConstruction> MarkedIterScan
        for SparseGraphScanner<U, T, D>
    {
        type Output = (SparseGraph<D>, Vec<<T as IterScan>::Output>);
        fn mscan<'a, I: Iterator<Item = &'a str>>(self, iter: &mut I) -> Option<Self::Output> {
            let mut edges = Vec::with_capacity(self.esize);
            let mut rest = Vec::with_capacity(self.esize);
            for _ in 0..self.esize {
                edges.push((U::scan(iter)?, U::scan(iter)?));
                rest.push(T::scan(iter)?);
            }
            let graph = SparseGraph::from_edges(self.vsize, edges);
            Some((graph, rest))
        }
    }
    pub type DirectedGraphScanner<U, T> = SparseGraphScanner<U, T, DirectedEdge>;
    pub type UndirectedGraphScanner<U, T> = SparseGraphScanner<U, T, UndirectedEdge>;
    pub type BidirectionalGraphScanner<U, T> = SparseGraphScanner<U, T, BidirectionalEdge>;
    pub struct TreeGraphScanner<U: IterScan<Output = usize>, T: IterScan>(
        std::marker::PhantomData<fn() -> (U, T)>,
    );
    impl<U: IterScan<Output = usize>, T: IterScan> TreeGraphScanner<U, T> {
        pub fn new(vsize: usize) -> SparseGraphScanner<U, T, UndirectedEdge> {
            SparseGraphScanner::new(vsize, vsize - 1)
        }
    }
}
#[derive(Debug, Clone)]
pub struct PrimalDualBuilder {
    vsize: usize,
    edges: Vec<(usize, usize)>,
    capacities: Vec<u64>,
    costs: Vec<i64>,
}
impl PrimalDualBuilder {
    pub fn new(vsize: usize, esize_expect: usize) -> Self {
        Self {
            vsize,
            edges: Vec::with_capacity(esize_expect),
            capacities: Vec::with_capacity(esize_expect * 2),
            costs: Vec::with_capacity(esize_expect * 2),
        }
    }
    pub fn add_edge(&mut self, from: usize, to: usize, cap: u64, cost: i64) {
        self.edges.push((from, to));
        self.capacities.push(cap);
        self.capacities.push(0);
        self.costs.push(cost);
        self.costs.push(-cost);
    }
    pub fn gen_graph(&mut self) -> BidirectionalSparseGraph {
        let edges = std::mem::take(&mut self.edges);
        BidirectionalSparseGraph::from_edges(self.vsize, edges)
    }
    pub fn build(self, graph: &BidirectionalSparseGraph) -> PrimalDual<'_> {
        let PrimalDualBuilder {
            vsize,
            capacities,
            costs,
            ..
        } = self;
        let pd = PrimalDual {
            graph,
            capacities,
            costs,
            potential: vec![0; vsize],
            dist: Vec::with_capacity(vsize),
            prev_vertex: vec![0; vsize],
            prev_edge: vec![0; vsize],
        };
        pd
    }
}

#[derive(Debug)]
pub struct PrimalDual<'a> {
    graph: &'a BidirectionalSparseGraph,
    capacities: Vec<u64>,
    costs: Vec<i64>,
    potential: Vec<i64>,
    dist: Vec<i64>,
    prev_vertex: Vec<usize>,
    prev_edge: Vec<usize>,
}
impl<'a> PrimalDual<'a> {
    pub fn minimum_cost_flow_limited(&mut self, s: usize, t: usize, mut limit: u64) -> Option<i64> {
        let mut res = 0;
        while limit > 0 {
            if !self.dijkstra(s, t) {
                return None;
            }
            for (p, d) in self.potential.iter_mut().zip(self.dist.iter()) {
                *p += *d;
            }
            let mut add_f = limit;
            let mut v = t;
            while v != s {
                add_f = add_f.min(self.capacities[self.prev_edge[v]]);
                v = self.prev_vertex[v];
            }
            limit -= add_f;
            res += add_f as i64 * self.potential[t];
            let mut v = t;
            while v != s {
                self.capacities[self.prev_edge[v]] -= add_f;
                self.capacities[self.prev_edge[v] ^ 1] += add_f;
                v = self.prev_vertex[v];
            }
        }
        Some(res)
    }
    fn dijkstra(&mut self, s: usize, t: usize) -> bool {
        use std::{cmp::Reverse, collections::BinaryHeap};
        self.dist.clear();
        self.dist.resize(self.graph.vertices_size(), std::i64::MAX);
        self.dist[s] = 0;
        let mut heap = BinaryHeap::new();
        heap.push((Reverse(0), s));
        while let Some((Reverse(d), u)) = heap.pop() {
            if self.dist[u] + self.potential[u] < d {
                continue;
            }
            if u == t {
                return true;
            }
            for a in self.graph.adjacencies(u) {
                let ncost =
                    self.dist[u] + self.costs[a.id] + self.potential[u] - self.potential[a.to];
                if self.capacities[a.id] > 0 && self.dist[a.to] > ncost {
                    self.dist[a.to] = ncost;
                    self.prev_vertex[a.to] = u;
                    self.prev_edge[a.to] = a.id;
                    heap.push((Reverse(d + self.costs[a.id]), a.to));
                }
            }
        }
        false
    }
    pub fn get_flow(&self, eid: usize) -> u64 {
        self.capacities[eid * 2 + 1]
    }
}

fn main() {
    #![allow(unused_imports, unused_macros)]
    use std::io::{stdin, stdout, BufWriter, Read as _, Write as _};
    let mut _in_buf = Vec::new();
    stdin().read_to_end(&mut _in_buf).expect("io error");
    let _in_buf = unsafe { String::from_utf8_unchecked(_in_buf) };
    let mut scanner = Scanner::new(&_in_buf);
    macro_rules !scan {() =>{scan !(usize ) } ;(($($t :tt ) ,*) ) =>{($(scan !($t ) ) ,*) } ;([$t :tt ;$len :expr ] ) =>{(0 ..$len ) .map (|_ |scan !($t ) ) .collect ::<Vec <_ >>() } ;([$t :ty ] ) =>{scanner .iter ::<$t >() } ;({$e :expr } ) =>{scanner .mscan ($e ) } ;($t :ty ) =>{scanner .scan ::<$t >() } ;}
    let _out = stdout();
    let mut _out = BufWriter::new(_out.lock());
    macro_rules !print {($($arg :tt ) *) =>(::std ::write !(_out ,$($arg ) *) .expect ("io error" ) ) }
    macro_rules !println {($($arg :tt ) *) =>(::std ::writeln !(_out ,$($arg ) *) .expect ("io error" ) ) }
    macro_rules! echo {
        ($iter :expr ) => {
            echo!($iter, '\n')
        };
        ($iter :expr ,$sep :expr ) => {
            let mut iter = $iter.into_iter();
            if let Some(item) = iter.next() {
                print!("{}", item);
            }
            for item in iter {
                print!("{}{}", $sep, item);
            }
            println!();
        };
    }
    let n = scan!();
    let k = scan!(u64);
    let a = scan!([[i64; n]; n]);
    let mut builder = PrimalDualBuilder::new(n * 2 + 2, (n + 1).pow(2));
    const M: i64 = 1_000_000_000;
    for i in 0..n {
        for j in 0..n {
            builder.add_edge(i, n + j, 1, M - a[i][j]);
        }
    }
    for i in 0..n {
        builder.add_edge(n * 2, i, k, 0);
        builder.add_edge(n + i, n * 2 + 1, k, 0);
    }
    builder.add_edge(n * 2, n * 2 + 1, n as u64 * k, M);
    let graph = builder.gen_graph();
    let mut pd = builder.build(&graph);
    let min = pd
        .minimum_cost_flow_limited(n * 2, n * 2 + 1, n as u64 * k)
        .unwrap_or_default();
    println!("{}", (n as u64 * k) as i64 * M - min);
    let mut t = vec![vec!['.'; n]; n];
    for i in 0..n {
        for j in 0..n {
            if pd.get_flow(i * n + j) > 0 {
                t[i][j] = 'X';
            }
        }
    }
    for t in t {
        println!("{}", t.into_iter().collect::<String>());
    }
}