#![allow(unused_imports)]
#![allow(unused_macros)]
#![allow(dead_code)]
#![allow(unused_labels)]

use std::char::*;
use std::cmp::*;
use std::collections::*;
use std::io::*;
use std::str::FromStr;

macro_rules! debug {($($a:expr),*) => {eprintln!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);}}
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 ) * } } ; }
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 ) * } } ; }
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 , usize1 ) => { read_value ! ( $ next , usize ) - 1 } ; ( $ next : expr , $ t : ty ) => { $ next ( ) . parse ::<$ t > ( ) . expect ( "Parse error" ) } ; }

fn read<T: FromStr>() -> T {
    let stdin = stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("failed to read char") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}

use std::f64;

fn min<T: PartialOrd>(a:T, b:T) -> T {
    if a < b { a }
    else { b }
}

fn max<T: PartialOrd>(a:T, b:T) -> T {
    if a < b { b }
    else { a }
}

const MAX:usize = 30;
const INF:i64 = std::i64::MAX;
const MOD:i64 = 1e9 as i64 + 7;

struct Graph {
    e: Vec<Vec<usize>>,
    v: Vec<usize>,
    u: Vec<usize>,
    f: Vec<bool>,
    c: i64,
    vc: Vec<i64>,
}

impl Graph {
    fn new(n:usize) -> Self {
        Graph {
            e: vec![vec![];n],
            v: vec![],
            u: vec![n;n],
            f: vec![false;n],
            c: 0,
            vc: vec![0;n],
        }
    }

    fn dfs(&mut self, crt: usize) {
        if self.f[crt] { return; }
        self.c += 1;
        self.f[crt] = true;
        self.v.push(crt);
        self.vc[crt] = self.c;
        self.u[crt] = self.v.len()-1;
        for i in 0..self.e[crt].len() {
            self.dfs(self.e[crt][i]);
        }
        //debug!(crt, self.c, self.vc[crt]);
        self.vc[crt] = self.c - self.vc[crt];
    }
}

fn binary_search(s: &Vec<i64>, v:i64) -> usize {
    let mut left = 0;
    let mut right = s.len();

    while right-left > 1 {
        let mid = (right+left)/2;
        //debug!(left,mid,right,s[mid]);
        if s[mid] < v { left = mid; }
        else { right = mid; }
    }
    left
}

fn main() {
    //let t:usize = read();

    //'outer: for _ in 0..t {
        let n:usize = read();
        let m:usize = read();
        let mut p:Vec<(usize,usize,i64,usize)> = (0..m).map(|i| (read::<usize>()-1,read::<usize>()-1,read(),i)).collect();

        let mut v = vec![];

        let mut f = vec![false;m];
        let mut c = vec![0;m];
        for i in 0..m { c[i] = p[i].2; }

        for i in 0..n {
            // examがあれば実行
            let mut idx = m;
            for j in 0..m {
                if p[j].1 == i {
                    idx = j;
                }
            }
            if idx != m {
                if c[idx] == 0 {
                    v.push(m+1);
                    continue;
                } else {
                    println!("-1");
                    return;
                }
            }
            // 可能なタスクの中で締め切りの近いものを求める
            let mut idx = m;
            let mut dead = n;
            for j in 0..m {
                if !f[j] && p[j].0 <= i && i < p[j].1 {
                    if dead > p[j].1 {
                        dead = p[j].1;
                        idx = j;
                    }
                }
            }

            // 可能なタスクがない場合は休む
            if idx == m {
                v.push(0);
                continue;
            }

            // タスクを実行
            v.push(idx+1);
            c[idx] -= 1;
            if c[idx] == 0 {
                f[idx] = true;
            }

        }

        for e in v {print!("{} ", e);} println!();

    //}
}

/*

*/

#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::*;
use std::io::{Read, Write, BufWriter};
#[allow(dead_code)]
fn getline() -> String {
    let mut ret = String::new();
    std::io::stdin().read_line(&mut ret).ok().unwrap();
    ret
}
fn get_word() -> String {
    let mut stdin = std::io::stdin();
    let mut u8b: [u8; 1] = [0];
    loop {
        let mut buf: Vec<u8> = Vec::with_capacity(16);
        loop {
            let res = stdin.read(&mut u8b);
            if res.unwrap_or(0) == 0 || u8b[0] <= b' ' {
                break;
            } else {
                buf.push(u8b[0]);
            }
        }
        if buf.len() >= 1 {
            let ret = String::from_utf8(buf).unwrap();
            return ret;
        }
    }
}

#[allow(dead_code)]
fn get<T: std::str::FromStr>() -> T { get_word().parse().ok().unwrap() }

/**
 * Dinic's algorithm for maximum flow problem.
 * Verified by: yukicoder No.177 (http://yukicoder.me/submissions/148371)
 * Min-cut (the second element of max_flow's returned values) is not verified.
 */

#[derive(Clone)]
struct Edge<T> {
    to: usize,
    cap: T,
    rev: usize, // rev is the position of the reverse edge in graph[to]
}

struct Dinic<T> {
    graph: Vec<Vec<Edge<T>>>,
    iter: Vec<usize>,
    zero: T,
}

impl<T> Dinic<T>
    where T: Clone,
          T: Copy,
          T: Ord,
          T: std::ops::AddAssign,
          T: std::ops::SubAssign,
{
    fn bfs(&self, s: usize, level: &mut [Option<usize>]) {
        let n = level.len();
        for i in 0 .. n {
            level[i] = None;
        }
        let mut que = std::collections::VecDeque::new();
        level[s] = Some(0);
        que.push_back(s);
        while let Some(v) = que.pop_front() {
            for e in self.graph[v].iter() {
	        if e.cap > self.zero && level[e.to] == None {
	            level[e.to] = Some(level[v].unwrap() + 1);
	            que.push_back(e.to);
                }
            }
	}
    }
    /* search augment path by dfs.
     * if f == None, f is treated as infinity.
     */
    fn dfs(&mut self, v: usize, t: usize, f: Option<T>, level: &mut [Option<usize>]) -> T {
        if v == t {
            return f.unwrap();
        }
        while self.iter[v] < self.graph[v].len() {
            let i = self.iter[v];
            let e = self.graph[v][i].clone();
            if e.cap > self.zero && level[v] < level[e.to] {
                let newf = std::cmp::min(f.unwrap_or(e.cap), e.cap);
                let d = self.dfs(e.to, t, Some(newf), level);
                if d > self.zero {
                    self.graph[v][i].cap -= d;
                    self.graph[e.to][e.rev].cap += d;
                    return d;
                }
            }
            self.iter[v] += 1;
        }
        self.zero
    }
    pub fn new(n: usize, zero: T) -> Self {
        Dinic {
            graph: vec![Vec::new(); n],
            iter: vec![0; n],
            zero: zero,
        }
    }
    pub fn add_edge(&mut self, from: usize, to: usize, cap: T) {
        let added_from = Edge { to: to, cap: cap,
                            rev: self.graph[to].len() };
        let added_to = Edge { to: from, cap: self.zero,
                            rev: self.graph[from].len() };
        self.graph[from].push(added_from);
        self.graph[to].push(added_to);
    }
    pub fn max_flow(&mut self, s: usize, t: usize) -> (T, Vec<usize>) {
        let mut flow = self.zero;
        let n = self.graph.len();
        let mut level = vec![None; n];
        loop {
            self.bfs(s, &mut level);
            if level[t] == None {
                let ret = (0 .. n).filter(|&i| level[i] == None)
                    .collect();
                return (flow, ret);
            }
            self.iter.clear();
            self.iter.resize(n, 0);
            loop {
                let f = self.dfs(s, t, None, &mut level);
                if f <= self.zero { break; }
                flow += f;
            }
        }
    }
}

fn solve() {
    let out = std::io::stdout();
    let mut out = BufWriter::new(out.lock());
    macro_rules! puts {
        ($format:expr) => (write!(out,$format).unwrap());
        ($format:expr, $($args:expr),+) => (write!(out,$format,$($args),*).unwrap())
    }
    let n = get();
    let m = get();
    let mut s = vec![0; n];
    let mut t = vec![0; n];
    let mut c = vec![0; n];
    let mut ex = vec![false; n];
    for i in 0 .. m {
        s[i] = get::<usize>() - 1;
        t[i] = get::<usize>() - 1;
        c[i] = get::<usize>();
        ex[t[i]] = true;
    }
    let mut din = Dinic::new(2 + n + m, 0);
    let mut expect = 0;
    for i in 0 .. n {
        din.add_edge(0, 2 + i, 1);
    }
    for i in 0 .. m {
        din.add_edge(2 + n + i, 1, c[i]);
        expect += c[i];
    }
    for i in 0 .. m {
        for j in s[i] .. t[i] {
            if !ex[j] {
                din.add_edge(2 + j, 2 + n + i, 1);
            }
        }
    }
    let (ans, _) = din.max_flow(0, 1);
    if ans != expect {
        puts!("-1\n");
        return;
    }
    let mut ans = vec![0; n];
    let graph = din.graph;
    for (i, g) in graph.into_iter().enumerate() {
        if i < 2 || i >= 2 + n { continue; }
        let v = i - 2;
        if ex[v] {
            ans[v] = m + 1;
            continue;
        }
        for Edge { to: to, cap: cap, rev: _ } in g {
            if to < 2 + n { continue; }
            let w = to - 2 - n;
            if cap == 0 {
                ans[v] = 1 + w;
            }
        }
    }
    for i in 0 .. n {
        puts!("{}{}", ans[i], if i == n - 1 { "\n" } else { " " });
    }
}

fn main() {
    // In order to avoid potential stack overflow, spawn a new thread.
    let stack_size = 104_857_600; // 100 MB
    let thd = std::thread::Builder::new().stack_size(stack_size);
    thd.spawn(|| solve()).unwrap().join().unwrap();
}

#![allow(unused_imports)]
#![allow(unused_macros)]
#![allow(dead_code)]
#![allow(unused_labels)]

use std::char::*;
use std::cmp::*;
use std::collections::*;
use std::io::*;
use std::str::FromStr;

macro_rules! debug {($($a:expr),*) => {eprintln!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);}}
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 ) * } } ; }
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 ) * } } ; }
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 , usize1 ) => { read_value ! ( $ next , usize ) - 1 } ; ( $ next : expr , $ t : ty ) => { $ next ( ) . parse ::<$ t > ( ) . expect ( "Parse error" ) } ; }

fn read<T: FromStr>() -> T {
    let stdin = stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("failed to read char") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}

