Created
April 12, 2015 16:05
-
-
Save anonymous/688e69cfe75282322bdb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::error::Error; | |
use std::io; | |
use std::io::prelude::*; | |
use std::process; | |
macro_rules! strerr { | |
($($tt:tt)*) => (Err(From::from(&*format!($($tt)*)))); | |
} | |
type CliResult<T> = Result<T, Box<Error + Send>>; | |
fn main() { | |
if let Err(err) = run() { | |
writeln!(&mut io::stdout(), "{}", err).unwrap(); | |
process::exit(1); | |
} | |
} | |
fn run() -> CliResult<()> { | |
let stdin = io::stdin(); | |
let mut stdin = stdin.lock(); // gives us buffered access | |
let num_cases: i32 = try!(try!(read_line(&mut stdin)).trim().parse()); | |
for i in 0..num_cases { | |
let line = try!(read_line(&mut stdin)); | |
let pieces: Vec<&str> = line.trim().split(" ").collect(); | |
if pieces.len() != 2 { | |
return strerr!("Parse error: '{}'", line); | |
}; | |
let max_shyness: i32 = try!(pieces[0].parse()); | |
let str_digits: &str = &pieces[1]; | |
let mut people_sum: u32 = 0; | |
let mut friends_required: u32 = 0; | |
for (i, c) in str_digits.chars().enumerate() { | |
let i = i as u32; | |
let digit = match c.to_digit(10) { | |
Some(digit) => digit, | |
None => return strerr!("Not a digit: '{}'", c), | |
}; | |
if people_sum < i { | |
friends_required += i - people_sum; | |
people_sum += friends_required; | |
} | |
people_sum += digit; | |
} | |
println!("Case #{}: {}", i, friends_required); | |
} | |
Ok(()) | |
} | |
fn read_line<R: BufRead>(mut rdr: R) -> CliResult<String> { | |
let mut buf = String::new(); | |
let n = try!(rdr.read_line(&mut buf)); | |
if n == 0 { | |
strerr!("Expected to read new line, but got EOF.") | |
} else { | |
Ok(buf) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment