package mainPackage

import java.util.*

fun main(args: Array<String>) {
    val scanner = Scanner(System.`in`)
    val s = scanner.nextLine()

    var ans = 0

    for(i in 0 .. s.length - 1) {
        for(j in i + 1 .. s.length - 1) {
            for (h in j + 1 .. s.length - 1) {
                if(s[i] == 'Q' && s[j] == 'A' && s[h] == 'Q') {
                    ++ans
                }
            }
        }
    }

    print(ans)
}


import java.io.BufferedReader
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader
import java.util.*
import kotlin.collections.ArrayList
import kotlin.math.*
fun main(args: Array<String>) {

    val scanner = Scanner(System.`in`)
    val Q = Array<String>(2) { "X" + scanner.next() + "X" }
    var last = 0
    var res = 0
    for (i in 0 until Q[0].length) {
        if (Q[0][i] == 'X' && Q[1][i] == 'X') {
            if ((i - last) % 3 == 0)
                res += ((i - last) / 3) * 2
            else if ((i - last) % 3== 2)
                res += ((i - last) / 3) * 2 + 1
            else
                res += ((i - last) / 3) * 2
            last = i + 1
        }
        else if (Q[0][i] == 'X' || Q[1][i] == 'X') {
            if ((i - last) % 3 == 0)
                res += ((i - last) / 3) * 2
            else if ((last - i) % 3 == 2)
                res += ((i - last) / 3) * 2 + 1
            else
                res += (((i - last) / 3) * 2) + 1
            last = i + 1
        }
        else if (Q[0][i] == '0' && Q[1][i] == '0' && ((Q[0][i - 1] == 'X' && Q[1][i - 1] != 'X') || (Q[1][i - 1] == 'X' && Q[0][i - 1] != 'X'))) {
            res++
            last = i + 1
        }
    }
    println(res)

}

class Scanner(s: InputStream) {
    var st: StringTokenizer? = null
    var br: BufferedReader = BufferedReader(InputStreamReader(s))
    @Throws(IOException::class)
    operator fun next(): String {
        while (st == null || !st!!.hasMoreTokens())
            st = StringTokenizer(br.readLine())
        return st!!.nextToken()
    }
    @Throws(IOException::class)
    fun nextInt(): Int {
        return Integer.parseInt(next())
    }
    @Throws(IOException::class)
    fun nextLong(): Long {
        return java.lang.Long.parseLong(next())
    }
    @Throws(IOException::class)
    fun nextLine(): String {
        return br.readLine()
    }
    @Throws(IOException::class)
    fun nextDouble(): Double {
        return java.lang.Double.parseDouble(next())
    }
    @Throws(IOException::class)
    fun ready(): Boolean {
        return br.ready()
    }
}

fun IntArray.print() {
    println(Arrays.toString(this))
}

//class Pair(var a: Int, var b: Int): Comparable<Pair> {
//    override fun compareTo(other: Pair): Int {
//        return b - a - other.b + other.a
//    }
//}


fun main() {
    val n = readLine()!!.toInt()
    val k = readLine()!!.toInt()
    print(subtract(n, k))

}

tailrec fun subtract(num: Int, times: Int): Int {
    if(times == 0)
        return num

    if(num % 10 == 0) {
        return subtract(num/10, times.minus(1))
    } else {
        return subtract(num.minus(1), times.minus(1))
    }
}


fun main(args: Array<String>) {
    var n = readLine()!!.toLong()
    var k = readLine()!!.toLong()
    while(k>0)
    {
        var lastDigit = n % 10
        if(lastDigit > k)
        {
            n = n - k
            k = 0
        }
        else
        {
            n = (n / 10)*10
            k = k - lastDigit
        }
        if(n % 10 == 0 && k > 0)
        {
            k--;
            n = n / 10
        }
    }
}


fun main() {
    var n = readLine()!!.toLong()
    var k = readLine()!!.toLong()
    while(k>0)
    {
        var lastDigit = n % 10
        if(lastDigit > k)
        {
            n -= k
            k = 0
        }
        else
        {
            n = (n / 10)*10
            k -= lastDigit
        }
        if(n % 10L == 0L && k > 0)
        {
            k--
            n /= 10
        }
    }
}


fun main() {
    //println("Hello, World!")
    //var num1=Scanner(System.`in`)
    var n=readLine()!!.toInt()
    var k=readLine()!!.toInt()
    for (i in 1..k) {
        if(n%10==0){
            n/=10
        }
        else{
            n=n-1
        }
        //println("$n")
    }
    println("$n")

}


fun main() {
    //println("Hello, World!")
    //var num1=Scanner(System.`in`)
    val n=readLine()!!.toInt()
    val k=readLine()!!.toInt()
    for (i in 1..k) {
        if(n%10==0){
            n/=10
        }
        else{
            n=n-1
        }
        //println("$n")
    }
    println("$n")

}


val readIn = readLine() ?: throw RuntimeException("Expected a line from readIn, got null")
val (n, k) = readIn.split(" ").map { it.toInt() }
var tmp = n
repeat(k) {
    if (tmp % 10 == 0)
        tmp -= 1
    else
        tmp /= 10
}
return tmp


fun decrease(): Int {
    val readIn = readLine() ?: throw RuntimeException("Expected a line from readIn, got null")
    val (n, k) = readIn.split(" ").map { it.toInt() }
    var tmp = n
    repeat(k) {
        if (tmp % 10 == 0)
            tmp -= 1
        else
            tmp /= 10
    }
    return tmp
}


fun main(): Unit {
    var (n, k) = readLine()!!.split(" ")!!.let { Pair(it[0].toInt(), it[1].toInt()) }
    repeat(k) {
        if (n.toString().last() == '0') {
            n = n / 10
        } else {
            n = n -1
        }
    }
    return n
}


fun main(args: Array<String>)
{
    val read = Scanner(System.`in`)
    var number = read.nextInt()
    var k  = read.nextInt()
    for(h in 0 until k){
        if(number%10>0)
            number-=1;
        else
             number/=10;
    }
    println(number)
}


fun main (args: Array<String>)
{

var n =readLine()!!.toInt()
var k= readLine()!!.toInt()
var m= n
var d= 0;
while (k>0)
{
d=m%10;
if (d!=0)
m=m-1
else
m=m/10

k--
}
println("Result is $m")
}


fun wrongSubtraction(n: Int, k: Int) {
    var value = n
    for (i in 1..k) {
        if (value % 10 != 0) {
            value -= 1
        } else {
            value /= 10
        }
    }
    print(value)
}


    fun main(args: Array<String>) {
        var (a, j) = readLine()!!.split(' ').map(String::toInt)
        for (i in 1..j)
        {
            if (a%10 == 0)
                n /= 10
            else
                a--
        }

        println(a)
    }


fun main() {
    var (n, k) = readLine()!!.split(' ')
    n = n.toInt()
    k = k.toInt()

    while (k>0) {
        if (n%10 == 0) {
            n = (n/10).toInt()
        }
        else {
            n -= 1
        }
        k--
    }
    println(n)
}


fun runSubtraction(number: Int, subtractor: Int){
    println(wrongSubtraction(number,subtractor))
}

private tailrec fun wrongSubtraction(number: Int, subtractor: Int): Int {
    return if (subtractor == 0) {
        number
    } else if (number % 10 == 0) {
        wrongSubtraction(number / 10, subtractor - 1)
    } else {
        wrongSubtraction(number - 1, subtractor - 1)
    }
}


#include<iostream>
using namespace std;
int main(){
	int n,k;
	cin>>n>>k;
	for(int i=1;i<=k;i++){
		if(n%10)n--;
		else n/=10;
	}
	cout<<n;
}


import java.util.Scanner
object Solution {
  @JvmStatic fun main(args:Array<String>) {
    val sc = Scanner(System.`in`)
    val str = sc.nextLine().split((" ").toRegex()).dropLastWhile({ it.isEmpty() }).toTypedArray()
    val number = Integer.parseInt(str[0])
    val k = Integer.parseInt(str[1])
    while (k > 0)
    {
      val rem = number % 10
      if (rem != 0)
      {
        number = number - 1
      }
      else
      {
        number = number / 10
      }
      k--
    }
    println(number)
  }
}


fun main(arg: Array<String>) {
  var n = arg[0].toInt()
  val k = arg[1].toInt()
  for( i in 0 until k)
  {
  	val lastDigit = n % 10
    if(lastDigit == 0)
    {
        n /= 10
    }
    else
    {
        n--
    }
  }
  print(n)
}


fun Array<String>.readInts() = map { it.toInt() }

fun main(args: Array<String>) {
    val (n, k) = args.readInts()

    var result = n
    for (i in 0 until k) {
        if (result % 10 == 0) {
            result /= 10
        } else {
            result--
        }
    }
    println(result)
}


package practice2.a

import utils.Utils
import java.util.stream.IntStream

object WrongSubtraction {

    fun subtract(_number: Int, times: Int): Int {
        var number = _number

        IntStream.range(0, times).forEach {
            if (number % 10 == 0) {
                number /= 10
            } else {
                number--
            }
        }

        return number
    }

}

fun main(args: Array<String>) {
    println(WrongSubtraction.subtract(args[0].toInt(), args[1].toInt()))
}


object WrongSubtraction {

    fun subtract(number: Int, times: Int): Int {
        if (times == 0)
            return number

        return if (number % 10 == 0)
            subtract(number / 10, times - 1)
        else
            subtract(number - 1, times - 1)
    }

}

fun main(args: Array<String>) {
    println(WrongSubtraction.subtract(args[0].toInt(), args[1].toInt()))
}


//package codeForces.c491_2

fun tryEat(n: Long, c: Long): Boolean {
    var remains = n
    var eaten = 0L

    while (remains > c) {
        remains -= c
        eaten += c

        remains -= remains / 10
    }
    eaten += remains

    return eaten >= n / 2
}

fun main(args: Array<String>) {
    val n = readLine()!!.toLong()

    var left = 0L
    var right = n
    var lastSuccess = -1L

    while (left <= right) {
        val c = (left + right) / 2

        if (tryEat(n, c)) {
            lastSuccess = c
            right = c - 1
        } else {
            left = c + 1
        }
    }

    println(lastSuccess)
}


//package codeForces.c491_2

fun tryEat(n: Long, c: Long): Boolean {
    var remains = n
    var eaten = 0L

    while (remains > c) {
        remains -= c
        eaten += c

        remains -= remains / 10
    }
    eaten += remains

    return eaten >= n / 2
}

fun main(args: Array<String>) {
    val n = readLine()!!.toLong()

    var left = 1L
    var right = n
    var lastSuccess = -1L

    while (left <= right) {
        val c = (left + right) / 2

        if (tryEat(n, c)) {
            lastSuccess = c
            right = c - 1
        } else {
            left = c + 1
        }
    }

    println(lastSuccess)
}


fun model(n: Long, k: Long): Long {
    var rem = n
    var ans = 0L

    while (rem > 0) {
        val vasyaCount = Math.min(rem, k)
        ans += vasyaCount
        rem -= vasyaCount
        rem -= rem / 10
    }

    return ans
}

fun check(vasyaCount: Long, n: Long) = 2 * vasyaCount >= n

const val LIMIT = 10_000

fun main(args: Array<String>) {
    val n = readLine()!!.toLong()

    var a = 1L
    var b = n

    while (b - a > 1) {
        val c = (a + b) / 2
        if (check(vasyaCount = model(n = n, k = c), n = n)) {
            b = c
        } else {
            a = c
        }
    }

    a = Math.max(a - LIMIT / 2, 1L)
    b = a + LIMIT / 2

    for (k in a..b) {
        if (check(vasyaCount = model(n = n, k = k), n = n)) {
            println(k)
            break
        }
    }
}


import kotlin.*

fun readLn() = readLine()!!
fun readStrings() = readLn().split(" ")
fun readInts() = readStrings().map{ it.toInt() }

fun main() {
  var (n) = readInts()
  var (s) = readStrings()
  var mp = HashMap<String, Int>()
  for (i in 0..n - 2) {
    var t = s.substring(i, i + 2)
    mp[t] = mp.getOrDefault(t, 0) + 1
  }
  var ans = ""
  var mx = 0
  for ((key, val) in mp) {
    if (val > mx) {
      mx = val
      ans = key
    }
  }
  println(ans)
}


