import scala.collection.mutable.ArrayBuffer

object C extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }

  val MOD = 1000000007L

  case class M1x2(a11: Long, a12: Long) {

    def +(b: M1x2) = M1x2(
      (a11 + b.a11) % MOD,
      (a12 + b.a12) % MOD)

    def *(b: M2x2) = M1x2(
      (a11 * b.a11 + a12 * b.a21) % MOD,
      (a11 * b.a12 + a12 * b.a22) % MOD)

  }

  val FibStart = M1x2(0, 1)

  case class M2x2(a11: Long, a12: Long, a21: Long, a22: Long) {

    def *(b: M2x2) = M2x2(
      (a11 * b.a11 + a12 * b.a21) % MOD,
      (a11 * b.a12 + a12 * b.a22) % MOD,
      (a21 * b.a11 + a22 * b.a21) % MOD,
      (a21 * b.a12 + a22 * b.a22) % MOD)

    def pow(n: Long) = {
      var pow2 = this
      var res = M2x2.Unit
      var deg = n

      while (deg > 0) {
        if ((deg & 1) != 0) res *= pow2
        pow2 *= pow2
        deg >>= 1
      }

      res
    }

  }

  object M2x2 {

    val Unit = M2x2(
      1, 0,
      0, 1)

    val FibMul = M2x2(
      0, 1,
      1, 1)
  }

  def fib(n: Long) = FibStart * M2x2.FibMul.pow(n)

  case class SegTree(as: Array[M1x2]) {

    val NEUTRAL = M1x2(0, 0) // neutral element in respect of operation used (+)

    val n = as.length
    val t = Array.fill(4 * Integer.highestOneBit(n))(NEUTRAL)
    val lazyMul = Array.fill(4 * Integer.highestOneBit(n))(M2x2.Unit)
    build(1, 0, n - 1)

    def build(v: Int, tl: Int, tr: Int) {
      if (tl == tr) t(v) = as(tl)
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        build(v2, tl, tm)
        build(v2 + 1, tm + 1, tr)
        t(v) = t(v2) + t(v2 + 1)
      }
    }

    def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Long = {
      if (l > r) 0
      else if (l == tl && r == tr) t(v).a11
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1

        lazyMul(v2) *= lazyMul(v)
        lazyMul(v2 + 1) *= lazyMul(v)
        t(v2) *= lazyMul(v)
        t(v2 + 1) *= lazyMul(v)
        lazyMul(v) = M2x2.Unit

        (query(l, Math.min(r, tm), v2, tl, tm) +
          query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr)) % MOD
      }
    }

    def update(l: Int, r: Int, mul: M2x2, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {
      if (l == tl && r == tr) {
        lazyMul(v) *= mul
        t(v) *= mul
      } else if (l <= r) {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        update(l, Math.min(r, tm), mul, v2, tl, tm)
        update(Math.max(l, tm + 1), r, mul, v2 + 1, tm + 1, tr)
        t(v) = (t(v2) + t(v2 + 1)) * lazyMul(v)
      }
    }

  }

  val Array(n, m) = readInts(2)
  val as = readInts(n)
  val st = SegTree(as.map(x => fib(x)))

  val res = ArrayBuffer.empty[Long]

  for (_ <- 0 until m) {

    val s = readLine
    val tl = new java.util.StringTokenizer(s)

    if (s.startsWith("1")) {
      val Array(_, l, r, x) = Array.fill(4)(tl.nextToken.toInt)
      st.update(l - 1, r - 1, M2x2.FibMul.pow(x))
    } else {
      val Array(_, l, r) = Array.fill(3)(tl.nextToken.toInt)
      res += st.query(l - 1, r - 1)
    }
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  println(res.mkString("\n"))

  Console.flush
}

import scala.collection.mutable.ArrayBuffer

object C extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }

  val MOD = 1000000007L

  final case class M1x2(a11: Long, a12: Long) {

    def +(b: M1x2) = M1x2(
      (a11 + b.a11) % MOD,
      (a12 + b.a12) % MOD)

    def *(b: M2x2) = M1x2(
      (a11 * b.a11 + a12 * b.a21) % MOD,
      (a11 * b.a12 + a12 * b.a22) % MOD)

  }

  val FibStart = M1x2(0, 1)

  final case class M2x2(a11: Long, a12: Long, a21: Long, a22: Long) {

    def *(b: M2x2) = M2x2(
      (a11 * b.a11 + a12 * b.a21) % MOD,
      (a11 * b.a12 + a12 * b.a22) % MOD,
      (a21 * b.a11 + a22 * b.a21) % MOD,
      (a21 * b.a12 + a22 * b.a22) % MOD)

    def pow(n: Long) = {
      var pow2 = this
      var res = M2x2.Unit
      var deg = n

      while (deg > 0) {
        if ((deg & 1) != 0) res *= pow2
        pow2 *= pow2
        deg >>= 1
      }

      res
    }

  }

  object M2x2 {

    val Unit = M2x2(
      1, 0,
      0, 1)

    val FibMul = M2x2(
      0, 1,
      1, 1)
  }

  def fib(n: Long) = FibStart * M2x2.FibMul.pow(n)

  case class SegTree(as: Array[M1x2]) {

    val NEUTRAL = M1x2(0, 0) // neutral element in respect of operation used (+)

    val n = as.length
    val t = Array.fill(4 * Integer.highestOneBit(n))(NEUTRAL)
    val lazyMul = Array.fill(4 * Integer.highestOneBit(n))(M2x2.Unit)
    build(1, 0, n - 1)

    def build(v: Int, tl: Int, tr: Int) {
      if (tl == tr) t(v) = as(tl)
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        build(v2, tl, tm)
        build(v2 + 1, tm + 1, tr)
        t(v) = t(v2) + t(v2 + 1)
      }
    }

    def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Long = {
      if (l > r) 0
      else if (l == tl && r == tr) t(v).a11
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1

        lazyMul(v2) *= lazyMul(v)
        lazyMul(v2 + 1) *= lazyMul(v)
        t(v2) *= lazyMul(v)
        t(v2 + 1) *= lazyMul(v)
        lazyMul(v) = M2x2.Unit

        (query(l, Math.min(r, tm), v2, tl, tm) +
          query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr)) % MOD
      }
    }

    def update(l: Int, r: Int, mul: M2x2, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {
      if (l == tl && r == tr) {
        lazyMul(v) *= mul
        t(v) *= mul
      } else if (l <= r) {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        update(l, Math.min(r, tm), mul, v2, tl, tm)
        update(Math.max(l, tm + 1), r, mul, v2 + 1, tm + 1, tr)
        t(v) = (t(v2) + t(v2 + 1)) * lazyMul(v)
      }
    }

  }

  val Array(n, m) = readInts(2)
  val as = readInts(n)
  val st = SegTree(as.map(x => fib(x)))

  val res = ArrayBuffer.empty[Long]

  for (_ <- 0 until m) {

    val s = readLine
    val tl = new java.util.StringTokenizer(s)

    if (s.startsWith("1")) {
      val Array(_, l, r, x) = Array.fill(4)(tl.nextToken.toInt)
      st.update(l - 1, r - 1, M2x2.FibMul.pow(x))
    } else {
      val Array(_, l, r) = Array.fill(3)(tl.nextToken.toInt)
      res += st.query(l - 1, r - 1)
    }
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  println(res.mkString("\n"))

  Console.flush
}

import scala.collection.mutable.ArrayBuffer

