def ternary(n):
    orders = []
    while n > 0:
        orders.append(n % 3)
        n //= 3
    return orders[::-1]

def decimal(a):
    p = 1
    s = 0
    for i in range(len(a) - 1, -1, -1):
        s += p * a[i]
        p *= 3

    return s

def maxpower(n):
    power = 0

    while n > 0:
        power += 1
        n //= 3

    return power

def isgood(n):
    while n > 0:
        if n % 3 > 1:
            return False
        n //= 3

    return True

q = int(input())

for _ in range(q):
    n = int(input())

    if n < 10**15:
        while not isgood(n):
            n += 1
        print(n)
    else:
        t = ternary(n)
        i = len(t) - 1
        while i > 0:
            if t[i] > 1:
                t[i] = 1
                t[i - 1] += 1
            i -= 1
            # print(t, decimal(t))

        if t[0] > 1:
            print(3 ** maxpower(n))
        else:
            print(decimal(t))


def ternary(n):
    orders = []
    while n > 0:
        orders.append(n % 3)
        n //= 3
    return orders[::-1]

def decimal(a):
    p = 1
    s = 0
    for i in range(len(a) - 1, -1, -1):
        s += p * a[i]
        p *= 3

    return s

def maxpower(n):
    power = 0

    while n > 0:
        power += 1
        n //= 3

    return power

def isgood(n):
    while n > 0:
        if n % 3 > 1:
            return False
        n //= 3

    return True

q = int(input())

for _ in range(q):
    n = int(input())

    if n < 10**14:
        while not isgood(n):
            n += 1
        print(n)
    else:
        t = ternary(n)
        i = len(t) - 1
        while i > 0:
            if t[i] > 1:
                t[i] = 1
                t[i - 1] += 1
            i -= 1
            print(t, decimal(t))

        if t[0] > 1:
            print(3 ** maxpower(n))
        else:
            print(decimal(t))


def ternary(n):
    orders = []
    while n > 0:
        orders.append(n % 3)
        n //= 3
    return orders[::-1]

def decimal(a):
    p = 1
    s = 0
    for i in range(len(a) - 1, -1, -1):
        s += p * a[i]
        p *= 3
    return s

def maxpower(n):
    power = 0

    while n > 0:
        power += 1
        n //= 3

    return power

def isgood(n):
    while n > 0:
        if n % 3 > 1:
            return False
        n //= 3

    return True

q = int(input())

for _ in range(q):
    n = int(input())

    if n < 10**14:
        while not isgood(n):
            n += 1
        print(n)
    else:
        t = ternary(n)
        i = len(t) - 1
        while i > 0:
            if t[i] > 1:
                t[i] = 0
                t[i - 1] += 1
            i -= 1
            # print(t, decimal(t))

        if t[0] > 1:
            print(3 ** maxpower(n))
        else:
            print(decimal(t))


def ternary(n):
    orders = []
    while n > 0:
        orders.append(n % 3)
        n //= 3
    return orders[::-1]

def decimal(a):
    p = 1
    s = 0
    for i in range(len(a) - 1, -1, -1):
        s += p * a[i]
        p *= 3
    return s

def maxpower(n):
    power = 0

    while n > 0:
        power += 1
        n //= 3

    return power

def isgood(n):
    while n > 0:
        if n % 3 > 1:
            return False
        n //= 3

    return True

q = int(input())

for _ in range(q):
    n = int(input())

    if n < 10**14:
        while not isgood(n):
            n += 1
        print(n)
    else:
        t = ternary(n)
        i = len(t) - 1
        while i > 0:
            if t[i] > 1:
                t[i] = 0
                t[i - 1] += 1
            i -= 1
            # print(t, decimal(t))

        if t[0] > 1:
            t[0] = 0
            t = [1] + t
        print(decimal(t))


def ternary(n):
    orders = []
    while n > 0:
        orders.append(n % 3)
        n //= 3

    return orders[::-1]

def decimal(a):
    p = 1
    s = 0
    for i in range(len(a) - 1, -1, -1):
        s += p * a[i]
        p *= 3

    return s

def maxpower(n):
    power = 0

    while n > 0:
        power += 1
        n //= 3

    return power

def isgood(n):
    while n > 0:
        if n % 3 > 1:
            return False
        n //= 3

    return True

q = int(input())

for _ in range(q):
    n = int(input())

    if n < 10**14:
        while not isgood(n):
            n += 1
        print(n)
    else:
        t = ternary(n)
        i = len(t) - 1
        while i > 0:
            if t[i] == 2:
                t[i] = 1
                t[i - 1] = t[i - 1] + 1
            i -= 1

        # print(t)

        if t[0] == 2:
            print(3 ** maxpower(n))
        else:
            print(decimal(t))


def fun(n):
    while n>0:
        if n%3 == 2:
            return 0;
        n = n//3
    return 1

for _ in range(int(input())):
    n = int(input())
    while fun(n)!=1:
        n += 1
    print(n)


l = [ 0 for i in range(41)]
c = 1
for i in range(1, 41):
    l[i] = l[i-1] + c
    c *= 3
for _ in range(int(input())):
    n = int(input())
    temp = 0
    for i in range(40,-1,-1):
        if l[i] < n:
            n -= l[i+1] - l[i]
            temp += l[i+1] - l[i]
    print(temp)


from sys import *
from math import *
t=int(stdin.readline())
for _ in range(t):
    n=int(stdin.readline())
    ans=1
    i=1
    x=1
    a=[1]
    while ans<n:
        x=x*3
        ans+=x
        a.append(ans)
    ans1=[]
    for i in range(len(a)):
        if ans-a[i]>=n:
            ans1.append(ans-a[i])
    if len(ans1)!=0:
        ans=min(ans1)
    x=1
    while x<n:
        x=x*3
    ans=min(ans,x)
    print(ans)


from sys import *
from math import *
t=int(stdin.readline())
for _ in range(t):
    n=int(stdin.readline())
    ans=1
    i=1
    x=1
    while ans<n:
        x=x*3
        ans+=x
    x=1
    while x<n:
        x=x*3
    ans=min(ans,x)
    print(ans)


from sys import *
from math import *
t=int(stdin.readline())
for _ in range(t):
    n=int(stdin.readline())
    a=[]
    for i in range(50):
        a.append(3**i)
    a=a[::-1]
    s=sum(a)
    for i in a:
        if s-i>=n:
            s-=i
    print(s)


from sys import *
from math import *
t=int(stdin.readline())
for _ in range(t):
    n=int(stdin.readline())
    ans=1
    i=1
    x=1
    a=[1]
    while ans<n:
        x=x*3
        ans+=x
        a.append(ans)
    ans1=[]
    for i in range(len(a)):
        if ans-a[i]>=n:
            ans1.append(ans-a[i])
    if len(ans1)!=0:
        a1=min(ans1)
    else:
        a1=ans
    x=1
    a=[1]
    while x<n:
        x=x*3
        a.append(x)
    ans1 = []
    for i in range(len(a)):
        if ans - a[i] >= n:
            ans1.append(ans - a[i])
    if len(ans1) != 0:
        a2 = min(x,min(ans1))
    else:
        a2=x
    ans=min(a1,a2)
    print(ans)


def maxM1(n):
	for x in range(0, n):
		if 3 ** x == n:
			return int(x)
		elif 3 ** x > n:
			return x - 1

def maxM(n):
	for x in range(0, n):
		if 3 ** x == n:
			return int(x)
		elif x == 0 and 3 ** x >= n:
			return 0
		elif 3 ** x > n:
			return int(x - 1)

for _ in range(int(input())):
	num = int(input())
	mxM = maxM(num)
	ans = 3 ** mxM
	li = []
	for i in range(mxM - 1, -1, -1):
		if ans >= num:
			break
		if ans + 3 ** i <= num:
			ans += 3 ** i
		else:
			x = ans
			x += 3 ** i
			li += [x]
	if ans == num:
		print(ans)
	else:
		if not li:
			print(3 ** (mxM + 1))
		else:
			print(min(min(li), 3 ** (mxM + 1)))


li = [3 ** i for i in range(40)]
s = sum(li)
t = int(input())
for _ in range(t):
	n = int(input())
	ans = s
	for i in li[::-1]:
		if ans - i >= n:
			ans -= i
	print(ans)


fun to3(n: Long): MutableList<Int> {
  val ans = ArrayList<Int>()
  var m = n
  while(m != 0L) {
    ans.add((m % 3).toInt())
    m /= 3
  }
  return ans
}

fun main() {
  repeat(readLine()!!.toInt()) {
    val n = readLine()!!.toLong()
    val to3 = to3(n)
    var bigger = 0
    var i = 0
    for (j in to3.size - 1 downTo 0) {
      if (to3[j] == 2) {
        i = j
        for (k in i - 1 downTo 0) {
          to3[k] = 0
        }
      }
    }
    while (i < to3.size) {
      to3[i] += bigger
      bigger = to3[i] / 3
      to3[i] %= 3
      if (to3[i] == 2) {
        to3[i] = 0
        bigger = 1
      }
      i++
    }
    var ans = 0L
    var pow = 1L
    for (j in to3) {
      check(j != 2) { "Blay!" }
      ans += pow * j
      pow *= 3
    }
    ans += bigger * pow
    println(ans)
  }
}


fun main() {
    var t = readLine()!!.toInt()
    while (t > 0) {
        t--;
        var n = readLine()!!.toLong()
        var a = MutableList<Long>(0) {0}
        while (n > 0) {
            a.add(n % 3)
            n /= 3
        }
        a.add(0)
        var pos = -1
        for (i in a.size - 1 downTo 0) {
            if (a[i] == 2.toLong()) {
                pos = i
                break
            }
        }
        if (pos != -1) {
            for (i in pos until a.size) {
                if (a[i] == 0.toLong()) {
                    pos = i
                    break
                }
            }
            a[pos] = 1;
            for (i in pos - 1 downTo 0) {
                a[i] = 0
            }
        }
        var res = 0.toLong()
        var cur = 1.toLong()
        for (i in 0 until a.size) {
            res += a[i] * cur
            cur *= 3
        }
        println(res)
    }
}


import java.math.BigInteger
import kotlin.math.pow

/** CODED WITH LOVE BY SATYAM KUMAR*/
// kotlin tips becoz I'm still learning

/** useful links
 * https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-array/index.html
 * https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-array-list/index.html
 * https://kotlinlang.org/docs/reference/ranges.html
 */

/** valid ways to sort
 * 1
 * val a = nextLongs().sorted() // a is mutable list
 * 2
 * val a = arrayListOf<Long>()
 * a.addAll(nextLongs())
 * a.sort()
 */

/** declare 2D array
 * val ori = Array(n, {IntArray(n)})
 * val ori = arrayOf(
intArrayOf(8, 9, 1, 13),
intArrayOf(3, 12, 7, 5),
intArrayOf(0, 2, 4, 11),
intArrayOf(6, 10, 15, 14)
)
 */

/** printing variables:
 * println("${l+1} and $r")
 * evidently print has high constant factor
 * print stringbuilder instead?
 */

// ArrayList to Array: toArray

// IntArray with size:
// val arr = IntArray(1 shl 20, { 1 })

// lower bound: use binary search
// https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/binary-search.html

// if/switch
// https://kotlinlang.org/docs/reference/control-flow.html

// swap:
// https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/also.html
// a = b.also { b = a }

/** comparing pairs
 * val ed = ArrayList<Pair<Int,Pair<Int,Int>>>()
ed.sortBy {it.first}
 *  class CustomComparator : Comparator<Pair<Int,Pair<Int,Int>>> {
override fun compare(o1: Pair<Int,Pair<Int,Int>>, o2: Pair<Int,Pair<Int,Int>>): Int {
return o1.first.compareTo(o2.first)
}
}
val v = ed.sortedWith(CustomComparator())
 */

// (tree/hash)(map/set)
// ??
fun pow(n: Long, exp: Int): Long{
    return BigInteger.valueOf(n).pow(exp).toLong()
}

fun main(){
    val t = readLine()!!.toLong()
    for (j in 1..t){
        var n = readLine()!!.toLong()
        var power = 0
        while (pow(3, power)<n) power++
        //print(power)
        var res: Long = 0
        for (exp in power.downTo(0)){
            //println("$exp d ${n-res}")
            if (pow(3, exp) - (n-res) <= pow(3, exp)/2)
                res += pow(3, exp)
        }
        println(res)
    }
}


fun main() {
    C1_1249()
}

fun C1_1249() {
    var q = readLine()!!.toInt()
    while (q != 0) {
        val num = readLine()!!.toLong()
        println(nextGood(num))
        q--
    }
}

fun nextGood(num: Long): Long {
    var x = num
    val digits = mutableListOf<Int>()
    var ans: Long = 0
    var pos2 = -1
    while (x != 0L) {
        digits.add((x % 3).toInt())
        if ((x % 3).toInt() == 2) pos2 = digits.size - 1
        x /= 3
    }
    digits.add(0)

    if (pos2 != -1) {
        var pos0 = -1
        for (i in pos2 until digits.size)
            if (digits[i] == 0) {
                pos0 = i
                break
            }
        digits[pos0] = 1
        for (i in pos0 - 1 downTo 0)
            digits[i] = 0
    }

    var pow = 1L
    digits.forEach {
        ans += it * pow
        pow *= 3L
    }
    return ans
}


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