import kotlin.math.absoluteValue
import kotlin.math.pow

fun main(args: Array<String>) {
    val inputString = readLine()!!.split(" ")
    val n = inputString[0].toInt()
    val s = inputString[1]

    var pattern = mutableListOf<String>()
    var pmap = mutableMapOf<String, Int>()
    if (n >= 2 && n <= 100) {

        for (i in 0..(n - 2)) {
            if (s.substring(i, i + 2) in pattern) {
                var count = pmap[s.substring(i, i + 2)]

                if (count != null) {
                    pmap[s.substring(i, i + 2)] = count + 1
                }
            } else {
                pattern.add(s.substring(i, i + 2))
                pmap.put(s.substring(i, i + 2), 1)
            }
        }
    }
    println(pmap.maxBy { it.value }?.key)
}


package c1212

fun main() {
    readLine()
    val s = readLine()!!
    val res=s.zipWithNext { a, b -> a.toString() + b }
        .groupingBy { it }
        .eachCount()
        .maxBy { it.value }
        ?.key!!
    println(res)
}


fun main() {
    val sc = Scanner(System.`in`)
    val n = sc.nextInt()
    val s = sc.next()
    val m = hashMapOf<String, Int>()
    for (i in 0 until n - 1) {
        val x = s.substring(i, i + 2)
        m[x] = m.getOrDefault(x, 0) + 1
    }
    var cnt = 0
    var res: String? = null
    for (e in m) {
        if (cnt < e.value) {
            cnt = e.value
            res = e.key
        }
    }
    println(res)
}


import java.util.Scanner

fun main(args: Array<String>) {
    val inp = Scanner(System.`in`)
    var n = inp.nextInt()
    var s = inp.next()
    var all = ArrayList<String>()
    var ans = s.substring(0,2)
    var i = 0
    for(i in 0..n-1)
    {
        var x = s.substring(i,i+2)
        all.add(x)
    }
    all.sort()
    var f = 0
    var x; var mx = 0;
    for(i in all)
    {
        if(i==x)
        {
            f++;
        }
        else
        {
            f = 1;
            x = i;
        }
        if(f >mx)
        {
            ans = i
            mx = f
        }

    }

    println(ans)
}


import java.util.Scanner

fun main(args: Array<String>) {
    val inp = Scanner(System.`in`)
    var n = inp.nextInt()
    var s = inp.next()
    var all = ArrayList<String>()
    var ans = s.substring(0,2)
    var i = 0
    for(i in 0..n-1)
    {
        var x = s.substring(i,i+2)
        all.add(x)
    }
    all.sort()
    var f = 0
    var x="A"; var mx = 0;
    for(i in all)
    {
        if(i==x)
        {
            f++;
        }
        else
        {
            f = 1;
            x = i;
        }
        if(f >mx)
        {
            ans = i
            mx = f
        }

    }

    println(ans)
}


package practice

fun String.twoGrams(): Map<String, Int> = this.zipWithNext { a, b -> "$a$b" }.groupingBy { it }.eachCount()

fun Map<String, Int>.max(): String? = this.maxBy { it.value }?.key

fun main() {
    val n = readLine()?.toIntOrNull() ?: error("n not valid")
    val s = readLine()?.substring(0 until n) ?: error("s not valid")

    println(s.twoGrams().max())
}


fun main(){
    var(n,k)=readLine()!!.split(' ').map{x->x.toInt()}
    val arr=readLine()!!.split(' ').map{x->x.toInt()}.sorted()
    if (k==n){
        print("1000000000\n")
    }
    else if (k==0){
        if (arr[0]==1) print("-1\n")
        else print("1\n")
    }
    else{
        if (arr[k]==arr[k-1]) print("-1\n")
        else print("${arr[k-1]}\n")
    }
}


rivate fun readLn() = readLine()!! // string line
private fun readInt() = readLn().toInt() // single int
private fun readStrings() = readLn().split(" ") // list of strings
private fun readInts() = readStrings().map { it.toInt() } // list of ints

fun main(args: Array<String>) {
    var n = readInt()
    var s = readLn()
    var m = HashMap<String, Int>()
    for (i in 0..n-2) {
        var t = s.substring(i, i + 2)
        if (m.containsKey(t)) {
            m.put(t, m.get(t)!! + 1)
        } else {
            m.put(t, 1)
        }
    }
    var mx = -1
    var res = ""
    for (t in m.keys) {
        if (m.get(t)!! > mx) {
            mx = m.get(t)!!
            res = t
        }
    }
    println(res)
}


fun test(args: Array<String>) {
    val a = readLine()!!.toInt()
    val b = readLine()!!
    twoGram(a, b)
}

fun twoGram(length: Int, str: String) {
    val countMap = mutableMapOf<String, Int>()
    for (i in 0 until length - 1) {
        val twoGram = str.substring(i, i + 2)
        countMap[twoGram] = countMap[twoGram]?.plus(1) ?: 1
    }
    println(countMap.maxBy { it.value }?.key)
}


import java.io.BufferedInputStream
import java.io.BufferedOutputStream
import java.io.OutputStreamWriter
import java.util.*
import kotlin.math.max

fun main(args: Array<String>) {
    val scanner = Scanner(BufferedInputStream(System.`in`))
    val output = OutputStreamWriter(BufferedOutputStream(System.out))

    val a = scanner.nextInt()
    val b = scanner.nextInt()
    val c = scanner.nextInt()
    val d = scanner.nextInt()

    val p1 = points(a, c)
    val p2 = points(b, d)

    when {
        p1 == p2 -> output.write("TIE\n")
        p1 > p2 -> output.write("Misha\n")
        else -> output.write("Vasya\n")
    }

    output.flush()
    output.close()
    scanner.close()
}

fun points(p: Int, t: Int) = max(3*p/10f, p - (p/250f * t))


import java.io.*
import java.util.*

class Solution : Runnable {
    override fun run() {
        solve()
    }

    fun start() {
        Thread(null, Solution(), "whatever", (1 shl 26).toLong()).start()
    }
}

fun main(args: Array<String>) {
    Solution().start()
}

class IO {
    companion object {

        private val reader: InputReader
        private val writer: OutputWriter

        init {
            if (System.getProperty("ONLINE_JUDGE") == null) {
                reader = InputReader(FileInputStream("/Users/300041735/competitiveProgramming/src/codeforces/in.txt"))
                writer = OutputWriter(FileOutputStream("/Users/300041735/competitiveProgramming/src/codeforces/out.txt"))
            } else {
                reader = InputReader(System.`in`)
                writer = OutputWriter(System.`out`)
            }
        }

        private fun readMultipleInts(count: Int): List<Int> {
            val map = mutableListOf<Int>()
            repeat(count) {
                map.add(reader.readInt())
            }
            return map
        }

        fun readInt() = reader.readInt()
        fun readLong() = reader.readLong()
        fun readTwoInts() = readMultipleInts(2)
        fun readThreeInts() = readMultipleInts(3)
        fun readFourInts() = readMultipleInts(4)
        fun readString() = reader.readString()
        fun readTree(n: Int): MutableMap<Int, MutableSet<Int>> {
            val graph = mutableMapOf<Int, MutableSet<Int>>()
            repeat(n - 1) {
                val u = reader.readInt()
                val v = reader.readInt()
                if (!graph.containsKey(u)) graph[u] = mutableSetOf()
                if (!graph.containsKey(v)) graph[v] = mutableSetOf()
                graph[u]!!.add(v)
                graph[v]!!.add(u)
            }
            return graph
        }

        fun readIntArray(n: Int): Array<Int> {
            return Array(n) { readInt() }
        }

        fun readLongArray(n: Int): Array<Long> {
            return Array(n) { readLong() }
        }

        fun write(obj: Any) {
            writer.printLine(obj)
        }

        fun flushOutput() {
            writer.flush()
        }

        fun closeOutput() {
            writer.close()
        }
    }
}

class MATH {
    companion object {

        val mod = 998244353
        var ispre = false

        val factMod = Array(300002) { 1 }

        fun pre() {
            for (i in 2 until 300001) {
                factMod[i] = ((factMod[i - 1] * i.toLong()) % MATH.mod).toInt()
            }
        }

        fun gcd(a: Int, b: Int): Int {
            if (b == 0)
                return a
            return gcd(b, a % b)
        }

        fun gcd(a: Long, b: Long): Long {
            if (b == 0L)
                return a
            return gcd(b, a % b)
        }

        fun inverseMod(a: Int): Int {
            return powMod(a, mod - 2)
        }

        fun powMod(a: Int, b: Int): Int {
            //calculate a to the power b mod m
            if (b == 0) return 1
            return if (b % 2 == 1) {
                prodMod(a, powMod(a, b - 1))
            } else {
                val p = powMod(a, b / 2)
                prodMod(p, p)
            }
        }

        fun ncr(n: Int, r: Int): Int {
            if (!ispre) pre(); ispre = true
            return ((factMod[n].toLong() * inverseMod(((factMod[r].toLong() * factMod[n - r]) % mod).toInt())) % mod).toInt()
        }

        fun prodMod(val1: Int, val2: Int): Int {
            return ((val1.toLong() * val2) % mod).toInt()
        }

    }
}

fun solve() {
    val n = IO.readInt()
    val (a1, a2, a3) = IO.readThreeInts()
    val (b1, b2, b3) = IO.readThreeInts()

    //minimum wins
    var aa1 = a1
    var aa2 = a2
    var aa3 = a3
    var bb1 = b1
    var bb2 = b2
    var bb3 = b3

    val max = Math.min(aa1, bb2) + Math.min(aa2, bb3) + Math.min(aa3, bb1)

    IO.write("${Math.max(0, aa1 - bb1 - bb3) + Math.min(0, aa2 - bb1 - bb2) + Math.min(0, aa3 - bb2 - bb3)} $max")

    IO.flushOutput()
    IO.closeOutput()
}

fun factorize(n: Int, primes: MutableList<Int>): MutableList<Pair<Int, Int>> {
    val factors = mutableListOf<Pair<Int, Int>>()
    var nn = n
    primes.forEach {
        var power = 0
        while (nn % it == 0) {
            nn /= it
            power++
        }
        if (power != 0) {
            factors.add(Pair(it, power))
        }
    }
    if (nn != 1) {
        factors.add(Pair(nn, 1))
    }
    return factors
}

fun generateDivisors(index: Int, factors: MutableList<Pair<Int, Int>>): List<Int> {
    if (index == factors.size - 1) {
        var cur = 1
        val list = mutableListOf<Int>()
        for (i in 0 until factors[index].second + 1) {
            list.add(cur)
            cur *= factors[index].first
        }
        return list
    }
    val list = generateDivisors(index + 1, factors)
    val newList = mutableListOf<Int>()
    var cur = 1
    for (i in 0 until factors[index].second + 1) {
        list.forEach {
            newList.add(it * cur)
        }
        cur *= factors[index].first
    }
    return newList
}

class ArrayUtils {

    fun lowerBound(arr: Array<Int>, value: Int): Int {
        val pos = arr.binarySearch(value)
        if (pos < 0) return -1 * pos - 1
        var low = 0
        var high = arr.size
        while (low < high) {
            val middle = low + (high - low) / 2
            if (value > arr[middle]) {
                low = middle + 1
            } else {
                high = middle
            }
        }
        return low
    }
}

class InputReader(private val stream: InputStream) {
    private val buf = ByteArray(1024)
    private var curChar: Int = 0
    private var numChars: Int = 0
    private val filter: SpaceCharFilter? = null

    fun read(): Int {
        if (numChars == -1)
            throw InputMismatchException()
        if (curChar >= numChars) {
            curChar = 0
            try {
                numChars = stream.read(buf)
            } catch (e: IOException) {
                throw InputMismatchException()
            }

            if (numChars <= 0)
                return -1
        }
        return buf[curChar++].toInt()
    }

    fun readInt(): Int {
        var c = read()
        while (isSpaceChar(c))
            c = read()
        var sgn = 1
        if (c == '-'.toInt()) {
            sgn = -1
            c = read()
        }
        var res = 0
        do {
            if (c < '0'.toInt() || c > '9'.toInt())
                throw InputMismatchException()
            res *= 10
            res += c - '0'.toInt()
            c = read()
        } while (!isSpaceChar(c))
        return res * sgn
    }