use std::f64;

fn min<T: PartialOrd>(a:T, b:T) -> T {
    if a < b { a }
    else { b }
}

fn max<T: PartialOrd>(a:T, b:T) -> T {
    if a < b { b }
    else { a }
}

const MAX:usize = 30;
const INF:i64 = std::i64::MAX;
const MOD:i64 = 1e9 as i64 + 7;

struct Graph {
    e: Vec<Vec<usize>>,
    v: Vec<usize>,
    u: Vec<usize>,
    f: Vec<bool>,
    c: i64,
    vc: Vec<i64>,
}

impl Graph {
    fn new(n:usize) -> Self {
        Graph {
            e: vec![vec![];n],
            v: vec![],
            u: vec![n;n],
            f: vec![false;n],
            c: 0,
            vc: vec![0;n],
        }
    }

    fn dfs(&mut self, crt: usize) {
        if self.f[crt] { return; }
        self.c += 1;
        self.f[crt] = true;
        self.v.push(crt);
        self.vc[crt] = self.c;
        self.u[crt] = self.v.len()-1;
        for i in 0..self.e[crt].len() {
            self.dfs(self.e[crt][i]);
        }
        //debug!(crt, self.c, self.vc[crt]);
        self.vc[crt] = self.c - self.vc[crt];
    }
}

fn binary_search(s: &Vec<i64>, v:i64) -> usize {
    let mut left = 0;
    let mut right = s.len();

    while right-left > 1 {
        let mid = (right+left)/2;
        //debug!(left,mid,right,s[mid]);
        if s[mid] < v { left = mid; }
        else { right = mid; }
    }
    left
}

fn main() {
    //let t:usize = read();

    //'outer: for _ in 0..t {
        let n:usize = read();
        let m:usize = read();
        let mut p:Vec<(usize,usize,i64,usize)> = (0..m).map(|i| (read::<usize>()-1,read::<usize>()-1,read(),i)).collect();

        p.sort_by(|a,b| a.0.cmp(&b.0));
        //debug!(p);

        let mut e = vec![m;n];
        let mut c = vec![0;m];
        for i in 0..m {
            e[p[i].1] = i;
            c[p[i].3] = p[i].2;
        }

        let mut idx = 0;
        let mut v = vec![];
        for i in 0..n {
            if e[i] != m {
                if c[e[i]] != 0 {
                    println!("-1");
                    return;
                }
                v.push(m+1);
            }
            else if idx == m {
                v.push(0);
            }
            else if i >= p[idx].0 {
                v.push(p[idx].3+1);
                c[p[idx].3] -= 1;
                if c[p[idx].3] == 0 {
                    idx += 1;
                }
            }
            else {
                v.push(0);
            }
        }
        //debug!(v);
        for e in v {print!("{} ", e);} println!();

    //}
}

/*

*/


#[allow(unused_imports)]
use std::cmp::{max, min, Ordering};
#[allow(unused_imports)]
use std::collections::{HashMap, HashSet, BinaryHeap};
#[allow(unused_imports)]
use std::iter::FromIterator;

mod util {
    use std::io::stdin;
    use std::str::FromStr;
    use std::fmt::Debug;

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

    #[allow(dead_code)]
    pub fn get<T: FromStr>() -> T
    where
        <T as FromStr>::Err: Debug,
    {
        let mut line: String = String::new();
        stdin().read_line(&mut line).unwrap();
        line.trim().parse().unwrap()
    }

    #[allow(dead_code)]
    pub fn gets<T: FromStr>() -> Vec<T>
    where
        <T as FromStr>::Err: Debug,
    {
        let mut line: String = String::new();
        stdin().read_line(&mut line).unwrap();
        line.split_whitespace()
            .map(|t| t.parse().unwrap())
            .collect()
    }

    #[allow(dead_code)]
    pub fn get2<T: FromStr, U: FromStr>() -> (T, U)
    where
        <T as FromStr>::Err: Debug,
        <U as FromStr>::Err: Debug,
    {
        let mut line: String = String::new();
        stdin().read_line(&mut line).unwrap();
        let mut iter = line.split_whitespace();
        (
            iter.next().unwrap().parse().unwrap(),
            iter.next().unwrap().parse().unwrap(),
        )
    }

    #[allow(dead_code)]
    pub fn get3<S: FromStr, T: FromStr, U: FromStr>() -> (S, T, U)
    where
        <S as FromStr>::Err: Debug,
        <T as FromStr>::Err: Debug,
        <U as FromStr>::Err: Debug,
    {
        let mut line: String = String::new();
        stdin().read_line(&mut line).unwrap();
        let mut iter = line.split_whitespace();
        (
            iter.next().unwrap().parse().unwrap(),
            iter.next().unwrap().parse().unwrap(),
            iter.next().unwrap().parse().unwrap(),
        )
    }
}

#[allow(unused_macros)]
macro_rules! debug {
    ($x: expr) => {
        println!("{}: {:?}", stringify!($x), $x)
    }
}

fn main() {
    let n: usize = util::get();
    let ss: Vec<Vec<usize>> = (0..n)
        .map(|_| {
            let mut v: Vec<usize> = util::gets();
            v.sort();
            v
        })
        .collect();

    let ans = (1..)
        .take_while(|&x| if x < 10 {
            ss.iter().any(|v| v.binary_search(&x).is_ok())
        } else if x < 100 {
            let a1 = x % 10;
            let a2 = x / 10;

            let h1 = (0..ss.len())
                .filter(|&i| ss[i].binary_search(&a1).is_ok())
                .collect::<HashSet<_>>();
            let h2 = (0..ss.len())
                .filter(|&i| ss[i].binary_search(&a2).is_ok())
                .collect::<HashSet<_>>();

            (h1.len() > 1 && h2.len() > 1) ||
                (h1.len() > 0 && h2.len() > 0 &&
                     (h1.difference(&h2).count() != 0 || h2.difference(&h1).count() != 0))

        } else {
            let perm = vec![
                vec![0, 1, 2],
                vec![0, 2, 1],
                vec![1, 0, 2],
                vec![1, 2, 0],
                vec![2, 0, 1],
                vec![2, 1, 0],
            ];

            let a1 = x % 10;
            let a2 = x / 10 % 10;
            let a3 = x / 100;
            let a = vec![a1, a2, a3];

            if n < 3 {
                false
            } else {
                perm.iter().any(|p| {
                    p.iter().zip(a.iter()).all(|(&i, &k)| {
                        ss[i].binary_search(&k).is_ok()
                    })
                })
            }

        })
        .last();

    if let Some(a) = ans {
        println!("{}", a);
    } else {
        println!("0");
    }

}

use std::io;
use std::str::FromStr;

use std::io::prelude::*;
use std::io::BufReader;
use std::cmp::{max, min};

fn get_line() -> String {
    let mut input = String::new();
    io::stdin().read_line(&mut input).unwrap();
    input
}

fn get_vec<T>() -> Vec<T>
where T: FromStr,
      <T as FromStr>::Err: std::fmt::Debug,
{
    get_line().split_whitespace().map(|k| k.parse().unwrap()).collect()
}

fn extended_euclid(a: i64, b: i64) -> (i64, i64, i64) {
    if b == 0 {
        (a, 1, 0)
    } else {
        let (d0, x0, y0) = extended_euclid(b, a % b);
        (d0, y0, x0 - a / b * y0)
    }
}

fn main() {
    let n: usize = get_line().trim().parse().unwrap();

    let cubes: Vec<_> = BufReader::new(io::stdin()).lines()
        .map(|s| {
            let s = s.unwrap();
            let mut cube = [false; 10];
            for s in s.split_whitespace() {
                let d = s.bytes().last().unwrap();
                let d = (d - b'0') as usize;
                cube[d] = true;
            }
            cube
        }).collect();

    let perms = match n {
        3 => vec![
            vec![0, 1, 2],
            vec![0, 2, 1],
            vec![1, 0, 2],
            vec![1, 2, 0],
            vec![2, 0, 1],
            vec![2, 1, 0],
        ],
        2 => vec![
            vec![0, 1],
            vec![1, 0],
        ],
        1 => vec![vec![0]],
        _ => panic!(""),
    };

    let fact = |n| {
        let mut ret_val = 1;
        for i in 0..n {
            ret_val *= i + 1;
        }
        ret_val
    };

    let check = |x| {
        let x = format!("{}", x);
        for perm in perms.iter().take(fact(n)) {
            let p = x.bytes().map(|b| (b - b'0') as usize)
                .zip(perm.iter()).all(|(d, &i)| cubes[i][d]);
            if p {
                return true;
            }
        }
        false
    };

    for i in 1.. {
        if !check(i) {
            println!("{}", i - 1);
            return;
        }
    }
}

fn read_line() -> String {
    let stdin = std::io::stdin();
    let mut line = String::new();
    stdin.read_line(&mut line).unwrap();
    String::from(line.trim())
}

macro_rules! scan_line {
    ($($ty: ty),*) => {{
        let line = read_line();
        let mut tok = line.split_whitespace();
        ($(tok.next().unwrap().parse::<$ty>().unwrap()),*)
    }}
}

fn check(dice: &[[i32; 6]], digits: &[i32]) -> bool {
    if dice.len() < digits.len() {
        println!("a");
        false
    } else if digits.len() == 0 {
        true
    } else {
        let mut leftover_dice: Vec<[i32; 6]> = dice[1..].iter().cloned().collect();
        let mut has_solution = false;
        for (i, &die) in dice.iter().enumerate() {
            if die.iter().any(|&a| a == digits[0]) && check(&leftover_dice, &digits[1..]) {
                has_solution = true;
                break;
            }
            if i < leftover_dice.len() {
                leftover_dice[i] = die;
            }
        }
        has_solution
    }
}

fn main() {
    let n = scan_line!(i32);
    let mut dice = Vec::new();
    for _ in 0..n {
        let (a, b, c, d, e, f) = scan_line!(i32, i32, i32, i32, i32, i32);
        dice.push([a, b, c, d, e, f]);
    }
    let mut max_valid = 0;
    for i in 1.. {
        let mut digits = Vec::new();
        let mut j = i;
        while j > 0 {
            digits.push(j % 10);
            j /= 10;
        }
        let is_valid = check(&dice, &digits);
        if is_valid {
            max_valid = i;
        } else {
            break;
        }
    }
    println!("{}", max_valid);
}

use std::iter::*;