object C extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }

  val MOD = 1000000007

  case class M1x2(a11: Long, a12: Long) {

    def +(other: M1x2) = M1x2(
      (this.a11 + other.a11) % MOD,
      (this.a12 + other.a12) % MOD)

    def *(other: M2x2) = M1x2(
      (this.a11 * other.a11 + this.a12 * other.a21) % MOD,
      (this.a11 * other.a12 + this.a12 * other.a22) % MOD)

  }

  val FibStart = M1x2(1, 1)

  case class M2x2(a11: Long, a12: Long, a21: Long, a22: Long) {

    def *(other: M2x2) = M2x2(
      (this.a11 * other.a11 + this.a12 * other.a21) % MOD,
      (this.a11 * other.a12 + this.a12 * other.a22) % MOD,
      (this.a21 * other.a11 + this.a22 * other.a21) % MOD,
      (this.a21 * other.a12 + this.a22 * other.a22) % MOD)

    def pow(n: Long) = {
      var pow2 = this
      var res = M2x2.Unit
      var deg = n

      while (deg > 0) {
        if ((deg & 1) != 0) res *= pow2
        pow2 *= pow2
        deg >>= 1
      }

      res
    }

  }

  object M2x2 {
    val Unit = M2x2(1, 0, 0, 1)
    val Fib = M2x2(0, 1, 1, 1)
  }

  case class SegTree(as: Array[M1x2]) {

    val NEUTRAL = M1x2(0, 0) // neutral element in respect of operation used (+)

    val n = as.length
    val t = Array.fill(4 * Integer.highestOneBit(n))(NEUTRAL)
    val lazyMul = Array.fill(4 * Integer.highestOneBit(n))(M2x2.Unit)
    build(1, 0, n - 1)

    def build(v: Int, tl: Int, tr: Int) {
      if (tl == tr) t(v) = as(tl)
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        build(v2, tl, tm)
        build(v2 + 1, tm + 1, tr)
        t(v) = t(v2) + t(v2 + 1)
      }
    }

    def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Long = {
      if (l > r) 0
      else if (l == tl && r == tr) t(v).a11
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1

        lazyMul(v2) *= lazyMul(v)
        lazyMul(v2 + 1) *= lazyMul(v)
        t(v2) *= lazyMul(v)
        t(v2 + 1) *= lazyMul(v)
        lazyMul(v) = M2x2.Unit

        (query(l, Math.min(r, tm), v2, tl, tm) +
          query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr)) % MOD
      }
    }

    def update(l: Int, r: Int, mul: M2x2, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {
      if (l == tl && r == tr) {
        lazyMul(v) *= mul
        t(v) *= mul
      } else if (l <= r) {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        update(l, Math.min(r, tm), mul, v2, tl, tm)
        update(Math.max(l, tm + 1), r, mul, v2 + 1, tm + 1, tr)
        t(v) = (t(v2) + t(v2 + 1)) * lazyMul(v)
      }
    }

  }

  val Array(n, m) = readInts(2)
  val as = readInts(n)
  val st = SegTree(as.map(x => FibStart * M2x2.Fib.pow(x - 1)))

  val res = ArrayBuffer.empty[Long]

  for (_ <- 0 until m) {

    val s = readLine
    val tl = new java.util.StringTokenizer(s)

    if (s.startsWith("1")) {
      val Array(_, l, r, x) = Array.fill(4)(tl.nextToken.toInt)
      st.update(l - 1, r - 1, M2x2.Fib.pow(x))
    } else {
      val Array(_, l, r) = Array.fill(3)(tl.nextToken.toInt)
      res += st.query(l - 1, r - 1)
    }
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  println(res.mkString("\n"))

  Console.flush
}

import scala.collection.mutable.ArrayBuffer

object C extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }

  val MOD = 1000000007

  case class M1x2(a11: Long, a12: Long) {

    def +(other: M1x2) = M1x2(
      (this.a11 + other.a11) % MOD,
      (this.a12 + other.a12) % MOD)

    def *(other: M2x2) = M1x2(
      (this.a11 * other.a11 + this.a12 * other.a21) % MOD,
      (this.a11 * other.a12 + this.a12 * other.a22) % MOD)

  }

  val FibStart = M1x2(1, 1)

  case class M2x2(a11: Long, a12: Long, a21: Long, a22: Long) {

    def *(other: M2x2) = M2x2(
      (this.a11 * other.a11 + this.a12 * other.a21) % MOD,
      (this.a11 * other.a12 + this.a12 * other.a22) % MOD,
      (this.a21 * other.a11 + this.a22 * other.a21) % MOD,
      (this.a21 * other.a12 + this.a22 * other.a22) % MOD)

    def pow(n: Long) = {
      var pow2 = this
      var res = M2x2.Unit
      var deg = n

      while (deg > 0) {
        if ((deg & 1) != 0) res *= pow2
        pow2 *= pow2
        deg >>= 1
      }

      res
    }

  }

  object M2x2 {
    val Unit = M2x2(1, 0, 0, 1)
    val Fib = M2x2(0, 1, 1, 1)
  }

  case class SegTree(as: Array[M1x2]) {

    val NEUTRAL = M1x2(0, 0) // neutral element in respect of operation used (+)

    val n = as.length
    val t = Array.fill(4 * Integer.highestOneBit(n))(NEUTRAL)
    val lazyMul = Array.fill(4 * Integer.highestOneBit(n))(M2x2.Unit)
    build(1, 0, n - 1)

    def build(v: Int, tl: Int, tr: Int) {
      if (tl == tr) t(v) = as(tl)
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        build(v2, tl, tm)
        build(v2 + 1, tm + 1, tr)
        t(v) = t(v2) + t(v2 + 1)
      }
    }

    def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Long = {
      if (l > r) 0
      else if (l == tl && r == tr) t(v).a11
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1

        lazyMul(v2) *= lazyMul(v)
        lazyMul(v2 + 1) *= lazyMul(v)
        t(v2) *= lazyMul(v)
        t(v2 + 1) *= lazyMul(v)
        lazyMul(v) = M2x2.Unit

        (query(l, Math.min(r, tm), v2, tl, tm) +
          query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr)) % MOD
      }
    }

    def update(l: Int, r: Int, mul: M2x2, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {
      if (l == tl && r == tr) {
        lazyMul(v) *= mul
        t(v) *= mul
      } else if (l <= r) {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        update(l, Math.min(r, tm), mul, v2, tl, tm)
        update(Math.max(l, tm + 1), r, mul, v2 + 1, tm + 1, tr)
        t(v) = t(v2) + t(v2 + 1)
      }
    }

  }

  val Array(n, m) = readInts(2)
  val as = readInts(n)
  val st = SegTree(as.map(x => FibStart * M2x2.Fib.pow(x - 1)))

  val res = ArrayBuffer.empty[Long]

  for (_ <- 0 until m) {

    val s = readLine
    val tl = new java.util.StringTokenizer(s)

    if (s.startsWith("1")) {
      val Array(_, l, r, x) = Array.fill(4)(tl.nextToken.toInt)
      st.update(l - 1, r - 1, M2x2.Fib.pow(x))
    } else {
      val Array(_, l, r) = Array.fill(3)(tl.nextToken.toInt)
      res += st.query(l - 1, r - 1)
    }
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  println(res.mkString("\n"))

  Console.flush
}


import java.io._
import java.util.StringTokenizer

