-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.rs
95 lines (81 loc) · 2.47 KB
/
main.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
use std::{
collections::HashSet,
io::{self, BufRead},
};
type BoardRow = Vec<i32>;
type Board = Vec<BoardRow>;
fn is_bingo(board: &Board, selected_nums: &HashSet<i32>) -> bool {
for row in board {
let bingo = row
.iter()
.map(|x| selected_nums.contains(x))
.fold(true, |x, y| x && y);
if bingo {
return bingo;
}
}
let cols_num = board.get(0).unwrap().len();
for col_index in 0..cols_num {
let bingo = board
.iter()
.map(|row| selected_nums.contains(row.get(col_index).unwrap()))
.fold(true, |x, y| x && y);
if bingo {
return bingo;
}
}
false
}
fn main() {
let stdin = io::stdin();
let stdin_str = String::from_utf8(stdin.lock().fill_buf().unwrap().to_vec()).unwrap();
let mut splited = stdin_str.split("\n\n");
// parse nums
let nums = splited
.next()
.unwrap()
.split(",")
.map(|x| x.parse::<i32>().unwrap());
// parse boards
let mut boards: Vec<Board> = Vec::new();
for board_str in splited {
let board = board_str
.split("\n")
.filter(|line| line != &"")
.map(|line| {
line.split(" ")
.filter(|x| x != &"")
.map(|x| x.parse::<i32>().unwrap())
.collect::<BoardRow>()
})
.collect::<Board>();
boards.push(board);
}
let mut selected_nums: HashSet<i32> = HashSet::new();
let mut finished_boards_id: HashSet<usize> = HashSet::new();
'num_loop: for num in nums {
selected_nums.insert(num);
for (board, i) in boards.iter().zip(0..) {
if finished_boards_id.contains(&i) {
continue;
}
let bingo = is_bingo(&board, &selected_nums);
if bingo {
finished_boards_id.insert(i);
if finished_boards_id.len() != boards.len() {
continue;
}
let rest_sum = board
.iter()
.map(|row| {
row.iter()
.filter(|x| !selected_nums.contains(x))
.fold(0, |x, y| x + y)
})
.fold(0, |x, y| x + y);
println!("ans {}", rest_sum * num);
break 'num_loop;
}
}
}
}