fn main() {
    let mut inp = ReadIn::new();
    let n = inp.int() as usize;
    let dices: Vec<Vec<i32>> = repeat(()).take(n).map(|_| inp.intvec()).collect();
    let mut res = nums(&dices);
    res.sort();
    let cnt = res.iter().scan(0, |p, &el| {
        if *p + 1 >= el {
            *p = el;
            Some(el)
        } else { None }
    }
    ).last().unwrap();
    println!("{:?}", cnt);
}

fn nums(digs: &Vec<Vec<i32>>) -> Vec<i32> {
    if digs.is_empty() { vec![0] } else {
        digs.iter()
            .enumerate()
            .flat_map(|(i, v)| {
                let mut v1 = digs.clone();
                v1.remove(i);
                nums(&v1)
                    .into_iter()
                    .flat_map(move |n| v
                        .iter()
                        .map(move |d| n * 10 + d)
                        .chain(once(n)))
            })
            .collect()
    }
}

use std::str::SplitWhitespace;
use std::io::stdin;
use std::mem::forget;

pub struct ReadIn(pub String);

impl ReadIn {
    pub fn new() -> ReadIn { ReadIn(String::new()) }
    fn read_i32(s: &str) -> i32 { s.parse().unwrap() }
    pub fn read_line(&mut self) {
        self.0.clear();
        forget(stdin().read_line(&mut self.0));
    }
    pub fn ints(&mut self) -> Map<SplitWhitespace, fn(&str) -> i32> {
        self.read_line();
        self.0.split_whitespace().map(ReadIn::read_i32)
    }
    pub fn intvec(&mut self) -> Vec<i32> { self.ints().collect() }
    pub fn int(&mut self) -> i32 { self.ints().next().unwrap() }
    pub fn int2(&mut self) -> (i32, i32) {
        let mut it = self.ints();
        (it.next().unwrap(), it.next().unwrap())
    }

    pub fn int3(&mut self) -> (i32, i32, i32) {
        let mut it = self.ints();
        (it.next().unwrap(), it.next().unwrap(), it.next().unwrap())
    }
    pub fn int4(&mut self) -> (i32, i32, i32, i32) {
        let mut it = self.ints();
        (it.next().unwrap(), it.next().unwrap(), it.next().unwrap(), it.next().unwrap())
    }
}

use std::iter::*;

fn main() {
    let mut inp = ReadIn::new();
    let n = inp.int() as usize;
    let dices: Vec<Vec<i32>> = repeat(()).take(n).map(|_| inp.intvec()).collect();
    let mut res: Vec<i32> = nums(dices).collect();
    res.sort();
    let cnt = res.iter().scan(0, |p, &el| {
        if *p + 1 >= el {
            *p = el;
            Some(el)
        } else { None }
    }
    ).last().unwrap();
    println!("{:?}", cnt);
}

fn nums<'a>(digs: Vec<Vec<i32>>) -> Box<Iterator<Item=i32> + 'a> {
    if digs.is_empty() { Box::new(once(0)) } else {
        let d1 = digs.clone();
        Box::new(d1.into_iter()
            .enumerate()
            .flat_map(move |(i, v)| {
                let mut v1 = digs.clone();
                v1.remove(i);
                nums(v1)
                    .into_iter()
                    .flat_map(move |n|
                        v.clone()
                            .into_iter()
                            .map(move |d| n * 10 + d)
                            .chain(once(n)))
            }))
    }
}

use std::str::SplitWhitespace;
use std::io::stdin;
use std::mem::forget;

pub struct ReadIn(pub String);

impl ReadIn {
    pub fn new() -> ReadIn { ReadIn(String::new()) }
    fn read_i32(s: &str) -> i32 { s.parse().unwrap() }
    pub fn read_line(&mut self) {
        self.0.clear();
        forget(stdin().read_line(&mut self.0));
    }
    pub fn ints(&mut self) -> Map<SplitWhitespace, fn(&str) -> i32> {
        self.read_line();
        self.0.split_whitespace().map(ReadIn::read_i32)
    }
    pub fn intvec(&mut self) -> Vec<i32> { self.ints().collect() }
    pub fn int(&mut self) -> i32 { self.ints().next().unwrap() }
    pub fn int2(&mut self) -> (i32, i32) {
        let mut it = self.ints();
        (it.next().unwrap(), it.next().unwrap())
    }

    pub fn int3(&mut self) -> (i32, i32, i32) {
        let mut it = self.ints();
        (it.next().unwrap(), it.next().unwrap(), it.next().unwrap())
    }
    pub fn int4(&mut self) -> (i32, i32, i32, i32) {
        let mut it = self.ints();
        (it.next().unwrap(), it.next().unwrap(), it.next().unwrap(), it.next().unwrap())
    }
}

#[allow(unused_imports)]
use std::cmp::{max, min, Ordering};
#[allow(unused_imports)]
use std::collections::{HashMap, HashSet, BinaryHeap};
#[allow(unused_imports)]
use std::iter::FromIterator;

mod util {
    use std::io::stdin;
    use std::str::FromStr;
    use std::fmt::Debug;

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

    #[allow(dead_code)]
    pub fn get<T: FromStr>() -> T
    where
        <T as FromStr>::Err: Debug,
    {
        let mut line: String = String::new();
        stdin().read_line(&mut line).unwrap();
        line.trim().parse().unwrap()
    }

    #[allow(dead_code)]
    pub fn gets<T: FromStr>() -> Vec<T>
    where
        <T as FromStr>::Err: Debug,
    {
        let mut line: String = String::new();
        stdin().read_line(&mut line).unwrap();
        line.split_whitespace()
            .map(|t| t.parse().unwrap())
            .collect()
    }

    #[allow(dead_code)]
    pub fn get2<T: FromStr, U: FromStr>() -> (T, U)
    where
        <T as FromStr>::Err: Debug,
        <U as FromStr>::Err: Debug,
    {
        let mut line: String = String::new();
        stdin().read_line(&mut line).unwrap();
        let mut iter = line.split_whitespace();
        (
            iter.next().unwrap().parse().unwrap(),
            iter.next().unwrap().parse().unwrap(),
        )
    }

    #[allow(dead_code)]
    pub fn get3<S: FromStr, T: FromStr, U: FromStr>() -> (S, T, U)
    where
        <S as FromStr>::Err: Debug,
        <T as FromStr>::Err: Debug,
        <U as FromStr>::Err: Debug,
    {
        let mut line: String = String::new();
        stdin().read_line(&mut line).unwrap();
        let mut iter = line.split_whitespace();
        (
            iter.next().unwrap().parse().unwrap(),
            iter.next().unwrap().parse().unwrap(),
            iter.next().unwrap().parse().unwrap(),
        )
    }
}

#[allow(unused_macros)]
macro_rules! debug {
    ($x: expr) => {
        println!("{}: {:?}", stringify!($x), $x)
    }
}

fn main() {
    let n: usize = util::get();
    let ss: Vec<Vec<usize>> = (0..n)
        .map(|_| {
            let mut v: Vec<usize> = util::gets();
            v.sort();
            v
        })
        .collect();

    let ans = (1..)
        .take_while(|&x| if x < 10 {
            ss.iter().any(|v| v.binary_search(&x).is_ok())
        } else if x < 100 {
            let a1 = x % 10;
            let a2 = x / 10;

            let h1 = (0..ss.len())
                .filter(|&i| ss[i].binary_search(&a1).is_ok())
                .collect::<HashSet<_>>();
            let h2 = (0..ss.len())
                .filter(|&i| ss[i].binary_search(&a2).is_ok())
                .collect::<HashSet<_>>();

            (h1.len() > 1 && h2.len() > 1) || h1.difference(&h2).count() != 0 ||
                h2.difference(&h1).count() != 0

        } else {
            let perm = vec![
                vec![0, 1, 2],
                vec![0, 2, 1],
                vec![1, 0, 2],
                vec![1, 2, 0],
                vec![2, 0, 1],
                vec![2, 1, 0],
            ];

            let a1 = x % 10;
            let a2 = x / 10 % 10;
            let a3 = x / 100;
            let a = vec![a1, a2, a3];

            if n < 3 {
                false
            } else {
                perm.iter().any(|p| {
                    p.iter().zip(a.iter()).all(|(&i, &k)| {
                        ss[i].binary_search(&k).is_ok()
                    })
                })
            }

        })
        .last();

    if let Some(a) = ans {
        println!("{}", a);
    } else {
        println!("0");
    }

}

use std::io;
use std::str::FromStr;

use std::io::prelude::*;
use std::io::BufReader;
use std::cmp::{max, min};

fn get_line() -> String {
    let mut input = String::new();
    io::stdin().read_line(&mut input).unwrap();
    input
}

fn get_vec<T>() -> Vec<T>
where T: FromStr,
      <T as FromStr>::Err: std::fmt::Debug,
{
    get_line().split_whitespace().map(|k| k.parse().unwrap()).collect()
}

fn extended_euclid(a: i64, b: i64) -> (i64, i64, i64) {
    if b == 0 {
        (a, 1, 0)
    } else {
        let (d0, x0, y0) = extended_euclid(b, a % b);
        (d0, y0, x0 - a / b * y0)
    }
}

fn main() {
    let n: usize = get_line().trim().parse().unwrap();

    let cubes: Vec<_> = BufReader::new(io::stdin()).lines()
        .map(|s| {
            let s = s.unwrap();
            let mut cube = [false; 10];
            for s in s.split_whitespace() {
                let d = s.bytes().last().unwrap();
                let d = (d - b'0') as usize;
                cube[d] = true;
            }
            cube
        }).collect();

    let perms = [
        [0, 1, 2],
        [0, 2, 1],
        [1, 0, 2],
        [1, 2, 0],
        [2, 0, 1],
        [2, 1, 0],
    ];

    let fact = |n| {
        let mut ret_val = 1;
        for i in 0..n {
            ret_val *= i + 1;
        }
        ret_val
    };

    let check = |x| {
        let x = format!("{}", x);
        for perm in perms.iter().take(fact(n)) {
            let p = x.bytes().map(|b| (b - b'0') as usize)
                .zip(perm.iter()).all(|(d, &i)| cubes[i][d]);
            if p {
                return true;
            }
        }
        false
    };

    for i in 1.. {
        if !check(i) {
            println!("{}", i - 1);
            return;
        }
    }
}

use std::io;
use std::str::FromStr;

use std::io::prelude::*;
use std::io::BufReader;
use std::cmp::{max, min};

fn get_line() -> String {
    let mut input = String::new();
    io::stdin().read_line(&mut input).unwrap();
    input
}

