Today Patrick waits for a visit from his friend Spongebob. To prepare for the visit, Patrick needs to buy some goodies in two stores located near his house. There is a d1 meter long road between his house and the first shop and a d2 meter long road between his house and the second shop. Also, there is a road of length d3 directly connecting these two shops to each other. Help Patrick calculate the minimum distance that he needs to walk in order to go to both shops and return to his house.  Patrick always starts at his house. He should visit both shops moving only along the three existing roads and return back to his house. He doesn't mind visiting the same shop or passing the same road multiple times. The only goal is to minimize the total distance traveled.

The first line of the input contains three integers d1, d2, d3 (1 ≤ d1, d2, d3 ≤ 108) — the lengths of the paths.    d1 is the length of the path connecting Patrick's house and the first shop;  d2 is the length of the path connecting Patrick's house and the second shop;  d3 is the length of the path connecting both shops.

Print the minimum distance that Patrick will have to walk in order to visit both shops and return to his house.

NoteThe first sample is shown on the picture in the problem statement. One of the optimal routes is: house  first shop  second shop  house.In the second sample one of the optimal routes is: house  first shop  house  second shop  house.

type Trio = (u32, u32, u32);
fn input_trio() -> Trio {
    let mut buf = String::new();
    std::io::stdin().read_line(&mut buf).unwrap();
    let buf: Vec<u32> = buf
        .trim()
        .split_whitespace()
        .map(|elem| elem.parse().unwrap())
        .collect();
    (buf[0], buf[1], buf[2])
}

fn main() {
    let (d1, d2, d3) = input_trio();
    print!(
        "{}",
        d1.min(d2) + d3.min(d1 + d2) + (d1.max(d2)).min(d1.min(d2) + d3)
    )
}

use std::cmp::min;
fn main() {
    let mut reader = scanner::TokenReader::new();
    let (a, b, c) = (
        reader.next::<u32>(),
        reader.next::<u32>(),
        reader.next::<u32>(),
    );

    println!(
        "{}",
        min(a + b + c, min((a + b) * 2, min((b + c) * 2, (a + c) * 2)))
    );
}

// ---------- Begin Scanner ----------
#[allow(dead_code)]
mod scanner {
    use std::fmt::Debug;
    use std::str::FromStr;

    pub struct TokenReader {
        reader: std::io::Stdin,
        tokens: Vec<String>,
        index: usize,
    }

    impl TokenReader {
        pub fn new() -> Self {
            Self {
                reader: std::io::stdin(),
                tokens: Vec::new(),
                index: 0,
            }
        }

        pub fn next<T>(&mut self) -> T
        where
            T: FromStr,
            T::Err: Debug,
        {
            if self.index >= self.tokens.len() {
                self.load_next_line();
            }
            self.index += 1;
            self.tokens[self.index - 1].parse().unwrap()
        }

        pub fn vector<T>(&mut self) -> Vec<T>
        where
            T: FromStr,
            T::Err: Debug,
        {
            if self.index >= self.tokens.len() {
                self.load_next_line();
            }
            self.index = self.tokens.len();
            self.tokens.iter().map(|tok| tok.parse().unwrap()).collect()
        }

        pub fn load_next_line(&mut self) {
            let mut line = String::new();
            self.reader.read_line(&mut line).unwrap();

            self.tokens = line.split_whitespace().map(String::from).collect();
            self.index = 0;
        }
    }
}
// ---------- End Scanner ----------

//spnauti-rust
#[allow(unused_macros)]
macro_rules! a {
    ($c: tt, $x: expr, $y: expr) => {{
        let b = $y; let a = &mut $x;
        if b $c *a { *a = b; true } else { false }
    }};
}
use std::str::*;
use std::fmt::Debug;
struct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }
#[allow(dead_code)]
impl<'a> WordReader<'a> {
    fn new<T: std::io::Read>(b: &mut String, mut r: T) -> WordReader {
        b.clear();
        r.read_to_string(b).unwrap();
        WordReader { it: b.split_ascii_whitespace() }
    }
    fn from_stdin(b: &mut String) -> WordReader {
        WordReader::new(b, std::io::stdin())
    }
    fn sl(&mut self) ->  &str { self.it.next().unwrap() }
    fn bs(&mut self) -> &[u8] { self.sl().as_bytes()    }
    fn s(&mut self) -> String { String::from(self.sl()) }
    fn i(&mut self) ->    i32 { self.p()                }
    fn p<T: FromStr>(&mut self) -> T where T::Err: Debug {
        self.sl().parse::<T>().unwrap()
    }
    fn vp<T: FromStr>(&mut self, n: usize) -> Vec<T> where T::Err: Debug {
        (0..n).map(|_| self.p()).collect()
    }
}

fn main() {
    let mut buffer = String::new();
    let mut input = WordReader::from_stdin(&mut buffer);

    let a = input.i();
    let b = input.i();
    let c = input.i();
    let sol = a.min(b + c) + b.min(a + c) + c.min(a + b);
    println!("{}", sol);
}

#[allow(unused_imports)]
use std::cmp::{max,min};

macro_rules! readln {
    () => {{
        use std::io;

        let mut buf = String::new();
        io::stdin().read_line(&mut buf).unwrap();
        buf.trim().to_string()
    }};
    ( $t:ty ) => {{
        let input = readln!();
        input.parse::<$t>().unwrap()
    }};
    ( $( $t:ty ),+ ) => {{
        let input = readln!();
        let mut input = input.split_whitespace();
        (
            $(
                input.next().unwrap().parse::<$t>().unwrap(),
            )+
        )
    }}
}

macro_rules! readvec {
    ( $t:ty ) => {{
        let input = readln!();
        let mut input = input.split_whitespace();
        let mut result = Vec::new();
        for elem in input {
            result.push(elem.parse::<$t>().unwrap());
        }
        result
    }}
}

fn main() {
    let a = readvec!(i32);
    println!("{}",
    min(min(a[0]+a[2]+a[1],
    a[0]*2+a[1]*2),
    min(a[0]*2+a[2]*2,
    a[1]*2+a[2]*2)));
}

// {{{ by shik

use std::io;

#[allow(dead_code)]
fn gets() -> String {
    let mut s = String::new();
    io::stdin().read_line(&mut s).unwrap();
    s.trim().to_string()
}

#[allow(unused_macros)]
macro_rules! R {
    ( $ty:ty, ... ) => {
        gets().split_whitespace().map(|x| x.parse::<$ty>().unwrap()).collect::<Vec<_>>()
    };
    ( $($ty:ty),* ) => {{
        let line = gets();
        let mut it = line.split_whitespace();
        ( $(it.next().unwrap().parse::<$ty>().unwrap(),)* )
    }}
}

#[allow(unused_macros)]
macro_rules! W {
    ( $x:expr ) => {{
        println!("{}", $x);
    }};
    ( $x:expr, $($xs:expr),* ) => {{
        print!("{} ", $x);
        W!($($xs),*);
    }}
}

#[allow(unused_macros)]
macro_rules! join {
    ($x:expr, $($xs:expr),*; $sep:expr) => { concat!($x, $($sep, $xs),*) }
}

#[allow(unused_macros)]
macro_rules! dump {
    ($($x:expr),*) => {
        eprintln!(join!($(concat!(stringify!($x), " = {:?}")),*; ", "), $($x),*);
    }
}

// }}}

use std::cmp;

fn main() {
    let (a, b, c) = R!(u32, u32, u32);
    let ans = cmp::min(cmp::min(2*(a+b), 2*(b+c)), cmp::min(2*(a+c), a+b+c));
    W!(ans);
}

#[allow(unused_imports)]
use std::io;
use std::cmp::{min, max};
pub struct Scanner<B> {
    reader: B,
    buffer: Vec<String>,
}

impl<B: io::BufRead> Scanner<B> {
    pub fn new(reader: B) -> Scanner<B> {
        Scanner {
            reader: reader,
            buffer: Vec::new(),
        }
    }

    /// Use "turbofish" syntax next::<T>() to select data type of next token.
    pub fn next<T: ::std::str::FromStr>(&mut self) -> T
    where
        T::Err: ::std::fmt::Debug,
    {
        if let Some(front) = self.buffer.pop() {
            front.parse::<T>().expect(&front)
        } else {
            let mut input = String::new();
            self.reader.read_line(&mut input).expect("Line not read");
            self.buffer = input.split_whitespace().rev().map(String::from).collect();
            self.next()
        }
    }

    pub fn next_vec<T: ::std::str::FromStr>(&mut self, len: usize) -> Vec<T>
    where
        T::Err: ::std::fmt::Debug,
    {
        (0..len).map(|_| self.next::<T>()).collect::<Vec<T>>()
    }
}

fn main1() {
    let stdin = io::stdin();
    let mut input = Scanner::new(stdin.lock());
    let d = input.next_vec::<i64>(3);
    println!("{}", min(d[0] + d[1] + d[2], min(2 * (d[0] + d[1]), 2 * min(d[0], d[1]) + 2 * d[2])));
}

fn main() {
    std::thread::Builder::new().stack_size(50 << 20)
        .spawn(main1).unwrap().join().unwrap();
}

struct Scan {
    buffer: std::collections::VecDeque<String>
}

impl Scan {
    fn new() -> Scan {
        Scan { buffer: std::collections::VecDeque::new() }
    }

    fn next<T: std::str::FromStr>(&mut self)-> T {
        loop {
            if let Some(token) = self.buffer.pop_front() {
                break token.parse::<T>().ok().unwrap();
            }
            let mut line = String::new();
            std::io::stdin().read_line(&mut line).expect("Fail to read");
            self.buffer = line.split_whitespace().map(String::from).collect();
        }
    }

}

fn _main() {
    let mut scan = Scan::new();
    let d1: usize = scan.next();
    let d2: usize = scan.next();
    let d3: usize = scan.next();
    let result = (d1+d2+d3).min((d1+d2)*2).min(d1*2+d3*2).min(d3*2+d2*2);
    println!("{}", result);
}

fn main() {
    std::thread::Builder::new()
        .stack_size(1<<23).spawn(_main).unwrap().join().unwrap();
}

#![allow(unused_imports)]

use std::mem;
use std::io;
use std::string;
use std::cmp::*;
use std::collections::*;

fn load() -> Vec<i64> {
    let mut line = String::new();
    io::stdin().read_line(&mut line).expect("Failed to read line");
    let vec: Vec<&str> = line.split(" ").collect();
    let mut data: Vec<i64> = Vec::new();
    for i in vec {
        let el: i64 = i.trim().parse().unwrap();
        data.push(el);
    }
    data
}

fn main() {
    let s = load();
    let (a, b, c) = (s[0], s[1], s[2]);
    let mx = max(a, max(b, c));
    let sum = a + b + c;
    println!("{}", min(sum, 2 * (sum - mx)));
}
// min, max
// HashSet, insert, contains
// HashMap, insert, get
// Vec, len, sort
// primitive retype: i as f64

#[allow(unused_imports)]
use std::io;
use std::cmp::{min, max};
pub struct Scanner<B> {
    reader: B,
    buffer: Vec<String>,
}

impl<B: io::BufRead> Scanner<B> {
    pub fn new(reader: B) -> Scanner<B> {
        Scanner {
            reader: reader,
            buffer: Vec::new(),
        }
    }

    /// Use "turbofish" syntax next::<T>() to select data type of next token.
    pub fn next<T: ::std::str::FromStr>(&mut self) -> T
    where
        T::Err: ::std::fmt::Debug,
    {
        if let Some(front) = self.buffer.pop() {
            front.parse::<T>().expect(&front)
        } else {
            let mut input = String::new();
            self.reader.read_line(&mut input).expect("Line not read");
            self.buffer = input.split_whitespace().rev().map(String::from).collect();
            self.next()
        }
    }

    pub fn next_vec<T: ::std::str::FromStr>(&mut self, len: usize) -> Vec<T>
    where
        T::Err: ::std::fmt::Debug,
    {
        (0..len).map(|_| self.next::<T>()).collect::<Vec<T>>()
    }
}

fn main1() {
    let stdin = io::stdin();
    let mut input = Scanner::new(stdin.lock());
    let d = input.next_vec::<i64>(3);
    println!("{}", min(d[0] + d[1] + d[2], 2 * (d[0] + d[1])))
}

fn main() {
    std::thread::Builder::new().stack_size(50 << 20)
        .spawn(main1).unwrap().join().unwrap();
}

struct Scan {
    buffer: std::collections::VecDeque<String>
}

impl Scan {
    fn new() -> Scan {
        Scan { buffer: std::collections::VecDeque::new() }
    }

    fn next<T: std::str::FromStr>(&mut self)-> T {
        loop {
            if let Some(token) = self.buffer.pop_front() {
                break token.parse::<T>().ok().unwrap();
            }
            let mut line = String::new();
            std::io::stdin().read_line(&mut line).expect("Fail to read");
            self.buffer = line.split_whitespace().map(String::from).collect();
        }
    }

    fn next_n<T: std::str::FromStr>(&mut self, n: usize) -> Vec<T> {
        (0..n).map(|_| self.next::<T>()).collect()
    }

}

fn _main() {
    let mut scan = Scan::new();
    let d1: usize = scan.next();
    let d2: usize = scan.next();
    let d3: usize = scan.next();
    let result = (d1+d2+d3).min((d1+d2)*2).min(d1*2+d3*2);
    println!("{}", result);
}

fn main() {
    std::thread::Builder::new()
        .stack_size(1<<23).spawn(_main).unwrap().join().unwrap();
}


You are given set of n points in 5-dimensional space. The points are labeled from 1 to n. No two points coincide.We will call point a bad if there are different points b and c, not equal to a, from the given set such that angle between vectors  and  is acute (i.e. strictly less than ). Otherwise, the point is called good.The angle between vectors  and  in 5-dimensional space is defined as , where  is the scalar product and  is length of .Given the list of points, print the indices of the good points in ascending order.

The first line of input contains a single integer n (1 ≤ n ≤ 103) — the number of points. The next n lines of input contain five integers ai, bi, ci, di, ei (|ai|, |bi|, |ci|, |di|, |ei| ≤ 103)  — the coordinates of the i-th point. All points are distinct.

First, print a single integer k — the number of good points. Then, print k integers, each on their own line — the indices of the good points in ascending order.

NoteIn the first sample, the first point forms exactly a  angle with all other pairs of points, so it is good.In the second sample, along the cd plane, we can see the points look as follows:We can see that all angles here are acute, so no points are good.

use std::io;

fn main() {
    let n: usize = {
        let mut input = String::new();
        io::stdin().read_line(&mut input).unwrap();
        input.trim().parse().unwrap()
    };

    let mut points = Vec::with_capacity(n);

    for _ in 0..n {
        let point: Vec<i32> = {
            let mut input = String::new();
            io::stdin().read_line(&mut input).unwrap();
            input.split_whitespace().map(|k| k.parse().unwrap()).collect()
        };
        points.push(point);
    }

    let mut is_good = vec![true; n];

    let test = |a: usize, b: usize, c: usize| {
        let mut res = 0i32;
        for i in 0..5 {
            res += (points[b][i] - points[a][i]) * (points[c][i] - points[a][i]);
        }
        res <= 0
    };

    for i in 0..n {
        if !is_good[i] {
            continue;
        }
        for j in 0..n {
            if j == i {
                continue;
            }
            for k in 0..n {
                if k == j || k == i {
                    continue;
                }
                let good = test(i, j, k);
                if good {
                    is_good[j] = false;
                    is_good[k] = false;
                } else {
                    is_good[i] = false;
                }
            }
        }
    }

    println!("{}", is_good.iter().filter(|&&b| b).count());

    for i in 0..n {
        if is_good[i] {
            println!("{}", i + 1);
        }
    }
}

use std::io::{ self, BufRead };
use std::collections::*;

macro_rules! scan_line {
    () => ({
        let stdin = io::stdin();
        let mut handle = stdin.lock();
        let mut buffer = String::new();
        handle.read_line(&mut buffer)
            .expect("scan_line: failed at `handle.read_line`.");
        buffer
    });
    ( $($t:ty)+ ) => ({
        let stdin = io::stdin();
        let mut handle = stdin.lock();
        let mut buffer = String::new();
        handle.read_line(&mut buffer)
            .expect("scan_line: failed at `handle.read_line`.");
        let mut chunks = buffer.split_whitespace();

        ($(
            {
                chunks.next()
                    .expect("scan_line: failed at `next`, # of space separated strings not equal to requested #")
                .parse::<$t>()
                    .expect("scan_line: failed at `parse::<$t>`.")
            },
        )+)
    })
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
struct Point {
    x1: i64,
    x2: i64,
    x3: i64,
    x4: i64,
    x5: i64
}

impl Point {
    fn vect(&self, a : &Point) -> Point {
        Point {
            x1: a.x1 - self.x1,
            x2: a.x2 - self.x2,
            x3: a.x3 - self.x3,
            x4: a.x4 - self.x4,
            x5: a.x5 - self.x5
        }
    }

    fn product(a : &Point, b : &Point) -> i64 {
        a.x1*b.x1 + a.x2*b.x2 + a.x3*b.x3 + a.x4*b.x4 + a.x5*b.x5
    }

    fn length(&self) -> f64 {
        (Point::product(self, self) as f64).sqrt()
    }

    fn angle(&self, a : &Point, b : &Point) -> f64 {
        let vect1 = self.vect(a);
        let vect2 = self.vect(b);
        let n = Point::product(&vect1, &vect2) as f64;
        let d = vect1.length() * vect2.length();
        (n / d).acos()
    }

    fn sq_dist(a : &Point, b : &Point) -> i64 {
        (a.x1 - b.x1)*(a.x1 - b.x1)
            + (a.x2 - b.x2)*(a.x2 - b.x2)
            + (a.x3 - b.x3)*(a.x3 - b.x3)
            + (a.x4 - b.x4)*(a.x4 - b.x4)
            + (a.x5 - b.x5)*(a.x5 - b.x5)
    }
}

fn main() {
    let (n,) = scan_line!(usize);
    let mut points = vec![];
    let mut kind = vec![];
    let ninety = std::f64::consts::PI / 2.0;

    for i in 0..n {
        let (a, b, c, d, e) = scan_line!(i64 i64 i64 i64 i64);
        points.push(Point {
            x1: a, x2: b, x3: c, x4: d, x5: e
        });
        kind.push(true);
    }

    for i in 0..n {
        let test = points[i];
        let init = (i+1) % n;
        let mut constraint1 = points[init];
        let mut constraint2 = points[init];
        for j in 0..n {
            if i == j || init == j { continue; }

            let ang1 = test.angle(&constraint1, &points[j]);
            let ang2 = test.angle(&constraint2, &points[j]);

            if ang1 < ninety || ang2 < ninety {
                kind[i] = false;
                break;
            } else {
                let dist1 = Point::sq_dist(&constraint1, &points[j]);
                let dist2 = Point::sq_dist(&constraint2, &points[j]);
                if dist1 < dist2 {
                    constraint1 = points[j];
                } else {
                    constraint2 = points[j];
                }
            }
        }
    }

    let good_count = kind.iter().map(|&x| if x { 1 } else { 0 }).fold(0, |acc, x| acc + x);
    println!("{}", good_count);
    if good_count > 0 {
        for i in 0..n {
            if kind[i] {
                println!("{}", i+1);
            }
        }
    }
}

//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 より
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};
    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };
    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };
    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };
    ($iter:expr, bytes) => {
        read_value!($iter, String).bytes().collect::<Vec<u8>>()
    };
    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };
    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

//

fn run() {
    input! {
        n: usize,
        p: [[i64; 5]; n],
    }
    if n > 100 {
        println!("0");
        return;
    }
    let mut ans = vec![];
    for i in 0..n {
        let mut q = p.clone();
        let p = q.remove(i);
        for q in q.iter_mut() {
            for (q, p) in q.iter_mut().zip(p.iter()) {
                *q -= *p;
            }
        }
        let mut ok = true;
        for (i, a) in q.iter().enumerate() {
            for b in q.iter().take(i) {
                let mut sum = 0;
                for (a, b) in a.iter().zip(b.iter()) {
                    sum += *a * *b;
                }
                if sum > 0 {
                    ok = false;
                }
            }
        }
        if ok {
            ans.push(i + 1);
        }
    }
    println!("{}", ans.len());
    for (i, a) in ans.iter().enumerate() {
        if i > 0 {
            print!(" ");
        }
        print!("{}", a);
    }
    println!();
}

fn main() {
    run();
}

//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 より
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};
    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };
    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };
    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };
    ($iter:expr, bytes) => {
        read_value!($iter, String).bytes().collect::<Vec<u8>>()
    };
    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };
    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

//

fn run() {
    input! {
        n: usize,
        p: [[i64; 5]; n],
    }
    if n > 10 {
        println!("0");
        return;
    }
    let mut ans = vec![];
    for i in 0..n {
        let mut q = p.clone();
        let p = q.remove(i);
        for q in q.iter_mut() {
            for (q, p) in q.iter_mut().zip(p.iter()) {
                *q -= *p;
            }
        }
        let mut ok = true;
        for (i, a) in q.iter().enumerate() {
            for b in q.iter().take(i) {
                let mut sum = 0;
                for (a, b) in a.iter().zip(b.iter()) {
                    sum += *a * *b;
                }
                if sum > 0 {
                    ok = false;
                }
            }
        }
        if ok {
            ans.push(i + 1);
        }
    }
    println!("{}", ans.len());
    for (i, a) in ans.iter().enumerate() {
        if i > 0 {
            print!(" ");
        }
        print!("{}", a);
    }
    println!();
}

fn main() {
    run();
}


One day, Hongcow goes to the store and sees a brand new deck of n special cards. Each individual card is either red or blue. He decides he wants to buy them immediately. To do this, he needs to play a game with the owner of the store.This game takes some number of turns to complete. On a turn, Hongcow may do one of two things:   Collect tokens. Hongcow collects 1 red token and 1 blue token by choosing this option (thus, 2 tokens in total per one operation).  Buy a card. Hongcow chooses some card and spends tokens to purchase it as specified below. The i-th card requires ri red resources and bi blue resources. Suppose Hongcow currently has A red cards and B blue cards. Then, the i-th card will require Hongcow to spend max(ri - A, 0) red tokens, and max(bi - B, 0) blue tokens. Note, only tokens disappear, but the cards stay with Hongcow forever. Each card can be bought only once.Given a description of the cards and their costs determine the minimum number of turns Hongcow needs to purchase all cards.

The first line of input will contain a single integer n (1 ≤ n ≤ 16). The next n lines of input will contain three tokens ci, ri and bi. ci will be 'R' or 'B', denoting the color of the card as red or blue. ri will be an integer denoting the amount of red resources required to obtain the card, and bi will be an integer denoting the amount of blue resources required to obtain the card (0 ≤ ri, bi ≤ 107).

Output a single integer, denoting the minimum number of turns needed to acquire all the cards.

NoteFor the first sample, Hongcow's four moves are as follows:   Collect tokens  Buy card 1  Buy card 2  Buy card 3  Note, at the fourth step, Hongcow is able to buy card 3 because Hongcow already has one red and one blue card, so we don't need to collect tokens.For the second sample, one optimal strategy is as follows:   Collect tokens  Collect tokens  Buy card 2  Collect tokens  Buy card 3  Buy card 1  At the fifth step, even though Hongcow has a red token, Hongcow doesn't actually need to spend it, since Hongcow has a red card already.

//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 より
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};
    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };
    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };
    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };
    ($iter:expr, bytes) => {
        read_value!($iter, String).bytes().collect::<Vec<u8>>()
    };
    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };
    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

//

use std::cmp::*;

fn run() {
    input! {
        n: usize,
        p: [(chars, i32, i32); n],
    }
    let p = p
        .into_iter()
        .map(|p| ((p.0[0] == 'B') as usize, p.1, p.2))
        .collect::<Vec<_>>();
    let mut sum = vec![([0, 0], 0, 0)];
    for &(x, y, z) in p.iter() {
        for i in 0..sum.len() {
            let (mut a, mut b, mut c) = sum[i];
            a[x] += 1;
            b += y;
            c += z;
            sum.push((a, b, c));
        }
    }
    let mut now = std::collections::BTreeMap::new();
    now.insert((0, 0, 0), 0);
    for _ in 0..n {
        let mut next = std::collections::BTreeMap::new();
        for ((bit, rem_a, rem_b), v) in now {
            assert!(rem_a == 0 || rem_b == 0);
            let (cnt, _, _) = sum[bit];
            for (i, &(_, a, b)) in p.iter().enumerate() {
                if bit >> i & 1 == 1 {
                    continue;
                }
                let p = max(0, a - cnt[0]);
                let q = max(0, b - cnt[1]);
                let add = max(0, max(p - rem_a, q - rem_b));
                let v = v + add;
                let po = next.entry((bit | (1 << i), rem_a + add - p, rem_b + add - q)).or_insert(v);
                *po = std::cmp::min(*po, v);
            }
        }
        now = next;
    }
    let ans = now.into_iter().map(|(_, v)| v).min().unwrap() + n as i32;
    println!("{}", ans);
}

fn main() {
    run();
}

//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 より
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};
    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };
    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };
    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };
    ($iter:expr, bytes) => {
        read_value!($iter, String).bytes().collect::<Vec<u8>>()
    };
    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };
    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

//

// ---------- begin chmin, chmax ----------
trait ChangeMinMax {
    fn chmin(&mut self, x: Self) -> bool;
    fn chmax(&mut self, x: Self) -> bool;
}

impl<T: PartialOrd> ChangeMinMax for T {
    fn chmin(&mut self, x: Self) -> bool {
        if *self > x {
            *self = x;
            true
        } else {
            false
        }
    }
    fn chmax(&mut self, x: Self) -> bool {
        if *self < x {
            *self = x;
            true
        } else {
            false
        }
    }
}
// ---------- end chmin, chmax ----------

use std::cmp::*;

fn run() {
    input! {
        n: usize,
        p: [(chars, [i32; 2]); n],
    }
    let mut p = p
        .into_iter()
        .map(|p| ((p.0[0] == 'B') as usize, [p.1[0], p.1[1]]))
        .collect::<Vec<_>>();
    let mut need = [0; 2];
    for p in p.iter_mut() {
        let n = n as i32;
        for (need, v) in need.iter_mut().zip(p.1.iter_mut()) {
            *need += max(0, *v - n);
            v.chmin(n);
        }
    }
    let mut sum = vec![[0i32; 2]];
    for &(x, _) in p.iter() {
        for i in 0..sum.len() {
            let mut a = sum[i];
            a[x] += 1;
            sum.push(a);
        }
    }
    let inf = std::i32::MAX / 2;
    let mut dp = vec![vec![vec![inf; 1 << n]; n.pow(2) + 1]; 2];
    let abs = (need[1] - need[0]).abs() as usize;
    dp[(need[0] >= need[1]) as usize][min(n * n, abs)][0] = 0;
    for bit in 0..(1 << n) {
        let sum = sum[bit];
        for rem in 0..=n.pow(2) {
            for i in 0..2 {
                let v = dp[i][rem][bit];
                if v == inf {
                    continue;
                }
                for (j, &(_, p)) in p.iter().enumerate() {
                    let k = bit | (1 << j);
                    if k == bit {
                        continue;
                    }
                    let p = [max(0, p[0] - sum[0]), max(0, p[1] - sum[1])];
                    if rem as i32 + p[i ^ 1] >= p[i] {
                        let x = rem as i32 + p[i ^ 1] - p[i];
                        let v = v + p[i ^ 1];
                        dp[i][min(x as usize, n.pow(2))][k].chmin(v);
                    } else {
                        let x = p[i] - rem as i32 - p[i ^ 1];
                        let v = v + p[i] - rem as i32;
                        dp[i ^ 1][min(x as usize, n.pow(2))][k].chmin(v);
                    }
                }
            }
        }
    }
    let add = need.iter().copied().max().unwrap() + n as i32;
    let ans = add + dp.into_iter().flatten().map(|dp| dp[(1 << n) - 1]).min().unwrap();
    println!("{}", ans);
}

fn main() {
    run();
}

//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 より
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};
    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };
    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };
    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };
    ($iter:expr, bytes) => {
        read_value!($iter, String).bytes().collect::<Vec<u8>>()
    };
    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };
    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

//

// ---------- begin chmin, chmax ----------
trait ChangeMinMax {
    fn chmin(&mut self, x: Self) -> bool;
    fn chmax(&mut self, x: Self) -> bool;
}

impl<T: PartialOrd> ChangeMinMax for T {
    fn chmin(&mut self, x: Self) -> bool {
        if *self > x {
            *self = x;
            true
        } else {
            false
        }
    }
    fn chmax(&mut self, x: Self) -> bool {
        if *self < x {
            *self = x;
            true
        } else {
            false
        }
    }
}
// ---------- end chmin, chmax ----------

use std::cmp::*;

fn run() {
    input! {
        n: usize,
        p: [(chars, [i32; 2]); n],
    }
    let mut p = p
        .into_iter()
        .map(|p| ((p.0[0] == 'B') as usize, [p.1[0], p.1[1]]))
        .collect::<Vec<_>>();
    let mut need = [0; 2];
    for p in p.iter_mut() {
        let n = n as i32;
        for (need, v) in need.iter_mut().zip(p.1.iter_mut()) {
            *need += max(0, *v - n + 1);
            v.chmin(n - 1);
        }
    }
    let mut sum = vec![[0i32; 2]];
    for &(x, _) in p.iter() {
        for i in 0..sum.len() {
            let mut a = sum[i];
            a[x] += 1;
            sum.push(a);
        }
    }
    let inf = std::i32::MAX / 2;
    let sup = (n - 1) * (n - 1);
    let mut dp = vec![vec![vec![inf; 1 << n]; sup + 1]; 2];
    let abs = (need[1] - need[0]).abs() as usize;
    dp[(need[0] >= need[1]) as usize][min(sup, abs)][0] = 0;
    for bit in 0..(1 << n) {
        let sum = sum[bit];
        for rem in 0..=sup {
            for i in 0..2 {
                let v = dp[i][rem][bit];
                if v == inf {
                    continue;
                }
                for (j, &(_, p)) in p.iter().enumerate() {
                    let k = bit | (1 << j);
                    if k == bit {
                        continue;
                    }
                    let p = [max(0, p[0] - sum[0]), max(0, p[1] - sum[1])];
                    if rem as i32 + p[i ^ 1] >= p[i] {
                        let x = rem as i32 + p[i ^ 1] - p[i];
                        let v = v + p[i ^ 1];
                        dp[i][min(x as usize, sup)][k].chmin(v);
                    } else {
                        let x = p[i] - rem as i32 - p[i ^ 1];
                        let v = v + p[i] - rem as i32;
                        dp[i ^ 1][min(x as usize, sup)][k].chmin(v);
                    }
                }
            }
        }
    }
    let add = need.iter().copied().max().unwrap() + n as i32;
    let ans = add + dp.into_iter().flatten().map(|dp| dp[(1 << n) - 1]).min().unwrap();
    println!("{}", ans);
}

fn main() {
    run();
}

use std::io::{self, Stdin};
use std::str::{self, FromStr};
use std::error::Error;
use std::cmp::*;
use std::thread;
const INF: i64 = 1i64 << 60;
fn exec() {
    let mut sc = Scanner::new();
    let n: usize = sc.ne();
    let mut cards = Vec::new();
    for _ in 0..n {
        let c: String = sc.ne();
        let r: i64 = sc.ne();
        let b: i64 = sc.ne();
        let is_r = c == "R";
        cards.push((is_r, r, b));
    }
    let sn = 1 << n;
    let rn = n * (n + 1) / 2;
    let mut dp = vec![vec![-INF; rn]; sn];
    dp[0][0] = 0;
    for s in 0..sn {
        let mut rnum = 0;
        let mut bnum = 0;
        for i in 0..n {
            if (s >> i) & 1 == 0 {
                continue;
            }
            if cards[i].0 {
                rnum += 1;
            } else {
                bnum += 1;
            }
        }
        for i in 0..rn {
            // println!("{:b}, i: {}, {}", s, i, dp[s][i]);
            if dp[s][i] == -INF {
                continue;
            }
            for j in 0..n {
                if (s >> j) & 1 == 1 {
                    continue;
                }
                let ns = s | (1 << j);
                let ni = min(rnum, cards[j].1) as usize + i;
                dp[ns][ni] = max(dp[ns][ni], dp[s][i] + min(bnum, cards[j].2));
            }
        }
    }
    let rsum = cards.iter().fold(0, |acc, &t| acc + t.1);
    let bsum = cards.iter().fold(0, |acc, &t| acc + t.2);
    let mut ans = INF;
    for i in 0..rn {
        ans = min(ans, max(rsum - i as i64, bsum - dp[sn - 1][i]));
        // println!("{}", ans);
    }
    println!("{}", ans + n as i64);
}