    fun readLong(): Long {
        var c = read()
        while (isSpaceChar(c)) {
            c = read()
        }
        var sgn: Long = 1
        if (c == '-'.toInt()) {
            sgn = -1
            c = read()
        }
        var number: Long = 0
        do {
            number *= 10L
            number += (c - '0'.toInt()).toLong()
            c = read()
        } while (!isSpaceChar(c))
        return number * sgn
    }

    fun readString(): String {
        var c = read()
        while (isSpaceChar(c))
            c = read()
        val res = StringBuilder()
        do {
            res.appendCodePoint(c)
            c = read()
        } while (!isSpaceChar(c))
        return res.toString()
    }

    fun isSpaceChar(c: Int): Boolean {
        return filter?.isSpaceChar(c)
                ?: (c == ' '.toInt() || c == '\n'.toInt() || c == '\r'.toInt() || c == '\t'.toInt() || c == -1)
    }

    operator fun next(): String {
        return readString()
    }

    interface SpaceCharFilter {
        fun isSpaceChar(ch: Int): Boolean
    }
}

class OutputWriter {
    private val writer: PrintWriter

    constructor(outputStream: OutputStream) {
        writer = PrintWriter(BufferedWriter(OutputStreamWriter(outputStream)))
    }

    constructor(writer: Writer) {
        this.writer = PrintWriter(writer)
    }

    fun print(vararg objects: Any) {
        for (i in objects.indices) {
            if (i != 0)
                writer.print(' ')
            writer.print(objects[i])
        }
    }

    fun printLine(vararg objects: Any) {
        print(*objects)
        writer.println()
    }

    fun close() {
        writer.close()
    }

    fun flush() {
        writer.flush()
    }

}


import kotlin.math.*
import java.io.*
import java.util.*

class FastIO: PrintWriter(System.out) {
    val read = BufferedReader(InputStreamReader(System.`in`))
    var token = StringTokenizer("")

    fun next(): String {
        while (!token.hasMoreTokens()) token = StringTokenizer(read.readLine())
        return token.nextToken()
    }

    fun nextInt() = next().toInt()
    fun nextLong() = next().toLong()
    fun nextDouble() = next().toDouble()
}

fun main() {
    val koi = FastIO()

    // val t = koi.nextInt(); for (i in 1..t)
    solve(koi)

    koi.close()
}

class FF(val n: Int) {

	var adj = Array(n){ IntArray(n) }
	var seen = BooleanArray(n)

	fun add(u: Int, v: Int, cap: Int) {
		adj[u][v] += cap
	}

	fun dfs(u: Int, low: Int, t: Int): Int {
		if (u == t)
			return low

		seen[u] = true;

		for (v in 0..n-1) {
			if (adj[u][v] != 0 && !seen[v]) {
				var flow = dfs(v, min(adj[u][v], low), t)

				if (flow > 0) {
					adj[u][v] -= flow
					adj[v][u] += flow
					seen[u] = false
					return flow
				}
			}
		}

		seen[u] = false
		return 0
	}

	fun flow(s: Int, t: Int): Int {
		var flow = 0

		while (true) {
			var here = dfs(s, 100000000, t)
			if (here == 0)
				break
			flow += here
		}

		return flow
	}
}

fun solve(koi: FastIO) {

	var n = koi.nextInt()

	var a = koi.nextInt()
	var c = koi.nextInt()
	var b = koi.nextInt()

	var x = koi.nextInt()
	var z = koi.nextInt()
	var y = koi.nextInt()

	var g1 = FF(8)

	g1.add(6, 0, a)
	g1.add(6, 1, b)
	g1.add(6, 2, c)

	g1.add(3, 7, x)
	g1.add(4, 7, y)
	g1.add(5, 7, z)

	g1.add(0, 3, 100000000)
	g1.add(0, 4, 100000000)
	g1.add(1, 4, 100000000)
	g1.add(1, 5, 100000000)
	g1.add(2, 5, 100000000)
	g1.add(2, 3, 100000000)

	var g2 = FF(8)

	g2.add(6, 0, a)
	g2.add(6, 1, b)
	g2.add(6, 2, c)

	g2.add(3, 7, x)
	g2.add(4, 7, y)
	g2.add(5, 7, z)

	g2.add(0, 5, 100000000)
	g2.add(1, 3, 100000000)
	g2.add(2, 4, 100000000)

	val ans1 = n - g1.flow(6, 7)
	val ans2 = g2.flow(6, 7)

	koi.println("$ans1 $ans2")
}


import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.*
import kotlin.math.*
import kotlin.collections.*

private var fs = BufferedReader(InputStreamReader(System.`in`))
private val out = StringBuilder()
private fun readLn() = fs.readLine()!!
private fun readStrings() = readLn().split(" ")
private fun readLong() = readLn().toLong()
private fun readLongs() = readStrings().map { it.toLong() }
private fun readInt() = readLn().toInt()
private fun readInts() = readStrings().map { it.toInt() }

fun main() {
//    val t = readInt()
//    for (tt in 0 until t) {
    solve()
//    }
    print(out)
}

private fun solve() {
    var n = readInt()
    var (rA,sA,pA) = readInts()
    var (rB,sB,pB) = readInts()
    var max = min(rA,sB) + min(sA,pB) + min(pA,rB)
    var min = 0
    var copy = 0
    if(rB == max(rB,max(sB,pB))){
        copy = pA
        min += min(pA,pB)
        pA -= min(pA,pB).also{pB -= min(pA,pB)}
        min += min(pA,sB)
    }
    else if(sB == max(rB,max(sB,pB))){
        copy = rA
        min += min(rA,rB)
        rA -= min(rA,rB).also{rB -= min(rA,rB)}
        min += min(rA,pB)
    }
    else if(pB == max(rB,max(sB,pB))){
        copy =sA
        min += min(sA,sB)
        sA -= min(sA,sB).also{sB -= min(sA,sB)}
        min += min(sA,rB)
    }
    println("${copy-min} $max")

}


fun main(args: Array<String>){
    val n = readLine()!!.toInt()
    val sequence = readLine()!!.toList().map {it.toString().toInt()}
    var target_segment_sum = 0
    for (initial_segment_length in 1..n){
        target_segment_sum += sequence[initial_segment_length-1]
        var segment_sum = 0
        for(index in initial_segment_length..n-1){
            segment_sum += sequence[index]
            if(segment_sum == target_segment_sum){
                segment_sum = 0
            }
            else if(segment_sum > target_segment_sum){
                break
            }
        }
        if(segment_sum == 0) {
            println("YES")
            return
        }
    }
    println("NO")

}


fun main() {
    val positions = "V<^>"
    val fromTo = readLine()!!
    val duration = readLine()!!.toInt() % 4
    var sol = if (fromTo[2] == positions[(positions.indexOf(fromTo[0]) + duration) % 4]) 1 else 0
    if (fromTo[2] == positions[(positions.indexOf(fromTo[0]) + 4 - duration) % 4]) sol = sol or 2
    print(
        when (sol) {
            1 -> "cw"
            2 -> "ccw"
            else -> "undefined"
        }
    )
}


import kotlin.math.min

fun main() {
    //for (t in 1..nextInt()) {
        println(solve(nextInt(), nextInt(), nextInt(), nextInt()))
    //}
}

fun solve(a: Int, b: Int, c: Int, d: Int): String {
    val count = IntArray(b + c + 2)
    for (i in a + b .. b + c) {
        count[i - 1] = min(i - a - b + 1, b + c - i + 1)
    }
    for (i in b + c downTo 1) {
        count[i] += count[i + 1]
    }
    //println(count.joinToString(" "))
    var res = 0L
    for (i in c..d) {
        val t = min(i, b + c + 1)
        res += count[t]
    }
    return res.toString()
}

fun nextInt() = reader.nextInt()

fun nextLong() = reader.nextLong()

fun nextDouble() = reader.nextDouble()

fun next() = reader.next()

fun nextLine() = reader.nextLine()

object reader {

    private var tokens = listOf<String>()
    private var index = 0

    fun nextInt() = this.next().toInt()

    fun nextLong() = this.next().toLong()

    fun nextDouble() = this.next().toDouble()

    fun next(): String {
        if (index == tokens.size) {
            tokens = this.nextLine().split(" ")
            index = 0
        }
        return tokens[index++]
    }

    fun nextLine(): String {
        tokens = listOf()
        index = 0
        return readLine()!!
    }
}


@file:Suppress("NOTHING_TO_INLINE", "EXPERIMENTAL_FEATURE_WARNING", "OVERRIDE_BY_INLINE")

import java.io.PrintWriter
import java.util.PriorityQueue
import java.util.TreeSet
import kotlin.math.*
import kotlin.random.Random
import kotlin.system.exitProcess
import kotlin.collections.sort as _sort
import kotlin.collections.sortDescending as _sortDescending
import kotlin.io.println as iprintln

/** @author Spheniscine */
fun main() { _writer.solve(); _writer.flush() }
fun PrintWriter.solve() {
    val numCases = 1//readInt()
    for(case in 1..numCases) {
        //print("Case #$case: ")

        val a = readInt()
        val b = readInt()
        val c = readInt()
        val d = readInt()

        val ans = (a..b).sumByLong { x ->
            minOf(c-b+1, d-c+1, x).tr
        }

        println(ans)
    }
}

val Int.tr get() = toLong() * plus(1) / 2

/** IO */
//@JvmField val INPUT = File("input.txt").inputStream()
//@JvmField val OUTPUT = File("output.txt").outputStream()
@JvmField val INPUT = System.`in`
@JvmField val OUTPUT = System.out

@JvmField val _reader = INPUT.bufferedReader()
fun readLine(): String? = _reader.readLine()
fun readLn() = _reader.readLine()!!
@JvmField var _ln = ""
@JvmField var _lnPtr = 0
fun read(): String {
    while (_lnPtr >= _ln.length) {
        _ln = readLine() ?: return ""
        _lnPtr = 0
    }
    var j = _ln.indexOf(' ', _lnPtr)
    if(j < 0) j = _ln.length
    val res = _ln.substring(_lnPtr, j)
    _lnPtr = j + 1
    return res
}
fun readRem(): String /* reads remainder of current line */ =
    _ln.substring(min(_lnPtr, _ln.length)).also { _lnPtr = _ln.length }
fun readInt() = read().toInt()
fun readDouble() = read().toDouble()
fun readLong() = read().toLong()
fun readStrings(n: Int) = List(n) { read() }
fun readLines(n: Int) = List(n) { readLn() }
fun readInts(n: Int) = List(n) { read().toInt() }
fun readIntArray(n: Int) = IntArray(n) { read().toInt() }
fun readDoubles(n: Int) = List(n) { read().toDouble() }
fun readDoubleArray(n: Int) = DoubleArray(n) { read().toDouble() }
fun readLongs(n: Int) = List(n) { read().toLong() }
fun readLongArray(n: Int) = LongArray(n) { read().toLong() }

@JvmField val _writer = PrintWriter(OUTPUT, false)

/** shuffles and sort overrides to avoid quicksort attacks */
private inline fun <T> _shuffle(rnd: Random, get: (Int) -> T, set: (Int, T) -> Unit, size: Int) {
    // Fisher-Yates shuffle algorithm
    for (i in size - 1 downTo 1) {
        val j = rnd.nextInt(i + 1)
        val temp = get(i)
        set(i, get(j))
        set(j, temp)
    }
}

@JvmField var _random: Random? = null
val random get() = _random ?: Random(0x594E215C123 * System.nanoTime()).also { _random = it }

fun IntArray.shuffle(rnd: Random = random) = _shuffle(rnd, ::get, ::set, size)
fun IntArray.sort() { shuffle(); _sort() }
fun IntArray.sortDescending() { shuffle(); _sortDescending() }

fun LongArray.shuffle(rnd: Random = random) = _shuffle(rnd, ::get, ::set, size)
fun LongArray.sort() { shuffle(); _sort() }
fun LongArray.sortDescending() { shuffle(); _sortDescending() }

fun DoubleArray.shuffle(rnd: Random = random) = _shuffle(rnd, ::get, ::set, size)
fun DoubleArray.sort() { shuffle(); _sort() }
fun DoubleArray.sortDescending() { shuffle(); _sortDescending() }