fn get_vec<T>() -> Vec<T>
where T: FromStr,
      <T as FromStr>::Err: std::fmt::Debug,
{
    get_line().split_whitespace().map(|k| k.parse().unwrap()).collect()
}

fn extended_euclid(a: i64, b: i64) -> (i64, i64, i64) {
    if b == 0 {
        (a, 1, 0)
    } else {
        let (d0, x0, y0) = extended_euclid(b, a % b);
        (d0, y0, x0 - a / b * y0)
    }
}

fn main() {
    let n: usize = get_line().trim().parse().unwrap();

    let cubes: Vec<_> = (0..n).map(|_| {
        let v: Vec<usize> = get_vec();
        v
    }).collect();

    let mut digits = vec![0; 10];
    for cube in cubes {
        for x in cube {
            digits[x] += 1;
        }
    }

    let last1 = digits.iter().skip(1).position(|&x| x == 0);
    if let Some(i) = last1 {
        println!("{}", i);
        return;
    }

    let first = digits.iter().skip(1).position(|&x| x < 2).unwrap() + 1;
    println!("{}", first * 10 + first - 1);
}

use std::io;
use std::str::FromStr;

use std::io::prelude::*;
use std::io::BufReader;
use std::cmp::{max, min};

fn get_line() -> String {
    let mut input = String::new();
    io::stdin().read_line(&mut input).unwrap();
    input
}

fn get_vec<T>() -> Vec<T>
where T: FromStr,
      <T as FromStr>::Err: std::fmt::Debug,
{
    get_line().split_whitespace().map(|k| k.parse().unwrap()).collect()
}

fn extended_euclid(a: i64, b: i64) -> (i64, i64, i64) {
    if b == 0 {
        (a, 1, 0)
    } else {
        let (d0, x0, y0) = extended_euclid(b, a % b);
        (d0, y0, x0 - a / b * y0)
    }
}

fn main() {
    let n: usize = get_line().trim().parse().unwrap();

    let cubes: Vec<_> = (0..n).map(|_| {
        let v: Vec<usize> = get_vec();
        v
    }).collect();

    let mut digits = vec![0; 10];
    for cube in cubes {
        for x in cube {
            digits[x] += 1;
        }
    }

    let last1 = digits.iter().rposition(|&x| x >= 1).unwrap();
    if last1 != 9 {
        println!("{}", last1);
        return;
    }

    let first = digits.iter().skip(1).position(|&x| x < 2).unwrap() + 1;
    println!("{}", first * 10 + first - 1);
}


fn read_str() -> String {
    let mut buffer: String = String::new();
    std::io::stdin().read_line(&mut buffer).expect("Error");
    buffer.trim().to_string()
}

fn read_vec() -> Vec<u32> {
    read_str().trim()
        .split_whitespace()
        .map(|value| value
            .parse::<u32>()
            .expect("Error"))
        .collect()
}

fn main() {
    let mut total: u32 = 0;
    let (k, n, w): (u32, u32, u32) =  {
        let values: Vec<u32> = read_vec();
        (values[0], values[1], values[2])
    };

    for index in 1..w + 1 {
        total += index * k;
    }

    if total >= n { total -= n; }
    else { total = 0; }

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

fn main() {
    let mut text = String::new();
    std::io::stdin().read_line(&mut text).expect("");
    let it : Vec<i32> = text.trim().split_whitespace().map(|x| x.parse::<i32>().expect("")).collect();
    let k = it[0];
    let n = it[1];
    let w = it[2];
    println!("{}", std::cmp::max((w + 1) * w / 2 * k - n, 0));
}

#[allow(unused)] use std::io::*;
#[allow(unused)] use std::collections::*;
#[allow(unused)] use std::mem::*;
#[allow(unused)] use std::num::*;
#[allow(unused)] use std::cmp::*;
#[allow(unused)] fn strarr() -> Vec<String> {
    let mut inp = String::new();
    stdin().read_line(&mut inp).ok();
    inp.split(' ').map(|x| x.trim()).filter(|x| x.len() != 0).map(|x| x.to_string()).collect() }
#[allow(unused)] macro_rules! scan { ($($x:ty), +) => {{
    let s = strarr(); let mut cnt : usize = 0;
    fn next<T>(cnt: &mut usize, p: &Vec<String>) -> T
        where T:std::str::FromStr
        { *cnt += 1; p[*cnt-1].parse().ok().unwrap() }
    ($(next::<$x>(&mut cnt, &s)), +)
    }}; }
#[allow(unused)] macro_rules! arr { ($n:expr, $T:ty) => {{
    let mut s = strarr(); let mut v = Vec::new();
    for i in 0..$n { v.push(s[i as usize].parse::<$T>().unwrap()); } v
    }}; }

///////////////////////////////////////////////////////////////////////////////

fn main()
{
    let (k, n, w) = scan!(i64, i64, i64);
    let req = k * (w * (w + 1)) / 2 - n;
    println!("{}", max(req, 0));
}

use std::io;
use std::io::prelude::*;
fn main() {
    let mut inputnum = String::new();
    io::stdin().read_line(&mut inputnum).expect("Error");
    let mut result : Vec<i64> = inputnum.split_whitespace().map(|x| x.parse::<i64>().unwrap()).collect();
    let totalcost:i64= (result[0]*(result[2]*(result[2]+1)))/2;
    if totalcost-result[1]>0{
        println!("{}",totalcost-result[1]);
    }
    else{
        println!("0");
    }
}

use std::io;
use std::io::prelude::*;
fn main() {
    let mut inputnum = String::new();
    io::stdin().read_line(&mut inputnum).expect("Error");
    let mut result : Vec<i64> = inputnum.split_whitespace().map(|x| x.parse::<i64>().unwrap()).collect();
    let totalcost:i64= (result[0]*(result[2]*(result[2]+1)))/2;
    let diff:i64= totalcost-result[1];
    if diff>0{
        println!("{}",diff);
    }
    else{
        println!("0");
    }
}

use std::io;
use std::io::prelude::*;
fn main() {
    let mut inputnum = String::new();
    io::stdin().read_line(&mut inputnum).expect("Error");
    let result : Vec<i64> = inputnum.split_whitespace().map(|x| x.parse::<i64>().unwrap()).collect();
    let totalcost:i64= (result[0]*(result[2]*(result[2]+1)))/2;
    if totalcost>result[1]{
        println!("{}",totalcost-result[1]);
    }
    else{
        println!("0");
    }
}

fn main() {
    let (k, n, w) = {
        let mut buf = String::new();
        std::io::stdin().read_line(&mut buf).unwrap();
        let nums: Vec<u32> = buf
            .trim()
            .split_whitespace()
            .map(|a| a.parse().unwrap())
            .collect();
        (nums[0], nums[1], nums[2])
    };

    let total_price = (w * (w + 1) / 2) * k;
    if total_price <= n {
        print!("0");
    } else {
        print!("{}", total_price - n);
    }
}

//spnauti-rust
#[allow(unused_imports)]
use std::io::{self,Read};

struct WordReader {
    it : std::vec::IntoIter<String>,
}
#[allow(dead_code)]
impl WordReader {
    fn new<T : Read>(mut reader : T) -> WordReader {
        let mut s = String::new();
        reader.read_to_string(&mut s).unwrap();
        WordReader { it : s
            .split_ascii_whitespace()
            .map(String::from).collect::<Vec<_>>()
            .into_iter()
        }
    }
    fn from_stdin() -> WordReader {
        WordReader::new(std::io::stdin())
    }
    fn s(&mut self) -> String {
        self.it.next().unwrap()
    }
    fn ab(&mut self) -> Vec<u8> {
        self.it.next().unwrap().into_bytes()
    }
    fn i(&mut self) -> i32 {
        self.it.next().unwrap().parse().unwrap()
    }
}

fn main() {
    let mut input = WordReader::from_stdin();
    let k = input.i();
    let n = input.i();
    let w = input.i();
    let sol = std::cmp::max(0, k * w * (w + 1) / 2 - n);
    println!("{}", sol);
}

fn main() {
    let v: Vec<i32> = {
        let mut line = String::new();
        std::io::stdin().read_line(&mut line);
        line.trim().split(" ").map(|s| s.parse::<i32>().unwrap()).collect()
    };

    let (first, total, n) = (v[0], v[1], v[2]);
    println!("{:?}",
             std::cmp::max((0..n).fold(0, |total, i| total + first * (i + 1)) - total,
                           0));

}

/*
    Brute force - http://codeforces.com/problemset/problem/271/A
    Completed: 2/7/20 16:30
*/

use std::io;

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

    let vector: Vec<&str> = input.trim().split(" ").collect();

    let bananas = &vector[2].parse::<i32>().unwrap();
    let dollars = &vector[1].parse::<i32>().unwrap();
    let initial_cost = &vector[0].parse::<i32>().unwrap();
    let mut current_banana = 0;
    let mut final_cost = 0;
    let mut borrow;

    for _ in 0..*bananas {
        current_banana += 1;
        final_cost += initial_cost * current_banana;
    }

    borrow = *dollars - final_cost;

    if borrow < 0 {
        borrow = -borrow;
        println!("{}", borrow);
    } else {
        println!("0");
    }

}

fn read() -> String {
    let mut res = String::new();
    std::io::stdin().read_line(&mut res).expect("???");
    res
}

fn parse_int(s: &str) -> usize {
    s.trim().parse().expect("???")
}

fn parse_ints(s: &str) -> Vec<usize> {
    s.split_whitespace().map(parse_int).collect()
}

fn main() {
    let v = parse_ints(&read());
    let k = v[0];
    let n = v[1];
    let w = v[2];
    let cost = k * (w * (w + 1)) / 2;
    let borrow = std::cmp::max(cost as i32 - n as i32, 0);
    println!("{}", borrow);
}

use std::io;

fn main() {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    let read_in = buf.split_whitespace().map(|c| c.trim().parse::<usize>().unwrap()).collect::<Vec<usize>>();
    let (k, n, w) = (read_in[0], read_in[1], read_in[2]);
    let cost = w * (w + 1) / 2 * k;
    let ret: usize;
    if cost <= n {
        ret = 0;
    } else {
        ret = cost - n;
    }
    println!("{}", ret);
}

use std::io;

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

    let knw = s.split_whitespace()
        .map(|x| x.parse::<u64>().unwrap())
        .collect::<Vec<_>>();
    let needed = knw[2]*(knw[2] + 1)/2 * knw[0];

    if needed > knw[1] {
        println!("{}", needed - knw[1]);
    } else {
        println!("0");
    }
}

use std::io;
use std::cmp;

