Problem:
Score : 300 points

Problem Statement

A railroad running from west to east in Atcoder Kingdom is now complete.

There are N stations on the railroad, numbered 1 through N from west to east.

Tomorrow, the opening ceremony of the railroad will take place.

On this railroad, for each integer i such that 1≤i≤N-1, there will be trains that run from Station i to Station i+1 in C_i seconds. No other trains will be operated.

The first train from Station i to Station i+1 will depart Station i S_i seconds after the ceremony begins. Thereafter, there will be a train that departs Station i every F_i seconds.

Here, it is guaranteed that F_i divides S_i.

That is, for each Time t satisfying S_i≤t and t％F_i=0, there will be a train that departs Station i t seconds after the ceremony begins and arrives at Station i+1 t+C_i seconds after the ceremony begins, where A％B denotes A modulo B, and there will be no other trains.

For each i, find the earliest possible time we can reach Station N if we are at Station i when the ceremony begins, ignoring the time needed to change trains.

Constraints

1≤N≤500

1≤C_i≤100

1≤S_i≤10^5

1≤F_i≤10

S_i％F_i=0

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
C_1 S_1 F_1
:
C_{N-1} S_{N-1} F_{N-1}

Output

Print N lines. Assuming that we are at Station i (1≤i≤N) when the ceremony begins, if the earliest possible time we can reach Station N is x seconds after the ceremony begins, the i-th line should contain x.

Sample Input 1

3
6 5 1
1 10 1

Sample Output 1

12
11
0

We will travel from Station 1 as follows:

5 seconds after the beginning: take the train to Station 2.

11 seconds: arrive at Station 2.

11 seconds: take the train to Station 3.

12 seconds: arrive at Station 3.

We will travel from Station 2 as follows:

10 seconds: take the train to Station 3.

11 seconds: arrive at Station 3.

Note that we should print 0 for Station 3.

Sample Input 2

4
12 24 6
52 16 4
99 2 2

Sample Output 2

187
167
101
0

Sample Input 3

4
12 13 1
44 17 17
66 4096 64

Sample Output 3

4162
4162
4162
0

Solution in Rust (1.15.1) (judge verdict: Accepted)

#![allow(unused_imports)]
use std::cmp::{max, min};
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};

use nyan::*;

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

    let n: usize = sc.read();
    let p: Vec<_> = (0..n - 1)
        .map(|_| {
            let c: u64 = sc.read();
            let s: u64 = sc.read();
            let f: u64 = sc.read();
            (c, s, f)
        })
        .collect();

    let mut r = Vec::with_capacity(n - 1);
    r.push(0);

    let mut v = vec![0; n];
    v[n - 2] = p[n - 2].1 + p[n - 2].0;
    r.push(v[n - 2]);

    // println!("{}: {:?}", n - 2, v);

    for i in (0..n - 2).rev() {
        v[i] = p[i].1 + p[i].0;
        for j in i + 1..n - 1 {
            if v[j] - p[j].0 < v[j - 1] {
                let d = (v[j - 1] - (v[j] - p[j].0) + p[j].2 - 1) / p[j].2;
                v[j] += d * p[j].2;
            }
        }

        r.push(v[n - 2]);

        // println!("{}: {:?}", i, v);
    }

    // println!("{:?}", r);

    for i in r.iter().rev() {
        println!("{}", i);
    }
}

#[allow(dead_code)]
mod nyan {
    use std::cmp::*;
    use std::fmt::{Debug, Display};
    use std::io::{self, BufRead};
    use std::iter::FromIterator;
    use std::str::FromStr;

    // https://doc.rust-lang.org/1.39.0/src/core/num/mod.rs.html#4473-4523
    #[inline]
    pub fn is_ascii_whitespace(c: char) -> bool {
        match c {
            '\t' | '\n' | '\x0C' | '\r' | ' ' => true,
            _ => false,
        }
    }

    #[inline]
    pub fn is_ascii_linebreak(c: char) -> bool {
        match c {
            '\n' | '\r' => true,
            _ => false,
        }
    }

    struct Reader<R> {
        reader: R,
        buffer: String,
        cursor: usize,
    }

    impl<R: BufRead> Reader<R> {
        fn new(reader: R) -> Reader<R> {
            Reader {
                reader: reader,
                buffer: String::with_capacity(32),
                cursor: 0,
            }
        }

        #[inline]
        fn trim_start(&mut self) {
            match self.buffer[self.cursor..].find(|c| !is_ascii_whitespace(c)) {
                Some(l) => self.cursor += l,
                None => self.cursor = self.buffer.len(),
            }
        }