const DEFAULT_STACK: usize = 16 * 1024 * 1024;
fn main() {
    let builder = thread::Builder::new();
    let th = builder.stack_size(DEFAULT_STACK);
    let handle = th.spawn(|| { exec(); }).unwrap();
    let _ = handle.join();
}

#[allow(dead_code)]
struct Scanner {
    stdin: Stdin,
    id: usize,
    buf: Vec<u8>,
}

#[allow(dead_code)]
impl Scanner {
    fn new() -> Scanner {
        Scanner {
            stdin: io::stdin(),
            id: 0,
            buf: Vec::new(),
        }
    }
    fn next_line(&mut self) -> Option<String> {
        let mut res = String::new();
        match self.stdin.read_line(&mut res) {
            Ok(0) => return None,
            Ok(_) => Some(res),
            Err(why) => panic!("error in read_line: {}", why.description()),
        }
    }
    fn next<T: FromStr>(&mut self) -> Option<T> {
        while self.buf.len() == 0 {
            self.buf = match self.next_line() {
                Some(r) => {
                    self.id = 0;
                    r.trim().as_bytes().to_owned()
                }
                None => return None,
            };
        }
        let l = self.id;
        assert!(self.buf[l] != b' ');
        let n = self.buf.len();
        let mut r = l;
        while r < n && self.buf[r] != b' ' {
            r += 1;
        }
        let res = match str::from_utf8(&self.buf[l..r]).ok().unwrap().parse::<T>() {
            Ok(s) => Some(s),
            Err(_) => {
                panic!("parse error: {:?}",
                       str::from_utf8(&self.buf[l..r]).unwrap())
            }
        };
        while r < n && self.buf[r] == b' ' {
            r += 1;
        }
        if r == n {
            self.buf.clear();
        } else {
            self.id = r;
        }
        res
    }
    fn ne<T: FromStr>(&mut self) -> T {
        self.next::<T>().unwrap()
    }
}

//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 より
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};
    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };
    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };
    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };
    ($iter:expr, bytes) => {
        read_value!($iter, String).bytes().collect::<Vec<u8>>()
    };
    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };
    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

//

use std::cmp::*;

fn run() {
    input! {
        n: usize,
        p: [(chars, i32, i32); n],
    }
    let p = p
        .into_iter()
        .map(|p| ((p.0[0] == 'B') as usize, p.1, p.2))
        .collect::<Vec<_>>();
    let mut sum = vec![([0, 0], 0, 0)];
    for &(x, y, z) in p.iter() {
        for i in 0..sum.len() {
            let (mut a, mut b, mut c) = sum[i];
            a[x] += 1;
            b += y;
            c += z;
            sum.push((a, b, c));
        }
    }
    let inf = std::i32::MAX / 2;
    let mut now = vec![(0, 0, 0, 0)];// bit, Rのヒット、Bのヒット、最小値
    for _ in 0..n {
        let mut next = std::collections::BTreeMap::new();
        for (bit, x, y, v) in now {
//            println!("{} {} {} {}", bit, x, y, v);
            let rem_a = v - sum[bit].1 + x;
            let rem_b = v - sum[bit].2 + y;
            for (i, &(_, a, b)) in p.iter().enumerate() {
                if bit >> i & 1 == 1 {
                    continue;
                }
                let mut x = x;
                let mut y = y;
                let mut add = 0;
                let mut p = max(0, a - rem_a);
                if p > 0 {
                    x += std::cmp::min(p, sum[bit].0[0]);
                    p -= sum[bit].0[0];
                }
                add = max(add, p);
                let mut p = max(0, b - rem_b);
                if p > 0 {
                    y += std::cmp::min(p, sum[bit].0[1]);
                    p -= sum[bit].0[1];
                }
                add = max(add, p);
                let v = v + add;
                let po = next.entry((bit | (1 << i), x, y)).or_insert(v);
                *po = std::cmp::min(*po, v);
            }
        }
        let mut a = vec![];
        for ((bit, x, y), v) in next {
            a.push((bit, x, y, v));
        }
        now = a;
    }
    let ans = now.into_iter().map(|p| p.3).min().unwrap() + n as i32;
    println!("{}", ans);
}

fn main() {
    run();
}

//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 より
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};
    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };
    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };
    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };
    ($iter:expr, bytes) => {
        read_value!($iter, String).bytes().collect::<Vec<u8>>()
    };
    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };
    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

//

// ---------- begin chmin, chmax ----------
trait ChangeMinMax {
    fn chmin(&mut self, x: Self) -> bool;
    fn chmax(&mut self, x: Self) -> bool;
}

impl<T: PartialOrd> ChangeMinMax for T {
    fn chmin(&mut self, x: Self) -> bool {
        if *self > x {
            *self = x;
            true
        } else {
            false
        }
    }
    fn chmax(&mut self, x: Self) -> bool {
        if *self < x {
            *self = x;
            true
        } else {
            false
        }
    }
}
// ---------- end chmin, chmax ----------

use std::cmp::*;

fn run() {
    input! {
        n: usize,
        p: [(chars, i32, i32); n],
    }
    let mut p = p
        .into_iter()
        .map(|p| ((p.0[0] == 'B') as usize, p.1, p.2))
        .collect::<Vec<_>>();
    let mut add = 0;
    for p in p.iter_mut() {
        let n = n as i32;
        let mut v = 0;
        v.chmax(p.1 - n);
        v.chmax(p.2 - n);
        add += v;
        p.1.chmin(n);
        p.2.chmin(n);
    }
    let mut sum = vec![[0i32; 2]];
    for &(x, _, _) in p.iter() {
        for i in 0..sum.len() {
            let mut a = sum[i];
            a[x] += 1;
            sum.push(a);
        }
    }
    let inf = std::i32::MAX / 2;
    let mut dp_a = std::collections::BTreeMap::new();
    let mut dp_b = std::collections::BTreeMap::new();
    dp_a.insert((0, 0), 0);
    dp_b.insert((0, 0), 0);
    for _ in 0..n {
        let mut next_a = std::collections::BTreeMap::new();
        let mut next_b = std::collections::BTreeMap::new();
        for ((bit, rem), v) in dp_a {
            let sum = sum[bit];
            for (i, &(_, a, b)) in p.iter().enumerate() {
                if bit >> i & 1 == 1 {
                    continue;
                }
                let k = bit | (1 << i);
                let a = max(0, a - sum[0]);
                let b = max(0, b - sum[1]);
                if rem + b >= a {
                    let x = rem + b - a;
                    let po = next_a.entry((k, x)).or_insert(inf);
                    po.chmin(v + b);
                } else {
                    let x = a - (rem + b);
                    let po = next_b.entry((k, x)).or_insert(inf);
                    po.chmin(v + b + x);
                }
            }
        }
        for ((bit, rem), v) in dp_b {
            let sum = sum[bit];
            for (i, &(_, a, b)) in p.iter().enumerate() {
                if bit >> i & 1 == 1 {
                    continue;
                }
                let k = bit | (1 << i);
                let a = max(0, a - sum[0]);
                let b = max(0, b - sum[1]);
                if rem + a >= b {
                    let x = rem + a - b;
                    let po = next_b.entry((k, x)).or_insert(inf);
                    po.chmin(v + a);
                } else {
                    let x = b - (rem + a);
                    let po = next_a.entry((k, x)).or_insert(inf);
                    po.chmin(v + a + x);
                }
            }
        }
        dp_a = next_a;
        dp_b = next_b;
    }
    let ans = add + dp_a.values().chain(dp_b.values()).cloned().min().unwrap() + n as i32;
    println!("{}", ans);
}

fn main() {
    run();
}

//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 より
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};
    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };
    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };
    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };
    ($iter:expr, bytes) => {
        read_value!($iter, String).bytes().collect::<Vec<u8>>()
    };
    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };
    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

//

use std::cmp::*;

fn run() {
    input! {
        n: usize,
        p: [(chars, i32, i32); n],
    }
    let p = p
        .into_iter()
        .map(|p| ((p.0[0] == 'B') as usize, p.1, p.2))
        .collect::<Vec<_>>();
    let mut sum = vec![([0, 0], 0, 0)];
    for &(x, y, z) in p.iter() {
        for i in 0..sum.len() {
            let (mut a, mut b, mut c) = sum[i];
            a[x] += 1;
            b += y;
            c += z;
            sum.push((a, b, c));
        }
    }
    let inf = std::i32::MAX / 2;
    let mut dp = vec![vec![vec![inf; 1 << n]; n + 1]; n + 1];
    dp[0][0][0] = 0;
    for i in 0..=n {
        for j in 0..=n {
            for k in 0..(1 << n) {
                let v = dp[i][j][k];
                if v == inf {
                    continue;
                }
                let rem = [v - sum[k].1, v - sum[k].2];
                for (l, p) in p.iter().enumerate() {
                    if k >> l & 1 == 1 {
                        continue;
                    }
                    let mut add = 0;
                    add = max(add, p.1 - rem[0] - i as i32);
                    add = max(add, p.2 - rem[1] - j as i32);
                    let bit = k | (1 << l);
                    if p.0 == 0 {
                        dp[i + 1][j][bit] = std::cmp::min(dp[i + 1][j][bit], v + add);
                    } else {
                        dp[i][j + 1][bit] = std::cmp::min(dp[i][j + 1][bit], v + add);
                    }
                }
            }
        }
    }
    let mut ans = inf;
    for dp in dp {
        for dp in dp {
            ans = std::cmp::min(ans, dp[(1 << n) - 1]);
        }
    }
    ans += n as i32;
    println!("{}", ans);
}

fn main() {
    run();
}

//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 より
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};
    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };
    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };
    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };
    ($iter:expr, bytes) => {
        read_value!($iter, String).bytes().collect::<Vec<u8>>()
    };
    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };
    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

//

use std::cmp::*;

fn run() {
    input! {
        n: usize,
        p: [(chars, i32, i32); n],
    }
    let p = p
        .into_iter()
        .map(|p| ((p.0[0] == 'B') as usize, p.1, p.2))
        .collect::<Vec<_>>();
    let mut sum = vec![([0, 0], 0, 0)];
    for &(x, y, z) in p.iter() {
        for i in 0..sum.len() {
            let (mut a, mut b, mut c) = sum[i];
            a[x] += 1;
            b += y;
            c += z;
            sum.push((a, b, c));
        }
    }
    let inf = std::i32::MAX / 2;
    let mut dp = vec![vec![vec![inf; 1 << n]; n + 1]; n + 1];
    dp[0][0][0] = 0;
    for i in 0..=n {
        for j in 0..=n {
            for k in 0..(1 << n) {
                let v = dp[i][j][k];
                if v == inf {
                    continue;
                }
                let rem = [v - sum[k].0[0], v - sum[k].0[1]];
                for (l, p) in p.iter().enumerate() {
                    if k >> l & 1 == 1 {
                        continue;
                    }
                    let mut add = 0;
                    add = max(add, p.1 - rem[0] - i as i32);
                    add = max(add, p.2 - rem[1] - j as i32);
                    let bit = k | (1 << l);
                    if p.0 == 0 {
                        dp[i + 1][j][bit] = std::cmp::min(dp[i + 1][j][bit], v + add);
                    } else {
                        dp[i][j + 1][bit] = std::cmp::min(dp[i][j + 1][bit], v + add);
                    }
                }
            }
        }
    }
    let mut ans = inf;
    for dp in dp {
        for dp in dp {
            ans = std::cmp::min(ans, dp[(1 << n) - 1]);
        }
    }
    ans += n as i32;
    println!("{}", ans);
}