import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new C153A(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true

  class FastScanner(val streamReader: InputStreamReader) {
    private[this] val reader = new BufferedReader(streamReader, 32768)
    private[this] var tokenizer: StringTokenizer = _

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())

    def nextLong(): Long = java.lang.Long.parseLong(next())

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

    def ns(n: Int): Array[Char] = ns().toCharArray

    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)

    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }

    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }

    def nal(n: Int): Array[Long] = map(n)(_ => nl())

    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while (i < N) {
      f(i);
      i += 1
    }
  }

  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while (i >= offset) {
      f(i);
      i -= 1
    }
  }

  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    REP(as.length)(i => s += as(i))
    s
  }

  def cumSum(as: Array[Int]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

class C153A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  var a: Array[Int] = _

  def solve(): Unit = {
    val n = ni()
    val d = ni()

    a = na(n)

    val ans = a.zipWithIndex.map { f =>
      val x = (bs(f._2, n-1, f._1 + d + 1) - f._2 - 1).toLong
//      println(bs(f._2, n-1, f._1 + d + 1) + " " +x)
      if(x >= 2) {
        (x*(x-1))/2
      }
      else 0L
    }.sum
    out.println(ans)
  }

  def bs(st: Int, en: Int, tar: Long): Int = {
    var l = st
    var r = en
    while (r > l) {
      val m = l + (r - l) / 2
      if(a(m) >= tar) r = m
      else l = m+1
    }
    if(a(l) < tar) l+1
    else l
  }
}

import collection.mutable.Map
import collection.mutable.ArrayBuffer
import java.util.Scanner

object test6 extends App {
    val Array(n,d)=readLine.split(" ").map(_.toInt)
    val arr=readLine.split(" ").map(_.toInt)
    val dp=new Array[Long](n)
    val sum=new Array[Long](n)
    sum(0)=0
    for(i<-1 until n) sum(i)=sum(i-1)+i-1

    var i=0
    var j=0
    while(j<n){
        if(arr(j)-arr(i)<=d){
            j+=1
        }
        else{
            dp(i)=sum(j-1-i)
            i+=1
        }
    }
    for(k<-i until n){
        dp(k)=sum(n-1-k)
    }
    //println(dp.mkString(","))
    println(dp.sum)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, d) = in.next().split(' ').map(_.toInt)
  val data = in.next().split(' ').map(_.toInt)

  def count(first: Int, last: Int): Long = {
    if (last - first < 2)
      0
    else {
      val diff: Long = last - first
      diff * (diff - 1) / 2
    }
  }

  val res = (1 until n).foldLeft(0, 0l) {
    case ((first, sum), i) if data(i) - data(first) > d =>
      val newFirst = (first to i).find(j => data(i) - data(j) <= d).get
      val newSum = sum + (first until newFirst).map(count(_, i - 1)).sum
      (newFirst, newSum)
    case ((first, sum), i) => (first, sum)
  }
  println(res._2 + (res._1 until n).map(count(_, n - 1)).sum)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, d) = in.next().split(' ').map(_.toInt)
  val data = in.next().split(' ').map(_.toInt)

  def count(first: Int, last: Int) = {
    if (last - first < 2)
      0
    else {
      val diff = last - first
      diff * (diff - 1) / 2
    }
  }

  val res = (1 until n).foldLeft(0, 0) {
    case ((first, sum), i) if data(i) - data(first) > d =>
      val newFirst = (first to i).find(j => data(i) - data(j) <= d).get
      val newSum = sum + (first until newFirst).map(count(_, i - 1)).sum
      (newFirst, newSum)
    case ((first, sum), i) => (first, sum)
  }
  println(res._2 + (res._1 until n).map(count(_, n - 1)).sum)
}

import collection.mutable.Map
import collection.mutable.ArrayBuffer
import java.util.Scanner

object test6 extends App {
    val Array(n,d)=readLine.split(" ").map(_.toInt)
    val arr=readLine.split(" ").map(_.toInt)
    val dp=new Array[Long](n)
    val sum=new Array[Int](n)
    sum(0)=0
    for(i<-1 until n) sum(i)=sum(i-1)+i-1

    var i=0
    var j=0
    while(j<n){
        if(arr(j)-arr(i)<=d){
            j+=1
        }
        else{
            dp(i)=sum(j-1-i)
            i+=1
        }
    }
    for(k<-i until n){
        dp(k)=sum(n-1-k)
    }
    //println(dp.mkString(","))
    println(dp.sum)
}

import collection.mutable.Map
import collection.mutable.ArrayBuffer
import java.util.Scanner

object test6 extends App {
    val Array(n,d)=readLine.split(" ").map(_.toInt)
    val arr=readLine.split(" ").map(_.toInt)
    val dp=new Array[Int](n)

    var i=0
    var j=0
    while(j<n){
        if(arr(j)-arr(i)<=d){
            if(j-i>1) dp(i)+=math.max(0,j-i-1)
            j+=1
        }
        else{
            i+=1
            if(j-i>1) dp(i)=math.max(0,dp(i-1)-(j-i-1))
        }
    }
    for(k<-i+1 to n-3){
        dp(k)=math.max(0, dp(k-1)-(n-1-i-1))
    }
    //println(dp.mkString(","))
    println(dp.sum)
}

import collection.mutable.Map
import collection.mutable.ArrayBuffer
import java.util.Scanner

object test6 extends App {
    val Array(n,d)=readLine.split(" ").map(_.toInt)
    val arr=readLine.split(" ").map(_.toInt)
    val dp=new Array[Int](n)
    val sum=new Array[Int](n)
    sum(0)=0
    for(i<-1 until n) sum(i)=sum(i-1)+i-1

    var i=0
    var j=0
    while(j<n){
        if(arr(j)-arr(i)<=d){
            j+=1
        }
        else{
            dp(i)=sum(j-1-i)
            i+=1
        }
    }
    for(k<-i until n){
        dp(k)=sum(n-1-k)
    }
    //println(dp.mkString(","))
    println(dp.sum)
}


import scala.io.StdIn.readLine
object Main {
  def main(args: Array[String]) = {
    val T = readLine().toInt
    for(cas <- 0 until T) {
      var n = readLine().toInt
      var c1 = 0
      var c2 = 0
      while(n % 2 == 0) {
        n /= 2
        c1 += 1
      }
      while(n % 3 == 0) {
        n /= 3
        c2 += 1
      }
      if(c1 > c2 || n != 1) {
        println("-1")
      } else {
        println(c2 - c1 + c2)
      }
    }
  }
}

//package codeforces.contests._1374

/*
https://codeforces.com/contest/1374/problem/B
 */
object MultiplyByTwoDivideBySix {

  @scala.annotation.tailrec
  def countFactors(n: Int, m: Int, acc: Int = 0): Int =
    if (n == 1 || n % m != 0) acc else countFactors(n / m, m, acc + 1)

  def main(args: Array[String]): Unit = {
    for (_ <- 1 to io.StdIn.readInt()) {
      val n = io.StdIn.readInt()

      val twos = countFactors(n, 2)
      val threes = countFactors(n, 3)

      val noOtherFactors = (math.pow(2, twos) * math.pow(3, threes)).toInt == n

      println {
        if (n == 1) 0
        else if (noOtherFactors && threes >= twos) threes + (threes - twos)
        else -1
      }
    }
  }
}

import scala.io.StdIn._

object CF653_B extends App {
  var t = readInt()
  while (t > 0) {
    t -= 1;

    var n = readInt()
    var (cnt2, cnt3) = (0, 0)
    while (n % 3 == 0) {
      n /= 3
      cnt3 += 1
    }
    while (n % 2 == 0) {
      n /= 2
      cnt2 += 1
    }

    if (n > 1 || cnt3 < cnt2) {
      println(-1)
//      sys.exit()
    } else {
      println(2 * cnt3 - cnt2)
    }
  }
}

