Problem:
Quick Sort

Let's arrange a deck of cards. Your task is to sort totally n cards. A card consists of a part of a suit (S, H, C or D) and an number. Write a program which sorts such cards based on the following pseudocode:

Partition(A, p, r)
1 x = A[r]
2 i = p-1
3 for j = p to r-1
4 do if A[j] <= x
5 then i = i+1
6 exchange A[i] and A[j]
7 exchange A[i+1] and A[r]
8 return i+1

Quicksort(A, p, r)
1 if p < r
2 then q = Partition(A, p, r)
3 run Quicksort(A, p, q-1)
4 run Quicksort(A, q+1, r)

Here, A is an array which represents a deck of cards and comparison operations are performed based on the numbers.

Your program should also report the stability of the output for the given input (instance). Here, 'stability of the output' means that: cards with the same value appear in the output in the same order as they do in the input (instance).

Input

The first line contains an integer n, the number of cards.

n cards are given in the following lines. Each card is given in a line and represented by a pair of a character and an integer separated by a single space.

Output

In the first line, print the stability ("Stable" or "Not stable") of this output.

In the following lines, print the arranged cards in the same manner of that of the input.

Constraints

1 ≤ n ≤ 100,000

1 ≤ the number of a card ≤ 109

There are no identical card in the input

Sample Input 1

6
D 3
H 2
D 1
S 3
D 2
C 1

Sample Output 1

Not stable
D 1
C 1
D 2
H 2
D 3
S 3

Sample Input 2

2
S 1
H 1

Sample Output 2

Stable
S 1
H 1

Solution in Rust (judge verdict: Accepted)

use std::collections::VecDeque;
use std::env;
//use std::fmt::Debug;
use std::io;
use std::io::prelude::*;
//use std::time::{Duration, Instant};
use std::fmt::{Display, Formatter};
use std::cmp::{PartialOrd, Ordering};
use std::str::{FromStr};

//===================================================
// MACROs need to be defined above the use place ... ?
macro_rules! dprintln {
    ($($x:expr),*) => {{
        if $crate::is_debug_mode() {
            let f = || {println!( $($x),*)};
            f()
        }
    }}
}

/// Backward For-Loop Helper
///  from -> to (exclude `to`)
///
/// # Examples
/// see tests::macro_backward()
///
#[macro_export]
macro_rules! backward_ho {
    ($from:expr, $to:expr) => {{
        (($to + 1)..($from + 1)).rev()
    }};
}
//===================================================

fn main() {
    // Initialize
    set_debug_mode(false);
    for arg in env::args() {
        if arg == "--debug" {
            set_debug_mode(true);
        }
    }
    dprintln!("[DebugMode] {}", "On");

    // Execute
    dprintln!("=================");
    dprintln!("= READ INPUT     ");
    let stdin = io::stdin();
    let input = BufReadInput::new(stdin.lock());
    dprintln!("[Input] \n{:?}", input);
    dprintln!("=================");
    dprintln!("= INTERPRET INPUT");
    let q = input.into_quiz();
    dprintln!("[Quiz] \n{:?}", q);
    dprintln!("=================");
    dprintln!("= SOLVE QUIZE    ");
    let a = q.solve();
    dprintln!("[Answer] \n{:?}", a);
    dprintln!("=================");
    dprintln!("= PRINT ANSWER   ");
    a.print();
    dprintln!("=================");
}

#[derive(Debug,Copy,Clone,PartialEq,Eq)]
enum Suit {
    S,
    H,
    C,
    D,
}

#[derive(Debug,Copy,Clone)]
struct Card{
    suit: Suit,
    number: u32,
}