fn main() {
    run();
}


Gennady owns a small hotel in the countryside where he lives a peaceful life. He loves to take long walks, watch sunsets and play cards with tourists staying in his hotel. His favorite game is called "Mau-Mau".To play Mau-Mau, you need a pack of $$$52$$$ cards. Each card has a suit (Diamonds — D, Clubs — C, Spades — S, or Hearts — H), and a rank (2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K, or A).At the start of the game, there is one card on the table and you have five cards in your hand. You can play a card from your hand if and only if it has the same rank or the same suit as the card on the table.In order to check if you'd be a good playing partner, Gennady has prepared a task for you. Given the card on the table and five cards in your hand, check if you can play at least one card.

The first line of the input contains one string which describes the card on the table. The second line contains five strings which describe the cards in your hand. Each string is two characters long. The first character denotes the rank and belongs to the set $$$\{{\tt 2}, {\tt 3}, {\tt 4}, {\tt 5}, {\tt 6}, {\tt 7}, {\tt 8}, {\tt 9}, {\tt T}, {\tt J}, {\tt Q}, {\tt K}, {\tt A}\}$$$. The second character denotes the suit and belongs to the set $$$\{{\tt D}, {\tt C}, {\tt S}, {\tt H}\}$$$. All the cards in the input are different.

If it is possible to play a card from your hand, print one word "YES". Otherwise, print "NO". You can print each letter in any case (upper or lower).

NoteIn the first example, there is an Ace of Spades (AS) on the table. You can play an Ace of Diamonds (AD) because both of them are Aces.In the second example, you cannot play any card.In the third example, you can play an Ace of Diamonds (AD) because it has the same suit as a Four of Diamonds (4D), which lies on the table.

fn main() {
    let mut card_on_table = String::new();
    std::io::stdin().read_line(&mut card_on_table).expect("CARD_ON_TABLE::Read line failed!");

    let mut cards_in_hand = String::new();
    std::io::stdin().read_line(&mut cards_in_hand).expect("CARDS_IN_HAND::Read line failed!");

    let mut card = card_on_table.trim().chars();
    let suit = card.next().expect("SUIT::Not exist next char!");
    let rank = card.next().expect("RANK::Not exist next char!");

    let can_play = cards_in_hand.contains(suit) || cards_in_hand.contains(rank);

    match can_play {
        true => println!("YES"),
        false => println!("NO"),
    }
}

use std::io;

macro_rules! readln {
    () => {{
        use std::io;
        let mut buf = String::new();
        io::stdin().read_line(&mut buf).unwrap();
        buf.trim().to_string()
    }};
    ( $t:ty ) => {{
        let input = readln!();
        input.parse::<$t>().unwrap()
    }};
    ( $( $t:ty ),+ ) => {{
        let input = readln!();
        let mut input = input.split_whitespace();
        (
            $(
                input.next().unwrap().parse::<$t>().unwrap(),
            )+
        )
    }}
}

macro_rules! readvec {
    ( $t:ty ) => {{
        let input = readln!();
        let mut input = input.split_whitespace();
        let mut result = Vec::new();
        for elem in input {
            result.push(elem.parse::<$t>().unwrap());
        }
        result
    }}
}

fn main() {
    let card = readln!();
    let card: Vec<char> = card.chars().collect();

    let cards = readvec!(String);
    let cards: Vec<Vec<char>> = cards.iter().map(|c| c.chars().collect()).collect();
    let mut ans = false;
    for current_card in cards {
        if current_card[0] == card[0] || current_card[1] == card[1] {
            ans = true;
        }
    }

    println!("{}", if ans { "YES" } else { "NO" });
}

#[derive(Debug, Copy, Clone, PartialEq)]
enum CardSuit {
    Diamonds,
    Clubs,
    Spades,
    Hearts,
    Unknown,
}

impl<'a> From<&'a str> for CardSuit {
    fn from(input: &'a str) -> CardSuit {
        match input {
            "D" => CardSuit::Diamonds,
            "C" => CardSuit::Clubs,
            "S" => CardSuit::Spades,
            "H" => CardSuit::Hearts,
            _ => CardSuit::Unknown,
        }
    }
}

#[derive(Debug, Copy, Clone, PartialEq)]
enum CardRank {
    Two,
    Three,
    Four,
    Five,
    Six,
    Seven,
    Eight,
    Nine,
    T,
    J,
    Q,
    K,
    A,
    Unknown,
}

impl<'a> From<&'a str> for CardRank {
    fn from(input: &'a str) -> CardRank {
        match input {
            "2" => CardRank::Two,
            "3" => CardRank::Three,
            "4" => CardRank::Four,
            "5" => CardRank::Five,
            "6" => CardRank::Six,
            "7" => CardRank::Seven,
            "8" => CardRank::Eight,
            "9" => CardRank::Nine,
            "T" => CardRank::T,
            "J" => CardRank::J,
            "Q" => CardRank::Q,
            "K" => CardRank::K,
            "A" => CardRank::A,
            _ => CardRank::Unknown,
        }
    }
}

#[derive(Debug, Copy, Clone)]
struct Card {
    suit: CardSuit,
    rank: CardRank,
}

impl Card {
    pub fn playable(&self, other: &Card) -> bool {
        self.rank == other.rank || self.suit == other.suit
    }
}

impl<'a> From<&'a str> for Card {
    fn from(input: &'a str) -> Card {
        Card {
            suit: CardSuit::from(&input[1..2]),
            rank: CardRank::from(&input[0..1]),
        }
    }
}

fn main() -> std::io::Result<()> {
    let mut table_input = String::default();
    std::io::stdin().read_line(&mut table_input)?;
    let table_card = Card::from(table_input.as_str());
    // println!("Table card: {:?}", table_card);

    let mut hand_input = String::default();
    std::io::stdin().read_line(&mut hand_input)?;
    let hand_cards = hand_input
        .split(" ")
        .into_iter()
        .map(|x| Card::from(x))
        .collect::<Vec<Card>>();
    // println!("Hand cards: {:#?}", hand_cards);

    let mut can_play = false;

    for card in &hand_cards {
        if card.playable(&table_card) {
            can_play = true;
        }
    }

    match can_play {
        true => println!("YES"),
        false => println!("NO"),
    }

    Ok(())
}

// First letter {2,3,4,5,6,7,8,9,T,J,Q,K,A}
// second letter {D,C,S,H}
use std::io::stdin;

fn main() {
    let mut table = String::new();
    let mut hand = String::new();
    let _ = stdin().read_line(&mut table);
    let _ = stdin().read_line(&mut hand);
    table = table.trim().to_string();
    hand = hand.trim().to_string();

    let mut response = "NO";
    for tab in table.chars() {
        for h in hand.chars() {
            if h == tab {
                response = "YES";
                break;
            }
        }
    }

    println!("{}", response);

    // println!("The table is {}", table);
    // println!("The hand is {}", hand);
}

//spnauti-rust
#[allow(unused_macros)]
macro_rules! a {
    ($c: tt, $x: expr, $y: expr) => {{
        let b = $y; let a = &mut $x;
        if b $c *a { *a = b; true } else { false }
    }};
}
use std::io::*;
use std::str::*;
use std::fmt::Debug;
struct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }
#[allow(dead_code)]
impl<'a> WordReader<'a> {
    fn new<T: Read>(b: &mut String, mut r: T) -> WordReader {
        b.clear();
        r.read_to_string(b).unwrap();
        WordReader { it: b.split_ascii_whitespace() }
    }
    fn from_stdin(b: &mut String) -> WordReader {
        WordReader::new(b, stdin())
    }
    fn sl(&mut self) ->  &str { self.it.next().unwrap() }
    fn bs(&mut self) -> &[u8] { self.sl().as_bytes()    }
    fn s(&mut self) -> String { String::from(self.sl()) }
    fn i(&mut self) ->    i32 { self.p()                }
    fn p<T: FromStr>(&mut self) -> T where T::Err: Debug {
        self.sl().parse::<T>().unwrap()
    }
    fn vp<T: FromStr>(&mut self, n: usize) -> Vec<T> where T::Err: Debug {
        (0..n).map(|_| self.p()).collect()
    }
}

fn main() {
    let mut bin = String::new();
    let mut input = WordReader::from_stdin(&mut bin);

    let s = input.s();
    println!("{}", if (0..5).any(|_| {
        let t = input.s();
        s.bytes().zip(t.bytes()).any(|(a,b)| a == b)
    }) {
        "YES"
    } else {
        "NO"
    });
}

use std::io;

fn can_play(table: &str, hand: Vec<&str>) -> &'static str {
    for card in hand.iter() {
        let mut table_chars = table.chars();
        let mut card_chars = card.chars();

        if table_chars.nth(0).unwrap() == card_chars.nth(0).unwrap()
            || table_chars.nth(0).unwrap() == card_chars.nth(0).unwrap()
        {
            return "YES";
        }
    }

    "NO"
}

pub fn solution() -> io::Result<()> {
    let mut table = String::new();
    let mut hand = String::new();

    io::stdin().read_line(&mut table)?;
    io::stdin().read_line(&mut hand)?;
    let hand: Vec<&str> = hand.trim().split(" ").collect();

    println!("{}", can_play(&table, hand));
    Ok(())
}

fn main() {
    solution();
}

macro_rules! debug {
    ( $x:expr ) => {
        if cfg!(debug_assertions) {
            println!("{}:{} {} = {:?}", line!(), column!(), stringify!($x), $x);
        }
    };
}

macro_rules! array {
    ( $t:ty ; $size:expr ) => {
        [<$t>::default(); $size]
    };
}

mod my {
    pub mod io {
        use std::io::{BufRead, ErrorKind};

        pub fn read_word<R: BufRead>(r: &mut R, buf: &mut Vec<u8>)
                                              -> std::io::Result<usize> {
            let mut read = 0;
            loop {
                let (done, used) = {
                    let available = match r.fill_buf() {
                        Ok(n) => n,
                        Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
                        Err(e) => return Err(e)
                    };
                    match available.iter().position(|&x| x == b'\n' || x == b' ') {
                        Some(i) => {
                            buf.extend_from_slice(&available[..i]);
                            (true, i + 1)
                        }
                        None => {
                            buf.extend_from_slice(available);
                            (false, available.len())
                        }
                    }
                };
                r.consume(used);
                read += used;
                if done || used == 0 {
                    return Ok(read);
                }
            }
        }

        pub struct InputReader<R: BufRead> {
            reader: R,
            buf: Vec<u8>,
        }

        impl<R: BufRead> InputReader<R> {
            pub fn new(reader: R) -> Self {
                Self {
                    reader,
                    buf: Vec::<u8>::new(),
                }
            }