fun CharArray.shuffle(rnd: Random = random) = _shuffle(rnd, ::get, ::set, size)
inline fun CharArray.sort() { _sort() }
inline fun CharArray.sortDescending() { _sortDescending() }

inline fun <T: Comparable<T>> Array<out T>.sort() = _sort()
inline fun <T: Comparable<T>> Array<out T>.sortDescending() = _sortDescending()
inline fun <T: Comparable<T>> MutableList<out T>.sort() = _sort()
inline fun <T: Comparable<T>> MutableList<out T>.sortDescending() = _sortDescending()

fun `please stop removing these imports IntelliJ`() { iprintln(max(1, 2)) }

/** additional commons */
inline fun <T> Iterable<T>.sumByLong(func: (T) -> Long) = fold(0L) { acc, t -> acc + func(t) }
inline fun <T> Sequence<T>.sumByLong(func: (T) -> Long) = fold(0L) { acc, t -> acc + func(t) }
inline fun <T> Array<T>.sumByLong(func: (T) -> Long) = fold(0L) { acc, t -> acc + func(t) }
fun IntArray.sumLong() = fold(0L, Long::plus)


fun main() {
    repeat(readLine()!!.toInt()) {
        readLine()
        val input = readLine()!!.split(" ").map { it.toInt() }
        var number = 0
        var smaller = 0
        input.sorted().forEach {
            if (it <= smaller + 1) {
                number++
                smaller -= it - 1
            } else {
                smaller++
            }
        }
        println(number)
    }
}


import kotlin.math.max
import kotlin.math.min

fun soucetRady(n: Long) = n * (n + 1) / 2
fun soucetCisel(a: Long, b: Long) = max(0, soucetRady(b) - soucetRady(a - 1))

fun main() {
    val (a, b, c, d) = readLine()!!.split(" ").map { it.toLong() }
    var number = 0L
    for (i in c..d) {
        val aa = max(a, i + 1 - c)
        val pocet = b - aa + 1
        val pocet2 = c - b + 1
        val start = min(c - i + aa, pocet2)
        number += soucetCisel(start, min(pocet2, pocet + start - 1))
        number += (pocet - min(pocet2 - start + 1, pocet)) * pocet2
    }
    println(number)
}


import java.lang.StringBuilder
import java.util.*

private fun readLn() = readLine()!! // string line
private fun readInt() = readLn().toInt() // single int
private fun readStrings() = readLn().split(" ") // list of strings
private fun readInts() = readStrings().map { it.toInt() } // list of ints
private fun readLongs() = readStrings().map { it.toLong() } // list of longs

fun main(args: Array<String>) {
    c()
}

fun divisor(n: Int): Int {
    var i = 2
    while (i * i <= n) {
        if (n % i == 0) return i
        i++
    }
    return n
}

fun a() {
    val t = readInt()
    repeat(t) {
        val n = readInt()
        val e = readInts().sorted()

        var ans = 0

        var i = 0
        while (i < n) {
            var k = e[i]
            var j = 0

            while (j < k && i + j < n) {
                k = e[i + j]
                j++
            }

            if (j == k) {
                ans++
            }
            i += j
        }

        println(ans)
    }
}

fun b() {
    val t = readInt()
    repeat(t) {
        val n = readInt()

        val s = readInts()
        val d = IntArray(n + 1)

        d[1] = 1

        for (i in 2 until n + 1) {
            var j = 1
            d[i] = 1
            while (j * j <= i) {
                if (i % j == 0) {
                    val k = i / j
                    if (s[i - 1] > s[j - 1]) d[i] = maxOf(d[i], d[j] + 1)
                    if (s[i - 1] > s[k - 1]) d[i] = maxOf(d[i], d[k] + 1)
                }
                j++
            }
        }

        println(d.max()!!)
    }
}

private fun dif(a: Int, b: Int, i: Int): Int {
    val ai = (i % a) % b
    val bi = (i % b) % a

    return if (ai != bi) 1 else 0
}

private fun fff(p: IntArray, x: Long): Long {
    val n = p.size
    val times = x / n
    val rem = (x % n).toInt()
    return times * p.last() + p[rem]
}

fun c() {
    val (a, b, c, d) = readLongs()

    var ans = 0L

    var aSide = a
    var bSide = b

    for (k in c..d) {
        while (aSide + bSide <= k && aSide < b) aSide++
        while (aSide + bSide <= k && bSide < c) bSide++

        if (aSide + bSide > k) {
//            println("$k, $aSide, $bSide: $ans")
            ans += (c - bSide + 1) * (b - aSide + 1)

            if (c - bSide < aSide - a) {
                val s = c - bSide
                ans += s * (s + 1) / 2
            } else {
                val x = c - bSide
                val s = aSide - a
                ans += x * (x + 1) / 2 - s * (s + 1) / 2
            }
        }
    }

    println(ans)
}

fun d() {
    val (n, s) = readInts()

    if (s >= n * 2) {
        println("YES")
        val out = mutableListOf<Int>()
        repeat(n - 1) {
            out.add(2)
        }
        out.add(s - (n - 1) * 2)

        println(out.joinToString(separator = " "))
        println(1)
    } else {
        println("NO")
    }
}

//1
//4 3
//1 3 2 4

//1
//3 3
//1 3 2

private inline fun sqr(x: Int) = 1L * x * x

fun e() {
    val (n, m) = readInts()
    val land = readInts().sorted()
    val (g, r) = readInts()

    val d = Array(m) { LongArray(g + 1) { Long.MAX_VALUE } }
    d[0][0] = 0

    val q = PriorityQueue<Triple<Long, Int, Int>>( compareBy { it.first } )

    q.add(Triple(0, 0, 0))

    while (q.isNotEmpty()) {
        var (len, i, j) = q.poll()

//        println("$len, $i, $j")

        if (i == m - 1) break
        if (d[i][j] < len) continue

        if (j == g) {
            j = 0
            len += r
            if (d[i][j] < len) continue
        }

        if (i > 0) {
            val l = land[i] - land[i - 1]
            if (j + l <= g && d[i - 1][j + l] > len + l) {
                d[i - 1][j + l] = len + l
                q.add(Triple(len + l, i - 1, j + l))
            }
        }
        if (i < m - 1) {
            val l = land[i + 1] - land[i]
            if (j + l <= g && d[i + 1][j + l] > len + l) {
                d[i + 1][j + l] = len + l
                q.add(Triple(len + l, i + 1, j + l))
            }
        }
    }

    val ans = d[m - 1].min()!!
    println(if (ans < Long.MAX_VALUE) ans else -1)
}

fun Int.isEven(): Boolean = this % 2 == 0
fun Int.isOdd(): Boolean = this % 2 == 1

public operator fun <T> List<T>.component6(): T {
    return get(5)
}

fun allPrimesUpTo(n: Int): List<Int> {
    val isPrime = BooleanArray(n + 1) { true }
    val primes = mutableListOf<Int>()

    isPrime[0] = false
    isPrime[1] = false
    for (i in 2 until n + 1) {
        if (isPrime[i]) {
            primes.add(i)

            if (i.toLong() * i > n)
                continue

            for (j in i * i until n + 1 step i) {
                isPrime[j] = false
            }
        }
    }

    return primes
}


import java.io.BufferedReader
import java.io.InputStream
import java.io.InputStreamReader
import java.io.PrintWriter
import java.lang.StringBuilder
import java.util.*
import kotlin.concurrent.fixedRateTimer

fun PrintWriter.solve(sc: FastScanner) {
    val a = sc.nextInt()
    val b = sc.nextInt()
    val c = sc.nextInt()
    val d = sc.nextInt()
    var ans = 0L
    var count = 0
    for (s in a + b .. b + c) {
        if (s in a + b .. b + b) count++
        if (s in a + c + 1 .. b + c + 1) count--
        ans += count * maxOf(minOf(s, d + 1) - c, 0)
    }
    println(ans)
}

fun main(args: Array<String>) {
    val writer = PrintWriter(System.out, false)
    writer.solve(FastScanner(System.`in`))
    writer.flush()
}

class FastScanner(s: InputStream) {
    private var st = StringTokenizer("")
    private val br = BufferedReader(InputStreamReader(s))

    fun next(): String {
        while (!st.hasMoreTokens()) st = StringTokenizer(br.readLine())

        return st.nextToken()
    }

    fun nextInt() = next().toInt()
    fun nextLong() = next().toLong()
    fun nextLine() = br.readLine()
    fun nextDouble() = next().toDouble()
    fun ready() = br.ready()
}


import kotlin.math.min

fun main() {
    val (a, b, c, d) = readNumbers()
    println(solve(a, b, c, d))
}

fun solve(a: Int, b: Int, c: Int, d: Int): Long {
    var res = 0L
    for (k in a + b..b + c) {
        val k0 = k - a - b
        val t = min(k0, b - a) + min(k0, c - b) - k0 + 1
        if (t > 0)
            if (k > d) {
                res += t * (d - c + 1)
            } else if (k > c) {
                res += t * (k - c)
            }
    }
    return res;
}

fun readNumber() = readLine()!!.toInt()

fun readNumbers(line: String = readLine()!!): IntArray {
    return line
        .split(" ")
        .map { it.toInt() }
        .toIntArray()
}


import Mod.mdiv
import Mod.mmod
import Mod.mmult
import Mod.mplus
import Mod.mpow
import NumTh.inverse
import kotlin.collections.*
import kotlin.math.*
import java.util.Queue
import java.util.LinkedList
import java.util.PriorityQueue

fun readLn() = readLine()!!.trim() // string line
fun readInt() = readLn().trim().toInt() // single int
fun readStrings() = readLn().trim().split(" ") // list of strings
fun readInts() = readStrings().map { it.trim().toInt() } // list of ints
fun readLongs() = readStrings().map { it.trim().toLong() } // list of ints
fun readLong() = readLn().trim().toLong() // list of strings
fun writeGoogleAnswer(case: Int, str: String) = println("Case #$case: $str")

object NumTh {
    fun euclideanExt(la: Long, lb: Long): Triple<Long, Long, Long> {
        val signa = sign(la.toDouble()).toLong()
        val signb = sign(lb.toDouble()).toLong()

        var a = abs(la)
        var b = abs(lb)
        val reverse = a > b
        if (reverse) {
            a = b.also { b = a }
        }

        var m11 = 1L
        var m12 = 0L
        var m21 = 0L
        var m22 = 1L

        while (a > 0) {
            val tmp = b / a
            a = (b % a).also { b = a }
            m11 = (m12 - m11 * tmp).also { m12 = m11.also { m21 = (m22 - m21 * tmp).also { m22 = m21 } } }
        }
        var x = m12
        var y = m22
        var d = b
        if (reverse) {
            x = x.also { y = x }
        }
        return Triple(signa * x, signb * y, d)
    }

    fun euclideanExt(la: Int, lb: Int): Triple<Int, Int, Int> {
        val res = euclideanExt(la.toLong(), lb.toLong())
        return Triple(res.first.toInt(), res.second.toInt(), res.third.toInt())
    }

    public fun inverse(la: Long, mod: Long): Long {
        val res = euclideanExt(la mmod mod, mod).first
        return if (res < 0) res + mod else res
    }

    public fun inverse(la: Int, mod: Int): Int {
        val res = euclideanExt(la mmod mod, mod).first
        return if (res < 0) res + mod else res
    }

    infix fun Long.gcd(lb: Long) = euclideanExt(this, lb).third

    infix fun Int.gcd(lb: Int) = euclideanExt(this, lb).third

    fun chinese(qs: List<Int>, ans: List<Int>): Pair<Int, Int> {

        if (qs.count() == 1) {
            return Pair(qs[0], ans[0] % qs[0])
        }
        val rng1 = 0 until qs.count() / 2
        val res1 = chinese(qs.slice(rng1), ans.slice(rng1))
        val rng2 = qs.count() / 2 until qs.count()
        val res2 = chinese(qs.slice(rng2), ans.slice(rng2))
        // println(res1)
        // println( res2 )
        // println( inverse(res2.first, res1.first) )
        // println( inverse(res1.first, res2.first) )
        val mod = res1.first * res2.first
        val res = (res1.second * res2.first * inverse(res2.first, res1.first) + res2.second * res1.first * inverse(res1.first, res2.first)) % mod
        return Pair(mod, res)
    }