        fn prepare_buffer(&mut self) -> io::Result<()> {
            self.trim_start();

            while self.buffer.len() - self.cursor == 0 {
                self.buffer.clear();
                match self.reader.read_line(&mut self.buffer) {
                    Err(e) => return Err(e),
                    Ok(0) => return Err(io::Error::from(io::ErrorKind::UnexpectedEof)),
                    Ok(_) => {
                        self.cursor = 0;
                        self.trim_start();
                    }
                }
            }

            Ok(())
        }

        fn next_word(&mut self) -> io::Result<&str> {
            self.prepare_buffer()?;

            match self.buffer[self.cursor..].find(is_ascii_whitespace) {
                Some(l) => {
                    let start = self.cursor;
                    self.cursor += l;
                    Ok(&self.buffer[start..self.cursor])
                }
                None => Err(io::Error::from(io::ErrorKind::Other)),
            }
        }

        fn next_line(&mut self) -> io::Result<&str> {
            self.prepare_buffer()?;

            match self.buffer[self.cursor..].find(is_ascii_linebreak) {
                Some(l) => {
                    let start = self.cursor;
                    self.cursor += l;
                    Ok(&self.buffer[start..self.cursor])
                }
                None => Err(io::Error::from(io::ErrorKind::Other)),
            }
        }
    }

    pub struct Scanner<R> {
        reader: Reader<R>,
    }

    impl<R: BufRead> Scanner<R> {
        pub fn new(reader: R) -> Scanner<R> {
            Scanner {
                reader: Reader::new(reader),
            }
        }

        pub fn read<T>(&mut self) -> T
        where
            T: FromStr,
            <T as FromStr>::Err: Debug,
        {
            self.reader.next_word().unwrap().parse().unwrap()
        }

        pub fn read_vec<T, U>(&mut self, n: usize) -> T
        where
            T: FromIterator<U>,
            U: FromStr,
            <U as FromStr>::Err: Debug,
        {
            (0..n).map(|_| self.read()).collect()
        }

        pub fn read_vec2d<T, U, V>(&mut self, m: usize, n: usize) -> T
        where
            T: FromIterator<U>,
            U: FromIterator<V>,
            V: FromStr,
            <V as FromStr>::Err: Debug,
        {
            (0..m).map(|_| self.read_vec(n)).collect()
        }

        pub fn read_line<T: FromIterator<char>>(&mut self) -> T {
            self.reader.next_line().unwrap().chars().collect()
        }

        pub fn read_lines<T, U>(&mut self, n: usize) -> T
        where
            T: FromIterator<U>,
            U: FromIterator<char>,
        {
            (0..n).map(|_| self.read_line()).collect()
        }
    }

    pub fn print_vec<T: Display>(v: &[T]) {
        if v.is_empty() {
            return;
        }

        print!("{}", v[0]);
        for i in v.iter().skip(1) {
            print!(" {}", i);
        }
        println!();
    }

    // C++ like binary search functions (upper_bound, lower_bound, equal_range)
    pub trait BinarySearch<T> {
        fn lower_bound(&self, value: &T) -> usize;
        fn upper_bound(&self, value: &T) -> usize;
        fn equal_range(&self, value: &T) -> (usize, usize) {
            (self.lower_bound(value), self.upper_bound(value))
        }
    }

    impl<T: Ord> BinarySearch<T> for [T] {
        // https://en.cppreference.com/w/cpp/algorithm/lower_bound#Possible_implementation
        fn lower_bound(&self, value: &T) -> usize {
            let mut first = 0;
            let mut last = self.len();
            while last != first {
                let mid = (first + last) / 2;
                match self[mid].cmp(value) {
                    Ordering::Less => first = mid + 1,
                    _ => last = mid,
                }
            }
            first
        }

        // https://en.cppreference.com/w/cpp/algorithm/upper_bound#Possible_implementation
        fn upper_bound(&self, value: &T) -> usize {
            let mut first = 0;
            let mut last = self.len();
            while last != first {
                let mid = (first + last) / 2;
                match self[mid].cmp(value) {
                    Ordering::Greater => last = mid,
                    _ => first = mid + 1,
                }
            }
            first
        }
    }

    #[test]
    pub fn test_binary_search() {
        let data = vec![1, 1, 2, 3, 3, 3, 3, 4, 4, 4, 5, 5, 6];
        assert_eq!(data.lower_bound(&4), 7);
        assert_eq!(data.upper_bound(&4), 10);
    }