            pub fn read_word(&mut self) {
                read_word(&mut self.reader, &mut self.buf);
            }

            pub fn read<T>(&mut self) -> T
                where T: std::str::FromStr,
                      T::Err: std::fmt::Debug
            {
                self.buf.clear();
                self.read_word();
                std::str::from_utf8(&self.buf).unwrap().trim().parse().unwrap()
            }
        }
    }
}

fn main() {
    let stdin = std::io::stdin();
    let mut stdin = my::io::InputReader::new(stdin.lock());

    let table: String;
    let mut hands = Vec::<String>::new();

    table = stdin.read();
    for i in 0..5 {
        hands.push(stdin.read());
    }

    let mut result = false;
    for i in 0..5 {
        if table.bytes().zip(hands[i].bytes()).any(|(x, y)| x == y) {
            result = true;
            break;
        }
    }
    println!("{}", if result { "YES" } else { "NO" });
}

use std::io;

fn main() {
    let l1 = read_line();
    let l2 = read_line();

    let lb1 = l1.as_bytes();
    let r = l2.split(' ').any(|c| {
        let c = c.as_bytes();
        if c[0] == lb1[0] || c[1] == lb1[1] {
            true
        } else {
            false
        }
    });
    println!("{}", match r {
        true => "YES",
        false => "NO"
    });
}

fn read_line() -> String {
    let mut line = String::new();

    io::stdin().read_line(&mut line).unwrap();
    let l1 = line.trim();
    l1.to_string()
}

use std::io::{BufReader, BufRead};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut lines = BufReader::new(std::io::stdin())
        .lines()
        .map(Result::unwrap);

    let hand = lines.next().unwrap();
    let rank = &hand[0..1];
    let suit = &hand[1..2];

    for card in lines.next().unwrap().split_whitespace().take(5) {
        if rank == &card[0..1] || suit == &card[1..2] {
            println!("YES");
            return Ok(())
        }
    }

    println!("NO");
    Ok(())
}

use std::io;

fn get_line() -> io::Result<String> {
	let mut buffer = String::new();
	io::stdin().read_line(&mut buffer)?;
	Ok(buffer)
}

fn main() {
	let input = get_line().unwrap();
	let card = input.trim().as_bytes();
	let input = get_line().unwrap();
	let hand: Vec<&[u8]> = input.split_whitespace().map(|s| s.as_bytes()).collect();
	let mut play = "NO";
	for i in 0..hand.len() {
		if card[0] == hand[i][0] || card[1] == hand[i][1] {
			play = "YES";
			break;
		}
	}
	print!("{}", play);
}

fn main() {
    let mut card = String::new();
    std::io::stdin().read_line(&mut card)
        .expect("Error  input");
    let card_chars: Vec<char> = card.chars().collect();
    let mut hand = String::new();
    std::io::stdin().read_line(&mut hand)
        .expect("Error  input");
    let hand_chars: Vec<Vec<char>> = hand.split(' ').map(|s| s.chars().collect()).collect();

    for c in hand_chars {
        if c[0] == card_chars[0] || c[1] == card_chars[1] {
            println!("YES");
            std::process::exit(0);
        }
    }
    println!("NO");
}

use std::io;

fn main() {
    let card_on_desk = {
        let mut buf = String::new();
        io::stdin().read_line(&mut buf).unwrap();
        buf
    };
    let cards = {
        let mut buf = String::new();
        io::stdin().read_line(&mut buf).unwrap();
        buf
    };

    if cards.split_whitespace().any(|card| {
        card.as_bytes()[0] == card_on_desk.as_bytes()[0]
            || card.as_bytes()[1] == card_on_desk.as_bytes()[1]
    }) {
        println!("YES");
    } else {
        println!("NO");
    }
}

use std::io;

fn main() {
    let stdin = io::stdin();

    let card_on_desk = {
        let mut read_buf = String::new();
        stdin.read_line(&mut read_buf).unwrap();
        read_buf.trim().to_string()
    };

    let cards = {
        let mut read_buf = String::new();
        stdin.read_line(&mut read_buf).unwrap();
        read_buf
    };

    if cards.split_whitespace().any(|card| {
        card.as_bytes()[0] == card_on_desk.as_bytes()[0]
            || card.as_bytes()[1] == card_on_desk.as_bytes()[1]
    }) {
        println!("YES");
    } else {
        println!("NO");
    }
}

fn main() {
    let mut cin = io::Input::new();

    let s= cin.next_ascii_string();

    for _ in 1..=5 {
        let t = cin.next_ascii_string();
        if s[0] == t[0] || s[1] == t[1] {
            println!("YES");
            return;
        }
    }

    println!("NO");
}

#[allow(unused)]
pub mod io {

    const BUFFER_SIZE: usize = 8192;

    use std::collections::VecDeque;
    use std::str::FromStr;
    use std::io;
    use std::io::Read;

    type AsciiStr = Vec<u8>;

    pub struct Input {
        token_buffer: VecDeque<String>,
        remaining: String,
    }

    impl Input {

        pub fn new() -> Input {
            Input {
                token_buffer: VecDeque::with_capacity(100),
                remaining: String::new(),
            }
        }

        pub fn next<T: FromStr>(&mut self) -> T
            where T::Err: ::std::fmt::Debug
        {
            self.fill_buffer();
            self.token_buffer.pop_front().unwrap().parse().unwrap()
        }

        pub fn next_ascii_string(&mut self) -> AsciiStr {
            self.fill_buffer();
            Vec::from(self.token_buffer.pop_front().unwrap().as_bytes())
        }

        fn fill_buffer(&mut self) {
            while self.token_buffer.is_empty() {
                let mut minibuffer = [0u8; BUFFER_SIZE];
                let size = io::stdin().read(&mut minibuffer[..]).unwrap();

                self.remaining += &String::from_utf8_lossy(&minibuffer[..size]);

                if self.remaining.trim().len() > 0 {
                    for token in self.remaining.trim().split_whitespace() {
                        self.token_buffer.push_back(String::from(token))
                    }

                    if size > 0 && ! self.remaining.ends_with(|c: char|char::is_ascii_whitespace(&c)) {
                        self.remaining = self.token_buffer.pop_back().unwrap();
                    } else {
                        self.remaining.clear();
                    }

                } else if size == 0 {
                    panic!("EOF");
                }
            }
        }
    }
}

#![allow(dead_code, unused_imports)]

use std::fmt::Debug;
use std::str::FromStr;

fn read_stdin() -> String {
    let mut s = String::new();
    std::io::stdin()
        .read_line(&mut s)
        .expect("cannot read stdin");
    s.trim().to_string()
}

fn read<T>() -> T
where
    T: FromStr,
    <T as FromStr>::Err: Debug,
{
    read_stdin().parse::<T>().unwrap()
}

fn read_usize() -> usize {
    read::<usize>()
}

fn read_2<A, B>() -> (A, B)
where
    A: FromStr,
    <A as FromStr>::Err: Debug,
    B: FromStr,
    <B as FromStr>::Err: Debug,
{
    let s = read_stdin();
    let mut s = s.split_whitespace();
    let a = s.next().unwrap().parse::<A>().unwrap();
    let b = s.next().unwrap().parse::<B>().unwrap();
    (a, b)
}

fn read_3<A, B, C>() -> (A, B, C)
where
    A: FromStr,
    <A as FromStr>::Err: Debug,
    B: FromStr,
    <B as FromStr>::Err: Debug,
    C: FromStr,
    <C as FromStr>::Err: Debug,
{
    let s = read_stdin();
    let mut s = s.split_whitespace();
    let a = s.next().unwrap().parse::<A>().unwrap();
    let b = s.next().unwrap().parse::<B>().unwrap();
    let c = s.next().unwrap().parse::<C>().unwrap();
    (a, b, c)
}

fn read_4<A, B, C, D>() -> (A, B, C, D)
where
    A: FromStr,
    <A as FromStr>::Err: Debug,
    B: FromStr,
    <B as FromStr>::Err: Debug,
    C: FromStr,
    <C as FromStr>::Err: Debug,
    D: FromStr,
    <D as FromStr>::Err: Debug,
{
    let s = read_stdin();
    let mut s = s.split_whitespace();
    let a = s.next().unwrap().parse::<A>().unwrap();
    let b = s.next().unwrap().parse::<B>().unwrap();
    let c = s.next().unwrap().parse::<C>().unwrap();
    let d = s.next().unwrap().parse::<D>().unwrap();
    (a, b, c, d)
}

fn read_multiple<T: FromStr>() -> Vec<T>
where
    <T as FromStr>::Err: Debug,
{
    read_stdin()
        .split_whitespace()
        .map(|x| x.parse::<T>().expect("cannot parse stdin"))
        .collect()
}

/// NOTE: sort iter beforehand if required
fn count<T>(iter: &mut impl Iterator<Item = T>) -> Vec<(T, usize)>
where
    T: std::cmp::Ord,
{
    let iter = iter.collect::<Vec<_>>();
    //iter.sort();
    let (mut v, o, c) =
        iter.into_iter()
            .fold((Vec::new(), None, 0), |(mut v, last, count), item| {
                if let Some(o) = last {
                    if item == o {
                        (v, Some(o), count + 1)
                    } else {
                        v.push((o, count));
                        (v, Some(item), 1)
                    }
                } else {
                    (v, Some(item), 1)
                }
            });
    if let Some(i) = o {
        v.push((i, c));
    }
    v
}

fn partial_sum<T>(v: impl Iterator<Item = T>) -> impl Iterator<Item = T>
where
    T: Default + std::ops::Add<Output = T> + Copy,
{
    v.scan(T::default(), |state, x| {
        *state = *state + x;
        Some(*state)
    })
}

fn max_subarray(v: impl Iterator<Item = i64>) -> (i64, (usize, usize)) {
    //assert!(v.len() > 0);
    let mut best_sum = 0;
    let (mut best_start, mut best_end) = (0, 0);
    let mut current_sum = 0;
    let mut current_start = 0;
    for (end, val) in v.enumerate() {
        if current_sum <= 0 {
            current_start = end;
            current_sum = val;
        } else {
            current_sum += val;
        }
        if current_sum > best_sum {
            best_sum = current_sum;
            best_start = current_start;
            best_end = end + 1;
        }
    }
    (best_sum, (best_start, best_end))
}

fn gcd(mut a: u64, mut b: u64) -> u64 {
    while a != 0 {
        let old_m = a;
        a = b % a;
        b = old_m;
    }
    b
}

/// returns gcd, and pair (x, y), such that x * a + b * y == gcd
fn egcd(a: i64, b: i64) -> (i64, i64, i64) {
    if a == 0 {
        (b, 0, 1)
    } else {
        let (g, x, y) = egcd(b % a, a);
        (g, y - (b / a) * x, x)
    }
}

fn factorize(mut n: u64) -> Vec<u64> {
    if n <= 3 {
        return vec![n];
    }
    let mut v = Vec::new();
    while n % 2 == 0 {
        n /= 2;
        v.push(2);
    }
    while n % 3 == 0 {
        n /= 3;
        v.push(3);
    }
    let mut f = 6;
    while (f - 1) * (f - 1) <= n {
        while n % (f - 1) == 0 {
            n /= f - 1;
            v.push(f - 1);
        }
        while n % (f + 1) == 0 {
            n /= f + 1;
            v.push(f + 1);
        }
        f += 6;
    }
    if n > 1 {
        v.push(n);
    }
    v
}