import java.io._
import java.util.StringTokenizer

import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new CF653A(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true

  class FastScanner(val streamReader: InputStreamReader) {
    private[this] val reader = new BufferedReader(streamReader, 32768)
    private[this] var tokenizer: StringTokenizer = _

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())

    def nextLong(): Long = java.lang.Long.parseLong(next())

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

    def ns(n: Int): Array[Char] = ns().toCharArray

    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)

    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }

    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }

    def nal(n: Int): Array[Long] = map(n)(_ => nl())

    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while (i < N) {
      f(i);
      i += 1
    }
  }

  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while (i >= offset) {
      f(i);
      i -= 1
    }
  }

  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    REP(as.length)(i => s += as(i))
    s
  }

  def cumSum(as: Array[Int]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

class CF653A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val t = ni()
    REP(t) { _ =>
      val n = ni()
      if(n == 1) out.println("0")
      else {
        var cnt3 = 0
        var x = n
        while (x > 0 && x % 3 == 0) {
          cnt3 += 1
          x /= 3
        }

        var cnt2 = 0
        while (x > 0 && x % 2 == 0) {
          cnt2 += 1
          x /= 2
        }

        if(cnt2 > cnt3 || x > 1) out.println("-1")
        else out.println(cnt2 + (cnt3 - cnt2) * 2)
      }
    }
  }

}

object a{
  def main(args: Array[String]) = {
    val n: Int = scala.io.StdIn.readInt()
    for(i <- 1 to n){
      var x: Int = scala.io.StdIn.readInt()
      var ans = 0
      var done = false
      while(!done){
        if(x == 1){
          done = true
        }
        else if(x%6 == 0){
          x /= 6;
          ans += 1
        }
        else if(x%3 == 0){
          x /= 3
          ans += 2
        }
        else{
          ans = -1
          done = true
        }
      }
      println(ans)
    }
  }
}

object B extends App {

  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer
  import scala.io.Source
  import scala.io.Codec

  /* Implicit methods */
  implicit def intWithTimes(n: Int) = {
    new {
      def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }
    }
  }

  /* Implicit methods */

//  val in = new CustomScanner(Source.fromResource("input.txt").mkString)
  val in = new CustomScanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val n = in.nextInt()

    n.times {
      val number     = in.nextInt()
      var number2    = number
      var noOfTwos   = 0
      var noOfThrees = 0

      while (number2 % 2 == 0) {
        number2 = number2 / 2
        noOfTwos = noOfTwos + 1
      }

      while (number2 % 3 == 0) {
        number2 = number2 / 3
        noOfThrees = noOfThrees + 1
      }

      if (number == 1) {
        println(0)
      } else if (number2 > 1) {
        println(-1)
      } else {
        if (noOfTwos == noOfThrees) {
          println(noOfTwos)
        } else if (noOfThrees > noOfTwos) {
          val diff = noOfThrees - noOfTwos
          println(noOfTwos + (diff * 2))
        } else {
          println(-1)
        }
      }
    }
  }

  try {
    solve()
  } catch {
    case ex: Exception =>
      println(ex)
      sys.exit(9999)
  } finally {
    out.flush()
    out.close()
  }

  /**
    * Util methods
    */

  def printArr[T](in: Array[T]) = {
    in.foreach(print)
    println()
  }

  /**
    * Scala implementation of a faster java.util.Scanner
    * See: http://codeforces.com/blog/entry/7018
    */
  class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {

    def this(reader: BufferedReader) = this(new LineNumberReader(reader))

    def this(reader: Reader) = this(new BufferedReader(reader))

    def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

    def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))

    def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

    def this(str: String) = this(new StringReader(str))

    private[this] val tokenizers = {
      Iterator
        .continually(reader.readLine())
        .takeWhile(_ != null)
        .map(new StringTokenizer(_))
        .filter(_.hasMoreTokens)
    }

    private[this] var current: Option[StringTokenizer] = None

    @inline private[this] def tokenizer(): Option[StringTokenizer] =
      current.find(_.hasMoreTokens) orElse {
        current = if (tokenizers.hasNext) Some(tokenizers.next()) else None
        current
      }

    /**
      * Unlike Java's scanner which returns till end of current line, this actually returns the next line
      *
     * @see line() if you want the Java behaviour
      */
    def nextLine(): String = {
      current = None // reset
      reader.readLine()
    }

    def lineNumber: Int = reader.getLineNumber

    def line(): String = tokenizer().get.nextToken("\n\r")

    def nextString(): String = next()

    def nextChar(): Char = next().ensuring(_.length == 1).head

    def nextBoolean(): Boolean = next().toBoolean

    def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

    def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

    def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

    def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

    def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

    def nextFloat(): Float = next().toFloat

    def nextDouble(): Double = next().toDouble

    def nextBigDecimal(): BigDecimal = BigDecimal(next())

    override def next(): String = tokenizer().get.nextToken()

    override def hasNext: Boolean = tokenizer().nonEmpty

    override def close(): Unit = reader.close()
  }

}


import java.io._
import java.util.StringTokenizer

import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new C627C(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true

  class FastScanner(val streamReader: InputStreamReader) {
    private[this] val reader = new BufferedReader(streamReader, 32768)
    private[this] var tokenizer: StringTokenizer = _

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())

    def nextLong(): Long = java.lang.Long.parseLong(next())

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

    def ns(n: Int): Array[Char] = ns().toCharArray

    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)

    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }

    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }

    def nal(n: Int): Array[Long] = map(n)(_ => nl())

    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while (i < N) {
      f(i);
      i += 1
    }
  }

  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while (i >= offset) {
      f(i);
      i -= 1
    }
  }

  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    REP(as.length)(i => s += as(i))
    s
  }

  def cumSum(as: Array[Int]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

class C627C(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val t = ni()
    REP(t) { _ =>
      val s = ('R' + ns() + 'R').toCharArray

      val n = s.length
      var prev = 0
      var mx = -1
      REP(n) { i =>
        if(i > 0 && s(i) == 'R') {
          mx = Math.max(mx, i - prev)
          prev = i
        }
      }
      out.println(mx)
    }
  }
}

object _1324C extends CodeForcesApp {
  import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._

  override def solve(io: IO) = io.repeat {
    val instrs = io.read[String]

    val ans = ('R' + instrs + 'R')
      .zipWithIndex
      .collect({case ('R', i) => i})
      .sliding(2)
      .map({case Seq(i, j) => j - i})
      .max

    io.write(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def solve(io: IO): Any
  def main(args: Array[String]): Unit = {
    val io = new IO(System.in, System.out)
    try solve(io) finally io.close()
  }
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]

  def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None

  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)

  implicit class GenericExtensions[A](a: A) {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }

  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]

    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)

    def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {
      val freqTable = t.groupBy(identity).mapValues(_.size)
      if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable
    }
  }

  implicit class PairExtensions[A, B](p: (A, B)) {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))
  }

  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())
  }

  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {
    def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m
  }

  implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }

  implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
  }

  implicit class BooleanExtensions(x: Boolean) {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "Yes" else "No"
  }

  implicit class IntExtensions(val x: Int) extends AnyVal {
    @inline def isEven = x%2 == 0
    @inline def isOdd = x%2 == 1
  }

  def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse  //e.g. students.sortBy(_.height)(desc)

  def map[K] = new {
    def to[V](default: => V): mutable.Map[K, V] = using(_ => default)
    def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }

  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]

  def memoize[A, B](f: A => B): A => B = map[A] using f
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

class IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {
  def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))
  def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))

  private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered
  val printer = new PrintWriter(out, true)

  @inline private[this] def tokenizer() = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    tokenizers.headOption
  }

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]
  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty

  def write(obj: Any*): this.type = writeAll(obj)
  def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = {printer.print(obj.mkString(separator)); this}
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                                   : Read[String]       = new Read(_.next())
    implicit val int                                                      : Read[Int]          = string.map(_.toInt)
    implicit val long                                                     : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                                   : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                                   : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                               : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                                 : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]                        : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]               : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                                  : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}


import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val employees = Array.ofDim[Array[Int]](n) // employee -> language
  val markedEmployees = Array.ofDim[Boolean](n) // is employee marked
  val languages = Array.fill[List[Int]](m){List.empty} // language -> employee
  val markedLanguages = Array.ofDim[Boolean](m) // is language marked

  def mark(employee: Int) = {
    if (!markedEmployees(employee)) {
//      println("mark employee " + employee)
      markedEmployees(employee) = true
      employees(employee).foreach { markLanguage }
    }
  }

  def markLanguage(language: Int) {
    if (!markedLanguages(language)) {
//      println("mark language " + language)
      markedLanguages(language) = true
      languages(language).foreach {
        mark
      }
    }
  }

  (0 until n).foreach { j =>
    val data = in.next().split(' ').tail.map(_.toInt - 1)
    employees(j) = data
    data.foreach { i => languages(i) ::= j }
  }
  val res = (0 until n).foldLeft(0) {
    case (acc, j) if markedEmployees(j) => acc
    case (acc, j) =>
      mark(j)
      acc + 1
  }
  println(Math.max(res - 1, employees.count(_.isEmpty)))
}

import scala.io.StdIn.readLine
import scala.collection.mutable

object Solution2 {
  class Graph(vertices: List[Int]) {

    val neighbours: Array[List[Int]] = Array.fill(vertices.length)(List.empty)

    def addConnection(a: Int, b: Int): Unit = neighbours(a) = b :: neighbours(a)

    def getNeighbours(v: Int): List[Int] = neighbours(v)

    def dfs(now: Int, visited: Array[Boolean], f: Int => Unit): Unit = {
      f(now)
      visited(now) = true
      getNeighbours(now) foreach { x => if (!visited(x)) dfs(x, visited, f) }
    }

    def connectedComponentsAmWithFilter(p: Int => Boolean): Int = {
      val visited: Array[Boolean] = Array.fill(vertices.length)(false)

      (vertices filter p).foldLeft(0) {
        (sol, x) =>
          if (!visited(x)) {
            dfs(x, visited, { x => visited(x) = true })
            sol + 1
          }
          else sol
      }
    }
  }

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readLine split " " map { _.toInt }
    val g: Graph = new Graph((0 until (n + m)).toList)
    var allZero = true
    0 until n foreach {
      i =>
        val line = readLine split " " map { _.toInt }
        val k = line(0)
        if (k > 0) allZero = false
        1 to k foreach { j =>
          val lang = line(j)
          g.addConnection(i, n + lang - 1)
          g.addConnection(n - 1 + lang, i)
        }
    }
    if (allZero) println(n)
    else println(g.connectedComponentsAmWithFilter({ x => 0 <= x && x < n}) - 1)
  }
}

import java.io._
import java.util.StringTokenizer

import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new C170A(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true

  class FastScanner(val streamReader: InputStreamReader) {
    private[this] val reader = new BufferedReader(streamReader, 32768)
    private[this] var tokenizer: StringTokenizer = _

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())

    def nextLong(): Long = java.lang.Long.parseLong(next())

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

    def ns(n: Int): Array[Char] = ns().toCharArray

    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)

    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }

    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }

    def nal(n: Int): Array[Long] = map(n)(_ => nl())

    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while (i < N) {
      f(i);
      i += 1
    }
  }

  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while (i >= offset) {
      f(i);
      i -= 1
    }
  }

  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    REP(as.length)(i => s += as(i))
    s
  }

  def cumSum(as: Array[Int]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

class C170A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val n = ni()
    val m = ni()
    val col = Array.fill[Boolean](n,m)(false)
    val adjA = Array.fill[Boolean](m,m)(false)

    REP(n) { i =>
      val k = ni()
      var prev = -1
      REP(k) { _ =>
        val j = ni()
        col(i)(j-1) = true
        if(prev == -1) prev = j-1
        else {
          adjA(prev)(j-1) = true
          adjA(j-1)(prev) = true
          prev = j-1
        }
      }
    }

    adjL = adjA.map(f => f.zipWithIndex.filter(p => p._1).map(_._2).toList)
    marked = Array.fill(m)(false)
    var count = 0
    var yes = false
    REP(n) { i =>
      val x = col(i).zipWithIndex.find(p => p._1 && marked(p._2))
      if(x.isEmpty) {
        count += 1
        val y: Option[(Boolean, Int)] = col(i).zipWithIndex.find(p => p._1)
        if(y.isDefined) {
          yes = true
          marked(y.get._2) = true
          dfs(y.get._2)
        }
      }
    }
    out.println(if(yes) count-1 else count)
  }

  var adjL: Array[List[Int]] = _
  var marked: Array[Boolean] = _

  def dfs(u: Int): Unit = {
    adjL(u).foreach { p =>
      if(!marked(p)) {
        marked(p) = true
        dfs(p)
      }
    }
  }
}

object tmp extends App {

  import java.io._
  import java.util.StringTokenizer

  import scala.collection.mutable

  class MyScanner(br: BufferedReader) {
    var st = new StringTokenizer("")

    def this(is: InputStream) = this(new BufferedReader(new InputStreamReader(is)))

    private def next() = {

      while (!st.hasMoreElements) {
        st = new StringTokenizer(br.readLine())
      }
      st.nextToken()
    }

    def nextInt() = java.lang.Integer.parseInt(next())

    def nextLong() = java.lang.Long.parseLong(next())

    def nextLine() = br.readLine()
  }

  val sc = new MyScanner(System.in)
  val n = sc.nextInt()
  val m = sc.nextInt()
  val graph = Array.fill(n + m)(mutable.ArrayBuffer[Int]())
  var empl = 0
  var anyLeng = false
  while (empl < n) {
    val amount = sc.nextInt()
    var k = 0
    while (k < amount) {
      anyLeng = true
      val leng = sc.nextInt() - 1
      graph(empl) += n + leng
      graph(n + leng) += empl
      k += 1
    }
    empl += 1
  }
  val res = if (!anyLeng) n
  else {
    val groups = Array.fill(n)(-1)
    var curGroup = 0
    var v = 0
    while ( {v = 0; while (v < n && groups(v) != -1) v += 1; v < n}) {
      dfs(v)
      curGroup += 1
    }
    def dfs(v: Int): Unit = {
      if (v < n) {
        groups(v) = curGroup
      }
      val graphV = graph(v)
      val size = graphV.size
      var i = 0
      while (i < size) {
        val to = graphV(i)
        if (to >= n || groups(to) == -1) {
          dfs(to)
        }
        i += 1
      }
    }
    curGroup - 1
  }
  println(res)
}

import scala.io.StdIn.readLine
import scala.collection.mutable

object Solution2 {
  class Graph(vertices: List[Int]) {

    val neighbours: Array[List[Int]] = Array.fill(vertices.length)(List.empty)

    def addConnection(a: Int, b: Int): Unit = neighbours(a) = b :: neighbours(a)

    def getNeighbours(v: Int): List[Int] = neighbours(v)