fn read_line() -> String {
    let mut line = String::new();
    io::stdin().read_line(&mut line).unwrap();
    line
}

fn main() {

    let line = read_line();
    let mut vs = line.trim().split_whitespace().map(|s| s.parse::<i32>().unwrap());
    let k = vs.next().unwrap();
    let n = vs.next().unwrap();
    let w = vs.next().unwrap();

    // 1k, 2k, 3k, ... wk
    // (1+w)w/2*k

    let need = (1 + w) * w / 2 * k;
    println!("{}", cmp::max(0, need - n));
}

use std::io::*;

fn reads<T: std::str::FromStr>(i: &mut StdinLock) -> Vec<T> {
    let mut s = String::new();
    i.by_ref().read_line(&mut s).ok();
    s.trim()
        .split_whitespace()
        .map(|e| e.parse().ok().unwrap())
        .collect()
}

fn main() {
    // initialize stdin
    let sin = std::io::stdin();
    let mut sin = sin.lock();
    let sin = &mut sin;

    let input: Vec<i64> = reads(sin);

    let ic_banana = input[0];
    let cash = input[1];
    let wants = input[2];

    let total_cost = (1..wants + 1)
        .map(|x| x * ic_banana)
        .fold(0, |acc, x| acc + x);

    if cash < total_cost {
        println!("{}", total_cost - cash);
    } else {
        println!("0");
    }
}

use std::io;
fn main() {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    // (unit_price, money, count)
    let v: Vec<_> = buf
        .trim()
        .split_whitespace()
        .map(|x| x.parse::<u32>().unwrap())
        .collect();
    let total_price = (v[2] + 1) * v[2] / 2 * v[0];
    if v[1] >= total_price {
        println!("{}", 0);
    } else {
        println!("{}", total_price - v[1]);
    }
}

fn read()->Vec<i32>{
    let mut line=String::new();
    std::io::stdin().read_line(&mut line).unwrap();
    line.split_whitespace().map(|x|x.parse::<i32>().unwrap()).collect()
}
fn main(){
    let a=read();
    let money=(2*a[0]+a[0]*(a[2]-1))*a[2]/2;
    let owe=money-a[1];
    if owe>0{
        print!("{}",owe)
    }
    else{print!("0")}
}

use std::io::BufRead;

fn main() {
    let i: Vec<i32> = std::io::stdin()
    .lock()
    .lines()
    .next()
    .expect("stdin not work")
    .expect("stdin not work")
    .trim()
    .split(' ')
    .map(|s| s.parse::<i32>().expect("not number"))
    .collect();
    println!("{}", std::cmp::max((1 + i[2])*i[2]*i[0]/2-i[1], 0));
}

use std::io;

fn read() -> String{
    let mut input=String::new();
    io::stdin().read_line(&mut input).expect("unable to read");
    input.trim().to_string()
}
fn main() {
    let inp=read();
    let list: Vec<_>=inp.split_whitespace().collect();
    let price=list[0].parse::<i32>().expect("Failed to parse");
    let money=list[1].parse::<i32>().expect("Failed to parse");
    let total=list[2].parse::<i32>().expect("Failed to parse");
    let mut sum=0;
    for i in 1..total+1{
        sum+=price*i;
    }sum-=money;
    if sum>0{
        println!("{}",sum);
    }else{
        println!("{}",0)
    }
}

use std::io;

fn main() {
    let mut input = String::new();

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

    let words: Vec<i64> =
        input
        .split_whitespace()
        .map(|x| x.parse().unwrap())
        .collect();

    let k = words[0];
    let n = words[1];
    let w = words[2];

    let mut total = 0;

    for i in 1..w+1 {
        total += i*k;
    }

    let borrow = total - n;

    let answer = std::cmp::max(0, borrow);

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

use std::io;

fn main() {
    let mut input = String::new();

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

    let words: Vec<i64> =
        input
        .split_whitespace()
        .map(|x| x.parse().unwrap())
        .collect();

    let k = words[0];
    let n = words[1];
    let w = words[2];

    let mut total = w*(w+1)/2*k;

    let borrow = total - n;

    let answer = std::cmp::max(0, borrow);

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

use std::io::stdin;
fn main() {
    let (banana_price, dolar_amount, banana_wanted) = parse_param();
    let price_to_pay = fact_add(banana_wanted, banana_price);
    if price_to_pay > dolar_amount {
        println!("{}", price_to_pay - dolar_amount)
    } else {
        println!("0")
    }
}

fn parse_param() -> (usize, usize, usize) {
    let mut entry_text = String::new();
    stdin().read_line(&mut entry_text).expect("msg: &str");
    let a: Vec<&str> = entry_text.trim().split_whitespace().collect();
    (
        a[0].parse().expect(""),
        a[1].parse().expect(""),
        a[2].parse().expect(""),
    )
}
fn fact_add(x: usize, y: usize) -> usize {
    if x <= 1 {
        return y;
    }
    (x * y) + fact_add(x - 1, y)
}

use std::io;

fn main() {
    let mut s = String::new();
    io::stdin().read_line(&mut s).unwrap();
    let arr : Vec<i64> = s.split_whitespace().map(|s| s.parse().unwrap()).collect();
    let k = arr[0];
    let n = arr[1];
    let w = arr[2];
    let sum = (1 + w) * w / 2 * k;
    if sum > n {
        println!("{}", sum - n);
    } else {
        println!("0");
    }
}

use std::cmp;

fn read_int_line() -> Vec<i64> {
    // Read vector of integers
    let cin = std::io::stdin();
    let mut line = String::new();
    cin.read_line(&mut line).unwrap();
    let values: Vec<i64> = line
                            .split_whitespace()
                            .map(|x| x.parse::<i64>().unwrap())
                            .collect();
    values
}

fn main() {
	let values: Vec<i64> = read_int_line();
	let k: i64 = values[0];
	let n: i64 = values[1];
	let w: i64 = values[2];

	let sum: i64 = w * (w + 1) / 2 * k;
	let mut ans: i64 = sum - n;

	ans = cmp::max(ans, 0);
	print!("{}", ans);
}

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

fn main() {
    let stdin = io::stdin();
    let vector:Vec<i32> = stdin.lock().lines().next().unwrap().unwrap().trim().split(' ').map(|s| s.parse().unwrap()).collect();
    let x = vector[0] * (( vector[2] * (vector[2] + 1) ) / 2 ) ;
    if vector[1] > x {
        println!("{}", 0);
    } else {
        println!("{}", x - vector[1]);
    }
}

fn main(){
    let mut a = Vec::with_capacity(3);
    let mut val = String::new();
    std::io::stdin().read_line(&mut val).unwrap();
    let val = val.trim().parse::<String>().unwrap();
    for j in val.split_whitespace(){
        let k = j.trim().parse::<i32>().unwrap();
        a.push(k);
    }
    let mut ans : i32 = 0;
    for p in 1..a[2]+1{
        ans += a[0]*p;
    }
    let last = ans - a[1];
    if last > 0 {
        println!("{}",last);
    }
    else{
        println!("0");
    }
}

fn main() {
    let mut buffer = String::new();

    std::io::stdin().read_line(&mut buffer).unwrap();

    let n: Vec<i32> = buffer
        .trim().split(' ')
        .map(|s: &str| s.parse::<i32>().unwrap())
        .collect();

    let sum = (1..=n[2]).sum::<i32>() * n[0];

    if sum > n[1] {
        println!("{}", sum - n[1])
    } else {
        println!("0")
    }
}

fn read_str() -> String {
    let mut buffer: String = String::new();
    std::io::stdin().read_line(&mut buffer).expect("Error");
    buffer.trim().to_string()
}

fn read_vec() -> Vec<u32> {
    read_str().trim()
        .split_whitespace()
        .map(|value| value
            .parse::<u32>()
            .expect("Error"))
        .collect()
}

fn main() {
    let (k, n, w): (u32, u32, u32) =  {
        let values: Vec<u32> = read_vec();
        (values[0], values[1], values[2])
    };

        let mut total: u32 = (1 + w) * w * k / 2;
    if total >= n { total -= n; }
    else { total = 0; }

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

use std::str::FromStr;

fn read_str() -> String {
    let mut buffer: String = String::new();
    std::io::stdin().read_line(&mut buffer).expect("Error");
    buffer.trim().to_string()
}

fn read_vec<T: FromStr>(split_char: char) -> Vec<T> {
    read_str()
        .split(split_char)
        .map(|value| value.parse::<T>().ok().expect("Error"))
        .collect()
}

fn main() {
    let (k, n, w): (u32, u32, u32) =  {
        let values: Vec<u32> = read_vec(' ');
        (values[0], values[1], values[2])
    };

    println!("{}", ((1 + w) * w * k / 2).saturating_sub(n));
}

use std::io::{Read, Write, stdin, stdout};

pub struct Scanner<U: Sized + Read> {
    pub buffer: Vec<String>,
    pub reader: U,
}
impl<U: Sized + Read> Scanner<U> {
    pub 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();
            self.reader.read_to_string(&mut input).expect("Failed read");
            self.buffer = input.lines().rev().map(String::from).collect();
        }
    }

    pub fn new(reader: U) -> Self {
        return Scanner {
            buffer: vec![],
            reader,
        };
    }
}

pub fn solution_of_p546a(input: &mut Read, out: &mut Write) {
    let mut scanner = Scanner::new(input);
    let arr: Vec<usize> = scanner.next::<String>().split(' ').map(|e| {
        e.parse::<usize>().unwrap()
    }).collect();
    let k = arr[0];
    let n = arr[1];
    let w = arr[2];
    let mut s = 0;
    for i in 1..=w {
        s += i * k;
    }
    if s > n {
        write!(out, "{}", s - n).ok();
    } else {
        write!(out, "{}", 0).ok();
    }
}

fn main() {
    solution_of_p546a(&mut stdin(), &mut stdout());
}

use std::io;
use std::io::Stdin;
use std::str::FromStr;

fn read_line(stdin : &Stdin, line : &mut String) {
    match stdin.read_line(line) {
        Ok(_) => return,
        Err(msg) => panic!("Could not read line! Message: {}.", msg),
    }
}

fn parse_t<T : FromStr>(s : &str) -> T {
    match s.trim().parse() {
        Ok(y) => y,
        Err(_) => panic!("Could not read from string!"),
    }
}

fn read_ts<T : FromStr>(stdin : &Stdin, ts : &mut Vec<T>) {
    let mut line = String::new();
    read_line(stdin, &mut line);
    let word_iter = line.split_whitespace();
    for word in word_iter {
        let x = parse_t(word);
        ts.push(x);
    }
}

fn sum_1_through_n(n : u64) -> u64 {
    // Do the division before the multiplication
    // so that the result does not overflow sooner.
    if (n % 2) == 0 {
        (n / 2) * (n + 1)
    } else {
        n * ((n + 1) / 2)
    }
}

fn main() {
    let stdin = io::stdin();
    let mut knw = vec![];
    read_ts(&stdin, &mut knw);
    let k = knw[0];
    let n = knw[1];
    let w = knw[2];
    let needed_amount = k * sum_1_through_n(w);
    if needed_amount > n {
        let x = needed_amount - n;
        println!("{}", x);
    } else {
        println!("{}", 0);
    }
}

use std::io;
use std::io::prelude::*;
use std::cmp;
macro_rules! scan {
    (  $( $x:ty ),+ ) => {{
    let mut s =String::new();
        io::stdin().read_line(& mut s);

        let mut iter = s.split_whitespace();
        ($(iter.next().and_then(|word| word.parse::<$x>().ok()).unwrap(),)*)
    }}
}

fn main(){

    let (k,n,w)= scan!(i64,i64,i64);

    let r =cmp::max(0i64, (w*(w+1))/2 *k -n);
    print!("{}",r);

}

use std::io;
use std::io::prelude::*;
use std::cmp;
macro_rules! scan {
    ( $string:expr, $( $x:ty ),+ ) => {{
        let mut iter = $string.split_whitespace();
        ($(iter.next().and_then(|word| word.parse::<$x>().ok()).unwrap(),)*)
    }}
}

fn main(){

   let mut s= String::new();
    io::stdin().read_line(& mut s);

    let (k,n,w)= scan!(s,i64,i64,i64);

    let r =cmp::max(0i64, (w*(w+1))/2 *k -n);
    print!("{}",r);

}

use std::io;
use std::io::prelude::*;
use std::cmp;
macro_rules! scan {
    ( $string:expr, $( $x:ty ),+ ) => {{
        let mut iter = $string.split_whitespace();
        ($(iter.next().and_then(|word| word.parse::<$x>().ok()).unwrap(),)*)
    }}
}

fn main(){

   let mut s= String::new();
    io::stdin().read_line(& mut s);

    let mut it= s.split_whitespace();
    let (k,n,w)= scan!(s,i64,i64,i64);

    let r =cmp::max(0i64, (w*(w+1))/2 *k -n);
    print!("{}",r);

}

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

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

    let mut it= s.split_whitespace();
    let k= it.next().unwrap().parse::<i64>().unwrap();
    let  n=it.next().unwrap().parse::<i64>().unwrap();
    let w=it.next().unwrap().parse::<i64>().unwrap();
    let r =cmp::max(0i64, (w*(w+1))/2 *k -n);
    print!("{}",r);

}

