题解 | #称砝码#
称砝码
http://www.nowcoder.com/practice/f9a4c19050fc477e9e27eb75f3bfd49c
use std::collections::HashSet; use std::io;
pub fn main() { loop { let mut num = String::new();
let mut weight = String::new();
let mut weights = String::new();
// Use the check size, when size equal 1, that's mean there is no input in console
let check_size = io::stdin().read_line(&mut num).expect("Fail to read line!");
// base on the practice if the check_size wasn't 1, that the next line will have contents
let _chec = io::stdin()
.read_line(&mut weight)
.expect("Fail to read this line");
let _che = io::stdin()
.read_line(&mut weights)
.expect("Fail to read this line");
// Check if the content is right
// println!("{}", num); // Check the array is exist to avoid error or panic! // println!("{}", weight); // println!("{}", weights); match num.trim().parse::() { Ok(num) => { let mut w: Vec = vec![]; // Use the HashSet to store data to avoid data repetive let mut sp: HashSet = HashSet::new(); // even 0 is a number we need sp.insert(0);
// Prove that the weight is exist and push it to store
for wt in weight.split_whitespace() {
match wt.parse::<u32>() {
Ok(wn) => {
w.push(wn);
}
Err(_) => {
// Print every error info in case we cann't find where is the error
println!("Parse Error 2");
break;
}
}
}
let mut wn: Vec<u32> = vec![];
for wt in weights.split_whitespace() {
match wt.parse::<u32>() {
Ok(ws) => {
wn.push(ws);
}
Err(_) => {
println!("Get error 3");
break;
}
}
}
// Use this flag to detect the weight we need
let mut hk: u32 = 0;
// Get all weights, and can known the number of weights
for i in wn {
// Every time store what we get number, and store it to a array
let mut result_list: Vec<u32> = Vec::new();
for se in sp.clone().into_iter() {
result_list.push(se);
}
let ip = i + 1;
for k in 1..ip {
for j in result_list.clone().into_iter() {
let mut hkk: u32 = 0;
// Use this break flag to end the loop
'scc: for jkk in w.clone().into_iter() {
if hkk == hk {
sp.insert(j + jkk * k);
break 'scc;
}
hkk += 1;
}
}
}
hk += 1;
}
let mut size: u32 = 0;
for _tr in sp.clone().into_iter() {
size += 1;
}
println!("{}", size);
}
Err(_) => {
// println!("Parse Error 1"); break; } }
// println!("{}", num);
if check_size == 0 {
println!("There is no input, and the check_size is {}", check_size);
break;
}
}
}