第一行输入一个整数
代表给定的整数个数。
第二行输入
个整数
。
保证数据随机生成。
如果存在满足条件的分配方案,输出
,否则输出
。
4 1 5 -5 1
true
在这个样例中,
数组可以为
,
数组可以为
,满足条件。
3 3 5 8
false
fn main() {
let mut n = String::new();
let mut nums = String::new();
std::io::stdin().read_line(&mut n);
std::io::stdin().read_line(&mut nums);
let mut sum3 = 0;
let mut sum5 = 0;
let mut others = vec![];
nums.trim()
.split(" ")
.map(|n| n.parse::<i32>().unwrap())
.for_each(|n| {
if n % 5 == 0 {
sum5 += n;
} else if n % 3 == 0 {
sum3 += n;
} else {
others.push(n);
}
});
println!("{}", backtrack(others, sum3, sum5));
}
fn backtrack(mut nums: Vec<i32>, sum1: i32, sum2: i32) -> bool {
match nums.pop() {
Some(x) => {
backtrack(nums.clone(), sum1 + x, sum2) || backtrack(nums.clone(), sum1, sum2 + x)
}
None => sum1 == sum2,
}
} use std::io;
fn is_str_numeric(s: &str) -> Option<i32> {
for c in s.to_string().chars() {
if !c.is_digit(10) && c != '-' {
return None;
}
}
Some(s.parse().unwrap())
}
fn have_same_sum(nums_five: &[i32], nums_three: &[i32],
nums_others: &[i32]) -> bool {
if nums_others.is_empty() {
return nums_five.iter().sum::<i32>() == nums_three.iter().sum::<i32>();
}
return have_same_sum(&[nums_five, &[nums_others[0]]].concat(),
nums_three,
&nums_others[1..])
|| have_same_sum(nums_five,
&[nums_three, &[nums_others[0]]].concat(),
&nums_others[1..]);
}
fn main() {
let stdin = io::stdin();
let mut n = String::new();
while let Ok(len) = stdin.read_line(&mut n) {
if len <= 0 {
break;
}
let mut line = String::new();
stdin.read_line(&mut line).unwrap();
line.truncate(line.len() - 1);
let nums: Vec<i32> = line
.split(" ")
.filter_map(|c| is_str_numeric(c))
.collect();
let nums_five: Vec<i32> = nums
.iter()
.filter(|&num| num % 5 == 0)
.cloned()
.collect();
let nums_three: Vec<i32> = nums
.iter()
.filter(|&num| num % 3 == 0)
.cloned()
.collect();
let nums_others: Vec<i32> = nums
.iter()
.filter(|&num| num % 3 != 0 && num % 5 != 0)
.cloned()
.collect();
println!("{}", have_same_sum(nums_five.as_slice(),
nums_three.as_slice(),
nums_others.as_slice()));
}
}