fn readln() -> Vec<i64> {
    let mut line = String::new();
    std::io::stdin().read_line(&mut line).unwrap();

    line.split_whitespace()
        .map(|s| s.parse().unwrap())
        .collect()
}

fn main() {
    let mut input = readln();

    let k = input[0];
    let n = input[1];
    let w = input[2];

    let mut ans = w * (w + 1) / 2 * k - n;
    if ans < 0 {
        ans = 0;
    }

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

fn readln() -> Vec<i64> {
    let mut line = String::new();
    std::io::stdin().read_line(&mut line).unwrap();

    line.split_whitespace()
        .map(|s| s.parse().unwrap())
        .collect()
}

fn main() {
    let mut input = readln();

    let k = input[0];
    let n = input[1];
    let w = input[2];

    println!("{}", std::cmp::max(0, w * (w + 1) / 2 * k - n));
}

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

fn main() {
    let mut line = String::new();
    io::stdin().read_line(&mut line).expect("Failed to read line");

    let vec: Vec<&str> = line.split(" ").collect();
    let a: i64 = vec[0].trim().parse().unwrap();
    let b: i64 = vec[1].trim().parse().unwrap();
    let c: i64 = vec[2].trim().parse().unwrap();
    println!("{}", max(0,a*(c+1)*c/2-b));
}

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

fn main() -> io::Result<()> {
    let mut input = String::new();
    io::stdin().read_to_string(&mut input)?;
    let mut ts = input.split_whitespace();
    let k : i64 = ts.next().expect("a").parse().expect("b");
    let n : i64 = ts.next().expect("c").parse().expect("d");
    let w : i64 = ts.next().expect("e").parse().expect("f");
    let a = (w * (w + 1) / 2 * k - n).max(0);
    println!("{}", a);
    Ok(())
}

use std::io;

fn main() {
	let mut inp = String::new();
	io::stdin().read_line(&mut inp).unwrap();
	let inp = inp.trim();
	let k: i32 = inp.split_whitespace().nth(0).unwrap().parse().unwrap();
	let n: i32 = inp.split_whitespace().nth(1).unwrap().parse().unwrap();
	let w: i32 = inp.split_whitespace().nth(2).unwrap().parse().unwrap();
	let mut all_money = 0;
	for i in 1..(w+1) {
		all_money += i*k;
	}
	if all_money - n <= 0 {
		println!("0");
	} else {
		println!("{}", all_money - n);
	}
}

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

    let mut numbers = buf.trim_end().split_whitespace();
    let first_banana_price = numbers.next().unwrap().parse::<u32>().unwrap();
    let money_amount       = numbers.next().unwrap().parse::<u32>().unwrap();
    let number_of_bananas  = numbers.next().unwrap().parse::<u32>().unwrap();

    let mut total_cost = 0;

    for index in 0..number_of_bananas {
        total_cost += (index + 1) * first_banana_price;
    }

    if total_cost <= money_amount {
        println!("{}", 0);
    }
    else {
        println!("{}", total_cost - money_amount);
    }
}

use std::io;

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

    let mut iter = input.split_whitespace();
    let k: u32 = iter.next().unwrap().parse().unwrap();
    let n: u32 = iter.next().unwrap().parse().unwrap();
    let w: u32 = iter.next().unwrap().parse().unwrap();

    let mut total_cost = 0;
    let mut output = 0;

    for i in 1..=w {
        total_cost += k * i;
    }

    if total_cost > n {
        output = total_cost - n;
    }

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

use std::io;
use std::cmp;

fn main() {
    let mut input_line = String::new();
    io::stdin().read_line(&mut input_line)
        .expect("Failed to read line");

    let nums: Vec<i32> = input_line.trim().split(' ')
        .map(|s| s.parse::<i32>().expect("oops"))
        .collect();

    let k = nums[0];
    let n = nums[1];
    let w = nums[2];

    let mut cost = 0;

    for i in 1..w + 1 {
        cost += k * i;
    }

    let b = cmp::max(cost - n, 0);

    println!("{}", b);

}

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 k = scan.next::<i64>();
	let n = scan.next::<i64>();
	let w = scan.next::<i64>();

    let sum: i64 = (1..w+1).map(|x| x * k).sum();
    let res = if n - sum > 0 { 0 } else { sum - n };

    writeln!(out, "{}", res).expect("fail");
}

fn main() {
    let v: Vec<i32> = {
        let mut line = String::new();
        std::io::stdin().read_line(&mut line);
        line.trim().split(" ").map(|s| s.parse::<i32>().unwrap()).collect()
    };

    let (first, total, n) = (v[0], v[1], v[2]);
    println!("{:?}",
             (0..n).fold(0, |total, i| total + first * (i + 1)) - total);
}

/*
    Brute force - http://codeforces.com/problemset/problem/271/A
    Completed: 2/7/20 16:30
*/

use std::io;

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

    let vector: Vec<&str> = input.trim().split(" ").collect();

    let bananas = &vector[2].parse::<i32>().unwrap();
    let dollars = &vector[1].parse::<i32>().unwrap();
    let initial_cost = &vector[0].parse::<i32>().unwrap();
    let mut current_banana = 0;
    let mut final_cost = 0;
    let mut borrow;

    for _ in 0..*bananas {
        current_banana += 1;
        final_cost += initial_cost * current_banana;
    }

    borrow = final_cost - *dollars;

    if borrow < 0 {
        borrow = -borrow;
    }

    println!("{}", borrow);

}

use std::io;

fn main() {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    let read_in = buf.split_whitespace().map(|c| c.trim().parse::<usize>().unwrap()).collect::<Vec<usize>>();
    let (k, n, w) = (read_in[0], read_in[1], read_in[2]);
    let ret = w * (w + 1) / 2 * k - n;
    println!("{}", ret);
}

use std::io;

fn main() {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    let read_in = buf.split_whitespace().map(|c| c.trim().parse::<usize>().unwrap()).collect::<Vec<usize>>();
    let (k, n, w) = (read_in[0], read_in[1], read_in[2]);
    let cost = w * (w + 1) / 2 * k;
    let ret: usize;
    if cost >= n {
        ret = 0;
    } else {
        ret = n - cost;
    }
    println!("{}", ret);
}

fn read()->Vec<i32>{
    let mut line=String::new();
    std::io::stdin().read_line(&mut line).unwrap();
    line.split_whitespace().map(|x|x.parse::<i32>().unwrap()).collect()
}
fn main(){
    let a=read();
    let money=(2*a[0]+a[0]*(a[2]-1))*a[2]/2;
    let owe=money-a[1];
    if owe>0{
        print!("{}",owe)
    }
    else{print!("0")}
    print!("{}",money)
}

fn read()->Vec<i32>{
    let mut line=String::new();
    std::io::stdin().read_line(&mut line).unwrap();
    line.split_whitespace().map(|x|x.parse::<i32>().unwrap()).collect()
}
fn main(){
    let a=read();
    let money=(2*a[0]+a[0]*(a[2]-1))/2*a[2];
    let owe=money-a[1];
    if owe>0{
        print!("{}",owe)
    }
    else{print!("0")}
}

use std::io;

fn read() -> String{
    let mut input=String::new();
    io::stdin().read_line(&mut input).expect("unable to read");
    input.trim().to_string()
}
fn main() {
    let inp=read();
    let list: Vec<_>=inp.split_whitespace().collect();
    let price=list[0].parse::<i32>().expect("Failed to parse");
    let money=list[1].parse::<i32>().expect("Failed to parse");
    let total=list[2].parse::<i32>().expect("Failed to parse");
    let mut sum=0;
    for i in 1..total+1{
        sum+=price*i;
    }println!("{}",sum-money);
}