    // https://doc.rust-lang.org/std/cmp/struct.Reverse.html
    #[derive(PartialEq, Eq, Debug)]
    pub struct Rev<T>(pub T);

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

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

    // Extended Euclidean algorithm
    // ax + by = gcd(x, y)
    pub fn extended_gcd(a: u64, b: u64) -> (u64, i64, i64) {
        if b == 0 {
            (a, 1, 0)
        } else {
            let (m, y, x) = extended_gcd(b, a % b);
            (m, x, y - (a / b) as i64 * x)
        }
    }

    pub fn gcd(a: u64, b: u64) -> u64 {
        if b == 0 {
            a
        } else {
            gcd(b, a % b)
        }
    }

    pub fn lcm(a: u64, b: u64) -> u64 {
        (a * b) / gcd(a, b)
    }

    // x^n (mod p)
    pub fn pow_mod(mut x: u64, mut n: u64, p: u64) -> u64 {
        let mut r = 1;
        while n > 0 {
            if n & 1 > 0 {
                r *= x;
                r %= p;
            }
            x *= x;
            x %= p;
            n >>= 1;
        }
        r
    }

    #[test]
    fn test_pow_mod() {
        assert_eq!(pow_mod(4, 13, 497), 445);
        assert_eq!(pow_mod(2, 90, 13), 12);
        assert_eq!(pow_mod(2, 99999999, 147), 134);
    }

    // a^{p-1} = 1 (mod p) (Fermat's little theorem)
    // a^{p - 2} * a = 1 → a^{-1} = a^{p-2}
    pub fn inv_mod(n: u64, p: u64) -> u64 {
        pow_mod(n, p - 2, p)
    }

    // s * (s + 1) * .. * t (mod p)
    pub fn prod_mod(s: u64, t: u64, p: u64) -> u64 {
        (s..t + 1).fold(1, |acc, x| acc * x % p)
    }

    // nCk (mod p)
    pub fn comb_mod(n: u64, k: u64, p: u64) -> u64 {
        // nCk = n! / (k! * (n - k)!)
        //     = ((n-k+1) * (n-k+2) * ... * n) * inv(k!)
        prod_mod(n - k + 1, n, p) * inv_mod(prod_mod(1, k, p), p) % p
    }

    #[inline]
    pub fn minmax<T: Ord>(a: T, b: T) -> (T, T) {
        if a < b {
            (a, b)
        } else {
            (b, a)
        }
    }

    #[test]
    fn test_minmax() {
        assert_eq!(minmax(1, 3), (1, 3));
        assert_eq!(minmax(3, 1), (1, 3));
    }

    #[inline]
    pub fn digits(x: u64) -> u32 {
        use std::u64;
        (0..)
            .find(|&i| 10u64.pow(i) <= x && x < 10u64.pow(i + 1))
            .map(|i| i + 1)
            .unwrap_or(0)
    }

    #[test]
    fn test_digits() {
        assert_eq!(digits(2), 1);
        assert_eq!(digits(23), 2);
        assert_eq!(digits(234), 3);
        assert_eq!(digits(2345), 4);
        assert_eq!(digits(23456), 5);
        assert_eq!(digits(234567), 6);
        assert_eq!(digits(2345678), 7);
        assert_eq!(digits(23456789), 8);
        assert_eq!(digits(234567890), 9);
    }

    pub struct UnionFind {
        n: usize,
        root: Vec<usize>,
        rank: Vec<usize>,
        size: Vec<usize>,
    }

    impl UnionFind {
        pub fn new(n: usize) -> UnionFind {
            UnionFind {
                n: n,
                root: (0..n).collect(),
                rank: vec![0; n],
                size: vec![1; n],
            }
        }

        pub fn root(&mut self, x: usize) -> usize {
            let r = self.root[x];
            if r == x {
                r
            } else {
                self.root[x] = self.root(r);
                self.root[x]
            }
        }

        pub fn merge(&mut self, x: usize, y: usize) {
            let rx = self.root(x);
            let ry = self.root(y);
            if rx == ry {
                return;
            }

            if self.rank[rx] < self.rank[ry] {
                self.root[rx] = ry;
                self.size[ry] += self.size[rx];
            } else {
                self.root[ry] = rx;
                self.size[rx] += self.size[ry];
                if self.rank[rx] == self.rank[ry] {
                    self.rank[rx] += 1;
                }
            }
        }

        pub fn size(&mut self, x: usize) -> usize {
            let rx = self.root(x);
            self.size[rx]
        }
    }
}