impl PartialEq for Card {
    fn eq(&self, other: &Self) -> bool {
        return self.number == other.number;
    }
}
impl Eq for Card {}
impl PartialOrd for Card {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        self.number.partial_cmp( &other.number )
    }
}
impl Ord for Card {
    fn cmp(&self, other: &Self) -> Ordering {
        self.number.cmp( &other.number )
    }
}
impl Display for Card {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        let suit_char = match self.suit {
            Suit::S => 'S',
            Suit::H => 'H',
            Suit::C => 'C',
            Suit::D => 'D',
        };
        write!(f, "{} {}", suit_char, self.number)
    }
}
impl FromStr for Suit {
    type Err = ();
    
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "S" => Ok(Suit::S),
            "H" => Ok(Suit::H),
            "C" => Ok(Suit::C),
            "D" => Ok(Suit::D),
            _   => Err(()),
        }
    }
}


#[derive(Debug)]
struct Quiz {
    n: usize,    // 1 <= N <= 100,000
    v: Vec<Card>, // 1 <= Card.number <= 100,000,000, length=N
}

#[derive(Debug)]
struct Answer {
    is_stable: bool,
    v: Vec<Card>,
}

trait IntoQuiz {
    fn into_quiz(self) -> Quiz;
}

impl<I: Input> IntoQuiz for I {
    fn into_quiz(mut self) -> Quiz {
        let n: usize = self.parse_next().unwrap();
        let mut v = Vec::new();
        for _i in 0..n {
            let suit: Suit = self.parse_next().unwrap();
            let number: u32 = self.parse_next().unwrap();
            v.push(Card { suit, number });
        }
        Quiz { n, v }
    }
}

mod solver{
    pub fn partition<T>(a: &mut[T], p: usize, r: usize) -> usize 
    where T: Ord + Copy + Clone
    {
        let x = a[r];
        let mut i = p;
        for j in p..r {
            if a[j] <= x {
                a.swap(i, j);
                i += 1;
            }
        }
        a.swap(i, r);
        i
    }

    pub fn qsort<T>(a: &mut[T], p: usize, r: usize) 
    where T: Ord + Copy + Clone
    {
        dprintln!("qsort p:{}, r:{}", p, r);
        
        if p < r {
            let q = partition(a, p, r);
            qsort(a, p, q-1);
            qsort(a, q+1, r);
        }
    }
}

impl Quiz {
    fn solve(self) -> Answer {
        use solver::*;

        let mut res_v = self.v.clone();
        let len = res_v.len();

        qsort(&mut res_v[..], 0, len-1); 

        let is_stable = Quiz::is_stable(&self.v, &res_v[..]);


        Answer{ 
            is_stable: is_stable,
            v: res_v, 
        }
    }

    fn is_stable(org: &[Card], sorted: &[Card]) -> bool {
        for e2 in sorted.iter() {
            let num = e2.number;
            let fa1 = org.iter().filter(|x| x.number == num).map(|x| x.suit);
            let fa2 = sorted.iter().filter(|x| x.number == num).map(|x| x.suit);
            let mut zip = fa1.zip(fa2);
            if zip.any(|(e1,e2)| e1 != e2) {
                return false;
            }
        }
        return true;
    }
}

impl Answer {
    fn print(self) {
        if self.is_stable {
            println!("Stable");
        } else {
            println!("Not stable");
        }
        for e in self.v {
            println!("{}", e);
        }
    }
}

// =====================================================
// =
// =====================================================

//==================================================
// Stdin Reader
#[derive(Debug)]
pub enum Token {
    Word(String),
    LineBreak,
}

impl Token {
    pub fn is_word(&self) -> bool {
        match *self {
            Token::Word(ref _x) => true,
            _ => false,
        }
    }
}

#[derive(Debug)]
pub struct BufReadInput<R: BufRead> {
    input: R,
    tokens: VecDeque<Token>,
}

pub trait Input {
    fn read_next_word(&mut self) -> Option<Token>;

    fn parse_next<T>(&mut self) -> Option<T>
    where
        T: std::str::FromStr,
    {
        if let Some(Token::Word(str)) = self.read_next_word() {
            match str.parse() {
                Ok(x) => Some(x),
                _ => None,
            }
        } else {
            None
        }
    }