use std::io::stdin;
fn main() {
    let (banana_price, dolar_amount, banana_wanted) = parse_param();
    println!("{}", fact_add(banana_wanted, banana_price) - dolar_amount)
}

fn parse_param() -> (usize, usize, usize) {
    let mut entry_text = String::new();
    stdin().read_line(&mut entry_text).expect("msg: &str");
    let a: Vec<&str> = entry_text.trim().split_whitespace().collect();
    (
        a[0].parse().expect(""),
        a[1].parse().expect(""),
        a[2].parse().expect(""),
    )
}
fn fact_add(x: usize, y: usize) -> usize {
    if x <= 1 {
        return y;
    }
    (x * y) + fact_add(x - 1, y)
}

fn read_int_line() -> Vec<i64> {
    // Read vector of integers
    let cin = std::io::stdin();
    let mut line = String::new();
    cin.read_line(&mut line).unwrap();
    let values: Vec<i64> = line
                            .split_whitespace()
                            .map(|x| x.parse::<i64>().unwrap())
                            .collect();
    values
}

fn main() {
	let values: Vec<i64> = read_int_line();
	let k: i64 = values[0];
	let n: i64 = values[1];
	let w: i64 = values[2];

	let sum: i64 = w * (w + 1) / 2 * k;
	let ans: i64 = sum - n;

	print!("{}", ans);
}

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

fn main() {
    let stdin = io::stdin();
    let vector:Vec<u32> = stdin.lock().lines().next().unwrap().unwrap().trim().split(' ').map(|s| s.parse().unwrap()).collect();
    let mut sum = 0;
    for i in 1..(vector[2] + 1) {
        sum = sum + (i * vector[0]);
    }
    println!("{}", sum - vector[1]);
}

fn main(){
    let mut a = Vec::with_capacity(3);
    let mut val = String::new();
    std::io::stdin().read_line(&mut val).unwrap();
    let val = val.trim().parse::<String>().unwrap();
    for j in val.split_whitespace(){
        let k = j.trim().parse::<i32>().unwrap();
        a.push(k);
    }
    let mut ans : i32 = 0;
    for p in 1..a[2]+1{
        ans += a[0]*p;
    }
    let last = ans - a[1];
    println!("{}",last);
}

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

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

    let mut it= s.split_whitespace();
    let k= it.next().unwrap().parse::<i64>().unwrap();
    let  n=it.next().unwrap().parse::<i64>().unwrap();
    let w=it.next().unwrap().parse::<i64>().unwrap();
    let r =(w*(w+1))/2 *k -n;
    print!("{}",r);

}

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

fn main() {
    let mut line = String::new();
    io::stdin().read_line(&mut line).expect("Failed to read line");

    let vec: Vec<&str> = line.split(" ").collect();
    let a: u64 = vec[0].trim().parse().unwrap();
    let b: u64 = vec[1].trim().parse().unwrap();
    let c: u64 = vec[2].trim().parse().unwrap();
    println!("{}", max(0,a*(c+1)*c/2-b));
}

use std::io;

fn main() {
	let mut inp = String::new();
	io::stdin().read_line(&mut inp).unwrap();
	let inp = inp.trim();
	let k: i32 = inp.split_whitespace().nth(0).unwrap().parse().unwrap();
	let n: i32 = inp.split_whitespace().nth(1).unwrap().parse().unwrap();
	let w: i32 = inp.split_whitespace().nth(2).unwrap().parse().unwrap();
	let mut all_money = 0;
	for i in 1..(w+1) {
		all_money += i*k;
	}
	println!("{}", all_money - n);
}


#[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,
    }
    if s.len() % 2 == 0 {
        let n = s.len();
        let m = s.len() / 2;
        let mut res = String::new();
        for i in (0..m).rev() {
            res.push(s[i]);
            res.push(s[n-i-1]);
        }
        println!("{}", res);
    }
    else {
        let n = s.len();
        let m = s.len() / 2;
        let mut res = String::new();
        res.push(s[m]);
        for i in (0..m).rev() {
            res.push(s[n-i-1]);
            res.push(s[i]);
        }
        println!("{}", res);
    }
}

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();
            }
        }
    }
}

pub fn continuous_division<T:PartialEq+Eq+Clone+Copy>(xs: &[T]) -> Vec<(T,usize)> {
    let mut res = vec![];
    let n = xs.len();
    for i in 0..n {
        if i == 0 || xs[i-1] != xs[i] {
            res.push((xs[i], 1));
        }
        else {
            let m = res.len();
            res[m-1].1 += 1;
        }
    }
    res
}

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;

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(),
            )+
        )
    }}
}

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

    if message.len() % 2 == 0 {
        for index in 0..message.len() / 2 {
            print!("{}{}", message[message.len() / 2 - 1 - index], message[message.len() / 2 + index]);
        }
    } else {
        print!("{}", message[message.len() / 2]);
        for index in 0..message.len() / 2 {
            print!("{}{}", message[message.len() / 2 + 1 + index], message[message.len() / 2 - 1 - index]);
        }
    }

    println!();
}

fn main() {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    let s = s.trim();
    let mut i: usize = 0;
    let mut j: usize = s.len()-1;

    let mut r = String::new();
    let mut last = s.len() % 2 == 0;

    for _ in 0..s.len() {
        if last {
            let c = s.chars().nth(j).unwrap();
            r.push(c);
            j -= 1;
        } else {
            let c = s.chars().nth(i).unwrap();
            r.push(c);
            i += 1;
        }
        last = !last;
    }
    println!("{}", r.chars().rev().collect::<String>());
}

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(),
            )+
        )
    }}
}

fn next_index(len: usize, curr: usize, go_left: bool) -> Option<usize> {
    if len % 2 == 0 {
        if go_left {
            if len >= curr + 1 {
                Some(len - curr - 1)
            } else {
                None
            }
        } else {
            if len >= curr + 2 {
                Some(len - curr - 2)
            } else {
                None
            }
        }
    } else {
        if go_left {
            if len >= curr + 1 {
                Some(len - curr - 1)
            } else {
                None
            }
        } else {
            if len >= curr && len - curr < len {
                Some(len - curr)
            } else {
                None
            }
        }
    }
}

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

    if message.len() == 1 {
        println!("z");
        return;
    }

    let mut index = (message.len() - 1) / 2;
    let mut go_left = true;
    loop {
        print!("{}", message[index]);

        match next_index(message.len(), index, go_left) {
            None => break,
            Some(new_index) => index = new_index
        };
        go_left = !go_left;
    }
    println!();
}


/// square root of an int
fn sqrti(b: u64) -> u64 {
    let n = 2;
    if b < 2 {
        return b
    };
    let n1 = n - 1;
    let n2 = n;
    let n3 = n1;
    let mut c = 1;
    let mut d = (n3 + b) / n2;
    let mut e = (n3 * d + b / d.pow(n1 as u32)) / n2;
    while c != d && c != e {
        c = d;
        d = e;
        e = (n3 * e + b / e.pow(n1 as u32)) / n2;
    }
    if d < e { d }
    else { e }
}

use std::ops::Range;

/// iterator that returns `(w, h)` for rectangles of provided area
struct Rects {
    area: u64,
    w: u64,
    rw: Range<u64>,
    rh: Range<u64>,
}

impl Rects {
    pub fn new(area: u64) -> Rects {
        let q = sqrti(area);
        Rects { area, rw: 1..q, rh: 1..area, w: q }
    }
    pub fn with_limits(area: u64, rw: Range<u64>, rh: Range<u64>) -> Rects {
        let q = sqrti(area);
        let maxw = q.min(area / rh.start).min(rw.end);
        let minw = (area / rh.end).max(rw.start);
        Rects { area, rw: minw..maxw, rh, w: maxw }
    }
}

impl Iterator for Rects {
    type Item = (u64, u64);
    fn next(&mut self) -> Option<(u64, u64)> {
        while self.w >= self.rw.start {
            let w = self.w;
            self.w -= 1;
            let h = self.area / w;
            if h < self.rh.start || h > self.rh.end || h * w != self.area {
                continue;
            }
            return Some((w, h));
        }
        None
    }
}

fn solve(a: u64, b: u64) -> Option<u64> {
    if a < 1 || b < 1 {
        return None;
    }
    let area = a + b;
    Rects::new(area).flat_map(|(ow, oh)| {
        let perimeter = (ow + oh) * 2;
        Rects::with_limits(a, 1..ow, 1..oh)
            .chain(Rects::with_limits(b, 1..ow, 1..oh))
            .find(|&(iw, ih)| iw <= ow && ih <= oh)
            .and(Some(perimeter))
    }).next()
}

use std::io::{stdin, BufRead};
use std::process::{exit};
fn input() -> Result<(u64, u64), String> {
    let std = stdin();
    let mut row = String::new();
    std.lock().read_line(&mut row).map_err(|_|"Cannot read stdin")?;
    let words: Vec<&str> = row.trim().split(' ').collect();
    let a: u64 = words[0].parse().map_err(|_|"Cannot parse input")?;
    let b: u64 = words[1].parse().map_err(|_|"Cannot parse input")?;
    Ok((a, b))
}

fn main() {
    let rv = input().map(|(a,b)| solve(a, b));
    match rv {
        Ok(Some(perimeter)) => {
            println!("{}", perimeter);
        }
        Ok(None) => {
            eprintln!("Error: solution not found");
            exit(1);
        }
        Err(e) => {
            eprintln!("Error: {}", e);
            exit(1);
        }
    }
}

use std::io;

fn main() {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    let rin = buf.split_whitespace().map(|c| c.parse::<u64>().unwrap()).collect::<Vec<_>>();
    let n = rin[0] + rin[1];

    let ret1 = factors(n, None);
    let x = ret1.last().unwrap();
    let ret3 = factors(rin[0], Some(*x));
    let ret4 = factors(rin[1], Some(*x));
//    println!("{:?} {:?}", ret3, ret4);

    let mut p: Option<u64> = None;
    'find: for i in ret1.iter().rev() {
        let x1 = i;
        let y1 = n / x1;
        for j in ret3.iter().rev() {
            let x2 = j;
            let y2 = rin[0] / x2;
//            println!("{} {}, {} {}", x1, y1, x2, y2);
            if x2 <= x1 && y2 <= y1 {
                let _p = (x1 + y1) * 2;
                if p.is_none() || _p < p.unwrap() {
                    p = Some(_p);
                }
                break;
            }
        }
        for j in ret4.iter().rev() {
            let x2 = j;
            let y2 = rin[1] / x2;
//            println!("{} {}, {} {}", x1, y1, x2, y2);
            if x2 <= x1 && y2 <= y1 {
                let _p = (x1 + y1) * 2;
                if p.is_none() || _p < p.unwrap() {
                    p = Some(_p);
                }
                break 'find;
            }
        }
    }
    println!("{}", p.unwrap());
}

