https://www.acmicpc.net/problem/2740
use std::ops::Mul;
use std::fmt::{Display, Formatter};
struct Mat {
data: Vec<Vec<i32>>,
}
impl Mat {
fn from(raw_data: Vec<Vec<i32>>) -> Mat {
Mat {
data: raw_data,
}
}
fn i_len(&self) -> usize {
self.data.len()
}
fn j_len(&self) -> usize {
self.data[0].len()
}
}
impl Mul for Mat {
type Output = Mat;
fn mul(self, rhs: Self) -> Self::Output {
let (li, lj) = (self.i_len(), self.j_len());
let (ri, rj) = (rhs.i_len(), rhs.j_len());
assert_eq!(lj, ri);
let mut raw_data = vec![vec![0 as i32; rhs.j_len()]; self.i_len()];
for i in 0..li {
for j in 0..rj {
for k in 0..lj {
raw_data[i][j] += self.data[i][k] * rhs.data[k][j];
}
}
}
Mat::from(raw_data)
}
}
impl Display for Mat {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
for i in 0..self.i_len() {
for j in 0..self.j_len() {
write!(f, "{} ", self.data[i][j])?;
}
write!(f, "\n")?;
}
Ok(())
}
}
fn main() {
let mut read_buf = String::new();
std::io::stdin().read_line(&mut read_buf).unwrap();
let mut iter = read_buf.split_whitespace();
let n: usize = iter.next().unwrap().parse().unwrap();
let mut matrix_as_vec2d = Vec::<Vec<i32>>::with_capacity(n);
for _ in 0..n {
let mut read_buf = String::new();
std::io::stdin().read_line(&mut read_buf).unwrap();
let iter = read_buf.split_whitespace().map(
|x: &str| x.parse::<i32>().unwrap()
);
matrix_as_vec2d.push(Vec::from_iter(iter));
}
let mat_a = Mat::from(matrix_as_vec2d);
read_buf = String::new();
std::io::stdin().read_line(&mut read_buf).unwrap();
iter = read_buf.split_whitespace();
let m: usize = iter.next().unwrap().parse().unwrap();
matrix_as_vec2d = Vec::<Vec<i32>>::with_capacity(m);
for _ in 0..m {
let mut read_buf = String::new();
std::io::stdin().read_line(&mut read_buf).unwrap();
let iter = read_buf.split_whitespace().map(
|x: &str| x.parse::<i32>().unwrap()
);
matrix_as_vec2d.push(Vec::from_iter(iter));
}
let mat_b = Mat::from(matrix_as_vec2d);
let ret= mat_a * mat_b;
println!("{}", &ret);
}
'Computer Science > Rust' 카테고리의 다른 글
[백준 2667] 단지번호붙이기 (Rust 풀이; Silver I) (0) | 2023.04.30 |
---|
댓글