    public fun Long.getPDivisors(): MutableList<Long> {
        if (this == 0L) {
            throw Exception()
        }
        var n = abs(this)
        val res = mutableListOf<Long>()
        while (n % 2L == 0L) {
            res.add(2L)
            n /= 2L
        }

        var cur = 3L
        while (n > 1) {
            if (n % cur != 0L) {
                cur += 2
                continue
            }
            while (n % cur == 0L) {
                res.add(cur)
                n /= cur
            }
            cur += 2
        }
        return res
    }

    public fun Long.getAllDivisors(): MutableList<Long> {
        if (this == 0L) {
            throw Exception()
        }
        val n = abs(this)
        val res = mutableListOf<Long>()
        var v = 2L
        while (v * v < n) {
            if (n % v == 0L) {
                res.add(v)
            }
            v++
        }
        if (v * v == n) {
            res.add(v)
        }
        return res
    }

    public fun Int.getAllDivisors(): MutableList<Int> {
        if (this == 0) {
            throw Exception()
        }
        val n = abs(this)
        val res = mutableListOf<Int>()
        var v = 2
        while (v * v < n) {
            if (n % v == 0) {
                res.add(v)
            }
            v++
        }
        if (v * v == n) {
            res.add(v)
        }
        return res
    }

    public fun Int.getPDivisors(): MutableList<Int> {
        if (this == 0) {
            throw Exception()
        }
        var n = abs(this)
        val res = mutableListOf<Int>()
        while (n % 2 == 0) {
            res.add(2)
            n /= 2
        }

        var cur = 3
        while (n > 1) {
            if (n % cur != 0) {
                cur += 2
                continue
            }
            while (n % cur == 0) {
                res.add(cur)
                n /= cur
            }
            cur += 2
        }
        return res
    }
}

object Mod {
    private var _div = 2L

    public val div: Long
        get() = _div

    public fun setMod(div: Long) {
        if (div <= 0) {
            throw Exception()
        }
        _div = div
    }

    public fun setMod(div: Int) {
        if (div <= 0) {
            throw Exception()
        }
        _div = div.toLong()
    }

    public fun Long.mmod(): Long {
        return if (this < 0) _div + (this % _div) else this % _div
    }

    public fun Int.mmod(): Int {
        return (if (this < 0) _div + (this % _div) else this % _div).toInt()
    }

    public infix fun Long.mrem(v: Long): Long {
        if (v == 0L) {
            throw Exception()
        }
        return abs(this) % v
    }

    public fun Long.mpow(exp: Long, divisor: Long): Long {
        if (this == 0L && exp <= 0) {
            throw Exception()
        }

        if (exp == 0L) {
            return 1L
        }
        if (exp == 1L) {
            return this
        }
        var lv = this
        var lexp = exp

        var res = 1L
        while (lexp > 0) {
            res = (res * if (lexp % 2 == 1L) lv else 1L) % divisor
            lv = (lv * lv) % divisor
            lexp /= 2L
        }
        return res
    }

    public fun Int.mpow(exp: Int, divisor: Long): Int {

        return (this.toLong()).mpow(exp.toLong(), divisor.toLong()).toInt()
    }

    public fun Long.mmult(v: Long, mod: Long): Long {
        if (mod <= 0) {
            throw Exception()
        }
        return (this * v) mmod mod
    }

    public fun Int.mmult(v: Int, mod: Int): Int {
        return this.toLong().mmult(v.toLong(), mod.toLong()).toInt()
    }

    public infix fun Long.mmult(v: Long): Long {
        return this.mmult(v, _div)
    }

    public infix fun Int.mmult(v: Int): Int {
        return this.toLong().mmult(v.toLong(), _div).toInt()
    }

    public fun Long.mdiv(v: Long, mod: Long): Long {
        if (mod <= 0) {
            throw Exception()
        }
        return this.mmult(inverse(v, mod), mod)
    }

    public fun Int.mdiv(v: Int, mod: Int): Int {
        if (mod <= 0) {
            throw Exception()
        }
        return this.toLong().mdiv(v.toLong(), mod.toLong()).toInt()
    }

    public infix fun Long.mdiv(v: Long): Long {
        return this.mdiv(v, _div)
    }

    public infix fun Int.mdiv(v: Int): Int {
        return this.toLong().mdiv(v.toLong(), _div).toInt()
    }

    public fun Long.mminus(v: Long, mod: Long): Long {
        return this.mplus(-1L*v, mod)
    }

    public fun Int.mminus(v: Int, mod: Int): Int {
        return this.mplus(-1*v, mod)
    }

    public fun Long.mplus(v: Long, mod: Long): Long {
        if (mod <= 0) {
            throw Exception()
        }
        return (this + v) mmod mod
    }

    public fun Int.mplus(v: Int, mod: Int): Int {
        return this.toLong().mplus(v.toLong(), mod.toLong()).toInt()
    }

    public infix fun Long.mminus(v: Long): Long {
        return this.mplus(-1L*v, _div)
    }

    public infix fun Int.mminus(v: Int): Int {
        return this.mplus(-1*v, _div.toInt()).toInt()
    }

    public infix fun Long.mplus(v: Long): Long {
        return this.mplus(v, _div)
    }

    public infix fun Int.mplus(v: Int): Int {
        return this.mplus(v, _div.toInt())
    }

    public infix fun Long.mmod(mod: Long): Long {
        if (mod <= 0L) {
            throw Exception()
        }
        return if (this < 0) mod + (this % mod) else this % mod
    }

    public infix fun Int.mmod(mod: Int): Int {
        if (mod <= 0) {
            throw Exception()
        }
        return (if (this < 0) mod + (this % mod) else this % mod).toInt()
    }

    public infix fun Long.mpow(exp: Long): Long {
        return this.mpow(exp, _div)
    }

    public infix fun Int.mpow(exp: Int): Int {
        return this.mpow(exp, _div)
    }
}

object Comb {

    var facts: LongArray = LongArray(0)
        private set

    public fun Int.mprecompute() {
        if (this < 0) {
            throw Exception()
        }
        facts = LongArray(this + 1)
        facts[0] = 1L
        for (i in 1..this) {
            facts[i] = facts[i - 1] mmult i.toLong()
        }
    }

    public fun Long.mfact(mod: Long): Long {
        if (this == 1L || this == 0L) {
            return 1L
        }

        var res = 1L
        for (i in 2L..this) {
            res = (res * i) mmod mod
        }
        return res
    }

    public fun Long.mfact(): Long {
        return this.mfact(Mod.div)
    }

    public fun Int.mfact(mod: Int): Int {
        return this.toLong().mfact(mod.toLong()).toInt()
    }

    public fun Int.fact(): Int {
        return this.mfact(Mod.div.toInt())
    }
}

fun getMaxBit(v: Long): Int {
    var res = 0
    var cur = v
    while (cur > 0) {
        res++
        cur = cur shr 1
    }
    return res
}

fun isPrime(vl: Long): Boolean {

    var test = 2L
    while (test * test <= vl && (vl % test != 0L)) {
        test++
    }
    return (vl == 2L) || (vl % test) != 0L
}

fun getBit(v: Long, s: Int): Long {
    return (v shr s) and 1
}

fun getNext1(v1: Long, s: Int): Int {
    var cur = s
    while (getBit(v1, cur) == 0L && cur < 64) {
        cur++
    }
    return cur
}

fun replace10(v1: Long, v2: Long, st: Int, reverse: Boolean, res: MutableList<String>): Int {
    var onep1 = getNext1(v1, st + 1)
    var onep2 = getNext1(v2, st + 1)
    var last = min(onep1, onep2)
    if (last == 64) {
        last = st + 2
    }
    last -= 1
    for (i in st..last - 1) {
        res.add(if (reverse) "S" else "W")
    }
    res.add(if (reverse) "N" else "E")
    return last + 1
}

fun replace11(v1: Long, v2: Long, st: Int, reverse: Boolean, res: MutableList<String>): Int? {
    var onep1 = getNext0(v1, st + 1)
    var onep2 = getNext0(v2, st + 1)
    if (onep1 != onep2) {
        return null
    }
    res.add(if (reverse) "S" else "W")

    var last = onep1
    for (i in (st + 1)..(last - 1)) {
        res.add(if (reverse) "E" else "N")
    }
    res.add(if (reverse) "N" else "E")
    return last + 1
}

fun getNext0(v1: Long, s: Int): Int {
    var cur = s
    while (getBit(v1, cur) == 1L && cur < 64) {
        cur++
    }
    return cur
}

fun pow(v: Long, pow: Long, mod: Long): Long {

    if (pow == 0L) {
        return 1L
    }
    if (pow == 1L) {
        return v
    }
    var res = if (pow % 2L == 1L) v else 1L
    val tmp = pow((v*v) % mod, pow / 2, mod)
    res *= (tmp * tmp) % mod
    res = res % mod
    return res
}

class UF {
    val rank = HashMap<Int, Int>()
    val parent = HashMap<Int, Int>()
    val counts = HashMap<Int, Int>()
    var groupCnt = 0

    fun add(v: Int) {
        if (!rank.containsKey(v)) {
            groupCnt ++
            // println("$v: $groupCnt")
            rank[v] = 1
            parent[v] = v
            counts[v] = 1
        }
    }

    fun getParent(v: Int): Int {

        add(v)
        var p1 = v

        while (parent[p1] != p1) {

            val tmp = p1
            p1 = parent[p1]!!
            parent[tmp] = parent[p1]!!
        }
        return p1
    }

    fun union(v1: Int, v2: Int) {

        // println("union: $v1, $v2")
        var p1 = getParent(v1)
        var p2 = getParent(v2)
        if (p1 == p2) {
            return
        }

        groupCnt --
        // println(groupCnt)
        if (rank[p2]!! > rank[p1]!!) {
            parent[p1] = p2
            counts[p2] = counts[p2]!! + counts[p1]!!
        } else if (rank[p2]!! < rank[p1]!!) {
            parent[p2] = p1
            counts[p1] = counts[p1]!! + counts[p2]!!
        } else {
            parent[p1] = p2
            counts[p2] = counts[p2]!! + counts[p1]!!
        }
    }

    fun connected(v1: Int, v2: Int): Boolean {
        return getParent(v1) == getParent(v2)
    }
}

fun solve(arr:MutableList<Int>, i: Int, j: Int, a:Int, b:Int) {
    if(i == j){
        arr[i] = a
        return
    } else if( j == i + 1){
        arr[i] = a
        arr[j] = a + b
        return
    }

    if((j - i + 1) % 2 == 0){
        arr[(j+i - 1) / 2] = a
        solve(arr, i, ((j+i - 1) / 2) - 1, a + 2 * b, 2*b)
        solve(arr, ((j+i - 1) / 2) + 1, j , a +  b, 2 * b)
    }
    else{
        arr[(j+i) / 2] = a
        solve(arr, i, ((j+i) / 2) - 1, a + b, 2*b)
        solve(arr, ((j+i) / 2) + 1, j , a + 2 * b, 2 * b)
    }
}

fun getProd(v:Long):Long{
    if(v == 0L) return 0

    var tmp = v
    var mn = 10L
    var mx = -1L
    while(tmp > 0){
        var cur = tmp % 10
        if(mn > cur){
            mn = cur
        }
        if(mx < cur){
            mx = cur
        }
        if(mn == 0L){
            return 0L
        }
        tmp = tmp / 10
    }
    return mn*mx

}

fun main(args: Array<String>) {

    val (a,b,c,d) = readLongs()
    var sum = 0L
    for (x in a..b) {
        val ymn = max(c + 1 - x, b)
        val ymx =min(c, d + 1 - x)
       // println(ymn)
       // println(ymx)
        if(ymx >= ymn){
            sum+= (((x + ymn - c) + (x + ymx - c)) * ((x + ymx - c) - (x + ymn - c) + 1) ) / 2
        }

        sum += if(ymx < c) (c- max(ymx, b) + 1)*(d - c + 1) else 0
    }
    println(sum)
}


@file:Suppress("NOTHING_TO_INLINE", "EXPERIMENTAL_FEATURE_WARNING", "OVERRIDE_BY_INLINE")

import java.io.PrintWriter
import java.lang.StringBuilder
import java.util.PriorityQueue
import java.util.StringTokenizer
import java.util.TreeMap
import kotlin.math.*
import kotlin.random.*
import kotlin.collections.sort as _sort
import kotlin.collections.sortDescending as _sortDescending
import kotlin.io.println as iprintln