fn factors(n: u64, max: Option<u64>) -> Vec<u64> {
    let sqrt = (n as f64).sqrt() as u64;
    let mut ret = Vec::<u64>::new();
    for i in 1..=sqrt {
        match max {
            Some(x) if i > x => {
//                println!("{}, {}", i, x);
                break;
            }
            _ => {}
        }
        if n % i == 0 {
            ret.push(i);
        }
    }
//    let ret = (1..=sqrt).rev().filter(|c| n % c == 0).collect::<Vec<_>>();
    return ret;
}

#![allow(unused_imports)]
#![allow(non_snake_case)]

use std::cell::RefCell;
use std::cmp::{max, min, Ordering};
use std::collections::*;
use std::fmt::{Debug, Formatter, Write as FmtWrite};
use std::io::{stderr, stdin, BufRead, Write};
use std::mem::{replace, swap};
use std::ops::*;
use std::rc::Rc;

// -----------------------------------------------
// Framework <https://github.com/vain0x/procon>
// -----------------------------------------------

#[allow(unused_macros)]
macro_rules! read {
    ([$t:ty] ; $n:expr) =>
        ((0..$n).map(|_| read!([$t])).collect::<Vec<_>>());
    ($($t:ty),+ ; $n:expr) =>
        ((0..$n).map(|_| read!($($t),+)).collect::<Vec<_>>());
    ([$t:ty]) =>
        (rl().split_whitespace().map(|w| w.parse().unwrap()).collect::<Vec<$t>>());
    ($t:ty) =>
        (rl().parse::<$t>().unwrap());
    ($($t:ty),*) => {{
        let buf = rl();
        let mut w = buf.split_whitespace();
        ($(w.next().unwrap().parse::<$t>().unwrap()),*)
    }};
}

#[allow(unused_macros)]
macro_rules! debug {
    ($($arg:expr),*) => {
        #[cfg(debug_assertions)]
        $(writeln!(stderr(), "{} = {:?}", stringify!($arg), $arg).unwrap());*
    };
}

#[allow(dead_code)]
fn rl() -> String {
    let mut buf = String::new();
    stdin().read_line(&mut buf).unwrap();
    buf.trim_right().to_owned()
}

trait IteratorExt: Iterator + Sized {
    fn vec(self) -> Vec<Self::Item> {
        self.collect()
    }
}

impl<T: Iterator> IteratorExt for T {}

// -----------------------------------------------
// Solution
// -----------------------------------------------

#[derive(PartialEq, Eq, Clone, Debug)]
pub struct Rev<T>(pub T);

impl<T: PartialOrd> PartialOrd for Rev<T> {
    fn partial_cmp(&self, other: &Rev<T>) -> Option<Ordering> {
        other.0.partial_cmp(&self.0)
    }
}

impl<T: Ord> Ord for Rev<T> {
    fn cmp(&self, other: &Rev<T>) -> Ordering {
        other.0.cmp(&self.0)
    }
}

fn divs(n: i64) -> Vec<i64> {
    let r = (n as f64).sqrt().ceil() as i64;

    let mut xs = vec![];

    for k in 1..r + 1 {
        if n % k == 0 {
            xs.push(k);
        }
    }

    xs
}

fn solve_core(a: i64, b: i64) -> i64 {
    let mut ts = divs(a);
    let ss = ts.iter().rev().map(|&t| a / t).vec();
    ts.extend(ss);

    let ys = divs(a + b);

    // debug!((a, b), ts, ys);

    let mut l = 0;
    let mut r = 0;
    let mut q: BinaryHeap<(Rev<i64>, usize)> = BinaryHeap::new();
    let mut mi = std::i64::MAX;

    for ti in 0..ts.len() {
        let t = ts[ti];

        while l < ys.len() && ys[l] < t {
            l += 1;
        }

        r = max(r, l);

        while r < ys.len() && (a + b) / ys[r] >= a / t {
            let y = ys[r];
            let x = (a + b) / y;
            q.push((Rev(2 * (y + x)), r));

            r += 1;
        }

        while let Some(&(_, yi)) = q.peek() {
            if l <= yi {
                break;
            }

            q.pop();
        }

        // debug!((ti, t, l, r));

        if let Some((Rev(p), _)) = q.pop() {
            // debug!(p);
            mi = min(mi, p);
        }
    }

    mi
}

fn solve(a: i64, b: i64) -> i64 {
    let mut mi = solve_core(a, b);
    if a != b {
        mi = min(mi, solve_core(b, a));
    }
    mi
}

fn main() {
    let (a, b) = read!(i64, i64);
    println!("{}", solve(a, b))
}

use std::io;

fn main() {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    let rin = buf.split_whitespace().map(|c| c.parse::<u64>().unwrap()).collect::<Vec<_>>();
    let n = rin[0] + rin[1];
    let m: u64;

    let ret1 = factors(n, None);
    let x = ret1.last().unwrap();
    let ret3 = factors(rin[0], Some(*x));
    let ret4 = factors(rin[1], Some(*x));
//    println!("{:?} {:?}", ret3, ret4);

    let ret2 = if ret3.last().unwrap() > ret4.last().unwrap() {
        m = rin[0];
        ret3
    } else {
        m = rin[1];
        ret4
    };
//    println!("{:?}", ret1);
//    println!("{:?}", ret2);
    let mut p: u64 = 0;
    'find: for i in ret1.iter().rev() {
        let x1 = i;
        let y1 = n / x1;
        for j in ret2.iter().rev() {
            let x2 = j;
            let y2 = m / x2;
//            println!("{} {}, {} {}", x1, y1, x2, y2);
            if x2 <= x1 && y2 <= y1 {
                p = (x1 + y1) * 2;
                break 'find;
            }
        }
    }
    println!("{}", p);
}

fn factors(n: u64, max: Option<u64>) -> Vec<u64> {
    let sqrt = (n as f64).sqrt() as u64;
    let mut ret = Vec::<u64>::new();
    for i in 1..=sqrt {
        match max {
            Some(x) if i > x => {
//                println!("{}, {}", i, x);
                break;
            }
            _ => {}
        }
        if n % i == 0 {
            ret.push(i);
        }
    }
//    let ret = (1..=sqrt).rev().filter(|c| n % c == 0).collect::<Vec<_>>();
    return ret;
}

use std::io;
use std::cmp;

fn main() {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    let rin = buf.split_whitespace().map(|c| c.parse::<u64>().unwrap()).collect::<Vec<_>>();
    let n = rin[0] + rin[1];
    let m = cmp::min(rin[0], rin[1]);
    let ret1 = factors(n);
    let ret2 = factors(m);
    let mut p: u64 = 0;
    'find: for i in ret1.iter() {
        let x1 = i;
        let y1 = n / x1;
        for j in ret2.iter() {
            let x2 = j;
            let y2 = m / x2;
            if x2 <= x1 && y2 <= y1 {
                p = (x1 + y1) * 2;
                break 'find;
            }
        }
    }
    println!("{}", p);
}

fn factors(n: u64) -> Vec<u64> {
    let sqrt = (n as f64).sqrt() as u64;
    let ret = (1..=sqrt).rev().filter(|c| n % c == 0).collect::<Vec<_>>();
    return ret;
}

use std::io;

fn main() {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    let rin = buf.split_whitespace().map(|c| c.parse::<u64>().unwrap()).collect::<Vec<_>>();
    let n = rin[0] + rin[1];
    let m: u64;

    let ret1 = factors(n);
//    println!("{:?}", ret1);
    let ret3 = factors(rin[0]);
    let ret4 = factors(rin[1]);

    let ret2 = if ret3[0] > ret4[0] {
        m = rin[0];
        ret3
    } else {
        m = rin[1];
        ret4
    };
//    println!("{:?}", ret2);
    let mut p: u64 = 0;
    'find: for i in ret1.iter() {
        let x1 = i;
        let y1 = n / x1;
        for j in ret2.iter() {
            let x2 = j;
            let y2 = m / x2;
//            println!("{} {}, {} {}", x1, y1, x2, y2);
            if x2 <= x1 && y2 <= y1 {
                p = (x1 + y1) * 2;
                break 'find;
            }
        }
    }
    println!("{}", p);
}

fn factors(n: u64) -> Vec<u64> {
    let sqrt = (n as f64).sqrt() as u64;
    let ret = (1..=sqrt).rev().filter(|c| n % c == 0).collect::<Vec<_>>();
    return ret;
}

use std::io;

fn main() {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    let rin = buf.split_whitespace().map(|c| c.parse::<u64>().unwrap()).collect::<Vec<_>>();
    let n = rin[0] + rin[1];
    let m: u64;

    let ret1 = factors(n, None);
    let x = ret1.last().unwrap();
    let ret3 = factors(rin[0], Some(*x));
    let ret4 = factors(rin[1], Some(*x));
//    println!("{:?} {:?}", ret3, ret4);

    let r3_last = *ret3.last().unwrap();
    let r4_last = *ret4.last().unwrap();
    let ret2 = if r3_last > r4_last {
        m = rin[0];
        ret3
    } else if r3_last < r4_last {
        m = rin[1];
        ret4
    } else if rin[0] < rin[1] {
        m = rin[0];
        ret3
    } else {
        m = rin[1];
        ret4
    };
//    println!("{:?}", ret1);
//    println!("{:?}", ret2);
    let mut p: u64 = 0;
    'find: for i in ret1.iter().rev() {
        let x1 = i;
        let y1 = n / x1;
        for j in ret2.iter().rev() {
            let x2 = j;
            let y2 = m / x2;
//            println!("{} {}, {} {}", x1, y1, x2, y2);
            if x2 <= x1 && y2 <= y1 {
                p = (x1 + y1) * 2;
                break 'find;
            }
        }
    }
    println!("{}", p);
}

fn factors(n: u64, max: Option<u64>) -> Vec<u64> {
    let sqrt = (n as f64).sqrt() as u64;
    let mut ret = Vec::<u64>::new();
    for i in 1..=sqrt {
        match max {
            Some(x) if i > x => {
//                println!("{}, {}", i, x);
                break;
            }
            _ => {}
        }
        if n % i == 0 {
            ret.push(i);
        }
    }
//    let ret = (1..=sqrt).rev().filter(|c| n % c == 0).collect::<Vec<_>>();
    return ret;
}