fn compact_factors(n: u64) -> Vec<(u64, usize)> {
    count(&mut factorize(n).into_iter())
}

fn all_factors(n: u64) -> Vec<u64> {
    if n == 0 {
        return vec![0];
    } else if n == 1 {
        return vec![1];
    }
    let factors = compact_factors(n);
    let mut v = vec![1];
    for (fac, num) in factors {
        let ori = v.clone();
        for i in 1..num + 1 {
            v.append(
                &mut ori
                    .clone()
                    .into_iter()
                    .map(|f| f * fac.pow(i as u32))
                    .collect::<Vec<_>>(),
            )
        }
    }
    v.sort();
    v
}

fn abs_diff<T>(a: T, b: T) -> T
where
    T: PartialOrd + std::ops::Sub<Output = T>,
{
    if a > b {
        a - b
    } else {
        b - a
    }
}

struct Permutations<T> {
    inner: Vec<T>,
    state: Vec<usize>,
    i: usize,
    start: bool,
}

impl<T> Permutations<T> {
    fn new(inner: Vec<T>) -> Self {
        Self {
            state: vec![0; inner.len()],
            i: 0,
            start: true,
            inner,
        }
    }
}

/*impl<T, X> From<X> for Permutations<T>
where
    X: IntoIterator<Item = T>,
{
    fn from(f: X) -> Self {
        Self::new(f.into_iter().collect::<Vec<T>>())
    }
}*/

impl<T> Iterator for Permutations<T>
where
    T: Clone,
{
    type Item = Vec<T>;
    fn next(&mut self) -> Option<Self::Item> {
        if self.start {
            self.start = false;
            return Some(self.inner.clone());
        }
        while self.i < self.inner.len() {
            if self.state[self.i] < self.i {
                if self.i % 2 == 0 {
                    self.inner.swap(0, self.i)
                } else {
                    self.inner.swap(self.state[self.i], self.i)
                }
                self.state[self.i] += 1;
                self.i = 0;
                return Some(self.inner.clone());
            } else {
                self.state[self.i] = 0;
                self.i += 1;
            }
        }
        None
    }
}

use std::cmp::{max, min, Ord, Ordering};
use std::collections::{BinaryHeap, VecDeque};
use std::mem::swap;

#[derive(Clone)]
struct Graph {
    nodes: usize,
    edges: Vec<Vec<(usize, u64)>>,
}

impl Graph {
    fn new(n: usize) -> Self {
        Self {
            nodes: n,
            edges: vec![Vec::new(); n + 1],
        }
    }

    fn add_edge(&mut self, x: usize, y: usize, cost: u64) {
        self.edges[x].push((y, cost));
        self.edges[y].push((x, cost));
    }

    fn dijkstra(&mut self, start: usize, end: usize) -> u64 {
        let mut dist = vec![None; self.nodes + 1];
        let mut prev = vec![None; self.nodes + 1];
        dist[start] = Some(0);
        let mut queue = (1..=self.nodes).collect::<Vec<_>>();
        queue.sort_unstable_by_key(|node| dist[*node].unwrap_or(std::u64::MAX));
        queue.reverse();
        while let Some(next_node) = queue.pop() {
            if next_node == end {
                return dist[next_node].unwrap();
            }
            for (neighbour, cost) in self.edges[next_node].iter() {
                let alt = dist[next_node].unwrap() + cost;
                if dist[*neighbour].is_none() {
                    dist[*neighbour] = Some(alt);
                    prev[*neighbour] = Some(next_node);
                } else {
                    if alt < dist[*neighbour].unwrap() {
                        dist[*neighbour] = Some(alt);
                        prev[*neighbour] = Some(next_node);
                    }
                }
            }
            //println!("{:?} {:?}", dist, prev);
            queue.sort_unstable_by_key(|node| dist[*node].unwrap_or(std::u64::MAX));
            queue.reverse();
        }
        0
    }

    fn set_cost(&mut self, x: usize, y: usize, cost: u64) {
        for i in 0..self.edges[x].len() {
            if self.edges[x][i].0 == y {
                self.edges[x][i].1 = cost
            }
        }
        for i in 0..self.edges[y].len() {
            if self.edges[y][i].0 == x {
                self.edges[y][i].1 = cost
            }
        }
    }
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let table = read_stdin();
    let hand = read_stdin();
    if hand.split(' ').any(|h| {
        h.chars().nth(0).unwrap() == table.chars().nth(0).unwrap()
            || h.chars().nth(1).unwrap() == table.chars().nth(1).unwrap()
    }) {
        println!("YES")
    } else {
        println!("NO")
    }
    Ok(())
}

use std::io;
use std::io::prelude::*;

fn main() {
	let stdin = io::stdin();
	let desk_card = stdin.lock().lines().next().unwrap().unwrap();
	let my_cards = stdin.lock().lines().next().unwrap().unwrap();

	let mut card = String::new();
	let mut status: bool = false;

	for c in my_cards.chars() {
		if c != ' ' {
			card.push(c);
		}

		if card.len() == 2 {
			if &desk_card[0..1] == &card[0..1] {
				status = true;
			}
			if &desk_card[1..2] == &card[1..2] {
				status = true;
			}
			card.clear();
		}

		if status {
			break;
		}
	}

	if status {
		println!("{}", "YES");
	} else {
		println!("{}", "NO");
	}
}

#[allow(unused_imports)]
use std::cmp::{max, min, Ordering};
#[allow(unused_imports)]
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};
#[allow(unused_imports)]
use std::io::{stdin, stdout, BufWriter, StdoutLock, Write};
#[allow(unused_imports)]
use std::iter::FromIterator;
#[allow(unused_macros)]
macro_rules ! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut iter = $ s . split_whitespace ( ) ; let mut next = || { iter . next ( ) . unwrap ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { let stdin = std :: io :: stdin ( ) ; let mut bytes = std :: io :: Read :: bytes ( std :: io :: BufReader :: new ( stdin . lock ( ) ) ) ; let mut next = move || -> String { bytes . by_ref ( ) . map ( | r | r . unwrap ( ) as char ) . skip_while ( | c | c . is_whitespace ( ) ) . take_while ( | c |! c . is_whitespace ( ) ) . collect ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; }
#[allow(unused_macros)]
macro_rules ! input_inner { ( $ next : expr ) => { } ; ( $ next : expr , ) => { } ; ( $ next : expr , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ next , $ t ) ; input_inner ! { $ next $ ( $ r ) * } } ; }
#[allow(unused_macros)]
macro_rules ! read_value { ( $ next : expr , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ next , $ t ) ) ,* ) } ; ( $ next : expr , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ next , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ next : expr , chars ) => { read_value ! ( $ next , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ next : expr , bytes ) => { read_value ! ( $ next , String ) . into_bytes ( ) } ; ( $ next : expr , usize1 ) => { read_value ! ( $ next , usize ) - 1 } ; ( $ next : expr , $ t : ty ) => { $ next ( ) . parse ::<$ t > ( ) . expect ( "Parse error" ) } ; }
#[allow(dead_code)]
pub fn with_bufwriter<F: FnOnce(BufWriter<StdoutLock>) -> ()>(f: F) {
    let out = stdout();
    let writer = BufWriter::new(out.lock());
    f(writer)
}
#[allow(unused_macros)]
macro_rules ! debug { ( $ ( $ a : expr ) ,* ) => { eprintln ! ( concat ! ( $ ( stringify ! ( $ a ) , " = {:?}, " ) ,* ) , $ ( $ a ) ,* ) } ; }
#[allow(dead_code)]
fn main() {
    input!{
        x: chars,
        my_cards: [chars; 5],
    }
    let mut can = false;
    for card in my_cards {
        if card[0] == x[0] || card[1] == x[1] {
            can = true;
            break;
        }
    }
    if can {
        println!("YES");
    } else {
        println!("NO");
    }
}

use std::io;

fn main() {
	let mut table = String::new();
	io::stdin().read_line(&mut table).expect("Time to panic");
	let table=table.trim();
	let mut hand = String::new();
	io::stdin().read_line(&mut hand).expect("Time to panic");
	let hand = hand.trim().split(' ');
	let mut possible = false;
	for card in hand {
		let card: Vec<char> = card.chars().collect();
		let table: Vec<char> = table.chars().collect();
		if card[0] == table[0] || card[1] == table[1] {
			possible = true;
		}
	}
	if possible {
		println!("YES");
	} else {
		println!("NO");
	}
}

use std::io::{self, BufRead, BufWriter, StdinLock, Write};

fn main() {
    let (stdin, stdout) = (io::stdin(), io::stdout());
    let mut scan = stdin.lock();
    let mut out = BufWriter::new(stdout.lock());

    let table = scan.next();
    let hand = scan.next();

    writeln!(
        out,
        "{}",
        if {
            let bytes = table.as_bytes();
            hand.contains(bytes[0] as char) || hand.contains(bytes[1] as char)
        } {
            "YES"
        } else {
            "NO"
        }
    )
    .ok();
}

trait Scan {
    fn next(&mut self) -> String;
}

impl<'a> Scan for StdinLock<'a> {
    fn next(&mut self) -> String {
        let mut buf = String::with_capacity(15);
        self.read_line(&mut buf).unwrap();
        return buf;
    }
}

struct Scan {
    buffer: std::collections::VecDeque<String>,
}

impl Scan {
    fn new() -> Scan {
        Scan {
            buffer: std::collections::VecDeque::new(),
        }
    }

    fn next<T: std::str::FromStr>(&mut self) -> T {
        loop {
            if let Some(token) = self.buffer.pop_front() {
                break token.parse::<T>().ok().unwrap();
            }
            let mut line = String::new();
            std::io::stdin().read_line(&mut line).expect("Fail to read");
            self.buffer = line.split_whitespace().map(String::from).collect();
        }
    }

    fn next_n<T: std::str::FromStr>(&mut self, n: usize) -> Vec<T> {
        (0..n).map(|_| self.next::<T>()).collect()
    }
}

fn _main() {
    let mut scan = Scan::new();
    let mine = scan.next::<String>();
    let mine = mine.as_bytes();
    let table: Vec<String> = scan.next_n(5);
    let mut result = false;
    for card in table.into_iter() {
        let x = card.as_bytes();
        if x[0] == mine[0] || x[1] == mine[1] {
            result = true;
            break;
        }
    }
    println!("{}", if result { "YES" } else { "NO" });
}

fn main() {
    std::thread::Builder::new()
        .stack_size(1 << 23)
        .spawn(_main)
        .unwrap()
        .join()
        .unwrap();
}

use std::io::stdin;