    def dfs(now: Int, visited: Array[Boolean]): Unit = {
      visited(now) = true
      getNeighbours(now) foreach { x => if (!visited(x)) dfs(x, visited) }
    }

    def connectedComponentsAmWithFilter(p: Int => Boolean): Int = {
      val visited: Array[Boolean] = Array.fill(vertices.length)(false)

      (vertices filter p).foldLeft(0) {
        (sol, x) =>
          if (!visited(x)) {
            dfs(x, visited)
            sol + 1
          }
          else sol
      }
    }
  }

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readLine split " " map { _.toInt }
    val g: Graph = new Graph((0 until (n + m)).toList)
    var allZero = true
    0 until n foreach {
      i =>
        val line = readLine split " " map { _.toInt }
        val k = line(0)
        if (k > 0) allZero = false
        1 to k foreach { j =>
          val lang = line(j)
          g.addConnection(i, n + lang - 1)
          g.addConnection(n - 1 + lang, i)
        }
    }
    if (allZero) println(n)
    else println(g.connectedComponentsAmWithFilter({ x => 0 <= x && x < n}) - 1)
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val employees = Array.ofDim[Array[Int]](n) // employee -> language
  val markedEmployees = Array.ofDim[Boolean](n) // is employee marked
  val languages = Array.fill[List[Int]](m){List.empty} // language -> employee
  val markedLanguages = Array.ofDim[Boolean](m) // is language marked

  def mark(employee: Int) = {
    if (!markedEmployees(employee)) {
//      println("mark employee " + employee)
      markedEmployees(employee) = true
      employees(employee).foreach { markLanguage }
    }
  }

  def markLanguage(language: Int) {
    if (!markedLanguages(language)) {
//      println("mark language " + language)
      markedLanguages(language) = true
      languages(language).foreach {
        mark
      }
    }
  }

  (0 until n).foreach { j =>
    val data = in.next().split(' ').tail.map(_.toInt - 1)
    employees(j) = data
    data.foreach { i => languages(i) ::= j }
  }
  val res = (0 until n).foldLeft(0) {
    case (acc, j) if markedEmployees(j) => acc
    case (acc, j) =>
      mark(j)
      acc + 1
  }
  println(res - 1)
}

import java.io._
import java.util.StringTokenizer

import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new C170A(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true

  class FastScanner(val streamReader: InputStreamReader) {
    private[this] val reader = new BufferedReader(streamReader, 32768)
    private[this] var tokenizer: StringTokenizer = _

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())

    def nextLong(): Long = java.lang.Long.parseLong(next())

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

    def ns(n: Int): Array[Char] = ns().toCharArray

    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)

    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }

    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }

    def nal(n: Int): Array[Long] = map(n)(_ => nl())

    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while (i < N) {
      f(i);
      i += 1
    }
  }

  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while (i >= offset) {
      f(i);
      i -= 1
    }
  }

  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    REP(as.length)(i => s += as(i))
    s
  }

  def cumSum(as: Array[Int]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

class C170A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val n = ni()
    val m = ni()
    val col = Array.fill[Boolean](n,m)(false)
    val adjA = Array.fill[Boolean](m,m)(false)

    REP(n) { i =>
      val k = ni()
      var prev = -1
      REP(k) { _ =>
        val j = ni()
        col(i)(j-1) = true
        if(prev == -1) prev = j-1
        else {
          adjA(prev)(j-1) = true
          adjA(j-1)(prev) = true
          prev = j-1
        }
      }
    }

    adjL = adjA.map(f => f.zipWithIndex.filter(p => p._1).map(_._2).toList)
    marked = Array.fill(m)(false)
    var count = 0

    REP(n) { i =>
      val x = col(i).zipWithIndex.find(p => p._1 && marked(p._2))
      if(x.isEmpty) {
        count += 1
        val y: Option[(Boolean, Int)] = col(i).zipWithIndex.find(p => p._1)
        if(y.isDefined) {
          marked(y.get._2) = true
          dfs(y.get._2)
        }
      }
    }
    out.println(count-1)
  }

  var adjL: Array[List[Int]] = _
  var marked: Array[Boolean] = _

  def dfs(u: Int): Unit = {
    adjL(u).foreach { p =>
      if(!marked(p)) {
        marked(p) = true
        dfs(p)
      }
    }
  }
}

import scala.collection.mutable

object Solution {

  class Graph[T](vertices: List[T]) {
  type Vertex = T
  type Connections = mutable.Map[Vertex, List[Vertex]]

  val neighbours: mutable.Map[Vertex, List[Vertex]] = mutable.Map.empty

  def addConnection(a: Vertex, b: Vertex): Unit = neighbours.put(a, b :: neighbours.getOrElse(a, List.empty[Vertex]))

  def getNeighbours(v: Vertex): List[Vertex] = neighbours.getOrElse(v, List.empty)

  def dfs(now: Vertex, visited: Set[Vertex], f: Vertex => Unit): Unit = {
    f(now)
    getNeighbours(now) filterNot { x => visited.contains(x) } foreach { x => dfs(x, visited + now, f) }
  }

  def connectedComponentsAm(): Int = {
    val visited: Set[Vertex] = Set.empty

    vertices.foldLeft(0) {
      (sol, x) =>
        if (!visited.contains(x)) {
          dfs(x, Set.empty, { x => visited + x }); sol + 1
        }
        else sol
    }
  }
}

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readLine.split(" ").map(_.toInt)
    val g: Graph[Int] = new Graph[Int]((1 to (n + m)).toList)
    1 to n foreach {
      i =>
        val line = readLine.split(" ").map(_.toInt)
        val k = line(0)
        1 to k foreach { j =>
          val lang = line(j)
          g.addConnection(i, n + lang)
          g.addConnection(n + lang, i)
        }
    }
    g.connectedComponentsAm()
  }
}

import scala.io.StdIn.readLine
import scala.collection.mutable

object Solution {
  class Graph[T](vertices: List[T]) {
    type Vertex = T
    type Connections = mutable.Map[Vertex, List[Vertex]]

    val neighbours: mutable.Map[Vertex, List[Vertex]] = mutable.Map.empty

    def addConnection(a: Vertex, b: Vertex): Unit = neighbours.put(a, b :: neighbours.getOrElse(a, List.empty[Vertex]))

    def getNeighbours(v: Vertex): List[Vertex] = neighbours.getOrElse(v, List.empty)

    def dfs(now: Vertex, visited: Set[Vertex], f: Vertex => Unit): Unit = {
      f(now)
      getNeighbours(now) filterNot { x => visited.contains(x) } foreach { x => dfs(x, visited + now, f) }
    }

    def connectedComponentsAmWithFilter(p: Vertex => Boolean): Int = {
      var visited: Set[Vertex] = Set.empty

      (vertices filter p).foldLeft(0) {
        (sol, x) =>
          if (!visited.contains(x)) {
            dfs(x, Set.empty, { x => visited += x })
            sol + 1
          }
          else sol
      }
    }
  }

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readLine.split(" ").map(_.toInt)
    val g: Graph[Int] = new Graph[Int]((1 to (n + m)).toList)
    1 to n foreach {
      i =>
        val line = readLine.split(" ").map(_.toInt)
        val k = line(0)
        1 to k foreach { j =>
          val lang = line(j)
          g.addConnection(i, n + lang)
          g.addConnection(n + lang, i)
        }
    }
    println(g.connectedComponentsAmWithFilter({ x => 1 <= x && x <= n}) - 1)
  }
}

import scala.io.StdIn.readLine
import scala.collection.mutable

object Solution {
  class Graph[T](vertices: List[T]) {
    type Vertex = T
    type Connections = mutable.Map[Vertex, List[Vertex]]