import java.io.PrintWriter
import java.math.BigInteger
import java.util.StringTokenizer
import kotlin.random.*
import kotlin.collections.sort as _sort
import kotlin.collections.sortDescending as _sortDescending
import kotlin.io.println as iprintln // immediate println for interactive

fun main() {
    output {
        val q = readInt()

        repeat(q) {
            val n = readLong()

            val s = ("0" + n.toString(3)).toCharArray()

            val first2 = s.indexOf('2')
            if(first2 >= 0) {
                val l = (first2 - 1 downTo 0).first { s[it] == '0' }
                s[l] = '1'
                for(j in l+1 until s.size) {
                    s[j] = '0'
                }
            }

            val m = String(s).toLong(3)

            println(m)
        }
    }
}

/** IO code start */
@JvmField val _reader = System.`in`.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 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(System.out, false)
inline fun output(block: PrintWriter.()->Unit) { _writer.apply(block).flush() }

/** shuffles and sort overrides to avoid quicksort attacks */
private inline fun <R, V> R._shuffle(rnd: Random, get: R.(Int) -> V, set: R.(Int, V) -> 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(System.nanoTime()).also { _random = it }

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

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

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

fun CharArray.shuffle(rnd: Random = random) = _shuffle(rnd, CharArray::get, CharArray::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()


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

import java.io.PrintWriter
import java.math.BigInteger
import java.util.StringTokenizer
import kotlin.random.*
import kotlin.collections.sort as _sort
import kotlin.collections.sortDescending as _sortDescending
import kotlin.io.println as iprintln // immediate println for interactive

fun main() {
    output {
        val q = readInt()

        repeat(q) {
            val n = readLong()

            val s = ("0" + n.toString(3)).toCharArray()

            var r = s.size
            for(l in s.lastIndex downTo 1) {
                when(s[l]) {
                    '2' -> {
                        s[l-1]++
                        for(i in l until r) {
                            s[i] = '0'
                        }
                        r = l
                    }
                    '3' -> {
                        s[l-1]++
                        s[l] = '0'
                    }
                }
            }

            val m = String(s).toLong(3)

            println(m)
        }
    }
}

/** IO code start */
@JvmField val _reader = System.`in`.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 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(System.out, false)
inline fun output(block: PrintWriter.()->Unit) { _writer.apply(block).flush() }

/** shuffles and sort overrides to avoid quicksort attacks */
private inline fun <R, V> R._shuffle(rnd: Random, get: R.(Int) -> V, set: R.(Int, V) -> 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(System.nanoTime()).also { _random = it }

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

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

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

fun CharArray.shuffle(rnd: Random = random) = _shuffle(rnd, CharArray::get, CharArray::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()


//package CodeforcesRound595Div3.C2

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

fun pow(a : Long, b : Int): Long{
    var res = 1L
    for(i in 1..b){
        res *= a
    }
    return res
}
fun getKL(list: MutableList<Int>): Pair<Int, Int>{
    val k =  list.indexOfLast { t -> t == 2 }
    var l = -1
    for(i in k until list.size){
        if(list[i] == 0) {
            l = i
            break
        }
    }
    return Pair(k, l)
}
fun main() {
    val q = readInt()
    for (i in 1..q) {
        var n = readLong()
        var p = n
        val number = mutableListOf<Int>()
        while(p > 0L){
            val k : Int = (p % 3).toInt()
            p /= 3
            number.add(k)
        }
        val kl : Pair<Int, Int> = getKL(number)
        var k = kl.first
        var l = kl.second
        if(k == -1) {
            println(n)
        }
        else{
            if(k + 1 != number.size) {
                if(l < k || l == -1){
                    val res = pow(3L, number.size)
                    println(res)
                }
                else{
                    var res: Long = 0L
                    for (j in 0..(number.size - 1 - l - 1)) {
                        res += pow(3L, number.size - 1 - j)* number[number.size - 1 - j]
                    }
                    res += pow(3L, l )
                    println(res)
                }
            }
            else{
                val res = pow(3L, number.size)
                println(res)
            }
        }
    }
}


//package CodeforcesRound595Div3.C2

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

fun pow(a : Long, b : Int): Long{
    var res = 1L
    for(i in 1..b){
        res *= a
    }
    return res
}

fun main() {
    val q = readInt()
    for (i in 1..q) {
        var n = readLong()
        var p = n
        val number = mutableListOf<Int>()
        while(p > 0L){
            val k : Int = (p % 3).toInt()
            p /= 3
            number.add(k)
        }
        var k = number.indexOfLast { t -> t == 2 }
        var l = number.indexOfLast { t -> t == 0 }
        if(k == -1) {
            println(n)
        }
        else{
            if(k + 1 != number.size) {
                if(l < k || l == -1){
                    val res = pow(3L, number.size)
                    println(res)
                }
                else{
                    var res: Long = 0L
                    for (j in (0..(number.size - l - 2))) {
                        res += pow(3L, number.size - 1 - j)* number[number.size - 1 - j]
                    }
                    res += pow(3L, l)
                    println(res)
                }
            }
            else{
                val res = pow(3L, number.size)
                println(res)
            }
        }
    }
}


//package CodeforcesRound595Div3.C2

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

fun pow(a : Long, b : Int): Long{
    var res = 1L
    for(i in 1..b){
        res *= a
    }
    return res
}

fun main() {
    val q = readInt()
    for (i in 1..q) {
        var n = readLong()
        var p = n
        val number = mutableListOf<Int>()
        while(p > 0L){
            val k : Int = (p % 3).toInt()
            p /= 3
            number.add(k)
        }
        var k = number.indexOfLast { t -> t == 2 }
        var l = number.indexOfLast { t -> t == 0 }
        if(k == -1) {
            println(n)
        }
        else{
            if(k + 1 != number.size) {
                if(l < k || l == -1){
                    val res = pow(3L, number.size)
                    println(res)
                }
                else{
                    var res: Long = 0L
                    for (j in (0..(l-2))) {
                        res += pow(3L, number.size - 1 - j)* number[number.size - 1 - j]
                    }
                    res += pow(3L, number.size - 1 - (l - 1))
                    println(res)
                }
            }
            else{
                val res = pow(3L, number.size)
                println(res)
            }
        }
    }
}


//package CodeforcesRound595Div3.C1

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

fun main() {
    val q = readInt()
    for (i in 1..q) {
        var n = readInt()
        var p = n
        while(p != 1){
            val k = p % 3
            if(k == 2){
                n++
                p = n
            }
            else p /= 3
        }
        println(n)
    }
}


//package CodeforcesRound595Div3.C2

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

fun pow(a : Long, b : Int): Long{
    var res = 1L
    for(i in 1..b){
        res *= a
    }
    return res
}
fun getKL(list: MutableList<Int>): Pair<Int, Int>{
    val k =  list.indexOfLast { t -> t == 2 }
    var l = -1
    if(k == -1)
        return Pair(k, l)
    for(i in k until list.size){
        if(list[i] == 0) {
            l = i
            break
        }
    }
    return Pair(k, l)
}
fun main() {
    val q = readInt()
    for (i in 1..q) {
        var n = readLong()
        var p = n
        val number = mutableListOf<Int>()
        while(p > 0L){
            val k : Int = (p % 3).toInt()
            p /= 3
            number.add(k)
        }
        val kl : Pair<Int, Int> = getKL(number)
        var k = kl.first
        var l = kl.second
        if(k == -1) {
            println(n)
        }
        else{
            if(k + 1 != number.size) {
                if(l < k || l == -1){
                    val res = pow(3L, number.size)
                    println(res)
                }
                else{
                    var res: Long = 0L
                    for (j in 0..(number.size - 1 - l - 1)) {
                        res += pow(3L, number.size - 1 - j)* number[number.size - 1 - j]
                    }
                    res += pow(3L, l )
                    println(res)
                }
            }
            else{
                val res = pow(3L, number.size)
                println(res)
            }
        }
    }
}


//package CodeforcesRound595Div3.C2

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

fun pow(a : Long, b : Int): Long{
    var res = 1L
    for(i in 1..b){
        res *= a
    }
    return res
}

fun main() {
    val q = readInt()
    for (i in 1..q) {
        var n = readLong()
        var p = n
        val number = mutableListOf<Int>()
        while(p > 0L){
            val k : Int = (p % 3).toInt()
            p /= 3
            number.add(k)
        }
        var k = number.indexOfLast { t -> t == 2 }
        var l = number.indexOfLast { t -> t == 0 }
        if(k == -1) {
            println(n)
        }
        else{
            if(k + 1 != number.size) {
                if(l < k || l == -1){
                    val res = pow(3L, number.size)
                    println(res)
                }
                else{
                    var res: Long = 0L
                    for (j in (0..l)) {
                        res += pow(3L, number[number.size - 1 - k])
                    }
                    println(res)
                }
            }
            else{
                val res = pow(3L, number.size)
                println(res)
            }
        }
    }
}


fun main() {
    fun readInt() = readLine()!!.toInt()
    fun readLong() = readLine()!!.toLong()
    fun readInts() = readLine()!!.split(" ").map(String::toInt)
    fun readLongs() = readLine()!!.split(" ").map(String::toLong)

    fun Long.toBaseThree(): Long {
        val binary = this.toString(radix = 2)
        var result = 0L
        for(bit in binary) result = result*3 + if(bit == '1') 1 else 0
        return result
    }

    val numQueries = readInt()
    val sols = LongArray(numQueries)
    for (query in 0 until numQueries) {
        val n = readLong()
        var left = 0L
        var right = 1099511627775L
        var middle: Long
        while(left < right) {
            middle = left + (right - left) / 2L
            val middleThree = middle.toBaseThree()
            if(middleThree == n) {
                left = middle
                break
            } else if (middleThree < n) {
                left = middle + 1
            } else {
                right = middle - 1
            }
        }
        if (left.toBaseThree() >= n) sols[query] = left.toBaseThree() else sols[query] = (left + 1L).toBaseThree()
    }
    print(sols.joinToString(System.lineSeparator()))
}


fun main() {
    fun readInt() = readLine()!!.toInt()
    fun readLong() = readLine()!!.toLong()
    fun readInts() = readLine()!!.split(" ").map(String::toInt)
    fun readLongs() = readLine()!!.split(" ").map(String::toLong)

    fun Long.toBaseThree(): Long {
        val binary = this.toString(radix = 2)
        var result = 0L
        for(bit in binary) result = result*3 + if(bit == '1') 1 else 0
        return result
    }

    val numQueries = readInt()
    val sols = LongArray(numQueries)
    for (query in 0 until numQueries) {
        val n = readLong()
        var left = 0L
        var right = 999999999999L
        var middle: Long
        while(left < right) {
            middle = left + (right - left) / 2L
            val middleThree = middle.toBaseThree()
            if(middleThree == n) {
                left = middle
                break
            } else if (middleThree < n) {
                left = middle + 1
            } else {
                right = middle - 1
            }
        }
        if (left.toBaseThree() >= n) sols[query] = left.toBaseThree() else sols[query] = (left + 1L).toBaseThree()
    }
    print(sols.joinToString(System.lineSeparator()))
}


import java.io.*

private fun rl() = readLine()!!
private fun ri() = rl().toInt()
private fun readStrings() = rl().split(" ")
private fun ris() = readStrings().map { it.toInt() }

fun main() {
  val _re = Regex("\\s+")
  val r = BufferedReader(InputStreamReader(System.`in`))
    .lineSequence()
    .flatMap { it.split(_re).asSequence().filterNot { it.isEmpty () } }
    .iterator()
  val o = PrintWriter(System.out)
  fun ri() = r.next().toInt()
  fun rl() = r.next().toLong()
  val p = LongArray(64)
  p[0] = 1
  for (i in 1 until p.size) {
    p[i] = 3 * p[i-1]
  }
  repeat(ri()) {
    val a = IntArray(64)
    val q = rl()
    var x = q
    var k = 0
    while (x > 0) {
      a[k] = (x % 3).toInt()
      x /= 3
      k += 1
    }
    //System.err.println(q)
    //System.err.println(a.joinToString())
    var found = false
    for (i in (k - 1) downTo 0) {
      if (a[i] == 2) {
        var j = i+1
        while (a[j] == 1) {
          j += 1
        }
        val t = q % (p[j])
        o.println ((q - t) + p[j])
        found = true
        break
      }
    }
    if (!found) {
      o.println(q)
    }

  }
  o.close()
}


private fun computed(){
    val n = readLine()!!.toLong()
    var m: Long = n

    //переводим число в троичную сиситему счсиления
    val arr = arrayListOf<Long>()
    while (m>0){
        arr.add(0, m%3)
        m /= 3
    }
    //ищем следующее число такое что оно только из 0 и 1 и не меньше заданного
    //находим наибольшую двойку
    val pos = findTwo(arr)
    if (pos==-1){
        //число уже хорошее
        println(n)
        return
    }
    //идем в обратную сторону
    arr.add(0,0)
    for (i in pos downTo 0){
        if (arr[i]==0L){
            arr[i]=1
            //а все что вниз зануляем
            for (j in i+1 until arr.size){
                arr[j]=0
            }
            break
        }
    }
    //переводим чсило обратно в десятичную систему
    var k = 3.0.pow(arr.size-1).toLong()
    var res = 0L
    for (i in 0 until arr.size){
        res+=(k*arr[i])
        k/=3
    }
    println(res)
}

private fun findTwo(arr: ArrayList<Long>): Int{
    for ((pos, i) in arr.withIndex()){
        if (i==2L){
            return pos
        }
    }
    return -1
}

fun main(){
    val q = readLine()!!.toInt()
    for (i in 0 until q){
        computed()
    }
}


private fun computed(){
    val n = readLine()!!.toLong()
    var m: Long = n

    //переводим число в троичную сиситему счсиления
    val arr = arrayListOf<Long>()
    while (m>0){
        arr.add(0, m%3)
        m /= 3
    }
    //ищем следующее число такое что оно только из 0 и 1 и не меньше заданного
    //находим наибольшую двойку
    val pos = findTwo(arr)
    if (pos==-1){
        //число уже хорошее
        println(n)
        return
    }
    //идем в обратную сторону
    arr.add(0,0)
    for (i in pos downTo 0){
        if (arr[i]==0L){
            arr[i]=1
            //а все что вниз зануляем
            for (j in i+1 until arr.size){
                arr[j]=0
            }
            break
        }
    }
    //переводим чсило обратно в десятичную систему
    var k = 1L
    for (i in 1 until arr.size){
        k*=3L
    }
//    var k = 3.0.pow(arr.size-1).toLong()
    var res = 0L
    for (i in 0 until arr.size){
        res+=(k*arr[i])
        k/=3
    }
    println(res)
}

private fun findTwo(arr: ArrayList<Long>): Int{
    for ((pos, i) in arr.withIndex()){
        if (i==2L){
            return pos
        }
    }
    return -1
}

fun main(){
    val q = readLine()!!.toInt()
    for (i in 0 until q){
        computed()
    }
}


import kotlin.math.pow

private fun computed(){
    val n = readLine()!!.toLong()
    var m: Long = n

    //переводим число в троичную сиситему счсиления
    val arr = arrayListOf<Long>()
    while (m>0){
        arr.add(0, m%3)
        m /= 3
    }
    //ищем следующее число такое что оно только из 0 и 1 и не меньше заданного
    //находим наибольшую двойку
    val pos = findTwo(arr)
    if (pos==-1){
        //число уже хорошее
        println(n)
        return
    }
    //идем в обратную сторону
    arr.add(0,0)
    for (i in pos downTo 0){
        if (arr[i]==0L){
            arr[i]=1
            //а все что вниз зануляем
            for (j in i+1 until arr.size){
                arr[j]=0
            }
            break
        }
    }
    //переводим чсило обратно в десятичную систему
    var k = 3.0.pow(arr.size-1).toLong()
    var res = 0L
    for (i in 0 until arr.size){
        res+=(k*arr[i])
        k/=3
    }
    println(res)
}

private fun findTwo(arr: ArrayList<Long>): Int{
    for ((pos, i) in arr.withIndex()){
        if (i==2L){
            return pos
        }
    }
    return -1
}

fun main(){
    val q = readLine()!!.toInt()
    for (i in 0 until q){
        computed()
    }
}


import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.PrintStream
import kotlin.math.*

val Number.i: Int get() = this.toInt()
val Number.l: Long get() = this.toLong()
val Number.f: Float get() = this.toFloat()
val Number.d: Double get() = this.toDouble()
val String.i: Int get() = this.toInt()
val String.l: Long get() = this.toLong()
val String.f: Float get() = this.toFloat()
val String.d: Double get() = this.toDouble()

fun main() = BufferedReader(InputStreamReader(System.`in`)).use { solve(it, System.out) }

fun solve(input: BufferedReader, output: PrintStream) {
    val q = input.readLine().i
    for (i in 0 until q) {
        val n = input.readLine().l

        val pows = ArrayList<Int>()
        var nn = n
        var lastPow = -1
        while (nn > 0) {
            val pow = log(nn.d, 3.0).i
            pows.add(pow)
            nn -= 3.toBigInteger().pow(pow).l
            if (pow == lastPow) break
            lastPow = pow
        }

        if (pows.size >= 2 && pows.last() == pows[pows.size - 2]) {
            val bigger = (pows.last()..Int.MAX_VALUE).first { !pows.contains(it) }
            pows.removeAll { it < bigger }
            pows.add(bigger)
        }

        var res = 0L
        for (pow in pows)
            res += 3.toBigInteger().pow(pow).l

        output.println(res)
    }
}


fun main(args: Array<String> ) {
    val t = readLine()!!.toInt()
    (1..t).forEach {
        var n = readLine()!!.toInt()
        var y = arrayListOf<Int>()
        while ( n > 0 ) {
            y.add( n % 3 )
            n = n / 3
        }
        var tr = 0
        var last = 0
        y.withIndex().forEach {
            var temp = it.value + tr
            if ( temp == 2 ) {
                temp ++
                last = it.index
            }
            y[ it.index ] = temp % 3
            tr = temp / 3
        }
        (0..last-1).forEach { y[ it ] = 0 }
        if ( tr > 0 ) y.add( tr )
        var res = 0
        y.reversed().forEach { res = res * 3 + it }
        println( res )
    }
}


fun main(args: Array<String> ) {
    val t = readLine()!!.toInt()
    (1..t).forEach {
        var n = readLine()!!.toLong()
        var y = arrayListOf<Long>()
        while ( n > 0L ) {
            y.add( n % 3L )
            n = n / 3L
        }
        var tr = 0L
        var last = 0
        y.withIndex().forEach {
            var temp = it.value + tr
            if ( temp == 2L ) {
                temp ++
                last = it.index
            }
            y[ it.index ] = temp % 3L
            tr = temp / 3L
        }
        (0..last-1).forEach { y[ it ] = 0L }
        if ( tr > 0L ) y.add( tr )
        var res = 0L
        y.reversed().forEach { res = res * 3L + it }
        println( res )
    }
}


fun main() {
    repeat(readLine()!!.toInt()) {

        val n = readLine()!!.toLong()
        val bits = n.toString(3).map { it.toInt() - '0'.toInt() }.reversed().toMutableList()

        var cutoff = -1
        for (i in bits.indices) {
            if (bits[i] >= 2) {
                cutoff = i
                if (bits.size == i + 1) {
                    bits.add(1)
                } else {
                    bits[i + 1]++
                }
            }
        }
        for (i in bits.indices) {
            if (i <= cutoff) bits[i] = 0
        }

        val r = bits.reversed().joinToString("").toLong(3)

        println(r)
    }
}


fun main() {
    repeat(readLine()!!.toInt()) {

        val n = readLine()!!.toLong()
        val bits = n.toString(3).map { it.toInt() }.reversed().toMutableList()

        var cutoff = 0
        for (i in bits.indices) {
            if (bits[i] > 2) {
                cutoff = i
                if (bits.size == i + 1) {
                    bits.add(1)
                } else {
                    bits[i + 1]++
                }
            }
        }
        for (i in bits.indices) {
            if (i <= cutoff) bits[i] = 0
        }

        val r = bits.reversed().joinToString("").toLong(3)

        println(r)
    }
}


fun main() {
    repeat(readLine()!!.toInt()) {

        val n = readLine()!!.toLong()
        val bits = n.toString(3).map { it.toInt() - '0'.toInt() }.reversed().toMutableList()

        var cutoff = 0
        for (i in bits.indices) {
            if (bits[i] > 2) {
                cutoff = i
                if (bits.size == i + 1) {
                    bits.add(1)
                } else {
                    bits[i + 1]++
                }
            }
        }
        for (i in bits.indices) {
            if (i <= cutoff) bits[i] = 0
        }

        val r = bits.reversed().joinToString("").toLong(3)

        println(r)
    }
}


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

public class C
{

	public static void main(String[] args)throws IOException
	{
		BufferedReader ob=new BufferedReader(new InputStreamReader(System.in));
		StringBuffer sb=new StringBuffer();
		int test=Integer.parseInt(ob.readLine());
		while(test-->0)
		{
			long n=Long.parseLong(ob.readLine());
			long pow=highestPowerof3(n);
            long sum=1;
            long prod=1;

            while(sum<n)
            {
                prod*=3;
                sum+=prod;
            }
            while(prod>=1)
            {
                if(sum-prod>=n)
                    sum-=prod;
//                else
//                	break;
                prod/=3;
            }
            sb.append(sum+"\n");
		}
		System.out.println(sb);
	}
	static long highestPowerof3(long n)
	{
    	long p = (int)(Math.log(n)/Math.log(3));
	    return p;
	}
	static long fastPow(long n, long m) {
		long res = 1L;

		while (m > 0) {
			if ((m & 1) != 0) {
				res *= n;
				m--;
			} else {
				n *= n;
				m /= 2;
			}
		}
		return res;
	}
}


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

public class Good_No {

	public static void main(String[] args)throws IOException {

		BufferedReader ob=new BufferedReader(new InputStreamReader(System.in));
		StringBuffer sb=new StringBuffer();
		int test=Integer.parseInt(ob.readLine());
		while(test-->0)
		{
			long n=Long.parseLong(ob.readLine());
			int pow=highestPowerof3(n);
			long num=(long)Math.pow(3,pow);
			if(num==n)
			{
				sb.append(num+"\n");
				continue;
			}
			long max=675425858836496068L;
			if(n>max)
			{
				sb.append("1350851717672992089\n");
				continue;
			}
			long cpy=num;
			long min=Integer.MAX_VALUE;
//			System.out.println("pow = "+pow);
//			System.out.println("num = "+num);
			for(int i=pow-1;i>=0;i--)
			{
				long temp=(long)Math.pow(3, i);
//				System.out.println(" i = "+i);

				cpy+=temp;
//				System.out.println("cpy = "+cpy);
				if(cpy>=n)
				{
					if(cpy<min)
						min=cpy;
					cpy-=temp;
				}
			}
			long next=(long)Math.pow(3,pow+1);
//			System.out.println("nex = "+next);
			if(min==Integer.MAX_VALUE)
				sb.append(next+"\n");
			else
				sb.append(min+"\n");
		}
		System.out.println(sb);
	}
	static int highestPowerof3(long n)
	{
    	int p = (int)(Math.log(n)/Math.log(3));
	    return p;
	}

}


import java.util.*;

import javax.imageio.ImageIO;
import javax.xml.bind.DatatypeConverter;

import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigInteger;
public class template {
	public static void main(String[] args) throws Exception {
		FastScanner sc = new FastScanner();
		PrintWriter pw = new PrintWriter(System.out);
		int n  = sc.nextInt();
		long[] x = new long[39];
		for(int i=0;i<39;i++){
			x[i]=get3p(i);
		}
		for(int i =0 ;i<n;i++){
			long f = sc.nextLong();
			long r = f;
			StringBuilder t = new StringBuilder();
			for(int j=38;j>=0;j--){
				int app = 0;
				while(f>=x[j]){
					f-=x[j];
					app++;
				}
				t.append(app);
			}
			String str = t.toString();
			if(str.replaceAll("[01]", "").equals("")){
				pw.println(r);
			}
			else{
				int s=0;
				int ind = 0;
				for(int j =0;j<str.length();j++){
					if(str.charAt(j)>'0'&&s==0){
						s=j;
					}
					if(str.charAt(j)=='0'){
						ind = j;
					}
					if(str.charAt(j)=='2'){
						break;
					}
				}
				if(ind ==0){
					if(s==0){
						pw.println(0);
					}
					else{
						pw.println(get3p(39-s));
					}
				}
				else {
					long o = get3p(39-ind-1);
					for(int j = 0;j<ind;j++){
						if(str.charAt(j)>'0'){
							o+=get3p(39-j-1);
						}
					}
					pw.println(o);
				}
			}

		}
		pw.close();
	}
	static long get3p(int x){
		long i = 1;
		for(int j = 0;j<x;j++){
			i*=3;
		}
		return i;
	}
}
@SuppressWarnings("all")
class FastScanner {
    BufferedReader br;
    StringTokenizer st;

    public FastScanner(String s) {
        try {
            br = new BufferedReader(new FileReader(s));
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public FastScanner() {
        br = new BufferedReader(new InputStreamReader(System.in));
    }

    String nextToken() {
        while (st == null || !st.hasMoreElements()) {
            try {
                st = new StringTokenizer(br.readLine());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return st.nextToken();
    }

    int nextInt() {
        return Integer.parseInt(nextToken());
    }

    long nextLong() {
        return Long.parseLong(nextToken());
    }

    double nextDouble() {
        return Double.parseDouble(nextToken());
    }
}


import java.util.*;

import javax.imageio.ImageIO;
import javax.xml.bind.DatatypeConverter;

import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigInteger;
public class template {
	public static void main(String[] args) throws Exception {
		FastScanner sc = new FastScanner();
		PrintWriter pw = new PrintWriter(System.out);
		int n  = sc.nextInt();
		long[] x = new long[39];
		for(int i=0;i<39;i++){
			x[i]=get3p(i);
		}
		for(int i =0 ;i<n;i++){
			long f = sc.nextLong();
			long r = f;
			StringBuilder t = new StringBuilder();
			for(int j=38;j>=0;j--){
				int app = 0;
				while(f>=x[j]){
					f-=x[j];
					app++;
				}
				t.append(app);
			}
			String str = t.toString();
			if(str.replaceAll("[01]", "").equals("")){
				pw.println(r);
			}
			else{
				int s=0;
				int ind = 0;
				for(int j =0;j<str.length();j++){
					if(str.charAt(j)>'0'&&s==0){
						s=j;
					}
					if(str.charAt(j)=='0'){
						ind = j;
					}
					if(str.charAt(j)=='2'){
						break;
					}
				}
				if(ind ==0){
					if(s==0){
						pw.println(0);
					}
					else{
						pw.println(get3p(39-s));
					}
				}
				else {
					long o = get3p(39-s);
					for(int j = 0;j<ind;j++){
						if(str.charAt(j)>'0'){
							o+=get3p(39-j);
						}
					}
					pw.println(o);
				}
			}

		}
		pw.close();
	}
	static long get3p(int x){
		long i = 1;
		for(int j = 0;j<x;j++){
			i*=3;
		}
		return i;
	}
}
@SuppressWarnings("all")
class FastScanner {
    BufferedReader br;
    StringTokenizer st;

    public FastScanner(String s) {
        try {
            br = new BufferedReader(new FileReader(s));
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public FastScanner() {
        br = new BufferedReader(new InputStreamReader(System.in));
    }

    String nextToken() {
        while (st == null || !st.hasMoreElements()) {
            try {
                st = new StringTokenizer(br.readLine());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return st.nextToken();
    }

    int nextInt() {
        return Integer.parseInt(nextToken());
    }

    long nextLong() {
        return Long.parseLong(nextToken());
    }

    double nextDouble() {
        return Double.parseDouble(nextToken());
    }
}


import java.util.Scanner;
import java.util.stream.IntStream;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);

		int q = sc.nextInt();
		for (int tc = 0; tc < q; tc++) {
			long n = sc.nextLong();

			System.out.println(solve(n));
		}

		sc.close();
	}

	static long solve(long n) {
		String s = "";
		while (n != 0) {
			s = n % 3 + s;
			n /= 3;
		}

		int twoIndex = s.indexOf('2');
		if (twoIndex >= 0) {
			int zeroIndex = s.substring(0, twoIndex).indexOf('0');
			if (zeroIndex >= 0) {
				s = String.format("%s1%s", s.substring(0, zeroIndex), repeat('0', s.length() - zeroIndex - 1));
			} else {
				s = String.format("1%s", repeat('0', s.length()));
			}
		}

		return Long.parseLong(s, 3);
	}

	static String repeat(char ch, int count) {
		return IntStream.range(0, count).mapToObj(i -> ch)
				.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append).toString();
	}
}


import java.util.Scanner;
import java.util.stream.IntStream;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);

		int q = sc.nextInt();
		for (int tc = 0; tc < q; tc++) {
			long n = sc.nextLong();

			System.out.println(solve(n));
		}

		sc.close();
	}

	static long solve(long n) {
		String s = "";
		while (n != 0) {
			s = n % 3 + s;
			n /= 3;
		}

		int twoIndex = s.indexOf('2');
		if (twoIndex >= 0) {
			int zeroIndex = s.substring(0, twoIndex).lastIndexOf('0');
			if (zeroIndex >= 0) {
				s = String.format("%s1%s", s.substring(0, zeroIndex), repeat('0', s.length() - zeroIndex - 1));
			} else {
				s = String.format("1%s", repeat('0', s.length()));
			}
		}

		return Long.parseLong(s, 3);
	}

	static String repeat(char ch, int count) {
		return IntStream.range(0, count).mapToObj(i -> ch)
				.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append).toString();
	}
}


import java.io.*;
import java.math.BigInteger;
import java.util.InputMismatchException;
import java.util.StringTokenizer;

public class C3 {
    static class FastWriter {
        private final BufferedWriter bw;

        public FastWriter() {
            this.bw = new BufferedWriter(new OutputStreamWriter(System.out));
        }

        public void print(Object object) throws IOException {
            bw.append("" + object);
        }

        public void println(Object object) throws IOException {
            print(object);
            bw.append("\n");
        }

        public void close() throws IOException {
            bw.close();
        }
    }

    static class FastReader {
        BufferedReader br;
        StringTokenizer st;

        public FastReader() {
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }

        long nextLong() {
            return Long.parseLong(next());
        }

        double nextDouble() {
            return Double.parseDouble(next());
        }

        String nextLine() {
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }

        BigInteger nextBigInteger() {
            try {
                return new BigInteger(nextLine());
            } catch (NumberFormatException e) {
                throw new InputMismatchException();
            }
        }
    }

    public static void main(String[] args) {
        FastReader fr = new FastReader();
        FastWriter fw = new FastWriter();
        int q = fr.nextInt();
        while (q-- > 0) {
            long n = fr.nextLong();
            BigInteger val = BigInteger.ZERO;
            int pow = 0;
            BigInteger ans = BigInteger.ZERO;
            while (val.compareTo(BigInteger.valueOf(n)) < 0) {
                val = BigInteger.valueOf(3).pow(pow);
                ans = ans.add(val);
                pow++;
            }
            pow--;
            for (int p = pow; p >= 0; p--) {
                BigInteger hola = BigInteger.valueOf(3).pow(p);
                BigInteger sub = ans.subtract(hola);
                if (sub.compareTo(BigInteger.valueOf(n)) >= 0) ans = sub;
            }
            System.out.println(ans);

        }
    }
}


#include <bits/stdc++.h>
using namespace std;

typedef long long ll;

const ll mxN = 1e6;
char line[mxN];

int main() {
	ios_base::sync_with_stdio(false);

	cin.getline(line, 1e6);
	vector<string> w;
	vector<char> s;
	for (ll i = 0; i < 1e5 + 500; i++) {
		if (line[i] == '\0') {
			string t = "";
			for (auto it : s) {
				t += it;
			}
			w.push_back(t);
			break;
		}
		if (line[i] == ' ') {
			string t = "";
			for (auto it : s) {
				t += it;
			}
			w.push_back(t);
			s.erase(s.begin(), s.end());
			continue;
		}
		s.push_back(line[i]);
	}
	ll cnt = w.size();
	bool masculine = false, feminine = false, ok = true;
	ll startadj = -1, endadj = -1, startnoun = -1, endnoun = -1, startverb = 1e6, endverb = 1e6;
	for (ll i = 0; i < cnt; i++) {
		ll n = w[i].length();
		if (n < 4) {
			ok = false;
			break;
		}
		string str1 = ".", str2 = ".", str3 = ".", str4 = ".";
		bool done = false;
		if (n >= 4)
			str1 = w[i].substr(n - 4, 4);
		if (n >= 5)
			str2 = w[i].substr(n - 5, 5);
		if (n >= 3)
			str3 = w[i].substr(n - 3, 3);
		if (n >= 6)
			str4 = w[i].substr(n - 6, 6);
		if (str1 != "." && str1 == "lios") {
			if (startadj == -1) {
				startadj = i;
			}
			endadj = i;
			masculine = true;
			done = true;
		}
		if (str1 != "." && str1 == "etra") {
			if (startnoun == -1) {
				startnoun = i;
			}
			endnoun = i;
			feminine = true;
			done = true;
		}
		if (str2 != "." && str2 == "liala") {
			if (startadj == -1) {
				startadj = i;
			}
			endadj = i;
			feminine = true;
			done = true;
		}
		if (str4 != "." && str4 == "inites") {
			if (startverb == 1e6) {
				startverb = i;
			}
			endverb = i;
			done = true;
			feminine = true;
		}
		if (str3 != "." && str3 == "etr") {
			if (startnoun == -1) {
				startnoun = i;
			}
			endnoun = i;
			done = true;
			masculine = true;
		}
		if (str4 != "." && str4 == "initis") {
			if (startverb == 1e6) {
				startverb = i;
			}
			endverb = i;
			done = true;
			masculine = true;
		}
		if (!done) {
			ok = false;
			break;
		}
	}
	if (!ok) {
		cout << "NO";
	} else {
		if ((masculine == true && feminine == true) || (masculine == false && feminine == false))
			cout << "NO";
		else {
			if (startnoun == endnoun && startnoun != -1 && startnoun > endadj && endnoun < startverb) {
				cout << "YES";
			} else {
				cout << "NO";
			}
		}
	}

	return 0;
}


#include <bits/stdc++.h>
using namespace std;

typedef long long ll;

const ll mxN = 1e6;
char line[mxN];

int main() {
	ios_base::sync_with_stdio(false);

	cin.getline(line, 1e6);
	vector<string> w;
	vector<char> s;
	for (ll i = 0; i < 1e5 + 500; i++) {
		if (line[i] == '\0') {
			string t = "";
			for (auto it : s) {
				t += it;
			}
			w.push_back(t);
			break;
		}
		if (line[i] == ' ') {
			string t = "";
			for (auto it : s) {
				t += it;
			}
			w.push_back(t);
			s.erase(s.begin(), s.end());
			continue;
		}
		s.push_back(line[i]);
	}
	ll cnt = w.size();
	bool masculine = false, feminine = false, ok = true;
	ll startadj = -1, endadj = -1, startnoun = 1e3, endnoun = 1e3, startverb = 1e6, endverb = 1e6;
	for (ll i = 0; i < cnt; i++) {
		ll n = w[i].length();
		if (n < 4) {
			ok = false;
			break;
		}
		string str1 = ".", str2 = ".", str3 = ".", str4 = ".";
		bool done = false;
		if (n >= 4)
			str1 = w[i].substr(n - 4, 4);
		if (n >= 5)
			str2 = w[i].substr(n - 5, 5);
		if (n >= 3)
			str3 = w[i].substr(n - 3, 3);
		if (n >= 6)
			str4 = w[i].substr(n - 6, 6);
		if (str1 != "." && str1 == "lios") {
			if (startadj == -1) {
				startadj = i;
			}
			endadj = i;
			masculine = true;
			done = true;
		}
		if (str1 != "." && str1 == "etra") {
			if (startnoun == 1e3) {
				startnoun = i;
			}
			endnoun = i;
			feminine = true;
			done = true;
		}
		if (str2 != "." && str2 == "liala") {
			if (startadj == -1) {
				startadj = i;
			}
			endadj = i;
			feminine = true;
			done = true;
		}
		if (str4 != "." && str4 == "inites") {
			if (startverb == 1e6) {
				startverb = i;
			}
			endverb = i;
			done = true;
			feminine = true;
		}
		if (str3 != "." && str3 == "etr") {
			if (startnoun == 1e3) {
				startnoun = i;
			}
			endnoun = i;
			done = true;
			masculine = true;
		}
		if (str4 != "." && str4 == "initis") {
			if (startverb == 1e6) {
				startverb = i;
			}
			endverb = i;
			done = true;
			masculine = true;
		}
		if (!done) {
			ok = false;
			break;
		}
	}
	if (!ok) {
		cout << "NO";
	} else {
		if ((masculine == true && feminine == true) || (masculine == false && feminine == false))
			cout << "NO";
		else {
			if (startnoun == endnoun && startnoun > endadj && endnoun < startverb) {
				cout << "YES";
			} else {
				cout << "NO";
			}
		}
	}

	return 0;
}


#include <bits/stdc++.h>
using namespace std;

typedef long long ll;

const ll mxN = 1e6;
char line[mxN];

int main() {
	ios_base::sync_with_stdio(false);

	cin.getline(line, 1e6);
	vector<string> w;
	vector<char> s;
	for (ll i = 0; i < 1e5 + 500; i++) {
		if (line[i] == '\0') {
			string t = "";
			for (auto it : s) {
				t += it;
			}
			w.push_back(t);
			break;
		}
		if (line[i] == ' ') {
			string t = "";
			for (auto it : s) {
				t += it;
			}
			w.push_back(t);
			s.erase(s.begin(), s.end());
			continue;
		}
		s.push_back(line[i]);
	}
	ll cnt = w.size();
	if (cnt == 1) {
		ll n = w[0].size();
		string str1 = ".", str2 = ".", str3 = ".", str4 = ".";
		if (n >= 4)
			str1 = w[0].substr(n - 4, 4);
		if (n >= 5)
			str2 = w[0].substr(n - 5, 5);
		if (n >= 3)
			str3 = w[0].substr(n - 3, 3);
		if (n >= 6)
			str4 = w[0].substr(n - 6, 6);
		if (str1 == "etra" || str1 == "lios" || str2 == "liala" || str3 == "etr" || str4 == "inites" || str4 == "initis")
			cout << "YES";
		else
			cout << "NO";
		return 0;
	}
	bool masculine = false, feminine = false, ok = true;
	ll startadj = -1, endadj = -1, startnoun = -1, endnoun = -1, startverb = 1e6, endverb = 1e6;
	for (ll i = 0; i < cnt; i++) {
		ll n = w[i].length();
		if (n < 4) {
			ok = false;
			break;
		}
		string str1 = ".", str2 = ".", str3 = ".", str4 = ".";
		bool done = false;
		if (n >= 4)
			str1 = w[i].substr(n - 4, 4);
		if (n >= 5)
			str2 = w[i].substr(n - 5, 5);
		if (n >= 3)
			str3 = w[i].substr(n - 3, 3);
		if (n >= 6)
			str4 = w[i].substr(n - 6, 6);
		if (str1 != "." && str1 == "lios") {
			if (startadj == -1) {
				startadj = i;
			}
			endadj = i;
			masculine = true;
			done = true;
		}
		if (str1 != "." && str1 == "etra") {
			if (startnoun == -1) {
				startnoun = i;
			}
			endnoun = i;
			feminine = true;
			done = true;
		}
		if (str2 != "." && str2 == "liala") {
			if (startadj == -1) {
				startadj = i;
			}
			endadj = i;
			feminine = true;
			done = true;
		}
		if (str4 != "." && str4 == "inites") {
			if (startverb == 1e6) {
				startverb = i;
			}
			endverb = i;
			done = true;
			feminine = true;
		}
		if (str3 != "." && str3 == "etr") {
			if (startnoun == -1) {
				startnoun = i;
			}
			endnoun = i;
			done = true;
			masculine = true;
		}
		if (str4 != "." && str4 == "initis") {
			if (startverb == 1e6) {
				startverb = i;
			}
			endverb = i;
			done = true;
			masculine = true;
		}
		if (!done) {
			ok = false;
			break;
		}
	}
	if (!ok) {
		cout << "NO";
	} else {
		if ((masculine == true && feminine == true) || (masculine == false && feminine == false))
			cout << "NO";
		else {
			if (startnoun == endnoun && startnoun != -1 && startnoun > endadj && endnoun < startverb) {
				cout << "YES";
			} else {
				cout << "NO";
			}
		}
	}

	return 0;
}


#include <bits/stdc++.h>
using namespace std;

typedef long long ll;

const ll mxN = 1e6;
char line[mxN];

int main() {
	ios_base::sync_with_stdio(false);

	cin.getline(line, 1e6);
	vector<string> w;
	vector<char> s;
	for (ll i = 0; i < 1e5 + 500; i++) {
		if (line[i] == '\0') {
			string t = "";
			for (auto it : s) {
				t += it;
			}
			w.push_back(t);
			break;
		}
		if (line[i] == ' ') {
			string t = "";
			for (auto it : s) {
				t += it;
			}
			w.push_back(t);
			s.erase(s.begin(), s.end());
			continue;
		}
		s.push_back(line[i]);
	}
	ll cnt = w.size();
	if (cnt == 1) {
		ll n = w[0].size();
		string str1 = ".", str2 = ".", str3 = ".", str4 = ".";
		if (n >= 4)
			str1 = w[0].substr(n - 4, 4);
		if (n >= 5)
			str2 = w[0].substr(n - 5, 5);
		if (n >= 3)
			str3 = w[0].substr(n - 3, 3);
		if (n >= 6)
			str4 = w[0].substr(n - 6, 6);
		if (str1 == "etra" || str1 == "lios" || str2 == "liala" || str3 == "etr" || str4 == "inites" || str4 == "initis")
			cout << "YES";
		else
			cout << "NO";
		return 0;
	}
	bool masculine = false, feminine = false, ok = true;
	ll startadj = -1, endadj = -1, startnoun = -1, endnoun = -1, startverb = 1e6, endverb = 1e6;
	for (ll i = 0; i < cnt; i++) {
		ll n = w[i].length();
		if (n < 3) {
			ok = false;
			break;
		}
		string str1 = ".", str2 = ".", str3 = ".", str4 = ".";
		bool done = false;
		if (n >= 4)
			str1 = w[i].substr(n - 4, 4);
		if (n >= 5)
			str2 = w[i].substr(n - 5, 5);
		if (n >= 3)
			str3 = w[i].substr(n - 3, 3);
		if (n >= 6)
			str4 = w[i].substr(n - 6, 6);
		if (str1 != "." && str1 == "lios") {
			if (startadj == -1) {
				startadj = i;
			}
			endadj = i;
			masculine = true;
			done = true;
		}
		if (str1 != "." && str1 == "etra") {
			if (startnoun == -1) {
				startnoun = i;
			}
			endnoun = i;
			feminine = true;
			done = true;
		}
		if (str2 != "." && str2 == "liala") {
			if (startadj == -1) {
				startadj = i;
			}
			endadj = i;
			feminine = true;
			done = true;
		}
		if (str4 != "." && str4 == "inites") {
			if (startverb == 1e6) {
				startverb = i;
			}
			endverb = i;
			done = true;
			feminine = true;
		}
		if (str3 != "." && str3 == "etr") {
			if (startnoun == -1) {
				startnoun = i;
			}
			endnoun = i;
			done = true;
			masculine = true;
		}
		if (str4 != "." && str4 == "initis") {
			if (startverb == 1e6) {
				startverb = i;
			}
			endverb = i;
			done = true;
			masculine = true;
		}
		if (!done) {
			ok = false;
			break;
		}
	}
	if (!ok) {
		cout << "NO";
	} else {
		if ((masculine == true && feminine == true) || (masculine == false && feminine == false))
			cout << "NO";
		else {
			if (startnoun == endnoun && startnoun != -1 && startnoun > endadj && endnoun < startverb) {
				cout << "YES";
			} else {
				cout << "NO";
			}
		}
	}

	return 0;
}


#include <bits/stdc++.h>
using namespace std;
int main()
{
    string s[100000];
    long long j=0,a=0,n=0,v=0,g=-1;
    while(1){
        s[j]=".";
        cin>>s[j];
        if(s[j]==".")break;
        s[j]="nhan1911_"+s[j];
        if(s[j].substr(s[j].length()-4,4) == "lios"){
            a++;
            if(g==1 || n>0)return cout<<"NO",0;
            g=0;
        }else if(s[j].substr(s[j].length()-5,5) == "liala"){
            a++;
            if(g==0 || n>0)return cout<<"NO",0;
            g=1;
        }else if(s[j].substr(s[j].length()-3,3) == "etr"){
            n++;
            if(n>1 || v>0 || g==1)return cout<<"NO",0;
            g=0;
        }else if(s[j].substr(s[j].length()-4,4) == "etra"){
            n++;
            if(n>1 || v>0 || g==0)return cout<<"NO",0;
            g=1;
        }else if(s[j].substr(s[j].length()-6,6) == "initis"){
            v++;
            if(n==0 || g==1)return cout<<"NO",0;
            g=0;
        }else if(s[j].substr(s[j].length()-6,6) == "inites"){
            v++;
            if(n==0 || g==0)return cout<<"NO",0;
            g=1;
        }else return cout<<"NO",0;
        j++;
    }
    cout<<"YES";
}


#include<bits/stdc++.h>
#define ll long long
#define mod 1000000007
#define pb push_back
#define pf push_front
#define pob pop_back
#define pof pop_front
#define len length
#define mp make_pair
#define pq priority_queue
#define fi first
#define se second
#define all(x) x.begin(),x.end()
#define forn(i,n) for (int i = 0; i < int(n); ++i)
#define take(v) for(int i=0;i<(int)v.size();i++){cin>>v[i];}
#define printvec(v) for(int i=0;i<(int)v.size();i++){cout<<v[i]<<" ";}
#define speed ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0)
#define printds(x) while(!x.empty()){cout<<x.top()<<" ";x.pop();}
#define input(n) int n;cin>>n;
#define PI 3.141592653589793238463
#define lnput(n) long long int n;cin>>n;
#define fr(i,s,e) for(int i=s;i<e;i++)
#define ms(arr,val) memset(arr,val,sizeof(arr))
using namespace std;
map<string,char> male;
map<string,char> female;
int main()
{
  speed;
  string s;
  getline(cin,s);
  stringstream ss(s);
  string word;
  vector<string> v;
  while(ss >> word)
  {
    v.pb(word);
  }
  for(int i = 0;i<(int)v.size();i++)
  {
    reverse(all(v[i]));
  }
  word = v[0];
  male["soil"] = 'a';
  male["rte"] = 'n';
  male["sitini"] = 'v';
  female["alail"] = 'a';
  female["arte"] = 'n';
  female["setini"] = 'v';
  s.clear();
  char gender = '0';
  for(int i = 0;i<(int)word.len();i++)
  {
    s.pb(word[i]);
    if(male.count(s))
    {
      // cout<<s<<endl;
      gender = 'm';
      break;
    }
    if(female.count(s))
    {
      // cout<<s<<endl;
      gender = 'f';
      break;
    }
  }
  if(gender == '0')
  {
    cout<<"NO"<<endl;
    return 0;
  }
  int n = (int)v.size();
  char prev;
  if(gender == 'm')
  {
    prev = male[s];
  }
  else
  {
    prev = female[s];
  }
  for(int i = 1;i<n;i++)
  {
    char cur = '0';
    s.clear();
    for(int j = 0;j<(int)v[i].len();j++)
    {
      s.pb(v[i][j]);
      if(gender == 'm' && male.count(s))
      {
        cur = male[s];
        break;
      }
      else if(gender == 'f' && female.count(s))
      {
        cur = female[s];
        break;
      }
    }
    if(cur == '0')
    {
      cout<<"NO"<<endl;
      return 0;
    }
    if(prev == 'n')
    {
      if(cur == 'v')
      {
        prev = cur;
        continue;
      }
      else
      {
        cout<<"NO"<<endl;
        return 0;
      }
    }
    else if(prev == 'v')
    {
      if(prev == cur )
      {
        prev = cur;
        continue;
      }
      else
      {
        cout<<"NO"<<endl;
        return 0;
      }
    }
    else
    {
      if(cur == 'a' || cur == 'n')
      {
        prev = cur;
        continue;
      }
      else
      {
        cout<<"NO"<<endl;
        return 0;
      }
    }
  }
  cout<<"YES"<<endl;
  return 0;
}


#include<bits/stdc++.h>
#define ll long long
#define mod 1000000007
#define pb push_back
#define pf push_front
#define pob pop_back
#define pof pop_front
#define len length
#define mp make_pair
#define pq priority_queue
#define fi first
#define se second
#define all(x) x.begin(),x.end()
#define forn(i,n) for (int i = 0; i < int(n); ++i)
#define take(v) for(int i=0;i<(int)v.size();i++){cin>>v[i];}
#define printvec(v) for(int i=0;i<(int)v.size();i++){cout<<v[i]<<" ";}
#define speed ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0)
#define printds(x) while(!x.empty()){cout<<x.top()<<" ";x.pop();}
#define input(n) int n;cin>>n;
#define PI 3.141592653589793238463
#define lnput(n) long long int n;cin>>n;
#define fr(i,s,e) for(int i=s;i<e;i++)
#define ms(arr,val) memset(arr,val,sizeof(arr))
using namespace std;
map<string,char> male;
map<string,char> female;
int main()
{
  speed;
  string s;
  getline(cin,s);
  stringstream ss(s);
  string word;
  vector<string> v;
  while(ss >> word)
  {
    v.pb(word);
  }
  for(int i = 0;i<(int)v.size();i++)
  {
    reverse(all(v[i]));
  }
  word = v[0];
  male["soil"] = 'a';
  male["rte"] = 'n';
  male["sitini"] = 'v';
  female["alail"] = 'a';
  female["arte"] = 'n';
  female["setini"] = 'v';
  s.clear();
  char gender = '0';
  for(int i = 0;i<(int)word.len();i++)
  {
    s.pb(word[i]);
    if(male.count(s))
    {
      // cout<<s<<endl;
      gender = 'm';
      break;
    }
    if(female.count(s))
    {
      // cout<<s<<endl;
      gender = 'f';
      break;
    }
  }
  if(v.size() == 1)
  {
    if(gender != '0')
    {
      cout<<"YES"<<endl;
      return 0;
    }
  }
  if(gender == '0')
  {
    cout<<"NO"<<endl;
    return 0;
  }
  int n = (int)v.size();
  int nc = 0,ind = 0;
  string ans;
  for(int i = 0;i<n;i++)
  {
    char cur = '0';
    s.clear();
    for(int j = 0;j<(int)v[i].len();j++)
    {
      s.pb(v[i][j]);
      if(gender == 'm' && male.count(s))
      {
        cur = male[s];
        break;
      }
      else if(gender == 'f' && female.count(s))
      {
        cur = female[s];
        break;
      }
    }
    if(cur == '0')
    {
      cout<<"NO"<<endl;
      return 0;
    }
    ans.pb(cur);
    if(cur == 'n')
    {
      nc++;
      ind = ans.size()-1;
    }
  }
  if(nc == 0)
  {
    cout<<"NO"<<endl;
    return 0;
  }
  for(int i = 0;i<ind;i++)
  {
    if(ans[i] != 'a')
    {
      cout<<"NO"<<endl;
      return 0;
    }
  }
  for(int i = ind+1;i<(int)ans.len();i++)
  {
    if(ans[i] != 'v')
    {
      cout<<"NO"<<endl;
      return 0;
    }
  }
  cout<<"YES"<<endl;
  return 0;
}


#include<bits/stdc++.h>
#define ll long long
#define mod 1000000007
#define pb push_back
#define pf push_front
#define pob pop_back
#define pof pop_front
#define len length
#define mp make_pair
#define pq priority_queue
#define fi first
#define se second
#define all(x) x.begin(),x.end()
#define forn(i,n) for (int i = 0; i < int(n); ++i)
#define take(v) for(int i=0;i<(int)v.size();i++){cin>>v[i];}
#define printvec(v) for(int i=0;i<(int)v.size();i++){cout<<v[i]<<" ";}
#define speed ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0)
#define printds(x) while(!x.empty()){cout<<x.top()<<" ";x.pop();}
#define input(n) int n;cin>>n;
#define PI 3.141592653589793238463
#define lnput(n) long long int n;cin>>n;
#define fr(i,s,e) for(int i=s;i<e;i++)
#define ms(arr,val) memset(arr,val,sizeof(arr))
using namespace std;
map<string,char> male;
map<string,char> female;
int main()
{
  speed;
  string s;
  getline(cin,s);
  stringstream ss(s);
  string word;
  vector<string> v;
  while(ss >> word)
  {
    v.pb(word);
  }
  for(int i = 0;i<v.size();i++)
  {
    reverse(all(v[i]));
  }
  word = v[0];
  male["soil"] = 'a';
  male["rte"] = 'n';
  male["sitini"] = 'v';
  female["alail"] = 'a';
  female["arte"] = 'n';
  female["setini"] = 'v';
  s.clear();
  char gender = '0';
  for(int i = 0;i<word.len();i++)
  {
    s.pb(word[i]);
    if(male.count(s))
    {
      gender = 'm';
      break;
    }
    if(female.count(s))
    {
      gender = 'f';
      break;
    }
  }
  // cout<<gender<<endl;
  if(gender == '0')
  {
    cout<<"NO"<<endl;
    return 0;
  }
  map<char,char> path;
  path['a'] = 'n';
  path['n'] = 'v';
  path['v'] = 'a';
  int n = v.size();
  char prev;
  if(gender == 'm')
  {
    prev = male[s];
  }
  else
  {
    prev = female[s];
  }
  for(int i = 1;i<n;i++)
  {
    char cur = '0';
    s.clear();
    for(int j = 0;j<v[i].len();j++)
    {
      s.pb(v[i][j]);
      if(gender == 'm' && male.count(s))
      {
        cur = male[s];
        break;
      }
      else if(gender == 'f' && female.count(s))
      {
        cur = female[s];
        break;
      }
    }
    if(cur == '0')
    {
      cout<<"NO"<<endl;
      return 0;
    }
    if(prev == 'n')
    {
      if(cur == 'v')
      {
        prev = cur;
        continue;
      }
      else
      {
        cout<<"NO"<<endl;
        return 0;
      }
    }
    else
    {
      if(prev == cur || cur == path[prev])
      {
        prev = cur;
        continue;
      }
      else
      {
        cout<<"NO"<<endl;
        return 0;
      }
    }
  }
  cout<<"YES"<<endl;
  return 0;
}


#include<bits/stdc++.h>
#define ll long long
#define mod 1000000007
#define pb push_back
#define pf push_front
#define pob pop_back
#define pof pop_front
#define len length
#define mp make_pair
#define pq priority_queue
#define fi first
#define se second
#define all(x) x.begin(),x.end()
#define forn(i,n) for (int i = 0; i < int(n); ++i)
#define take(v) for(int i=0;i<(int)v.size();i++){cin>>v[i];}
#define printvec(v) for(int i=0;i<(int)v.size();i++){cout<<v[i]<<" ";}
#define speed ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0)
#define printds(x) while(!x.empty()){cout<<x.top()<<" ";x.pop();}
#define input(n) int n;cin>>n;
#define PI 3.141592653589793238463
#define lnput(n) long long int n;cin>>n;
#define fr(i,s,e) for(int i=s;i<e;i++)
#define ms(arr,val) memset(arr,val,sizeof(arr))
using namespace std;
map<string,char> male;
map<string,char> female;
int main()
{
  speed;
  string s;
  getline(cin,s);
  stringstream ss(s);
  string word;
  vector<string> v;
  while(ss >> word)
  {
    v.pb(word);
  }
  for(int i = 0;i<(int)v.size();i++)
  {
    reverse(all(v[i]));
  }
  word = v[0];
  male["soil"] = 'a';
  male["rte"] = 'n';
  male["sitini"] = 'v';
  female["alail"] = 'a';
  female["arte"] = 'n';
  female["setini"] = 'v';
  s.clear();
  char gender = '0';
  for(int i = 0;i<(int)word.len();i++)
  {
    s.pb(word[i]);
    if(male.count(s))
    {
      // cout<<s<<endl;
      gender = 'm';
      break;
    }
    if(female.count(s))
    {
      // cout<<s<<endl;
      gender = 'f';
      break;
    }
  }
  if(gender == '0')
  {
    cout<<"NO"<<endl;
    return 0;
  }
  int n = (int)v.size();
  int nc = 0,ind = 0;
  string ans;
  for(int i = 0;i<n;i++)
  {
    char cur = '0';
    s.clear();
    for(int j = 0;j<(int)v[i].len();j++)
    {
      s.pb(v[i][j]);
      if(gender == 'm' && male.count(s))
      {
        cur = male[s];
        break;
      }
      else if(gender == 'f' && female.count(s))
      {
        cur = female[s];
        break;
      }
    }
    if(cur == '0')
    {
      cout<<"NO"<<endl;
      return 0;
    }
    ans.pb(cur);
    if(cur == 'n')
    {
      nc++;
      ind = ans.size()-1;
    }
  }
  if(nc == 0)
  {
    cout<<"NO"<<endl;
    return 0;
  }
  for(int i = 0;i<ind;i++)
  {
    if(ans[i] != 'a')
    {
      cout<<"NO"<<endl;
      return 0;
    }
  }
  for(int i = ind+1;i<(int)ans.len();i++)
  {
    if(ans[i] != 'v')
    {
      cout<<"NO"<<endl;
      return 0;
    }
  }
  cout<<"YES"<<endl;
  return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define int long long
#define endl '\n'
#define SPEED ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define MOD 1000000007
signed main()
{
  SPEED;
  string s,ma("lios"),fa("liala"),mn("etr"),fn("etra"),mv("initis"),fv("inites");
  reverse(ma.begin(),ma.end());
  reverse(fa.begin(),fa.end());
  reverse(mn.begin(),mn.end());
  reverse(fn.begin(),fn.end());
  reverse(mv.begin(),mv.end());
  reverse(fv.begin(),fv.end());
  int m=0,cnt=0;
  vector <int> vec;
  while(cin>>s)
  {
      int f=0;
      reverse(s.begin(),s.end());
      if(s.size()>=3)
      {
          string chk=s.substr(0,3);
          if(chk==mn)
          {
              ++f;
              if(m<0)
              {
                  f=-10;
              }
              m=1;
              vec.push_back(0);
              ++cnt;
          }
      }
      if(s.size()>=4)
      {
          string chk=s.substr(0,4);
          if(chk==ma)
          {
              ++f;
              if(m<0)
              {
                  f=-10;
              }
              m=1;
              vec.push_back(-1);
          }
      }
      if(s.size()>=4)
      {
          string chk=s.substr(0,4);
          if(chk==fn)
          {
              ++f;
              if(m>0)
              {
                  f=-10;
              }
              m=-1;
              vec.push_back(0);
              ++cnt;
          }
      }
      if(s.size()>=5)
      {
          string chk=s.substr(0,5);
          if(chk==fa)
          {
              ++f;
              if(m>0)
              {
                  f=-10;
              }
              m=-1;
              vec.push_back(-1);
          }
      }
      if(s.size()>=6)
      {
          string chk=s.substr(0,6);
          if(chk==mv)
          {
              ++f;
              if(m<0)
              {
                  f=-10;
              }
              m=1;
              vec.push_back(1);
          }
      }
      if(s.size()>=6)
      {
          string chk=s.substr(0,6);
          if(chk==fv)
          {
              ++f;
              if(m>0)
              {
                  f=-10;
              }
              m=-1;
              vec.push_back(1);
          }
      }
      if(f<=0)
      {
          cout<<"NO";
          return 0;
      }
  }
  int n=vec.size();
  if(n==1)
  {
      cout<<"YES";
      return 0;
  }
  if(cnt!=1)
  {
      cout<<"NO";
      return 0;
  }
  if(vec[0]==1 || vec[n-1]==-1)
  {
      cout<<"NO";
      return 0;
  }
  for(int i=1;i<n;i++)
  {
      if(vec[i-1]<0 && vec[i]>0)
      {
          cout<<"NO";
          return 0;
      }
      else if(vec[i]>0 && vec[i-1]<0)
      {
          cout<<"NO";
          return 0;
      }
  }
  cout<<"YES";
}


#include <bits/stdc++.h>
using namespace std;
#define int long long
#define endl '\n'
#define SPEED ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define MOD 1000000007
signed main()
{
  SPEED;
  string s,ma("lios"),fa("liala"),mn("etr"),fn("etra"),mv("initis"),fv("inites");
  reverse(ma.begin(),ma.end());
  reverse(fa.begin(),fa.end());
  reverse(mn.begin(),mn.end());
  reverse(fn.begin(),fn.end());
  reverse(mv.begin(),mv.end());
  reverse(fv.begin(),fv.end());
  int m=0;
  vector <int> vec;
  while(cin>>s)
  {
      int f=0;
      reverse(s.begin(),s.end());
      if(s.size()>=3)
      {
          string chk=s.substr(0,3);
          if(chk==mn)
          {
              ++f;
              if(m<0)
              {
                  f=-10;
              }
              m=1;
              vec.push_back(0);
          }
      }
      if(s.size()>=4)
      {
          string chk=s.substr(0,4);
          if(chk==ma)
          {
              ++f;
              if(m<0)
              {
                  f=-10;
              }
              m=1;
              vec.push_back(-1);
          }
      }
      if(s.size()>=4)
      {
          string chk=s.substr(0,4);
          if(chk==fn)
          {
              ++f;
              if(m>0)
              {
                  f=-10;
              }
              m=-1;
              vec.push_back(0);
          }
      }
      if(s.size()>=5)
      {
          string chk=s.substr(0,5);
          if(chk==fa)
          {
              ++f;
              if(m>0)
              {
                  f=-10;
              }
              m=-1;
              vec.push_back(-1);
          }
      }
      if(s.size()>=6)
      {
          string chk=s.substr(0,6);
          if(chk==mv)
          {
              ++f;
              if(m<0)
              {
                  f=-10;
              }
              m=1;
              vec.push_back(1);
          }
      }
      if(s.size()>=6)
      {
          string chk=s.substr(0,6);
          if(chk==fv)
          {
              ++f;
              if(m>0)
              {
                  f=-10;
              }
              m=-1;
              vec.push_back(1);
          }
      }
      if(f<=0)
      {
          cout<<"NO";
          return 0;
      }
  }
  int n=vec.size(),cnt=0;
  if(n==1)
  {
      cout<<"YES";
      return 0;
  }
  if(vec[0]==1 || vec[n-1]==-1)
  {
      cout<<"NO";
      return 0;
  }
  for(int i=1;i<n;i++)
  {
      if(vec[i-1]<0 && vec[i]>0)
      {
          cout<<"NO";
          return 0;
      }
      else if(vec[i]>0 && vec[i-1]<0)
      {
          cout<<"NO";
          return 0;
      }
      if(vec[i]==0)
      {
          ++cnt;
      }
  }
  if(vec[0]==-1 && cnt==0)
  {
      cout<<"NO";
      return 0;
  }
  if(vec[n-1]==1 && cnt==0)
  {
      cout<<"NO";
      return 0;
  }
  cout<<"YES";
}


#include <bits/stdc++.h>
using namespace std;
#define int long long
#define endl '\n'
#define SPEED ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define MOD 1000000007
signed main()
{
  SPEED;
  string s,ma("lios"),fa("liala"),mn("etr"),fn("etra"),mv("initis"),fv("inites");
  reverse(ma.begin(),ma.end());
  reverse(fa.begin(),fa.end());
  reverse(mn.begin(),mn.end());
  reverse(fn.begin(),fn.end());
  reverse(mv.begin(),mv.end());
  reverse(fv.begin(),fv.end());
  int m=0;
  vector <int> vec;
  while(cin>>s)
  {
      int f=0;
      reverse(s.begin(),s.end());
      if(s.size()>=3)
      {
          string chk=s.substr(0,3);
          if(chk==mn)
          {
              ++f;
              if(m<0)
              {
                  f=-10;
              }
              m=1;
              vec.push_back(0);
          }
      }
      if(s.size()>=4)
      {
          string chk=s.substr(0,4);
          if(chk==ma)
          {
              ++f;
              if(m<0)
              {
                  f=-10;
              }
              m=1;
              vec.push_back(-1);
          }
      }
      if(s.size()>=4)
      {
          string chk=s.substr(0,4);
          if(chk==fn)
          {
              ++f;
              if(m>0)
              {
                  f=-10;
              }
              m=-1;
              vec.push_back(0);
          }
      }
      if(s.size()>=5)
      {
          string chk=s.substr(0,5);
          if(chk==fa)
          {
              ++f;
              if(m>0)
              {
                  f=-10;
              }
              m=-1;
              vec.push_back(-1);
          }
      }
      if(s.size()>=6)
      {
          string chk=s.substr(0,6);
          if(chk==mv)
          {
              ++f;
              if(m<0)
              {
                  f=-10;
              }
              m=1;
              vec.push_back(1);
          }
      }
      if(s.size()>=6)
      {
          string chk=s.substr(0,6);
          if(chk==fv)
          {
              ++f;
              if(m>0)
              {
                  f=-10;
              }
              m=-1;
              vec.push_back(1);
          }
      }
      if(f<=0)
      {
          cout<<"NO";
          return 0;
      }
  }
  int n=vec.size(),cnt=0;
  if(vec[0]==1 || vec[n-1]==-1)
  {
      cout<<"NO";
      return 0;
  }
  for(int i=1;i<n;i++)
  {
      if(vec[i-1]<0 && vec[i]>0)
      {
          cout<<"NO";
          return 0;
      }
      else if(vec[i]>0 && vec[i-1]<0)
      {
          cout<<"NO";
          return 0;
      }
      if(vec[i]==0)
      {
          ++cnt;
      }
  }
  if(vec[0]==-1 && cnt==0)
  {
      cout<<"NO";
      return 0;
  }
  if(vec[n-1]==1 && cnt==0)
  {
      cout<<"NO";
      return 0;
  }
  cout<<"YES";
}


#include <bits/stdc++.h>

using namespace std;
double pi=3.14159265358979323846264338;
long long sum;
long long ma;
int pa, gen,cnt;
string cur;
bool ok=false;
long long pr(long long a, long long b){
	long long k=1;
	if(b==0)return 1;

	for(int i=0;i<b;i++)k=k*10;
	return k;
}
inline void ex(){cout<<"NO"<<endl;exit(0);}
void calc(string a){
	cnt++;
	if(a.length()>=4&&a.substr(a.length()-4,4)=="lios"){
		if(gen==-1)ex();
		else gen=1;
		if(pa==2||pa==3)ex();
		else pa=1;
		return;
	}
	if(a.length()>=5&&a.substr(a.length()-5,5)=="liala"){
		if(gen==1)ex();
		else gen=-1;
		if(pa==2||pa==3)ex();
		else pa=1;
		return;
	}
	if(a.length()>=3&&a.substr(a.length()-3,3)=="etr"){
		if(gen==-1)ex();
		else gen=1;
		if(pa==2||pa==3){ex();}
		else pa=2;
		ok=true;
		return;
	}
	if(a.length()>=4&&a.substr(a.length()-4,4)=="etra"){
		if(gen==1)ex();
		else gen=-1;

		if(pa==2||pa==3)ex();
		else pa=2;

		ok=true;
		return;
	}
	if(a.length()>=6&&a.substr(a.length()-6,6)=="liala"){
		if(gen==-1)ex();
		else gen=1;
		if(pa==1)ex();
		else pa=3;
		return;
	}
	if(a.length()>=6&&a.substr(a.length()-6,6)=="inites"){
		if(gen==1)ex();
		else gen=-1;
		if(pa==1)ex();
		else pa=3;
		return;
	}
	//cout<<a<<" "<<cnt<<endl;
	ex();
}
int main(){
	pa=0,gen=0;
	cnt=0;
	string a;
	while(cin>>a){

		calc(a);
		//cout<<a<<endl;
	}

	if(ok||cnt==1)cout<<"YES"<<endl;
	else cout<<"NO"<<endl;
	return 0;

}


#include <bits/stdc++.h>

using namespace std;
double pi=3.14159265358979323846264338;
long long sum;
long long ma;
int pa, gen,cnt;
string cur;
bool ok=false;
long long pr(long long a, long long b){
	long long k=1;
	if(b==0)return 1;

	for(int i=0;i<b;i++)k=k*10;
	return k;
}
inline void ex(){cout<<"NO"<<endl;exit(0);}
void calc(string a){
	cnt++;
	if(a.length()>=4&&a.substr(a.length()-4,4)=="lios"){
		if(gen==-1)ex();
		else gen=1;
		if(pa==2||pa==3)ex();
		else pa=1;
		return;
	}
	if(a.length()>=5&&a.substr(a.length()-5,5)=="liala"){
		if(gen==1)ex();
		else gen=-1;
		if(pa==2||pa==3)ex();
		else pa=1;
		return;
	}
	if(a.length()>=3&&a.substr(a.length()-3,3)=="etr"){
		if(gen==-1)ex();
		else gen=1;
		if(pa==2||pa==3)ex();
		else pa=2;
		ok=true;
		return;
	}
	if(a.length()>=4&&a.substr(a.length()-4,4)=="etra"){
		if(gen==1)ex();
		else gen=-1;

		if(pa==2||pa==3)ex();
		else pa=2;

		ok=true;
		return;
	}
	if(a.length()>=6&&a.substr(a.length()-6,6)=="liala"){
		if(gen==-1)ex();
		else gen=1;
		if(pa==1)ex();
		else pa=3;
		return;
	}
	if(a.length()>=6&&a.substr(a.length()-6,6)=="inites"){
		if(gen==1)ex();
		else gen=-1;
		if(pa==1)ex();
		else pa=3;
		return;
	}
	ex();
}
int main(){
	pa=0,gen=0;
	cnt=0;
	string a;
	while(!cin.eof()){
		cin>>a;
		calc(a);
		//cout<<a<<endl;
	}
	cnt--;
	if(ok||cnt==1)cout<<"YES"<<endl;
	else cout<<"NO"<<endl;
	return 0;

}


#include <bits/stdc++.h>

using namespace std;
double pi=3.14159265358979323846264338;
long long sum;
long long ma;
int pa, gen,cnt;
string cur;
bool ok=false;
long long pr(long long a, long long b){
	long long k=1;
	if(b==0)return 1;

	for(int i=0;i<b;i++)k=k*10;
	return k;
}
inline void ex(){cout<<"NO"<<endl;exit(0);}
void calc(string a){
	cnt++;
	if(a.length()>=4&&a.substr(a.length()-4,4)=="lios"){
		if(gen==-1)ex();
		else gen=1;
		if(pa==2||pa==3)ex();
		else pa==1;
	}
	if(a.length()>=5&&a.substr(a.length()-5,5)=="liala"){
		if(gen==1)ex();
		else gen=-1;
		if(pa==2||pa==3)ex();
		else pa==1;
	}
	if(a.length()>=3&&a.substr(a.length()-3,3)=="etr"){
		if(gen==-1)ex();
		else gen=1;
		if(pa==2||pa==3)ex();
		else pa==2;
		ok=true;
	}
	if(a.length()>=4&&a.substr(a.length()-4,4)=="etra"){
		if(gen==1)ex();
		else gen=-1;
		if(pa==2||pa==3)ex();
		else pa==2;
		ok=true;
	}
	if(a.length()>=6&&a.substr(a.length()-6,6)=="liala"){
		if(gen==-1)ex();
		else gen=1;
		if(pa==1)ex();
		else pa==3;
	}
	if(a.length()>=6&&a.substr(a.length()-6,6)=="inites"){
		if(gen==1)ex();
		else gen=-1;
		if(pa==1)ex();
		else pa==3;
	}
}
int main(){
	pa=0,gen=0;
	cnt=0;
	string a;
	while(!cin.eof()){
		cin>>a;
		calc(a);
		//cout<<a<<endl;
	}
	cnt--;
	if(ok||cnt==1)cout<<"YES"<<endl;
	else cout<<"NO"<<endl;
	return 0;

}


#include <bits/stdc++.h>

using namespace std;
double pi=3.14159265358979323846264338;
long long sum;
long long ma;
int pa, gen,cnt;
string cur;
bool ok=false;
long long pr(long long a, long long b){
	long long k=1;
	if(b==0)return 1;

	for(int i=0;i<b;i++)k=k*10;
	return k;
}
inline void ex(){cout<<"NO"<<endl;exit(0);}
void calc(string a){
	cnt++;
	if(a.length()>=4&&a.substr(a.length()-4,4)=="lios"){
		if(gen==-1)ex();
		else gen=1;
		if(pa==2||pa==3)ex();
		else pa==1;
	}
	if(a.length()>=5&&a.substr(a.length()-5,5)=="liala"){
		if(gen==1)ex();
		else gen=-1;
		if(pa==2||pa==3)ex();
		else pa==1;
	}
	if(a.length()>=3&&a.substr(a.length()-3,3)=="etr"){
		if(gen==-1)ex();
		else gen=1;
		if(pa==2||pa==3)ex();
		else pa==2;
		ok=true;
	}
	if(a.length()>=4&&a.substr(a.length()-4,4)=="etra"){
		if(gen==1)ex();
		else gen=-1;
		if(pa==2||pa==3)ex();
		else pa==2;
		ok=true;
	}
	if(a.length()>=6&&a.substr(a.length()-6,6)=="liala"){
		if(gen==-1)ex();
		else gen=1;
		if(pa==1)ex();
		else pa==3;
	}
	if(a.length()>=6&&a.substr(a.length()-6,6)=="inites"){
		if(gen==1)ex();
		else gen=-1;
		if(pa==1)ex();
		else pa==3;
	}
}
int main(){
	pa=0,gen=0;
	cnt=0;
	string a;
	while(!cin.eof()){
		cin>>a;
		calc(a);
		//cout<<a<<endl;
	}
	if(ok||cnt==1)cout<<"YES"<<endl;
	else cout<<"NO"<<endl;
	return 0;

}


#include <bits/stdc++.h>

using namespace std;
double pi=3.14159265358979323846264338;
long long sum;
long long ma;
int pa, gen,cnt;
string cur;
bool ok=false;
long long pr(long long a, long long b){
	long long k=1;
	if(b==0)return 1;

	for(int i=0;i<b;i++)k=k*10;
	return k;
}
inline void ex(){cout<<"NO"<<endl;exit(0);}
void calc(string a){
	cnt++;
	if(a.length()>=4&&a.substr(a.length()-4,4)=="lios"){
		if(gen==-1)ex();
		else gen=1;
		if(pa==2||pa==3)ex();
		else pa=1;
		return;
	}
	if(a.length()>=5&&a.substr(a.length()-5,5)=="liala"){
		if(gen==1)ex();
		else gen=-1;
		if(pa==2||pa==3)ex();
		else pa=1;
		return;
	}
	if(a.length()>=3&&a.substr(a.length()-3,3)=="etr"){
		if(gen==-1)ex();
		else gen=1;
		if(pa==2||pa==3){ex();}
		else pa=2;
		ok=true;
		return;
	}
	if(a.length()>=4&&a.substr(a.length()-4,4)=="etra"){
		if(gen==1)ex();
		else gen=-1;

		if(pa==2||pa==3)ex();
		else pa=2;

		ok=true;
		return;
	}
	if(a.length()>=6&&a.substr(a.length()-6,6)=="initis"){
		if(gen==-1)ex();
		else gen=1;
		if(pa==1)ex();
		else pa=3;
		return;
	}
	if(a.length()>=6&&a.substr(a.length()-6,6)=="inites"){
		if(gen==1)ex();
		else gen=-1;
		if(pa==1)ex();
		else pa=3;
		return;
	}
	//cout<<a<<" "<<cnt<<endl;
	ex();
}
int main(){
	pa=0,gen=0;
	cnt=0;
	string a;
	while(cin>>a){

		calc(a);
		//cout<<a<<endl;
	}

	if(ok||cnt==1)cout<<"YES"<<endl;
	else cout<<"NO"<<endl;
	return 0;

}


#include <bits/stdc++.h>

using namespace std;
double pi=3.14159265358979323846264338;
long long sum;
long long ma;
int pa, gen,cnt;
string cur;
bool ok=false;
long long pr(long long a, long long b){
	long long k=1;
	if(b==0)return 1;

	for(int i=0;i<b;i++)k=k*10;
	return k;
}
inline void ex(){cout<<"NO"<<endl;exit(0);}
void calc(string a){
	cnt++;
	if(a.length()>=4&&a.substr(a.length()-4,4)=="lios"){
		if(gen==-1)ex();
		else gen=1;
		if(pa==2||pa==3)ex();
		else pa==1;
		return;
	}
	if(a.length()>=5&&a.substr(a.length()-5,5)=="liala"){
		if(gen==1)ex();
		else gen=-1;
		if(pa==2||pa==3)ex();
		else pa==1;
		return;
	}
	if(a.length()>=3&&a.substr(a.length()-3,3)=="etr"){
		if(gen==-1)ex();
		else gen=1;
		if(pa==2||pa==3)ex();
		else pa==2;
		ok=true;
		return;
	}
	if(a.length()>=4&&a.substr(a.length()-4,4)=="etra"){
		if(gen==1)ex();
		else gen=-1;
		if(pa==2||pa==3)ex();
		else pa==2;
		ok=true;
		return;
	}
	if(a.length()>=6&&a.substr(a.length()-6,6)=="liala"){
		if(gen==-1)ex();
		else gen=1;
		if(pa==1)ex();
		else pa==3;
		return;
	}
	if(a.length()>=6&&a.substr(a.length()-6,6)=="inites"){
		if(gen==1)ex();
		else gen=-1;
		if(pa==1)ex();
		else pa==3;
		return;
	}
	ex();
}
int main(){
	pa=0,gen=0;
	cnt=0;
	string a;
	while(!cin.eof()){
		cin>>a;
		calc(a);
		//cout<<a<<endl;
	}
	cnt--;
	if(ok||cnt==1)cout<<"YES"<<endl;
	else cout<<"NO"<<endl;
	return 0;

}


#include<bits/stdc++.h>
using namespace std;

int adjective(char gender, string s)
{
	string tm, tf;
	if(s.size()>=4)
	tm=s.substr(s.size()-4);
	if(s.size()>=5)
		tf=s.substr(s.size()-5);
	if(gender!='M' && gender!='F')
	{
		if(tm=="lios")
			return 1;
		if(tf=="liala")
			return 2;
		else
			return -1;
	}
	// cout<<tf<<endl;
	if(tm!="lios" && tf!="liala")
		return -1;

	// cout<<" gender In: ";
	if(gender=='M' && tm=="lios")
		return 1;
	if(gender=='F' && tf=="liala")
		return 2;
	cout<<tf<<endl;
	return -1;
}

int noun(char gender, string s)
{
	string tm, tf;
	if(s.size()>=3)
		tm=s.substr(s.size()-3);
	if(s.size()>=4)
		tf=s.substr(s.size()-4);
	if(gender!='M' && gender!='F')
	{
		if(tm=="etr")
			return 3;
		if(tf=="etra")
			return 4;
		else
			return -1;
	}
	if(tm!="etr" && tf!="etra")
		return -1;
	if(gender=='M' && tm=="etr")
		return 3;
	if(gender=='F' && tf=="etra")
		return 4;
	return -1;
}

int verb(char gender, string s)
{
	string tm, tf;
	if(s.size()>=6)
	{
		tm=s.substr(s.size()-6);
		tf=s.substr(s.size()-6);
	}

	if(gender!='M' && gender!='F')
	{
		if(tm=="initis")
			return 5;
		if(tf=="inites")
			return 6;
		else
			return -1;
	}
	if(tm!="initis" && tf!="inites")
		return -1;
	if(gender=='M' && tm=="initis")
		return 5;
	if(gender=='F' && tf=="inites")
		return 6;
	return -1;
}

int main()
{
	string s;
	int t=0;
	char gender='0';
	bool flag=true;
	while(cin>>s)
	{
		if(t==-1)
		{
			flag=false;
			break;
		}
		if(gender=='0')
		{
			t=adjective(gender,s);
			if(t==-1 && s.size())
				t=noun(gender,s);
			if(t==-1)
				t=verb(gender,s);
			if(t==-1)
				flag=false;
			else
				(t%2) ? (gender='M') : (gender='F');
		}
		else
		{
			if(t<=2)
			{
				t=adjective(gender, s);
				if(t==-1)
				{
					// cout<<"adj out ";
					t=noun(gender, s);
					if(t==-1)
					{
						// cout<<"Noun out ";
						t=verb(gender,s);
					}
				}
			}
			else if(t>2)
				t=verb(gender,s);

			if(t==-1)
			{
				flag=false;
				break;
			}

		}
		// cout<<t<<gender<<endl;
	}
	(flag) ? (cout<<"YES") : (cout<<"NO");
	return 0;
}


#include<bits/stdc++.h>
using namespace std;

int adjective(char gender, string s)
{
	string tm, tf;
	if(s.size()>=4)
	tm=s.substr(s.size()-4);
	if(s.size()>=5)
		tf=s.substr(s.size()-5);
	if(gender!='M' && gender!='F')
	{
		if(tm=="lios")
			return 1;
		if(tf=="liala")
			return 2;
		else
			return -1;
	}
	// cout<<tf<<endl;
	if(tm!="lios" && tf!="liala")
		return -1;

	// cout<<" gender In: ";
	if(gender=='M' && tm=="lios")
		return 1;
	if(gender=='F' && tf=="liala")
		return 2;
	// cout<<tf<<endl;
	return -1;
}

int noun(char gender, string s)
{
	string tm, tf;
	if(s.size()>=3)
		tm=s.substr(s.size()-3);
	if(s.size()>=4)
		tf=s.substr(s.size()-4);
	if(gender!='M' && gender!='F')
	{
		if(tm=="etr")
			return 3;
		if(tf=="etra")
			return 4;
		else
			return -1;
	}
	if(tm!="etr" && tf!="etra")
		return -1;
	if(gender=='M' && tm=="etr")
		return 3;
	if(gender=='F' && tf=="etra")
		return 4;
	return -1;
}

int verb(char gender, string s)
{
	string tm, tf;
	if(s.size()>=6)
	{
		tm=s.substr(s.size()-6);
		tf=s.substr(s.size()-6);
	}

	if(gender!='M' && gender!='F')
	{
		if(tm=="initis")
			return 5;
		if(tf=="inites")
			return 6;
		else
			return -1;
	}
	if(tm!="initis" && tf!="inites")
		return -1;
	if(gender=='M' && tm=="initis")
		return 5;
	if(gender=='F' && tf=="inites")
		return 6;
	return -1;
}

int main()
{
	string s;
	int t=0;
	char gender='0';
	bool flag=true;
	bool nn=false;
	while(cin>>s)
	{
		if(t==-1)
		{
			flag=false;
			break;
		}
		if(gender=='0')
		{
			t=adjective(gender,s);
			if(t==-1 && s.size())
			{
				t=noun(gender,s);
				if(t!=-1)
					nn=true;
			}
			if(t==-1)
				t=verb(gender,s);

			if(t==-1)
				flag=false;
			else
				(t%2) ? (gender='M') : (gender='F');
		}
		else
		{
			if(t<=2)
			{
				t=adjective(gender, s);
				if(t==-1)
				{
					// cout<<"adj out ";
					t=noun(gender, s);
					if(t==-1)
					{
						flag=false;
						// cout<<"Noun out ";
						t=verb(gender,s);
					}
					else
						nn=true;
				}
			}
			// else if(t>2)
			// {
			// 	t=noun(gender, s);
			// 	t=verb(gender,s);
			// }
			else if(t>2)
			{
				if(nn)
					t=verb(gender,s);
				else
					t=-1;
			}

			if(t==-1)
			{
				flag=false;
				break;
			}

		}
		// cout<<t<<gender<<" "<<nn<<endl;
	}
	(flag) ? (cout<<"YES") : (cout<<"NO");
	return 0;
}


#include<bits/stdc++.h>
using namespace std;

int adjective(char gender, string s)
{
	string tm, tf;
	if(s.size()>=4)
	tm=s.substr(s.size()-4);
	if(s.size()>=5)
		tf=s.substr(s.size()-5);
	if(gender!='M' && gender!='F')
	{
		if(tm=="lios")
			return 1;
		if(tf=="liala")
			return 2;
		else
			return -1;
	}
	// cout<<tf<<endl;
	if(tm!="lios" && tf!="liala")
		return -1;

	// cout<<" gender In: ";
	if(gender=='M' && tm=="lios")
		return 1;
	if(gender=='F' && tf=="liala")
		return 2;
	cout<<tf<<endl;
	return -1;
}

int noun(char gender, string s)
{
	string tm, tf;
	if(s.size()>=3)
		tm=s.substr(s.size()-3);
	if(s.size()>=4)
		tf=s.substr(s.size()-4);
	if(gender!='M' && gender!='F')
	{
		if(tm=="etr")
			return 3;
		if(tf=="etra")
			return 4;
		else
			return -1;
	}
	if(tm!="etr" && tf!="etra")
		return -1;
	if(gender=='M' && tm=="etr")
		return 3;
	if(gender=='F' && tf=="etra")
		return 4;
	return -1;
}

int verb(char gender, string s)
{
	string tm, tf;
	if(s.size()>=6)
	{
		tm=s.substr(s.size()-6);
		tf=s.substr(s.size()-6);
	}

	if(gender!='M' && gender!='F')
	{
		if(tm=="initis")
			return 5;
		if(tf=="inites")
			return 6;
		else
			return -1;
	}
	if(tm!="initis" && tf!="inites")
		return -1;
	if(gender=='M' && tm=="initis")
		return 5;
	if(gender=='F' && tf=="inites")
		return 6;
	return -1;
}

int main()
{
	string s;
	int t=0;
	char gender='0';
	bool flag=true;
	bool nn=false;
	while(cin>>s)
	{
		if(t==-1)
		{
			flag=false;
			break;
		}
		if(gender=='0')
		{
			t=adjective(gender,s);
			if(t==-1 && s.size())
			{
				t=noun(gender,s);
				if(t!=-1)
					nn=true;
			}
			if(t==-1)
				t=verb(gender,s);

			if(t==-1)
				flag=false;
			else
				(t%2) ? (gender='M') : (gender='F');
		}
		else
		{
			if(t<=2)
			{
				t=adjective(gender, s);
				if(t==-1)
				{
					// cout<<"adj out ";
					t=noun(gender, s);
					if(t==-1)
					{
						flag=false;
						// cout<<"Noun out ";
						t=verb(gender,s);
					}
				}
			}
			// else if(t>2)
			// {
			// 	t=noun(gender, s);
			// 	t=verb(gender,s);
			// }
			else if(t>2)
			{
				if(nn)
					t=verb(gender,s);
				else
					t=-1;
			}

			if(t==-1)
			{
				flag=false;
				break;
			}

		}
		// cout<<t<<gender<<" "<<nn<<endl;
	}
	(flag) ? (cout<<"YES") : (cout<<"NO");
	return 0;
}


#include<bits/stdc++.h>
using namespace std;

int adjective(char gender, string s)
{
	string tm, tf;
	if(s.size()>=4)
	tm=s.substr(s.size()-4);
	if(s.size()>=5)
		tf=s.substr(s.size()-5);
	if(gender!='M' && gender!='F')
	{
		if(tm=="lios")
			return 1;
		if(tf=="liala")
			return 2;
		else
			return -1;
	}
	// cout<<tf<<endl;
	if(tm!="lios" && tf!="liala")
		return -1;

	// cout<<" gender In: ";
	if(gender=='M' && tm=="lios")
		return 1;
	if(gender=='F' && tf=="liala")
		return 2;
	// cout<<tf<<endl;
	return -1;
}

int noun(char gender, string s)
{
	string tm, tf;
	if(s.size()>=3)
		tm=s.substr(s.size()-3);
	if(s.size()>=4)
		tf=s.substr(s.size()-4);
	if(gender!='M' && gender!='F')
	{
		if(tm=="etr")
			return 3;
		if(tf=="etra")
			return 4;
		else
			return -1;
	}
	if(tm!="etr" && tf!="etra")
		return -1;
	if(gender=='M' && tm=="etr")
		return 3;
	if(gender=='F' && tf=="etra")
		return 4;
	return -1;
}

int verb(char gender, string s)
{
	string tm, tf;
	if(s.size()>=6)
	{
		tm=s.substr(s.size()-6);
		tf=s.substr(s.size()-6);
	}

	if(gender!='M' && gender!='F')
	{
		if(tm=="initis")
			return 5;
		if(tf=="inites")
			return 6;
		else
			return -1;
	}
	if(tm!="initis" && tf!="inites")
		return -1;
	if(gender=='M' && tm=="initis")
		return 5;
	if(gender=='F' && tf=="inites")
		return 6;
	return -1;
}

int main()
{
	string s;
	int t=0;
	char gender='0';
	bool flag=true;
	bool nn=false;
	int count=0;
	while(cin>>s)
	{
		count++;
		if(t==-1)
		{
			flag=false;
			break;
		}
		if(gender=='0')
		{
			t=adjective(gender,s);
			if(t==-1 && s.size())
			{
				t=noun(gender,s);
				if(t!=-1)
					nn=true;
			}
			if(t==-1)
				t=verb(gender,s);

			if(t==-1)
				flag=false;
			else
				(t%2) ? (gender='M') : (gender='F');
		}
		else
		{
			if(t<=2)
			{
				t=adjective(gender, s);
				if(t==-1)
				{
					// cout<<"adj out ";
					t=noun(gender, s);
					if(t==-1)
					{
						flag=false;
						// cout<<"Noun out ";
						t=verb(gender,s);
					}
					else
						nn=true;
				}
			}
			// else if(t>2)
			// {
			// 	t=noun(gender, s);
			// 	t=verb(gender,s);
			// }
			else if(t>2)
			{
				if(nn)
					t=verb(gender,s);
				else
					t=-1;
			}

			if(t==-1)
			{
				flag=false;
				break;
			}

		}
		// cout<<t<<gender<<" "<<nn<<endl;
	}
	if(count>1 && !nn)
		flag=false;
	(flag) ? (cout<<"YES") : (cout<<"NO");
	return 0;
}