/** @author Spheniscine */
fun main() { _writer.solve(); _writer.flush() }
fun PrintWriter.solve() {
    val percent = ModInt(100).inverse()

    val n = readInt()
    val pipes = List(n) { Pipe(readInt(), readInt(), percent * readInt()) }

    val tree = SegmentTree(n-1, null, nullIdentityCombiner(Seg::plus))

    tree.build { i ->
        Seg(
            ll = pipes[i].p.not() * pipes[i+1].p.not(),
            lr = pipes[i].p.not() * pipes[i+1].p,
            rl = pipes[i].p * pipes[i+1].p.not(),
            rr = pipes[i].p * pipes[i+1].p
        )
    }

    val cols = ArrayList<Collision>(2*n)

    for(i in 0 until n-1) {
        val a = pipes[i]
        val b = pipes[i+1]

        val d = b.x - a.x
        cols.add(Collision(i, RL, d, a.v + b.v))
        if(a.v > b.v) cols.add(Collision(i, RR, d, a.v - b.v))
        else if(a.v < b.v) cols.add(Collision(i, LL, d, b.v - a.v))
    }

    cols.sortWith(Collision.comparator)

    var currProb = ModInt(1)
    var ans = ModInt(0)
    for((a, t, d, v) in cols) {
        tree[a] = tree[a]!!.ban(t)
        val prob = tree[0, tree.size]!!.sum
        ans += (currProb - prob) * d / v
        currProb = prob
    }

    println(ans.int)
}

inline fun ModInt.not() = ModInt(1) - this

data class Pipe(val x: Int, val v: Int, val p: ModInt)
data class Collision(val a: Int, val type: CollisionType, val d: Int, val v: Int) {
    companion object {
        val comparator = Comparator<Collision> { a, b ->
            (a.d.toLong() * b.v).compareTo(b.d.toLong() * a.v)
        }
    }

    inline val b get() = a + 1
}

inline class CollisionType(val i: Int)
inline val LL get() = CollisionType(0)
inline val LR get() = CollisionType(1)
inline val RL get() = CollisionType(2)
inline val RR get() = CollisionType(3)

class Seg(private val values: IntArray) {
    constructor(ll: ModInt, lr: ModInt, rl: ModInt, rr: ModInt): this(intArrayOf(ll.int, lr.int, rl.int, rr.int))

    operator fun get(collisionType: CollisionType) = ModInt(values[collisionType.i])
    val ll get() = ModInt(values[0])
    val lr get() = ModInt(values[1])
    val rl get() = ModInt(values[2])
    val rr get() = ModInt(values[3])

    operator fun plus(b: Seg): Seg {
        val al = ll + lr
        val ar = rl + rr
        val bl = b.ll + b.rl
        val br = b.lr + b.rr

        return Seg(
            ll = al * bl,
            lr = al * br,
            rl = ar * bl,
            rr = ar * br
        )
    }

    val sum get() = ModIntArray(values).sum()

    fun ban(collisionType: CollisionType) = Seg(values.copyOf().also { it[collisionType.i] = 0 })
}

class SegmentTree<T>(
    val size: Int,
    val identityValue: T,
    val combiner: (T, T) -> T) {

    /* degenericization helpers
    val identityValue: T = TODO()
    fun combiner(a: T, b: T): T = TODO()
    */

    @Suppress("UNCHECKED_CAST")
    private val array = Array<Any?>(2 * size) { identityValue } as Array<T>

    inline val lastIndex get() = size - 1
    inline val indices get() = 0 until size
    val asList: List<T> by lazy {
        object : AbstractList<T>() {
            override val size: Int get() = this@SegmentTree.size
            override fun get(index: Int): T = this@SegmentTree[index]
        }
    }

    fun build(generator: (Int) -> T) {
        for(i in 0 until size) {
            array[i + size] = generator(i)
        }
        for(i in size-1 downTo 1) {
            array[i] = combiner(array[i shl 1], array[i shl 1 or 1])
        }
    }

    /** instantiates values from an iterable, O(n) time */
    fun copyFrom(iterable: Iterable<T>) {
        run {
            iterable.forEachIndexed { i, t ->
                if(i > lastIndex) return@run
                array[i + size] = t
            }
        }
        for(i in size-1 downTo 1) {
            array[i] = combiner(array[i shl 1], array[i shl 1 or 1])
        }
    }

    /** Updates a value, O(log n) time */
    operator fun set(index: Int, value: T) {
        require(index in 0 until size)
        var i = index + size
        array[i] = value
        while(true) {
            i = i shr 1
            if(i <= 0) break
            array[i] = combiner(array[i shl 1], array[i shl 1 or 1])
        }
    }

    /** Gets a value by its index, O(1) time */
    operator fun get(index: Int): T {
        require(index in 0 until size)
        return array[index + size]
    }

    /** gets the result of applying the monoid operation to the values in the index range, O(log n) time */
    operator fun get(start: Int, endExclusive: Int): T {
        var l = maxOf(start, 0) + size
        var r = minOf(endExclusive, size) + size

        // two accumulators to support non-commutative monoids
        var lAcc = identityValue
        var rAcc = identityValue

        while(l < r) {
            if(l and 1 == 1) {
                lAcc = combiner(lAcc, array[l++])
            }
            if(r and 1 == 1) {
                rAcc = combiner(array[--r], rAcc)
            }

            l = l shr 1
            r = r shr 1
        }

        return combiner(lAcc, rAcc)
    }

    operator fun get(range: IntRange) = get(range.first, range.last + 1)
}

/** Converts a semigroup to a monoid by using null as the identity value. */
inline fun <T: Any> nullIdentityCombiner(crossinline combiner: (T, T) -> T): (T?, T?) -> T? = { a, b ->
    when {
        a == null -> b
        b == null -> a
        else -> combiner(a, b)
    }
}

const val MOD = 998244353
const val TOTIENT = MOD - 1 // assumes MOD is prime

infix fun Int.umod(mod: Int): Int = (this % mod).let { (it shr Int.SIZE_BITS - 1 and mod) + it }
infix fun Long.umod(mod: Long) = (this % mod).let { (it shr Long.SIZE_BITS - 1 and mod) + it }
infix fun Long.umod(mod: Int) = umod(mod.toLong()).toInt()

fun Int.mulMod(other: Int, mod: Int) = toLong() * other umod mod

fun Int.powMod(exponent: Int, mod: Int): Int {
    if(exponent < 0) error("Inverse not implemented")
    var res = 1L
    var e = exponent
    var b = umod(mod).toLong()

    while(e > 0) {
        if(e and 1 == 1) {
            res = res * b % mod
        }
        e = e shr 1
        b = b * b % mod
    }
    return res.toInt()
}

inline fun Int.toModInt() = ModInt(this umod MOD)
inline fun Long.toModInt() = ModInt(this umod MOD)

/** note: Only use constructor for int within modulo range, otherwise use toModInt **/
inline class ModInt(val int: Int) {
    companion object {
        /** can't seem to make these private or inlined without causing compiler issues */
        @JvmField val _invMemo = HashMap<ModInt, ModInt>()
        fun _invMemoized(m: ModInt) = _invMemo.getOrPut(m) { m.inv_unmemoized() }
    }

    // normalizes an integer that's within range [-MOD, MOD) without branching
    private inline fun normalize(int: Int) = ModInt((int shr Int.SIZE_BITS - 1 and MOD) + int)

    operator fun plus(other: ModInt) = normalize(int + other.int - MOD) // overflow-safe even if MOD >= 2^30
    inline operator fun plus(other: Int) = plus(other.toModInt())
    operator fun inc() = normalize(int + (1 - MOD))

    operator fun minus(other: ModInt) = normalize(int - other.int)
    inline operator fun minus(other: Int) = minus(other.toModInt())
    operator fun dec() = normalize(int - 1)
    operator fun unaryMinus() = normalize(-int)

    operator fun times(other: ModInt) = ModInt((int.toLong() * other.int % MOD).toInt())
    inline operator fun times(other: Int) = ModInt(int.mulMod(other, MOD))

    fun pow(exponent: Int): ModInt {
        val e = if(exponent < 0) {
            require(int != 0) { "Can't invert/divide by 0" }
            exponent umod TOTIENT
        } else exponent
        return ModInt(int.powMod(e, MOD))
    }

    fun pow(exponent: Long) = if(int == 0) when {
        exponent > 0 -> this
        exponent == 0L -> ModInt(1)
        else -> error("Can't invert/divide by 0")
    } else pow(exponent umod TOTIENT)

    inline fun inverse() = inv_memoized() /** NOTE: Change if necessary */

    fun inv_unmemoized(): ModInt {
        require(int != 0) { "Can't invert/divide by 0" }
        return pow(TOTIENT - 1)
    }
    inline fun inv_memoized() = _invMemoized(this)

    operator fun div(other: ModInt) = times(other.inverse())
    inline operator fun div(other: Int) = div(other.toModInt())

    override inline fun toString() = int.toString()
}

inline operator fun Int.plus(modInt: ModInt) = modInt + this
inline operator fun Int.minus(modInt: ModInt) = toModInt() - modInt
inline operator fun Int.times(modInt: ModInt) = modInt * this
inline operator fun Int.div(modInt: ModInt) = modInt.inverse() * this

inline class ModIntArray(val intArray: IntArray): Collection<ModInt> {
    inline operator fun get(i: Int) = ModInt(intArray[i])
    inline operator fun set(i: Int, v: ModInt) { intArray[i] = v.int }

    override inline val size: Int get() = intArray.size
    inline val lastIndex get() = intArray.lastIndex
    inline val indices get() = intArray.indices

    override inline fun contains(element: ModInt): Boolean = element.int in intArray

    override fun containsAll(elements: Collection<ModInt>): Boolean = elements.all(::contains)

    override inline fun isEmpty(): Boolean = intArray.isEmpty()

    override fun iterator(): Iterator<ModInt> = object: Iterator<ModInt> {
        var index = 0
        override fun hasNext(): Boolean = index < size
        override fun next(): ModInt = get(index++)
    }

    fun copyOf(newSize: Int) = ModIntArray(intArray.copyOf(newSize))
    fun copyOf() = copyOf(size)
}
fun ModIntArray.copyInto(destination: ModIntArray, destinationOffset: Int = 0, startIndex: Int = 0, endIndex: Int = size) =
    ModIntArray(intArray.copyInto(destination.intArray, destinationOffset, startIndex, endIndex))
inline fun ModIntArray(size: Int) = ModIntArray(IntArray(size))
inline fun ModIntArray(size: Int, init: (Int) -> ModInt) = ModIntArray(IntArray(size) { init(it).int })

inline fun ModIntArray.first() = get(0)
inline fun ModIntArray.last() = get(lastIndex)
inline fun <R> ModIntArray.fold(init: R, op: (acc: R, ModInt) -> R) = intArray.fold(init) { acc, i -> op(acc, ModInt(i)) }
fun ModIntArray.sum() = fold(ModInt(0), ModInt::plus)
fun ModIntArray.product() = fold(ModInt(1), ModInt::times)

inline fun <T> Iterable<T>.sumByModInt(func: (T) -> ModInt) = fold(ModInt(0)) { acc, t -> acc + func(t) }
inline fun <T> Iterable<T>.productByModInt(func: (T) -> ModInt) = fold(ModInt(1)) { acc, t -> acc * func(t) }
inline fun <T> Sequence<T>.sumByModInt(func: (T) -> ModInt) = fold(ModInt(0)) { acc, t -> acc + func(t) }
inline fun <T> Sequence<T>.productByModInt(func: (T) -> ModInt) = fold(ModInt(1)) { acc, t -> acc * func(t) }
fun Iterable<ModInt>.sum() = sumByModInt { it }
fun Sequence<ModInt>.sum() = sumByModInt { it }
fun Iterable<ModInt>.product() = productByModInt { it }
fun Sequence<ModInt>.product() = productByModInt { it }
fun Collection<ModInt>.toModIntArray() = ModIntArray(size).also { var i = 0; for(e in this) { it[i++] = e } }

/** IO code start */
//@JvmField val INPUT = File("input.txt").inputStream()
//@JvmField val OUTPUT = File("output.txt").outputStream()
@JvmField val INPUT = System.`in`
@JvmField val OUTPUT = System.out

