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 ;} } ;}
#[derive(Debug, Clone)]
pub struct RevCEdge {
    pub to: usize,
    pub rev: usize,
    pub cap: u64,
    pub cost: i64,
}
impl RevCEdge {
    pub fn new(to: usize, rev: usize, cap: u64, cost: i64) -> Self {
        Self { to, rev, cap, cost }
    }
}
#[derive(Debug)]
pub struct PrimalDual {
    n: usize,
    pub graph: Vec<Vec<RevCEdge>>,
    potential: Vec<i64>,
    cost: Vec<i64>,
    prev_vertex: Vec<usize>,
    prev_edge: Vec<usize>,
}
impl PrimalDual {
    pub fn new(n: usize) -> Self {
        Self {
            n,
            graph: vec![vec![]; n],
            potential: vec![],
            cost: vec![],
            prev_vertex: vec![],
            prev_edge: vec![],
        }
    }
    pub fn add_edge(&mut self, from: usize, to: usize, cap: u64, cost: i64) {
        let e1 = RevCEdge::new(to, self.graph[to].len(), cap, cost);
        let e2 = RevCEdge::new(from, self.graph[from].len(), 0, -cost);
        self.graph[from].push(e1);
        self.graph[to].push(e2);
    }
    pub fn minimum_cost_flow(&mut self, s: usize, t: usize, f: u64) -> Option<i64> {
        use std::cmp::min;
        let mut res = 0;
        let mut f = f;
        self.potential = vec![0; self.n];
        self.prev_edge = vec![0; self.n];
        self.prev_vertex = vec![0; self.n];
        while f > 0 {
            self.dijkstra(s);
            if self.cost[t] == std::i64::MAX {
                return None;
            }
            for v in 0..self.n {
                self.potential[v] += self.cost[v];
            }
            let mut add_f = f;
            let mut v = t;
            while v != s {
                add_f = min(
                    add_f,
                    self.graph[self.prev_vertex[v]][self.prev_edge[v]].cap,
                );
                v = self.prev_vertex[v];
            }
            f -= add_f;
            res += add_f as i64 * self.potential[t];
            let mut v = t;
            while v != s {
                self.graph[self.prev_vertex[v]][self.prev_edge[v]].cap -= add_f;
                let r = self.graph[self.prev_vertex[v]][self.prev_edge[v]].rev;
                self.graph[v][r].cap += add_f;
                v = self.prev_vertex[v];
            }
        }
        Some(res)
    }
    fn dijkstra(&mut self, s: usize) {
        use std::collections::BinaryHeap;
        self.cost = vec![std::i64::MAX; self.n];
        let mut heap = BinaryHeap::new();
        self.cost[s] = 0;
        heap.push((std::cmp::Reverse(0), s));
        while let Some((d, u)) = heap.pop() {
            let d = d.0;
            for i in 0..self.graph[u].len() {
                let e = &self.graph[u][i];
                let ncost = self.cost[u] + e.cost + self.potential[u] - self.potential[e.to];
                if e.cap > 0 && self.cost[e.to] > ncost {
                    self.cost[e.to] = ncost;
                    self.prev_vertex[e.to] = u;
                    self.prev_edge[e.to] = i;
                    heap.push((std::cmp::Reverse(d + e.cost), e.to));
                }
            }
        }
    }
}
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 primal = PrimalDual::new(n * 2 + 2);
    primal.add_edge(n * 2, n * 2 + 1, n as u64 * k, 0);
    for i in 0..n {
        primal.add_edge(n * 2, i, k, 0);
        primal.add_edge(n + i, n * 2 + 1, k, 0);
        for j in 0..n {
            primal.add_edge(i, n + j, 1, -a[i][j]);
        }
    }
    let min = primal
        .minimum_cost_flow(n * 2, n * 2 + 1, n as u64 * k)
        .unwrap_or_default();
    println!("{}", -min);
    let mut t = vec![vec!['.'; n]; n];
    for i in 0..n {
        for j in primal.graph[i]
            .iter()
            .filter(|e| e.cap == 0 && e.to < n * 2)
            .map(|e| e.to - n)
        {
            t[i][j] = 'X';
        }
    }
    for t in t {
        println!("{}", t.into_iter().collect::<String>());
    }
}

Measured memory_bytes: 2416