use std::io;
use std::collections::HashMap;

fn main() {
    let mut departments: HashMap<String, Vec<String>> = HashMap::new();

    loop {
        let mut input = String::new();
        io::stdin().read_line(&mut input).unwrap();

        let words: Vec<&str> = input.split_whitespace().collect();

        if words.is_empty() { continue; }
        
        match words[0].to_lowercase().as_str() {
            "add" => {
                // Format: add [name] [department]
                if words.len() >= 3 {
                    let v = departments.entry(String::from(words[2])).or_insert(Vec::new());
                    v.push(String::from(words[1]));
                }
            },
            "del" => {
                // Format: del [name] [department]
                if words.len() >= 3 {
                    let v = departments.entry(String::from(words[2])).or_insert(Vec::new());
                    let mut idx: Option<usize> = None;

                    for (i, who2) in v.into_iter().enumerate() {
                        if who2 == words[1] {
                            idx = Some(i);
                            break;
                        }
                    }

                    match idx {
                        Some(x) => { v.remove(x); () },
                        None => (),
                    };
                }
            },
            "ls" => {
                if words.len() == 1 {
                    println!("{departments:?}");
                }
                if words.len() >= 2 {
                    let dpt = String::from(words[1]);
                    let ppl = departments.entry(dpt.clone()).or_insert(Vec::new());
                    ppl.sort();

                    println!("The following people are in the {} department:", dpt);

                    for pp in ppl {
                        println!("{pp}");
                    }
                }
            },
            _ => println!("Unknown command"),
        }

        println!("");
    }
}