    fn parse_next_vec<T>(&mut self, size: usize) -> Option<Vec<T>>
    where
        T: std::str::FromStr,
    {
        let mut v = Vec::new();

        for _i in 0..size {
            if let Some(t) = self.parse_next() {
                v.push(t);
            } else {
                return None;
            }
        }

        Some(v)
    }

    fn parse_next_vec2<T>(&mut self, size2: usize, size1: usize) -> Option<Vec<Vec<T>>>
    where
        T: std::str::FromStr,
    {
        let mut v = Vec::new();

        for _i in 0..size2 {
            if let Some(t) = self.parse_next_vec(size1) {
                v.push(t);
            } else {
                return None;
            }
        }

        Some(v)
    }

    fn parse_all_remaining_into_vec<T>(&mut self) -> Vec<T>
    where
        T: std::str::FromStr,
    {
        let mut v = Vec::new();

        loop {
            match self.parse_next() {
                Some(x) => v.push(x),
                None => return v,
            }
        }
    }
}
impl<R: BufRead> BufReadInput<R> {
    pub fn new(input: R) -> Self {
        let tokens = VecDeque::new();

        BufReadInput { input, tokens }
    }
}

impl<R: BufRead> Input for BufReadInput<R> {
    fn read_next_word(&mut self) -> Option<Token> {
        loop {
            match self.tokens.pop_front() {
                None => {
                    // Read Input
                    let mut line = String::new();
                    let n = self.input.read_line(&mut line).expect("Read Error.");
                    if n == 0 {
                        return None;
                    }
                    let mut line_tokens = tokenaize(line);
                    self.tokens.append(&mut line_tokens);
                }
                Some(Token::LineBreak) => (),
                x => return x,
            }
        }
    }

}

//TODO: Make CaseIterator
// ex) 
//  let mut input: Input ...
//  let mut iter: CaseIterator<Case=Command> = input.rest_into_cases(|i|   
//    let cmd:String = i.parse_next().expect("Parse error cmd");
//    let num:u32    = i.parse_next().expect("Parse error num");
//
//    Command::new(cmd, num)
//  );
//  let case1 = iter.next();
//  let case2 = iter.next();
//  ...


fn tokenaize(str: String) -> VecDeque<Token> {
    let mut v = VecDeque::new();

    for w in str.split_whitespace() {
        v.push_back(Token::Word(w.to_string()));
    }
    v.push_back(Token::LineBreak);
    v
}

//==================================================
// Utility Functions
pub fn concat_vec_to_string<T>(v: &Vec<T>) -> String
where
    T: std::fmt::Display,
{
    let mut string = String::with_capacity(v.len() * 2);

    if let Some((h, t)) = v.split_first() {
        string = h.to_string();

        for obj in t {
            string.push(' ');
            string.push_str(&obj.to_string());
        }
    }

    return string;
}

//
pub fn concat_to_string<T>(v: &[T]) -> String
where
    T: std::fmt::Display,
{
    let mut ret = String::with_capacity(v.len() * 2);

    if let Some((h, t)) = v.split_first() {
        ret = h.to_string();

        for obj in t {
            ret.push(' ');
            ret.push_str(&obj.to_string());
        }
    }

    ret
}

//==================================================
// Debug Switch
static mut S_DEBUG_MODE: bool = false;
fn is_debug_mode() -> bool {
    unsafe { S_DEBUG_MODE }
}

fn set_debug_mode(mode: bool) {
    unsafe {
        S_DEBUG_MODE = mode;
    }
}

//==================================================
// Usage
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn macro_backward() {
        let mut v = Vec::new();
        for i in backward_ho!(5, 1) {
            v.push(i);
        }
        assert_eq!(vec![5, 4, 3, 2], v);
    }
}