Problem:
Problem D: Goofy Converter

Nathan O. Davis is a student at the department of integrated systems. He is now taking a class in in-
tegrated curcuits. He is an idiot. One day, he got an assignment as follows: design a logic circuit that
takes a sequence of positive integers as input, and that outputs a sequence of 1-bit integers from which
the original input sequence can be restored uniquely.

Nathan has no idea. So he searched for hints on the Internet, and found several pages that describe the
1-bit DAC. This is a type of digital-analog converter which takes a sequence of positive integers as input,
and outputs a sequence of 1-bit integers.

Seeing how 1-bit DAC works on these pages, Nathan came up with a new idea for the desired converter.
His converter takes a sequence L of positive integers, and a positive integer M aside from the sequence,
and outputs a sequence K of 1-bit integers such that:

He is not so smart, however. It is clear that his converter does not work for some sequences. Your task is
to write a program in order to show the new converter cannot satisfy the requirements of his assignment,
even though it would make Nathan in despair.

Input

The input consists of a series of data sets. Each data set is given in the following format:

N M
L0 L1 . . . LN-1

N is the length of the sequence L. M and L are the input to Nathan’s converter as described above. You
may assume the followings: 1 ≤ N ≤ 1000, 1 ≤ M ≤ 12, and 0 ≤ Lj ≤ M for j = 0, . . . , N - 1.

The input is terminated by N = M = 0.

Output

For each data set, output a binary sequence K of the length (N + M - 1) if there exists a sequence which
holds the equation mentioned above, or “Goofy” (without quotes) otherwise. If more than one sequence
is possible, output any one of them.

Sample Input

4 4
4 3 2 2
4 4
4 3 2 3
0 0

Output for the Sample Input

1111001
Goofy

Solution in Rust (judge verdict: Accepted)

use std::ops::Sub;
use std::collections::BinaryHeap;
use std::fmt::Debug;