@JvmField val _reader = INPUT.bufferedReader()
fun readLine(): String? = _reader.readLine()
fun readLn() = _reader.readLine()!!
@JvmField var _tokenizer: StringTokenizer = StringTokenizer("")
fun read(): String {
    while (_tokenizer.hasMoreTokens().not()) _tokenizer = StringTokenizer(_reader.readLine() ?: return "", " ")
    return _tokenizer.nextToken()
}
fun readInt() = read().toInt()
fun readDouble() = read().toDouble()
fun readLong() = read().toLong()
fun readStrings(n: Int) = List(n) { read() }
fun readLines(n: Int) = List(n) { readLn() }
fun readInts(n: Int) = List(n) { read().toInt() }
fun readIntArray(n: Int) = IntArray(n) { read().toInt() }
fun readDoubles(n: Int) = List(n) { read().toDouble() }
fun readDoubleArray(n: Int) = DoubleArray(n) { read().toDouble() }
fun readLongs(n: Int) = List(n) { read().toLong() }
fun readLongArray(n: Int) = LongArray(n) { read().toLong() }

@JvmField val _writer = PrintWriter(OUTPUT, false)

/** shuffles and sort overrides to avoid quicksort attacks */
private inline fun <T> _shuffle(rnd: Random, get: (Int) -> T, set: (Int, T) -> Unit, size: Int) {
    // Fisher-Yates shuffle algorithm
    for (i in size - 1 downTo 1) {
        val j = rnd.nextInt(i + 1)
        val temp = get(i)
        set(i, get(j))
        set(j, temp)
    }
}

@JvmField var _random: Random? = null
val random get() = _random ?: Random(0x594E215C123 * System.nanoTime()).also { _random = it }

fun IntArray.shuffle(rnd: Random = random) = _shuffle(rnd, ::get, ::set, size)
fun IntArray.sort() { shuffle(); _sort() }
fun IntArray.sortDescending() { shuffle(); _sortDescending() }

fun LongArray.shuffle(rnd: Random = random) = _shuffle(rnd, ::get, ::set, size)
fun LongArray.sort() { shuffle(); _sort() }
fun LongArray.sortDescending() { shuffle(); _sortDescending() }

fun DoubleArray.shuffle(rnd: Random = random) = _shuffle(rnd, ::get, ::set, size)
fun DoubleArray.sort() { shuffle(); _sort() }
fun DoubleArray.sortDescending() { shuffle(); _sortDescending() }

fun CharArray.shuffle(rnd: Random = random) = _shuffle(rnd, ::get, ::set, size)
inline fun CharArray.sort() { _sort() }
inline fun CharArray.sortDescending() { _sortDescending() }

inline fun <T: Comparable<T>> Array<out T>.sort() = _sort()
inline fun <T: Comparable<T>> Array<out T>.sortDescending() = _sortDescending()
inline fun <T: Comparable<T>> MutableList<out T>.sort() = _sort()
inline fun <T: Comparable<T>> MutableList<out T>.sortDescending() = _sortDescending()

fun `please stop removing these imports IntelliJ`() {
    iprintln(max(1, 2))
}


@file:Suppress("NOTHING_TO_INLINE", "EXPERIMENTAL_FEATURE_WARNING", "OVERRIDE_BY_INLINE")

import java.io.PrintWriter
import java.lang.StringBuilder
import java.util.PriorityQueue
import java.util.StringTokenizer
import java.util.TreeMap
import kotlin.math.*
import kotlin.random.*
import kotlin.collections.sort as _sort
import kotlin.collections.sortDescending as _sortDescending
import kotlin.io.println as iprintln

/** @author Spheniscine */
fun main() { _writer.solve(); _writer.flush() }
fun PrintWriter.solve() {
    val percent = ModInt(100).inverse()

    val n = readInt()
    val pipes = List(n) { Pipe(readInt(), readInt(), percent * readInt()) }

    val tree = SegmentTree(n-1, null, nullIdentityCombiner(Seg::plus))

    tree.build { i ->
        Seg(
            ll = pipes[i].p.not() * pipes[i+1].p.not(),
            lr = pipes[i].p.not() * pipes[i+1].p,
            rl = pipes[i].p * pipes[i+1].p.not(),
            rr = pipes[i].p * pipes[i+1].p
        )
    }

    val cols = ArrayList<Collision>(2*n)

    for(i in 0 until n-1) {
        val a = pipes[i]
        val b = pipes[i+1]

        val d = b.x - a.x
        cols.add(Collision(i, RL, d, a.v + b.v))
        if(a.v > b.v) cols.add(Collision(i, RR, d, a.v - b.v))
        else if(a.v < b.v) cols.add(Collision(i, LL, d, b.v - a.v))
    }

    cols.sortWith(Collision.comparator)

    var currProb = ModInt(1)
    var ans = ModInt(0)
    for((a, t, d, v) in cols) {
        tree[a] = tree[a]!!.ban(t)
        val prob = tree[0, tree.size]!!.sum
        ans += (currProb - prob) * d / v
        currProb = prob
    }

    println(ans.int)
}

fun ModInt.not() = ModInt(1) - this

data class Pipe(val x: Int, val v: Int, val p: ModInt)
data class Collision(val a: Int, val type: CollisionType, val d: Int, val v: Int) {
    companion object {
        val comparator = Comparator<Collision> { a, b ->
            (a.d.toLong() * b.v).compareTo(b.d.toLong() * a.v)
        }
    }

    inline val b get() = a + 1
}

inline class CollisionType(val i: Int)
inline val LL get() = CollisionType(0)
inline val LR get() = CollisionType(1)
inline val RL get() = CollisionType(2)
inline val RR get() = CollisionType(3)

class Seg(private val values: IntArray) {
    constructor(ll: ModInt, lr: ModInt, rl: ModInt, rr: ModInt): this(intArrayOf(ll.int, lr.int, rl.int, rr.int))

    operator fun get(collisionType: CollisionType) = ModInt(values[collisionType.i])
    val ll get() = ModInt(values[0])
    val lr get() = ModInt(values[1])
    val rl get() = ModInt(values[2])
    val rr get() = ModInt(values[3])

    operator fun plus(b: Seg): Seg {
        val al = ll + lr
        val ar = rl + rr
        val bl = b.ll + b.rl
        val br = b.lr + b.rr

        return Seg(
            ll = al * bl,
            lr = al * br,
            rl = ar * bl,
            rr = ar * br
        )
    }

    val sum get() = ModIntArray(values).sum()

    fun ban(collisionType: CollisionType) = Seg(values.copyOf().also { it[collisionType.i] = 0 })
}

class SegmentTree<T>(
    val size: Int,
    val identityValue: T,
    val combiner: (T, T) -> T) {

    /* degenericization helpers
    val identityValue: T = TODO()
    fun combiner(a: T, b: T): T = TODO()
    */

    @Suppress("UNCHECKED_CAST")
    private val array = Array<Any?>(2 * size) { identityValue } as Array<T>

    inline val lastIndex get() = size - 1
    inline val indices get() = 0 until size
    val asList: List<T> by lazy {
        object : AbstractList<T>() {
            override val size: Int get() = this@SegmentTree.size
            override fun get(index: Int): T = this@SegmentTree[index]
        }
    }

    fun build(generator: (Int) -> T) {
        for(i in 0 until size) {
            array[i + size] = generator(i)
        }
        for(i in size-1 downTo 1) {
            array[i] = combiner(array[i shl 1], array[i shl 1 or 1])
        }
    }

    /** instantiates values from an iterable, O(n) time */
    fun copyFrom(iterable: Iterable<T>) {
        run {
            iterable.forEachIndexed { i, t ->
                if(i > lastIndex) return@run
                array[i + size] = t
            }
        }
        for(i in size-1 downTo 1) {
            array[i] = combiner(array[i shl 1], array[i shl 1 or 1])
        }
    }

    /** Updates a value, O(log n) time */
    operator fun set(index: Int, value: T) {
        require(index in 0 until size)
        var i = index + size
        array[i] = value
        while(true) {
            i = i shr 1
            if(i <= 0) break
            array[i] = combiner(array[i shl 1], array[i shl 1 or 1])
        }
    }

    /** Gets a value by its index, O(1) time */
    operator fun get(index: Int): T {
        require(index in 0 until size)
        return array[index + size]
    }

    /** gets the result of applying the monoid operation to the values in the index range, O(log n) time */
    operator fun get(start: Int, endExclusive: Int): T {
        var l = maxOf(start, 0) + size
        var r = minOf(endExclusive, size) + size

        // two accumulators to support non-commutative monoids
        var lAcc = identityValue
        var rAcc = identityValue

        while(l < r) {
            if(l and 1 == 1) {
                lAcc = combiner(lAcc, array[l++])
            }
            if(r and 1 == 1) {
                rAcc = combiner(array[--r], rAcc)
            }

            l = l shr 1
            r = r shr 1
        }

        return combiner(lAcc, rAcc)
    }

    operator fun get(range: IntRange) = get(range.first, range.last + 1)
}

/** Converts a semigroup to a monoid by using null as the identity value. */
inline fun <T: Any> nullIdentityCombiner(crossinline combiner: (T, T) -> T): (T?, T?) -> T? = { a, b ->
    when {
        a == null -> b
        b == null -> a
        else -> combiner(a, b)
    }
}

const val MOD = 998244353
const val TOTIENT = MOD - 1 // assumes MOD is prime

infix fun Int.umod(mod: Int): Int = (this % mod).let { (it shr Int.SIZE_BITS - 1 and mod) + it }
infix fun Long.umod(mod: Long) = (this % mod).let { (it shr Long.SIZE_BITS - 1 and mod) + it }
infix fun Long.umod(mod: Int) = umod(mod.toLong()).toInt()

fun Int.mulMod(other: Int, mod: Int) = toLong() * other umod mod

fun Int.powMod(exponent: Int, mod: Int): Int {
    if(exponent < 0) error("Inverse not implemented")
    var res = 1L
    var e = exponent
    var b = umod(mod).toLong()

    while(e > 0) {
        if(e and 1 == 1) {
            res = res * b % mod
        }
        e = e shr 1
        b = b * b % mod
    }
    return res.toInt()
}

inline fun Int.toModInt() = ModInt(this umod MOD)
inline fun Long.toModInt() = ModInt(this umod MOD)

/** note: Only use constructor for int within modulo range, otherwise use toModInt **/
inline class ModInt(val int: Int) {
    companion object {
        /** can't seem to make these private or inlined without causing compiler issues */
        @JvmField val _invMemo = HashMap<ModInt, ModInt>()
        fun _invMemoized(m: ModInt) = _invMemo.getOrPut(m) { m.inv_unmemoized() }
    }

    // normalizes an integer that's within range [-MOD, MOD) without branching
    private inline fun normalize(int: Int) = ModInt((int shr Int.SIZE_BITS - 1 and MOD) + int)

    operator fun plus(other: ModInt) = normalize(int + other.int - MOD) // overflow-safe even if MOD >= 2^30
    inline operator fun plus(other: Int) = plus(other.toModInt())
    operator fun inc() = normalize(int + (1 - MOD))

    operator fun minus(other: ModInt) = normalize(int - other.int)
    inline operator fun minus(other: Int) = minus(other.toModInt())
    operator fun dec() = normalize(int - 1)
    operator fun unaryMinus() = normalize(-int)

    operator fun times(other: ModInt) = ModInt((int.toLong() * other.int % MOD).toInt())
    inline operator fun times(other: Int) = ModInt(int.mulMod(other, MOD))

    fun pow(exponent: Int): ModInt {
        val e = if(exponent < 0) {
            require(int != 0) { "Can't invert/divide by 0" }
            exponent umod TOTIENT
        } else exponent
        return ModInt(int.powMod(e, MOD))
    }

    fun pow(exponent: Long) = if(int == 0) when {
        exponent > 0 -> this
        exponent == 0L -> ModInt(1)
        else -> error("Can't invert/divide by 0")
    } else pow(exponent umod TOTIENT)

    inline fun inverse() = inv_memoized() /** NOTE: Change if necessary */

    fun inv_unmemoized(): ModInt {
        require(int != 0) { "Can't invert/divide by 0" }
        return pow(TOTIENT - 1)
    }
    inline fun inv_memoized() = _invMemoized(this)

    operator fun div(other: ModInt) = times(other.inverse())
    inline operator fun div(other: Int) = div(other.toModInt())

    override inline fun toString() = int.toString()
}