    val neighbours: mutable.Map[Vertex, List[Vertex]] = mutable.Map.empty

    def addConnection(a: Vertex, b: Vertex): Unit = neighbours.put(a, b :: neighbours.getOrElse(a, List.empty[Vertex]))

    def getNeighbours(v: Vertex): List[Vertex] = neighbours.getOrElse(v, List.empty)

    def dfs(now: Vertex, visited: Set[Vertex], f: Vertex => Unit): Unit = {
      f(now)
      getNeighbours(now) filterNot { x => visited.contains(x) } foreach { x => dfs(x, visited + now, f) }
    }

    def connectedComponentsAm(): Int = {
      val visited: Set[Vertex] = Set.empty

      vertices.foldLeft(0) {
        (sol, x) =>
          if (!visited.contains(x)) {
            dfs(x, Set.empty, { x => visited + x }); sol + 1
          }
          else sol
      }
    }
  }

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readLine.split(" ").map(_.toInt)
    val g: Graph[Int] = new Graph[Int]((1 to (n + m)).toList)
    1 to n foreach {
      i =>
        val line = readLine.split(" ").map(_.toInt)
        val k = line(0)
        1 to k foreach { j =>
          val lang = line(j)
          g.addConnection(i, n + lang)
          g.addConnection(n + lang, i)
        }
    }
    println(g.connectedComponentsAm())
  }
}


import java.io._
import java.util._

import scala.collection.mutable

object C {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }

  def next: String = {
    while (st == null || !st.hasMoreTokens) {
      st = new StringTokenizer(br.readLine)
    }
    return st.nextToken
  }

  def nextInt: Int = return Integer.parseInt(next)

  def nextBoolean: Boolean = next.equalsIgnoreCase("1")

  def nextLong: Long = return java.lang.Long.parseLong(next)

  def nextDouble: Double = return java.lang.Double.parseDouble(next)

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      return map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }

    override def toString = s"MultiHashSet($map)"
  }

  class MultiTreeSet[T <% Comparable[T]] {
    val map = new TreeMap[T, Int]()

    def count(x: T): Int = {
      val res = map.get(x)
      if (res == null)
        return 0
      return res
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def first(): T = return map.firstKey()

    def last(): T = return map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  /**
    * Segment tree for any commutative function
    *
    * @param values      Array of Int
    * @param commutative function like min, max, sum
    * @param zero        zero value - e.g. 0 for sum, Inf for min, max
    */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???

    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  def solve: Int = {
    val n = nextInt
    var posToRemove = 1
    var ans = 0
    var list = scala.collection.immutable.List[Int]()
    var howMuchToSkip = 0
    for (_ <- 0 until 2 * n) {
      val command = next
      if (command.equalsIgnoreCase("add")) {
        val id = nextInt
        howMuchToSkip = 0
        list = id :: list
      } else {
        if (howMuchToSkip > 0) {
          howMuchToSkip -= 1
          posToRemove += 1
        } else if (list.isEmpty || list.head == posToRemove) {
          posToRemove += 1
          if (!list.isEmpty)
            list = list.tail
        } else {
          ans += 1
          posToRemove += 1
          //posToRemove += list.length
          howMuchToSkip = list.length
          list = Nil
        }
      }
    }
    out.println(ans)
    return 0
  }
}

object _821C extends CodeForcesApp {
  import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._

  override def apply(io: IO) = {import io.{read, readAll, write, writeAll, writeLine}
    val n = read[Int]
    val golden, temp = collection.mutable.Stack.empty[Int]
    var ans, expected = 0

    repeat(2*n) {
      val cmd = read[String]
      cmd match {
        case "add" => temp.push(read[Int])
        case "remove" =>
          expected += 1
          val popped = if (temp.isEmpty) {
            golden.pop()
          } else if (temp.head == expected) {
            temp.pop()
          } else {
            ans += 1
            golden.pushAll(temp.sorted.reverse)
            temp.clear()
            golden.pop()
          }
          //assert(popped == expected)
      }
      //debug(cmd, golden, temp, expected, ans)
    }

    write(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = assuming(t.size == 1)(t.head)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)
    def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
    def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
    def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "Yes" else "No"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {
    val (xs, ys) = points.unzip
    new java.awt.Polygon(xs.toArray, ys.toArray, points.size)
  }
  def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {
    val shape = new java.awt.geom.GeneralPath()
    points.headOption foreach {case (x, y) => shape.moveTo(x, y)}
    points.tail foreach {case (x, y) => shape.lineTo(x, y)}
    shape.closePath()
    shape
  }
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

class IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {
  def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))
  def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))

  private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered
  val printer = new PrintWriter(out, true)

  @inline private[this] def tokenizer() = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    when(tokenizers.nonEmpty)(tokenizers.head)
  }

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]

  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

  def readAll[A: IO.Read]: (Int, Vector[A]) = {
    val data = read[Vector[A]]
    (data.length, data)
  }

  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty

  def write(obj: Any): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val int                                          : Read[Int]          = string.map(_.toInt)
    implicit val long                                         : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                       : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                       : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                   : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                     : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                      : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}

import java.io._
import java.util._

import scala.collection.mutable