fn read_line() -> String {
    let mut buffer = String::new();
    std::io::stdin().read_line(&mut buffer).expect("No Line");
    buffer
}
fn read_lines<R, T: Fn(&str)->R> (count: usize, transformer: T) -> Vec<R> {
    let mut buffer = String::new();
    let mut vec = Vec::with_capacity(count);
    for _ in 0 .. count {
        std::io::stdin().read_line(&mut buffer).expect("No Line");
        vec.push(transformer(buffer.trim()));
        buffer.clear();
    }
    vec
}
fn read_value<T: std::str::FromStr>() -> T {
    read_line().trim().parse().ok().unwrap()
}
fn read_values<T: std::str::FromStr>() -> Vec<T> {
    read_line().trim().split(' ').map(|x| x.parse().ok().expect("Can't Parse")).collect::<Vec<T>>()
}
fn read_tabulate<T: std::str::FromStr>(count: usize) -> Vec<T> {
    let mut buffer = String::new();
    let mut vec = Vec::with_capacity(count);
    for _ in 0 .. count {
        std::io::stdin().read_line(&mut buffer).expect("No Line");
        vec.push(buffer.trim().parse().ok().expect("Can't Parse"));
        buffer.clear();
    }
    vec
}
macro_rules! define {
    () => {};
    ($($token:tt)*) => {
        let mut iter = read_values::<String>().into_iter();
        define_iter!(iter, $($token)*);
    };
}
macro_rules! define_iter {
    ($iter:expr) =>{};
    ($iter:expr,) =>{};
    ($iter:expr, $id:ident:$t:tt $($tail:tt)*) => {
        let $id: $t = $iter.next().unwrap().parse().ok().expect("Can't Parse");
        define_iter!($iter, $($tail)*);
    };
    ($iter:expr, mut $id:ident:$t:tt $($tail:tt)*) => {
        let mut $id: $t = $iter.next().unwrap().parse().ok().expect("Can't Parse");
        define_iter!($iter, $($tail)*)
    };
}
macro_rules! freeze {
    ($($id:ident), *) => {
        $(let $id = $id;)*
    };
}
struct KeyValue<K, V> {
    key: K,
    value: V
}
impl <K: PartialOrd, V> PartialEq for KeyValue<K, V> {
    fn eq(&self, other: &Self) -> bool {
        self.key.eq(&other.key)
    }
}
impl <K: PartialOrd, V> Eq for KeyValue<K, V> {}
impl <K: PartialOrd, V> PartialOrd for KeyValue<K, V> {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        self.key.partial_cmp(&other.key)
    }
}
impl <K: PartialOrd, V> Ord for KeyValue<K, V> {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.key.partial_cmp(&other.key).ok_or("Can't Compare").unwrap()
    }
} 
#[derive(PartialEq, Eq, Debug, Copy, Clone, Default, Hash)]
struct Reverse<T>(T);
impl <T: PartialOrd> PartialOrd for Reverse<T> {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        other.0.partial_cmp(&self.0)
    }
}
impl <T: Ord> Ord for Reverse<T> {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        other.0.cmp(&self.0)
    }
}
#[derive(Clone)]
struct Bit {
    vec: Vec<i32>
}
impl Bit {
    fn new(size: usize) -> Bit {
        Bit{vec: vec![0; size]}
    }
    fn add(&mut self, position: usize, value: i32) {
        let mut position = position as i32;
        while position < self.vec.len() as i32 {
            self.vec[position as usize] += value;
            position += !position & (position + 1);
        }
    }
    fn get(&self, mut position: i32) -> i32 {
        let mut result = 0;
        while position >= 0 {
            result += self.vec[position as usize];
            position -= !position & (position + 1);
        }
        result
    }
}
fn range_step_by(mut from: usize, until: usize, step: usize) -> Vec<usize> {
    let mut result = Vec::with_capacity((until - from) / step);
    while from < until {
        result.push(from);
        from += step;
    }
    result
}
fn main() {
    loop {
        define! {
            n: usize
            m: usize
        }
        if n == 0 && m == 0 {break;}
        let out = read_values::<usize>();
        let mut result = vec![0usize; n + m - 1];
        let mut confirm = vec![false; n + m - 1];
        for i in 1usize .. n {
            if out[i - 1] > out[i] {
                result[i - 1] = 1;
                result[i + m - 1] = 0;
                confirm[i - 1] = true;
                confirm[i + m - 1] = true;
            }else if out[i - 1] < out[i] {
                result[i - 1] = 0;
                result[i + m - 1] = 1;
                confirm[i - 1] = true;
                confirm[i + m - 1] = true;
            }else if confirm[i - 1] {
                result[i + m - 1] = result[i - 1];
                confirm[i + m - 1] = true;
            }
        }
        for i in (m .. n + m - 1).rev() {
            if out[i - m] == out[i - m + 1] && confirm[i] {
                result[i - m] = result[i];
                confirm[i - m] = true;
            }
        }
        let mut sum = out[0] as i32 - (0 .. m).map(|i| result[i]).fold(0, |acc, v| acc + v) as i32;
        for i in 0usize .. m {
            if confirm[i] {continue;}
            if sum > 0 {
                for j in range_step_by(i,  n + m - 1, m) {
                    result[j] = 1;
                    confirm[j] = true;
                }
                sum -= 1;
            }else {
                for j in range_step_by(i, n + m - 1, m) {
                    result[j] = 0;
                    confirm[j] = true;
                }
            }
        }
        let mut bit = Bit::new(result.len());
        for i in 0usize .. result.len() {
            bit.add(i, result[i] as i32);
        }
        freeze!(bit);
        let mut can_make = true;
        for i in 0 .. n as i32 {
            can_make &= (bit.get(i + m as i32 - 1) - bit.get(i - 1)) == out[i as usize] as i32;
        }
        if can_make {
            for b in result {
                print!("{}", b);
            }
            println!("");
        }else {
            println!("Goofy");
        }
    }
}