fn main()
{
    //handle input / output
    let mut s = String::new();
    stdin().read_line(&mut s).unwrap();
    let card: Vec<_> = s.split_whitespace().collect();
    let card = card[0].clone().chars().collect::<Vec<_>>();
    let mut s = String::new();
    stdin().read_line(&mut s).unwrap();
    let deck: Vec<_> = s.split_whitespace().collect();
    let deck = deck.iter().map( |c| c.chars().collect::<Vec<_>>()).collect::<Vec<_>>();

    for dc in deck {
        if dc[0] == card[0] || dc[1] == card[1] {
            println!("YES");
            return;
        }
    }

    println!("NO");
}

macro_rules! parse_line {
    ($t: ty) => ({
        let mut a_str = String::new();
        std::io::stdin().read_line(&mut a_str).expect("read error");
        let a_str = a_str.trim();
        a_str.parse::<$t>().expect("parse error")
    });
    ($($t: ty),+) => ({
        let mut a_str = String::new();
        std::io::stdin().read_line(&mut a_str).expect("read error");
        let mut a_iter = a_str.split_whitespace();
        (
            $(
            a_iter.next().unwrap().parse::<$t>().expect("parse error"),
            )+
        )
    })
}

#[allow(unused_macros)]
macro_rules! parse_line_to_vec {
    ($t: ty) => {{
        let mut a_str = String::new();
        std::io::stdin().read_line(&mut a_str).expect("read error");
        (a_str
            .split_whitespace()
            .map(|x| x.parse::<$t>().unwrap())
            .collect::<Vec<$t>>())
    }};
}

use std::io::Write;

fn solve(writer: &mut std::io::BufWriter<std::io::Stdout>) {
    let a: Vec<_> = parse_line!(String).bytes().collect();
    let mut result = false;
    for s in parse_line!(String).split_whitespace() {
        for (j, c) in s.bytes().enumerate() {
            result |= c == a[j];
        }
    }
    if result {
        writeln!(writer, "YES").unwrap()
    }else{
        writeln!(writer, "NO").unwrap()
    }
}

fn main() {
    let tests = 1; // parse_line!(usize);
    let mut writer = std::io::BufWriter::new(std::io::stdout());
    for _ in 0..tests {
        solve(&mut writer);
    }
}

#[allow(unused_imports)]
use std::cmp::{min,max};
use std::io::{BufWriter, stdin, stdout, Write};

#[derive(Default)]
struct Scanner {
    buffer: Vec<String>
}
impl Scanner {
    fn next<T: std::str::FromStr>(&mut self) -> T {
        loop {
            if let Some(token) = self.buffer.pop() {
                return token.parse().ok().expect("Failed parse");
            }
            let mut input = String::new();
            stdin().read_line(&mut input).expect("Failed read");
            self.buffer = input.split_whitespace().rev().map(String::from).collect();
        }
    }
}

fn main() {
    let mut scan = Scanner::default();
    let out = &mut BufWriter::new(stdout());

    let f = |s1:&str, s2:&str|  s1.chars().nth(0) == s2.chars().nth(0) || s1.chars().nth(1) == s2.chars().nth(1);
    let s1: String = scan.next::<String>();

    for _ in 0..5
    {
        let s2: String = scan.next::<String>();
        if f(s1.as_ref(), s2.as_ref())
        {
            write!(out, "YES").ok();
            return;
        }
    }
    write!(out, "NO").ok();
}

use std::io;

fn main() -> io::Result<()> {
    let mut input = String::new();

    io::stdin().read_line(&mut input)?;

    let table: Vec<char> = input.trim().chars().collect();
    input.clear();

    io::stdin().read_line(&mut input)?;

    let hand :Vec<Vec<char>> = input.trim().split(' ').map(|x| x.chars().collect()).collect();

    let mut yes = false;
    for i in 0..5 {
        if hand[i][0] == table[0] {
            yes = true;
        }
        if hand[i][1] == table[1] {
            yes = true;
        }
    }

    if yes {
        print!("YES");
    } else {
        print!("NO");
    }

    Ok(())
}

use std::io::{self, BufRead};

fn main() {
    let stdin = io::stdin();
    let mut table = String::new();
    let mut hand = String::new();

    stdin.lock().read_line(&mut table).unwrap();
    stdin.lock().read_line(&mut hand).unwrap();

    let table = table.as_bytes();
    let hand = hand.trim().split(" ");
    for card in hand {
        let card = card.as_bytes();
        if card[0] == table[0] || card[1] == table[1] {
            println!("YES");
            return;
        }
    }
    println!("NO");
}

use std::io;

fn main() {
  let mut ti = String::new();
  io::stdin().read_line(&mut ti).unwrap();
  let mut hi = String::new();
  io::stdin().read_line(&mut hi).unwrap();

  let t = ti.as_bytes();
  let h: Vec<&str> = hi.split_terminator(" ").collect();
  for i in 0..5 {
    let h = h[i].as_bytes();
    if (h[1] == t[1]) || (h[0] == t[0]) {
      println!("YES");
      return;
    }
  }
  println!("NO");
}

#[allow(unused_imports)]
use std::cmp::{min,max};
#[allow(unused_imports)]
use std::collections::{BTreeMap,BTreeSet};
#[allow(unused_imports)]
use std::ops::*;
#[allow(unused_imports)]
use std::collections::BinaryHeap;

#[allow(unused_macros)]
macro_rules! ite {
    ($c:expr, $t:expr, $f:expr) => {{
        if $c { $t } else { $f }
    }};
}

// ref: tanakh <https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8>
// diff: using Parser
#[macro_export]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut parser = Parser::from_str($s);
        input_inner!{parser, $($r)*}
    };
    (parser = $parser:ident, $($r:tt)*) => {
        input_inner!{$parser, $($r)*}
    };
    (new_stdin_parser = $parser:ident, $($r:tt)*) => {
        let stdin = std::io::stdin();
        let reader = std::io::BufReader::new(stdin.lock());
        let mut $parser = Parser::new(reader);
        input_inner!{$parser, $($r)*}
    };
    ($($r:tt)*) => {
        input!{new_stdin_parser = parser, $($r)*}
    };
}

#[macro_export]
macro_rules! input_inner {
    ($parser:ident) => {};
    ($parser:ident, ) => {};
    ($parser:ident, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($parser, $t);
        input_inner!{$parser $($r)*}
    };
}

#[macro_export]
macro_rules! read_value {
    ($parser:ident, ( $($t:tt),* )) => {
        ( $(read_value!($parser, $t)),* )
    };
    ($parser:ident, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($parser, $t)).collect::<Vec<_>>()
    };
    ($parser:ident, chars) => {
        read_value!($parser, String).chars().collect::<Vec<char>>()
    };
    ($parser:ident, usize1) => {
        read_value!($parser, usize) - 1
    };
    ($parser:ident, $t:ty) => {
        $parser.next::<$t>().expect("Parse error")
    };
}

fn main() {
    input! {
        s: chars,
        ts: [chars; 5],
    }
    let mut res = false;
    for i in 0..5 {
        if s[0] == ts[i][0] || s[1] == ts[i][1] {
            res = true;
        }
    }
    println!("{}", ite!(res, "YES", "NO"));
}

use std::io::BufRead;
use std::io;
use std::str;

// ref: tatsuya6502 <https://qiita.com/tatsuya6502/items/cd448486f7ef7b5b8c7e>
// ref: wariuni <https://qiita.com/tatsuya6502/items/cd448486f7ef7b5b8c7e#comment-7040a5ae96305e884eb9>
// diff: using std::io::BufRead::fill_buf()
pub struct Parser<R> {
    reader: R,
    buf: Vec<u8>,
    pos: usize,
}

impl Parser<io::Empty> {
    pub fn from_str(s: &str) -> Parser<io::Empty> {
        Parser {
            reader: io::empty(),
            buf: s.as_bytes().to_vec(),
            pos: 0,
        }
    }
}

impl<R:BufRead> Parser<R> {
    pub fn new(reader: R) -> Parser<R> {
        Parser {
            reader: reader,
            buf: vec![],
            pos: 0,
        }
    }
    pub fn update_buf(&mut self) {
        self.buf.clear();
        self.pos = 0;
        loop {
            let (len,complete) = {
                let buf2 = self.reader.fill_buf().unwrap();
                self.buf.extend_from_slice(buf2);
                let len = buf2.len();
                (len, buf2[len-1] <= 0x20)
            };
            self.reader.consume(len);
            if complete {
                break;
            }
        }
    }
    pub fn next<T:str::FromStr>(&mut self) -> Result<T, T::Err> {
        loop {
            let mut begin = self.pos;
            while begin < self.buf.len() && (self.buf[begin] <= 0x20) {
                begin += 1;
            }
            let mut end = begin;
            while end < self.buf.len() && (self.buf[end] > 0x20) {
                end += 1;
            }
            if begin != self.buf.len() {
                self.pos = end;
                return str::from_utf8(&self.buf[begin..end]).unwrap().parse::<T>();
            }
            else {
                self.update_buf();
            }
        }
    }
}

use std::fmt::Display;
#[allow(dead_code)]
fn write_vec<T: Display>(xs: &Vec<T>) {
    if xs.len() == 0 {
        println!();
        return;
    }
    print!("{}", xs[0]);
    for i in 1..xs.len() {
        print!(" {}", xs[i]);
    }
    println!();
}

use std::io::stdin;

fn main() {
    let mut input1 = String::new();
    stdin().read_line(&mut input1).unwrap();
    let mut input2 = String::new();
    stdin().read_line(&mut input2).unwrap();

    for x in input2.split_whitespace() {
        if x[0..1] == *input1[0..1].trim() || x[1..] == *input1[1..].trim() {
            println!("YES");
            return;
        }
    }

    println!("NO");
}

fn main() {
    let str = "010";
    let trimmed = str.trim();
    let mut negative = false;
    let mut lookup = &trimmed[..];
    if trimmed.starts_with('-') {
        negative = true;
        lookup = &trimmed[1..];
    }
    if trimmed.starts_with('+') {
        negative = false;
        lookup = &trimmed[1..];
    }

    let digits = lookup.chars().take_while(|c| c.is_digit(10)).collect::<Vec<_>>();
    let mut answer: i64 = 0;

    for d in digits.iter().map(|c| c.to_digit(10).unwrap()) {
        answer *= 10;

        answer += match negative {
            true => -1 * d as i64,
            false => d as i64,
        };

        if answer >= i32::max_value().into() {
            answer = i32::max_value() as i64;
            break;
        }
        if answer <= i32::min_value().into() {
            answer = i32::min_value() as i64;
            break;
        }
    }

    println!("{}", answer);
}

use std::io::stdin;

fn main()
{
    //handle input / output
    let mut s = String::new();
    stdin().read_line(&mut s).unwrap();
    let card: Vec<_> = s.split_whitespace().collect();
    let card = card[0].clone().chars().collect::<Vec<_>>();
    let mut s = String::new();
    stdin().read_line(&mut s).unwrap();
    let deck: Vec<_> = s.split_whitespace().collect();
    let deck = deck.iter().map( |c| c.chars().collect::<Vec<_>>()).collect::<Vec<_>>();

    for dc in deck {
        if dc[0] == card[0] || dc[1] == card[1] {
            println!("YES");
            return;
        }
    }

    println!("N");
}