object C {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }

  def next: String = {
    while (st == null || !st.hasMoreTokens) {
      st = new StringTokenizer(br.readLine)
    }
    return st.nextToken
  }

  def nextInt: Int = return Integer.parseInt(next)

  def nextBoolean: Boolean = next.equalsIgnoreCase("1")

  def nextLong: Long = return java.lang.Long.parseLong(next)

  def nextDouble: Double = return java.lang.Double.parseDouble(next)

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      return map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }

    override def toString = s"MultiHashSet($map)"
  }

  class MultiTreeSet[T <% Comparable[T]] {
    val map = new TreeMap[T, Int]()

    def count(x: T): Int = {
      val res = map.get(x)
      if (res == null)
        return 0
      return res
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def first(): T = return map.firstKey()

    def last(): T = return map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  /**
    * Segment tree for any commutative function
    *
    * @param values      Array of Int
    * @param commutative function like min, max, sum
    * @param zero        zero value - e.g. 0 for sum, Inf for min, max
    */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???

    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  def solve: Int = {
    val n = nextInt
    var posToRemove = 1
    var ans = 0
    val set = new mutable.TreeSet[Int]()
    var list = scala.collection.immutable.List[Int]()
    var howMuchToSkip = 0
    for (_ <- 0 until 2 * n) {
      val command = next
      if (command.equalsIgnoreCase("add")) {
        val id = nextInt
        set.add(id)
        list = id :: list
      } else {
        if (howMuchToSkip > 0) {
          howMuchToSkip -= 1
        }
        else if (list.head == posToRemove) {
          set.remove(list.head)
          posToRemove += 1
          list = list.tail
        } else {
          ans += 1
          set.clear()
          posToRemove += list.length
          howMuchToSkip = list.length
          list = Nil
        }
      }
    }
    out.println(ans)
    return 0
  }
}


import java.io._
import java.util.StringTokenizer
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import scala.util.Sorting.quickSort
import util.control.Breaks._

object Solution {
    val writer =  new PrintWriter(System.out)
    val reader = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer("")
    def next(): String = {
        while (!st.hasMoreTokens) {
            st = new StringTokenizer(reader.readLine())
        }
        st.nextToken()
    }

    def readInt() = next.toInt
    def readLong() = next.toLong
    def readString() = next()

    def pow(a: Int, b: Int): Long = {
        if (b == 0) return 1

        val rs = pow(a, b / 2)
        rs * rs * (if (b % 2 == 0) 1 else a)
    }

    def GCD(a: Int, b: Int): Int = {
        if (a == 0) return b
        GCD(b % a, a)
    }

    def LCM(a: Int, b: Int): Int = (a / GCD(a,b)) * b

    def root(u: Int, p: Array[Int]): Int = {
        if (p(u) < 0) return u
        p(u) = root(p(u), p)
        p(u)
    }

    def join(u: Int, v: Int, p: Array[Int]): Unit = {
        var x = root(u, p)
        var y = root(v, p)
        if (x == y) return

        if (p(y) < p(x)) {
            val t = x
            x = y
            y = t
        }
        p(x) += p(y)
        p(y) = x
    }

    def main(args: Array[String]) {
        var t = readInt()
        while (t > 0) {
            t -= 1
            val (a,b,c,m) = (readInt(),readInt(),readInt(),readInt())

            val s = Array(a,b,c)
            val maxS = s.max
            val sumS = s.sum
            val maxP = sumS - 3
            val minP = maxS - (sumS - maxS) - 1
            if (m <= maxP && m >= minP) writer.println("YES")
            else writer.println("NO")

        }
        writer.close()
    }
}

object B extends App {

  /** Assumption: a >= b >= c
    *
    * - Upper bound: (a - 1) + (b - 1) + (c - 1)
    *   Example: "aaaaabbbc"
    *
    * - Lower bound: a - b - c - 1
    *   Example: "abacabacababaaa"
    */
  def check(a: Int, b: Int, c: Int, m: Int): Boolean =
    m >= 2 * (a max b max c) - a - b - c - 1 && m <= a + b + c - 3

  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val Array(a, b, c, m) = nextInts(4)

    check(a, b, c, m) match {
      case true  =>
        out.println("YES")
        out.flush()
      case false =>
        out.println("NO")
        out.flush()
    }
  }

  final object InOut {
    val in  = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)

    def nextInt()        = Integer.parseInt(nextToken())
    def nextInts(n: Int) = Array.fill(n)(nextInt())

    def nextLong()        = java.lang.Long.parseLong(nextToken())
    def nextLongs(n: Int) = Array.fill(n)(nextLong())

    def nextBig()        = BigInt(nextToken())
    def nextBigs(n: Int) = Array.fill(n)(nextBig())

    def nextLine() = in.readLine()

    private[this] var tokenizer: java.util.StringTokenizer = _

    def nextToken(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens())
        tokenizer = new java.util.StringTokenizer(in.readLine())
      tokenizer.nextToken()
    }
  }
}

import java.io._
import java.util.StringTokenizer
import scala.collection.mutable._
import scala.math.max

object test {
    val writer =  new PrintWriter(System.out)
    val reader = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer("")
    def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}
    def readInt(): Int = next().toInt
    def readLong(): Long = next().toLong
    def readString(): String = next()

    def main(args: Array[String]): Unit = {
        val t = readInt()
        for (tt <- 1 to t) {
            val a = readInt()
            val b = readInt()
            val c = readInt()
            val m = readInt()
            val sum = a + b + c
            val valid = max(0, a - 1) + max(0, b - 1) + max(0, c - 1)
            val mx = max(a, max(b, c))
            if (m > valid || m < mx-1-(sum-mx))
                writer.println("NO")
            else
                writer.println("YES")

            writer.flush()
        }
    }
}

object B extends App {

  /** Assumption: a >= b >= c
    *
    * - Upper bound: (a - 1) + (b - 1) + (c - 1)
    *   Example: "aaaaabbbc"
    *
    * - Lower bound: a - b - c - 1
    *   Example: "abacabacababaaa"
    */
  def check(a: Int, b: Int, c: Int, m: Int): Boolean =
    m >= 2 * ((a max b max c) + (a min b min c)) - a - b - c - 1 && m <= a + b + c - 3

  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val Array(a, b, c, m) = nextInts(4)

    check(a, b, c, m) match {
      case true  =>
        out.println("YES")
        out.flush()
      case false =>
        out.println("NO")
        out.flush()
    }
  }

  final object InOut {
    val in  = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)

    def nextInt()        = Integer.parseInt(nextToken())
    def nextInts(n: Int) = Array.fill(n)(nextInt())

    def nextLong()        = java.lang.Long.parseLong(nextToken())
    def nextLongs(n: Int) = Array.fill(n)(nextLong())

    def nextBig()        = BigInt(nextToken())
    def nextBigs(n: Int) = Array.fill(n)(nextBig())

    def nextLine() = in.readLine()

    private[this] var tokenizer: java.util.StringTokenizer = _

    def nextToken(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens())
        tokenizer = new java.util.StringTokenizer(in.readLine())
      tokenizer.nextToken()
    }
  }
}

object B extends App {

  /** Assumption: a >= b >= c
    *
    * - Upper bound: (a - 1) + (b - 1) + (c - 1)
    *   Example: "aaaaabbbc"
    *
    * - Lower bound: a - b - c - 1
    *   Example: "abacabacababaaa"
    */
  def check(a: Int, b: Int, c: Int, m: Int): Boolean =
    m >= a - b - c - 1 && m <= a + b + c - 3

  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val Array(a, b, c, m) = nextInts(4)

    check(a, b, c, m) match {
      case true  =>
        out.println("YES")
        out.flush()
      case false =>
        out.println("NO")
        out.flush()
    }
  }

  final object InOut {
    val in  = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)

    def nextInt()        = Integer.parseInt(nextToken())
    def nextInts(n: Int) = Array.fill(n)(nextInt())

    def nextLong()        = java.lang.Long.parseLong(nextToken())
    def nextLongs(n: Int) = Array.fill(n)(nextLong())

    def nextBig()        = BigInt(nextToken())
    def nextBigs(n: Int) = Array.fill(n)(nextBig())

    def nextLine() = in.readLine()

    private[this] var tokenizer: java.util.StringTokenizer = _

    def nextToken(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens())
        tokenizer = new java.util.StringTokenizer(in.readLine())
      tokenizer.nextToken()
    }
  }
}

object B extends App {

  @annotation.tailrec
  def check(a: Int, b: Int, c: Int, m: Int, iter: Int = 0): Boolean =
    if (iter > 100) false
    else {
      val n = a + b + c

      if (a < b || a < c || b < c)
        check(a max b max c, n - (a max b max c) - (a min b min c), a min b min c, m, iter)
      else
        m match {
          case 0 => a <= (n + 1) / 2
          case m =>
            val ka = m min (a / 2)

            if (ka > 0 && a - ka <= (n - m + 1) / 2) check(a - 2 * ka, b, c, m - ka, iter + 1)
            else false
        }

    }

  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val Array(a, b, c, m) = nextInts(4)

    check(a, b, c, m) match {
      case true  =>
        out.println("YES")
        out.flush()
      case false =>
        out.println("NO")
        out.flush()
    }
  }

  final object InOut {
    val in  = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)

    def nextInt()        = Integer.parseInt(nextToken())
    def nextInts(n: Int) = Array.fill(n)(nextInt())

    def nextLong()        = java.lang.Long.parseLong(nextToken())
    def nextLongs(n: Int) = Array.fill(n)(nextLong())

    def nextBig()        = BigInt(nextToken())
    def nextBigs(n: Int) = Array.fill(n)(nextBig())

    def nextLine() = in.readLine()

    private[this] var tokenizer: java.util.StringTokenizer = _

    def nextToken(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens())
        tokenizer = new java.util.StringTokenizer(in.readLine())
      tokenizer.nextToken()
    }
  }
}