inline operator fun Int.plus(modInt: ModInt) = modInt + this
inline operator fun Int.minus(modInt: ModInt) = toModInt() - modInt
inline operator fun Int.times(modInt: ModInt) = modInt * this
inline operator fun Int.div(modInt: ModInt) = modInt.inverse() * this

inline class ModIntArray(val intArray: IntArray): Collection<ModInt> {
    inline operator fun get(i: Int) = ModInt(intArray[i])
    inline operator fun set(i: Int, v: ModInt) { intArray[i] = v.int }

    override inline val size: Int get() = intArray.size
    inline val lastIndex get() = intArray.lastIndex
    inline val indices get() = intArray.indices

    override inline fun contains(element: ModInt): Boolean = element.int in intArray

    override fun containsAll(elements: Collection<ModInt>): Boolean = elements.all(::contains)

    override inline fun isEmpty(): Boolean = intArray.isEmpty()

    override fun iterator(): Iterator<ModInt> = object: Iterator<ModInt> {
        var index = 0
        override fun hasNext(): Boolean = index < size
        override fun next(): ModInt = get(index++)
    }

    fun copyOf(newSize: Int) = ModIntArray(intArray.copyOf(newSize))
    fun copyOf() = copyOf(size)
    fun copyInto(destination: ModIntArray, destinationOffset: Int = 0, startIndex: Int = 0, endIndex: Int = size) =
        ModIntArray(intArray.copyInto(destination.intArray, destinationOffset, startIndex, endIndex))
}
inline fun ModIntArray(size: Int) = ModIntArray(IntArray(size))
inline fun ModIntArray(size: Int, init: (Int) -> ModInt) = ModIntArray(IntArray(size) { init(it).int })

inline fun ModIntArray.first() = get(0)
inline fun ModIntArray.last() = get(lastIndex)
inline fun <R> ModIntArray.fold(init: R, op: (acc: R, ModInt) -> R) = intArray.fold(init) { acc, i -> op(acc, ModInt(i)) }
fun ModIntArray.sum() = fold(ModInt(0), ModInt::plus)
fun ModIntArray.product() = fold(ModInt(1), ModInt::times)

inline fun <T> Iterable<T>.sumByModInt(func: (T) -> ModInt) = fold(ModInt(0)) { acc, t -> acc + func(t) }
inline fun <T> Iterable<T>.productByModInt(func: (T) -> ModInt) = fold(ModInt(1)) { acc, t -> acc * func(t) }
inline fun <T> Sequence<T>.sumByModInt(func: (T) -> ModInt) = fold(ModInt(0)) { acc, t -> acc + func(t) }
inline fun <T> Sequence<T>.productByModInt(func: (T) -> ModInt) = fold(ModInt(1)) { acc, t -> acc * func(t) }
fun Iterable<ModInt>.sum() = sumByModInt { it }
fun Sequence<ModInt>.sum() = sumByModInt { it }
fun Iterable<ModInt>.product() = productByModInt { it }
fun Sequence<ModInt>.product() = productByModInt { it }
fun Collection<ModInt>.toModIntArray() = ModIntArray(size).also { var i = 0; for(e in this) { it[i++] = e } }

/** IO code start */
//@JvmField val INPUT = File("input.txt").inputStream()
//@JvmField val OUTPUT = File("output.txt").outputStream()
@JvmField val INPUT = System.`in`
@JvmField val OUTPUT = System.out

@JvmField val _reader = INPUT.bufferedReader()
fun readLine(): String? = _reader.readLine()
fun readLn() = _reader.readLine()!!
@JvmField var _tokenizer: StringTokenizer = StringTokenizer("")
fun read(): String {
    while (_tokenizer.hasMoreTokens().not()) _tokenizer = StringTokenizer(_reader.readLine() ?: return "", " ")
    return _tokenizer.nextToken()
}
fun readInt() = read().toInt()
fun readDouble() = read().toDouble()
fun readLong() = read().toLong()
fun readStrings(n: Int) = List(n) { read() }
fun readLines(n: Int) = List(n) { readLn() }
fun readInts(n: Int) = List(n) { read().toInt() }
fun readIntArray(n: Int) = IntArray(n) { read().toInt() }
fun readDoubles(n: Int) = List(n) { read().toDouble() }
fun readDoubleArray(n: Int) = DoubleArray(n) { read().toDouble() }
fun readLongs(n: Int) = List(n) { read().toLong() }
fun readLongArray(n: Int) = LongArray(n) { read().toLong() }

@JvmField val _writer = PrintWriter(OUTPUT, false)

/** shuffles and sort overrides to avoid quicksort attacks */
private inline fun <T> _shuffle(rnd: Random, get: (Int) -> T, set: (Int, T) -> Unit, size: Int) {
    // Fisher-Yates shuffle algorithm
    for (i in size - 1 downTo 1) {
        val j = rnd.nextInt(i + 1)
        val temp = get(i)
        set(i, get(j))
        set(j, temp)
    }
}

@JvmField var _random: Random? = null
val random get() = _random ?: Random(0x594E215C123 * System.nanoTime()).also { _random = it }

fun IntArray.shuffle(rnd: Random = random) = _shuffle(rnd, ::get, ::set, size)
fun IntArray.sort() { shuffle(); _sort() }
fun IntArray.sortDescending() { shuffle(); _sortDescending() }

fun LongArray.shuffle(rnd: Random = random) = _shuffle(rnd, ::get, ::set, size)
fun LongArray.sort() { shuffle(); _sort() }
fun LongArray.sortDescending() { shuffle(); _sortDescending() }

fun DoubleArray.shuffle(rnd: Random = random) = _shuffle(rnd, ::get, ::set, size)
fun DoubleArray.sort() { shuffle(); _sort() }
fun DoubleArray.sortDescending() { shuffle(); _sortDescending() }

fun CharArray.shuffle(rnd: Random = random) = _shuffle(rnd, ::get, ::set, size)
inline fun CharArray.sort() { _sort() }
inline fun CharArray.sortDescending() { _sortDescending() }

inline fun <T: Comparable<T>> Array<out T>.sort() = _sort()
inline fun <T: Comparable<T>> Array<out T>.sortDescending() = _sortDescending()
inline fun <T: Comparable<T>> MutableList<out T>.sort() = _sort()
inline fun <T: Comparable<T>> MutableList<out T>.sortDescending() = _sortDescending()

fun `please stop removing these imports IntelliJ`() {
    iprintln(max(1, 2))
}


//package codeforces.round345

import java.io.PrintWriter
import java.util.*

fun main(args: Array<String>) {
    val inputStream = System.`in`
    val outputStream = System.out
    val `in` = Scanner(inputStream)
    val out = PrintWriter(outputStream)
    solve(`in`, out)
    out.close()
}

private fun solve(scanner: Scanner, out: PrintWriter) {
    var first = scanner.nextInt()
    var second = scanner.nextInt()

    var totalTime = 0

    while (first > 0 && second > 0) {
        if (first > second) {
            first -= 2
            second++
        } else {
            second -= 2
            first++
        }
        totalTime++
    }
    out.println(totalTime)
}


fun main(a: Array<String>)
{
    var (a,b) = readLine()!!.split(' ').map { it.toInt() }
    var counter = 0
    while (a != 0 && b != 0)
    {
        counter++
        when (a<b)
        {
            true -> {if (a < 100) ++a ; b-=2}
            else -> {if (b < 100) ++b; a-=2}
        }
    }
    println(counter)
}


const val data = "4 4"

fun main() {
    val line = readLine() ?: "1 1"
    val split = line.split(" ")
    Game(chargeFirst = split[0].toInt(), chargeSecond = split[1].toInt()).apply {
        while (canPlay) minutePasses()
        println(duration)
    }

}

class Game(chargeFirst: Int, chargeSecond: Int) {

    var duration = 0

    private val first: Joystick = Joystick(chargeFirst)
    private val second: Joystick = Joystick(chargeSecond)

    private val dischargingAmount = -2
    private val chargeAmount = 1

    private val chargingFirst get() = first.charge + 1 < second.charge

    fun minutePasses() {
        val firstNeedsCharging = chargingFirst
        if ((first.charge != 1 || firstNeedsCharging) && (second.charge != 1 || !firstNeedsCharging)) duration++

        first.charge += if (firstNeedsCharging) chargeAmount else dischargingAmount
        second.charge += if (firstNeedsCharging) dischargingAmount else chargeAmount
    }

    val canPlay get() = first.charge > 0 && second.charge > 0
}

data class Joystick(var charge: Int)


const val data = "4 4"

fun main(args: Array<String>) {
    //val charges = args[0].split(" ")
    Game(chargeFirst = args[0].toInt(), chargeSecond = args[1].toInt()).apply {
        while (canPlay) minutePasses()

        println(duration)
    }

}

class Game(chargeFirst: Int, chargeSecond: Int) {

    var duration = 0

    private val dischargingAmount = 2
    private val chargeAmount = 1
    private val first: Joystick = Joystick(chargeFirst)
    private val second: Joystick = Joystick(chargeSecond)
    private val chargingFirst get() = first.charge <= 2

    fun minutePasses() {
        duration++
        val addFirst = if (chargingFirst) chargeAmount else -dischargingAmount
        val addSecond = if (addFirst == 1) -dischargingAmount else chargeAmount

        first.charge += addFirst
        second.charge += addSecond
    }

    val canPlay get() = first.charge > 0 && second.charge > 0

}

data class Joystick(var charge: Int)


import java.util.*
import java.io.*

val MOD = 998244353L

fun main()
{
	Thread(null, Main(), "whatever", 1 shl 28).start()
}

class Main : Runnable {

	override fun run()
	{
		val inputStream = System.`in`
		val outputStream = System.out
		val `in` = InputReader(inputStream)
		val out = PrintWriter(outputStream)
		val solver = TaskD()
		var test = 1
		//test = `in`.nextInt()
		for (t in 1..test)
		{
			solver.solve(t, `in`, out)
		}
		out.close()
	}

	internal class TaskD
	{
		fun solve(testNumber: Int, `in`: InputReader, out: PrintWriter) {
			val INF = 4000000000000000000L
			val dx = intArrayOf(-1, 1, 0, 0)
			val dy = intArrayOf(0, 0, -1, 1)

			var n = `in`.nextLong()
			var m = `in`.nextLong()
			var L = `in`.nextLong()
			var R = `in`.nextLong()
			var len = R-L+1

			if (n*m%2 == 1L) return out.println(power(len, n*m, MOD))

			var a = len/2
			var b = len-a
			if (L%2 == 0L)
			{
				var tmp = a
				a = b
				b = tmp
			}

			fun go(a: Long, b: Long, n: Long): Pair<Long, Long>
			{
				if (n == 0L) return Pair<Long, Long>(1, 0)
				var (c, d) = go(a, b, n/2)
				var (tc, td) = Pair<Long, Long>((c*c+d*d)%MOD, (2*c*d)%MOD)
				c = tc
				d = td
				if (n%2 == 1L)
				{
					var (sc, sd) = Pair<Long, Long>(a*c+b*d, a*d+b*c)
					c = sc
					d = sd
				}
				return Pair<Long, Long>(c, d)
			}

			var (x, y) = go(a, b, n*m)
			out.println(x)
		}

	}

	internal class InputReader(stream: InputStream) {
		var reader: BufferedReader
		var tokenizer: StringTokenizer? = null

		init {
			reader = BufferedReader(InputStreamReader(stream), 32768)
			tokenizer = null
		}

		operator fun next(): String {
			while (tokenizer == null || !tokenizer!!.hasMoreTokens()) {
				try {
					tokenizer = StringTokenizer(reader.readLine())
				} catch (e: IOException) {
					throw RuntimeException(e)
				}

			}
			return tokenizer!!.nextToken()
		}

		fun nextInt(): Int {
			return Integer.parseInt(next())
		}

		fun nextLong(): Long {
		    return next().toLong()
		}

	}
}

fun gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a%b)

fun power(a: Long, b: Long, p: Long): Long
{
	if (b == 0L) return 1L
	var t = power(a, b/2, p)
	t = t*t%p
	if (b%2 == 1L) t = t*a%p
	return t
}