using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _1709A
{
    internal class Program
    {
        static void Main(string[] args)
        {
            int t = Convert.ToInt32(Console.ReadLine());
            while (t-- > 0)
            {
                int n = Convert.ToInt32(Console.ReadLine());
                int[] array = new int[3];
                var line = Console.ReadLine();
                var data = line.Split(' ');
                for (int i = 0; i < 3; i++)
                {
                    array[i] = int.Parse(data[i]);
                    // Console.WriteLine(array[i]);
                }
                bool test = true;
                if (array[n - 1] != 0)
                {
                    for (int i = 0; i < 3; i++)
                    {
                        if (array[i] == i + 1)
                            test = false;

                    }
                }
                else test = false;
               if (test)
                {
                    Console.WriteLine("YES");
                }
                else
                {
                    Console.WriteLine("NO");
                }

            }
        }
    }
}

int t = Convert.ToInt32(Console.ReadLine());
while (t > 0)
{
    int x = Convert.ToInt32(Console.ReadLine());
    string[] tokens = Console.ReadLine().Split();
    int a = int.Parse(tokens[0]);
    int b = int.Parse(tokens[1]);
    int c = int.Parse(tokens[2]);
    List<int> lst = new List<int> { a, b, c};
    if((x == 1 && lst[0] == 0) || (x == 2 && lst[1] == 0) || (x == 3 && lst[2] == 0))
    {
        Console.WriteLine("NO");
    }
    else
    {
        x = lst[x - 1];
        if(x == 1 && lst[0] == 0 || x == 2 && lst[1] == 0 || x == 3 && lst[2] == 0)
        {
            Console.WriteLine("NO");
        }
        else Console.WriteLine("YES");
    }
    t--;
}

using System;
using System.Collections.Generic;
using System.Linq;

namespace Testings
{
    public class Program
    {
        static void Main(string[] args)
        {
            int testCases = Int32.Parse(Console.ReadLine());
            while (testCases != 0){
                int firstKey = Int32.Parse(Console.ReadLine()) - 1;
                int[] doorArray = Console.ReadLine().Split(' ').Select(s => Int32.Parse(s)).ToArray();

                Console.WriteLine(doorArray[firstKey] != 0 && doorArray[doorArray[firstKey] - 1] != 0 ? "YES" : "NO");
                testCases--;
            };
        }

    }
}

using System.ComponentModel;
using System.Reflection.Metadata.Ecma335;
using System.Text.RegularExpressions;
using System;
using System.Linq;

namespace codeforces
{
    class Program
    {
        //1511/A. Review Site
        static void Main(string[] args)
        {
            int t = int.Parse(Console.ReadLine());

            while (t-- > 0)
            {
                int mykey = int.Parse(Console.ReadLine());

                var doors = Console.ReadLine().Split(" ").Select(int.Parse).ToArray();

                if (doors[mykey-1] != 0 && doors[doors[mykey-1]-1] != 0)
                    Console.WriteLine("YES");
                else
                Console.WriteLine("NO");

            }

        }

    }
}

int n = int.Parse(Console.ReadLine());
for (int i = 0; i < n; i++)
{
    int key = int.Parse(Console.ReadLine());
    int[] doors = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);
    Console.WriteLine(doors[key - 1] != 0 && doors[doors[key - 1] - 1] != 0 ? "YES" : "NO");
}

int n = int.Parse(Console.ReadLine());
            for (int i = 0; i < n; i++)
            {
                int key = int.Parse(Console.ReadLine());
                int[] doors = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);
                bool flag = true;
                for (int j = 0; j < doors.Length - 1; j++)
                {
                    key = doors[key - 1];
                    if (key == 0)
                    {
                        flag = false;
                        break;
                    }
                }
                Console.WriteLine(flag ? "YES" : "NO");
            }

using System;
using System.Linq;
using System.Collections.Generic;

namespace CodeForces_CS
{
    internal class Program
    {
        static void Main(string[] args)
        {
            int t = Convert.ToInt32(Console.ReadLine());

            while(t-- > 0)
            {
                int key = Convert.ToInt32(Console.ReadLine());

                string s = Console.ReadLine();
                int[] arr = s.Split(' ').Select(int.Parse).ToArray();

                int index = 0;

                while(true)
                {
                    key = arr[key - 1];
                    index++;
                    if (key == 0) break;

                }

                if (index != 3) Console.WriteLine("NO");
                else Console.WriteLine("YES");

                //Console.WriteLine(index);
            }
        }
    }
}

int tc = int.Parse(Console.ReadLine());
string[] results = new string[tc];

for (int t = 0; t < tc; t++)
{
    int x = int.Parse(Console.ReadLine());
    int[] keysBehindDoors = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();

    var keysObtained = 1;
    string textResult = "YES";

    int i = x - 1;
    while (keysObtained != keysBehindDoors.Length)
    {
        if (keysBehindDoors[i] == 0)
        {
            textResult = "NO";
            break;
        }

        i = keysBehindDoors[i] - 1;
        keysObtained++;
    }

    results[t] = textResult;
}

foreach(var r in results) Console.WriteLine(r);

/* #codeforceio #contestio #yandexcupio #csharp
 * task: input output template contests
*/

using System;
using System.Linq;

namespace CodeforcesByTDD.gen20220722003800
{
    public class Program
    {
        static void ToSolve()
        {
        }

        static void Main()
        {
            var setOfData = int.Parse(Console.ReadLine());
            for(var dataIndex = 0; dataIndex < setOfData; ++dataIndex)
            {
                var key = int.Parse(Console.ReadLine());
                var doors = Console.ReadLine().Split(new char[] {' '}).Select(number => int.Parse(number)).ToArray();
                if (doors[key - 1] == 0)
                {
                    Console.WriteLine("NO");
                    continue;
                }
                if (doors[doors[key - 1] - 1] == 0)
                {
                    Console.WriteLine("NO");
                    continue;
                }
                Console.WriteLine("YES");
            }
        }
    }
}

// solved by: asmjaime

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

public sealed class CodeForces
{
    private static void Main()
    {
        int t = int.Parse(Console.ReadLine());
        for (int i = 0; i < t; i++)
        {
            int x = int.Parse(Console.ReadLine());
            int[] doors = intArr(Console.ReadLine());
            Console.WriteLine(Solve(doors, x));
        }
    }

    private static int[] intArr(string input)
    {
        return input.Split(' ').Select(int.Parse).ToArray();
    }

    private static string Solve(int[] doors, int x)
    {
        int firstKey = doors[x - 1];
        int secondKey = firstKey > 0 ? doors[firstKey - 1] : 0;
        return firstKey > 0 && secondKey > 0 ? "YES" : "NO";
    }
}

using System;
using System.Collections.Generic;
class Program
{
    public static void Main(string[] args)
    {
        //write code here
        int T, x;

        T = int.Parse(Console.ReadLine());

        while(T -- > 0)
        {
            bool[] open = new bool[5];
            x = int.Parse(Console.ReadLine());
            open[x] = true;

            string str = Console.ReadLine();
            string[] strs = str.Split(' ');

            for(int i = 0; i < strs.Length; i++)
            {
                x = int.Parse(strs[x - 1]);
                if (x == 0)
                    break;
                open[x] = true;
            }

            bool p = true;

            for(int i = 1; i <= 3; i++)
            {
                if (open[i] == false)
                    p = false;
            }

            if(p == true)
                Console.WriteLine("YES");
            else
                Console.WriteLine("NO");
        }
    }
}

int t = int.Parse(Console.ReadLine());
while (t-- > 0)
{
    int k = int.Parse(Console.ReadLine());
    int[] a = ("0 "+ Console.ReadLine()).Split().Select(int.Parse).ToArray();
    Console.WriteLine(a[a[k]] == 0 ? "NO" : "YES");
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
using System.Threading;

namespace A
{
    class Program
    {
        static void Main(string[] args)
        {
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
            int tc = 1;
            tc = int.Parse(Console.ReadLine());
            while (tc-- > 0)
            {
                solve();
            }
        }

        // write your code in solve function
        static void solve()
        {
            int x = int.Parse(Console.ReadLine());
            int[] a = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
            bool[] open = new bool[3];
            open[x - 1] = true;

            while (a[x - 1] != 0)
            {
                x = a[x - 1];
                open[x - 1] = true;
            }

            bool ok = true;
            for (int i = 0; i < 3; i++ ) {
                if (!open[i])
                    ok = false;
            }

            Console.WriteLine((ok) ? "YES" : "NO");
        }
    }
}

using System;
using System.Linq;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Text;
using System.Numerics;

public class Test
{
    private static readonly Random r = new Random();
    public static void Main()
    {
        var t = GetInt();
        for (int i = 0; i < t; i++)
            Solve();
    }

    public static bool IsVowel(char c) => c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';

    public static void Solve()
    {
        int key = GetInt();
        key--;
        var locks = GetIntArray();
        bool canOpen = true;
        //try lock1
        if (locks[key] == 0)
            canOpen = false;
        else
        {
            key = locks[key] - 1;
            //try lock2
            if (locks[key] == 0)
                canOpen = false;
            else
            {
                //key = locks[key] - 1;
                ////try lock3
                //if (locks[key] == 0)
                //    canOpen = false;
                //else
                //{
                //    key = locks[key] - 1;
                //}
            }
        }
        string ans = canOpen ? "YES" : "NO";
#if DEBUG
        Console.Write("Answer is --------------> ");
#endif
        Console.WriteLine(String.Join(" ",ans));
    }

    public static int GetInt() => int.Parse(Console.ReadLine());
    public static long GetLong() => long.Parse(Console.ReadLine());

    public static int[] GetIntArray() => Console.ReadLine().Trim().Split(' ').Select(int.Parse).ToArray();
    public static long[] GetLongArray() => Console.ReadLine().Trim().Split(' ').Select(long.Parse).ToArray();

    public static int Gcd(int a, int b) => b == 0 ? a : Gcd(b, a % b);
    public static int Gcd(int[] n) => n.Aggregate((a, b) => Gcd(a, b));

    public static bool IsBitSet(long a, int bit)
    {
        return (a & (1L << bit)) != 0;
    }
}

int count = int.Parse(Console.ReadLine());
for (int i = 0; i < count; i++)
{
    int curr = int.Parse(Console.ReadLine());
    int OpenDoor = 0;
    int[] arr = Console.ReadLine().Split().Select(x=>int.Parse(x)).ToArray();
    while (curr != 0)
    {
        curr = arr[curr - 1];
        OpenDoor++;
    }
    if (OpenDoor == arr.Length) Console.WriteLine("YES");
    else Console.WriteLine("NO");
}

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ForTestCSharp
{
    internal static class Program
    {
        private const bool hasFewCases = true;

        private static readonly StringBuilder output = new();

        public static void Main(string[] args)
        {
            var caseCount = hasFewCases ? int.Parse(Console.ReadLine()) : 1;

            while (caseCount-- > 0)
            {
                Solve();
            }

            Console.WriteLine(output);
        }

        private static void Solve()
        {
            var key = int.Parse(Console.ReadLine());
            var doors = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();

            var toOpen = 3;

            while (key != 0 && toOpen > 0)
            {
                key = doors[key - 1];
                toOpen--;
            }

            output.AppendLine(toOpen == 0 ? "YES" : "NO");
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Specialized;
using System.Collections;
using System.Numerics;
using System.Text.RegularExpressions;

namespace basicDS6
{
    public class st
    {
        private int MOD = 1000000007;
        public void Test()
        {
            int n = int.Parse(Console.ReadLine());
            //var s = Console.ReadLine();
            var nums = Console.ReadLine().Split(' ').Select(ti => int.Parse(ti)).ToList();
            int res = 0;
            var d = new Dictionary<int, int>();
            d.Add(1, nums[0]);
            d.Add(2, nums[1]);
            d.Add(3, nums[2]);
            for (int i = 1; i < 3; i++)
            {
                if (d[n] == 0)
                {
                    res = 1;
                    break;
                }
                n = d[n];
            }
            if (res == 0) Console.WriteLine("YES");
            else Console.WriteLine("NO");
        }

        static void Main()
        {
            st p = new st();
            int T = int.Parse(Console.ReadLine());
            for (int test_no = 1; test_no < T + 1; test_no++)
            {
                p.Test();
            }
        }
    }
}

using System.Text;

StringBuilder output = new StringBuilder();
long t = ReadNum();
while (t-- > 0)
{
    long x = ReadNum();
    long[] a = ReadNumArray();

    long ans = 1;

    while (a[x - 1] > 0)
    {
        ans++;
        x = a[x - 1];
    }

    output.AppendLine(ans == 3 ? "YES" : "NO");
}
Console.Write(output.ToString());

long ReadNum() => long.Parse(Console.ReadLine());
long[] ReadNumArray() => Array.ConvertAll(Console.ReadLine().Split(' '), long.Parse);
(long, long) ReadTwoNum() { long[] a = ReadNumArray(); return (a[0], a[1]); }
(long, long, long) ReadThreeNum() { long[] a = ReadNumArray(); return (a[0], a[1], a[2]); }

using System;
using System.Collections.Generic;

namespace CF1709A_Three_Doors
{
    class Program
    {
        static void Main(string[] args)
        {
            int t = int.Parse(Console.ReadLine());

            for(int i = 1; i <= t; i++)
            {
                int x = int.Parse(Console.ReadLine());
                int[] keysBehind = Array.ConvertAll(Console.ReadLine().Split(' '), s => int.Parse(s));
                IDictionary<int, bool> doorUnlock = new Dictionary<int, bool>()
                {
                    { 1, false },
                    { 2, false },
                    { 3, false }
                };

                int count = 1;
                int key = x;
                bool flag = true;

                int key1 = 0, key2 = 0, key3 = 0;
                doorUnlock[key] = true;

                if (key > 0 && doorUnlock[key] == true)
                {
                    key1 = keysBehind[key - 1];
                    doorUnlock[key1] = true;
                }
                else
                    flag = false;

                if (key1 > 0 && doorUnlock[key1] == true)
                {
                    key2 = keysBehind[key1 - 1];
                    doorUnlock[key2] = true;
                }
                else
                    flag = false;

                if (key2 > 0 && doorUnlock[key2] == true)
                {
                    key3 = keysBehind[key2 - 1];
                    doorUnlock[key3] = true;
                }
                else
                    flag = false;

                if(flag)
                    Console.WriteLine("YES");
                else
                    Console.WriteLine("NO");
            }
        }
    }
}

var input = Convert.ToInt32(Console.ReadLine());

for (int i = 1; i <= input; i++)
{
    var input2= Convert.ToInt32(Console.ReadLine());

    var inputArr = Console.ReadLine().Split(' ').Select(x=>int.Parse(x)).ToArray();
    int j = 0;
    var count = 0;
    var value = input2;

    while (true)
    {

       var  temp = inputArr[value-1];
        if (temp == 0)
        {
            count++;
            break;
        }
        else if (temp > 0)
        {
            value = temp;
            count++;

        }

            j++;
        if (j == 3)
            break;

    }

    if (count == 3)
        Console.WriteLine("YES");
    else
        Console.WriteLine("NO");
}

var t = int.Parse(Console.ReadLine()!);

while (t-- > 0)
{
    var x = int.Parse(Console.ReadLine()!);

    var array = Console.ReadLine()!.Split(" ").Select(int.Parse).ToList();

    var a = array[0];
    var b = array[1];
    var c = array[2];

    var doorOpened = 0;

    switch (x)
    {
        case 1:
            doorOpened++;
            x = a;
            break;
        case 2:
            doorOpened++;
            x = b;
            break;
        case 3:
            doorOpened++;
            x = c;
            break;
    }

    switch (x)
    {
        case 1:
            doorOpened++;
            x = a;
            break;
        case 2:
            doorOpened++;
            x = b;
            break;
        case 3:
            doorOpened++;
            x = c;
            break;
    }

    switch (x)
    {
        case 1:
            doorOpened++;
            break;
        case 2:
            doorOpened++;
            break;
        case 3:
            doorOpened++;
            break;
    }

    Console.WriteLine(doorOpened == 3 ? "YES" : "NO");
}

using System.Numerics;
using System.Text;

int intTemp = Convert.ToInt32(Console.ReadLine());
for (int index = 0; index < intTemp; index++)
{
    int x = Convert.ToInt32(Console.ReadLine());

    //Read line, and split it by whitespace into an array of strings
    string[] tokens = Console.ReadLine().Split();
    //Parse element 0
    var arr = new int[3];
    arr[0] = int.Parse(tokens[0]);
    //Parse element 1
    arr[1] = int.Parse(tokens[1]);
    arr[2] = int.Parse(tokens[2]);

    var firstNum = arr[x - 1];//2
    if(firstNum != 0)
    {
        var sec = arr[firstNum - 1];//1
        if(sec != 0)
        {
            var third=arr[sec-1];
            if(third == 0)
            {
                Console.WriteLine("YES");

            }
            else
            {
                Console.WriteLine("NO");
            }
        }
        else
        {
            Console.WriteLine("NO");
        }
    }
    else
    {
        Console.WriteLine("NO");
    }

}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace A
{
    class Program
    {
        static void Main(string[] args)
        {
            int t = int.Parse(Console.ReadLine());
            for (int i = 0; i<t; i++)
            {
                int k = int.Parse(Console.ReadLine());
                int[] mass = Console.ReadLine().Split(' ').Select(x => int.Parse(x)).ToArray();
                int s = 0;
                while (mass[k-1] != 0)
                {
                    k = mass[k - 1];
                    s = s + 1;
                }
                s = s + 1;
                if (s < mass.Length)
                {
                    Console.WriteLine("NO");
                }
                else
                {
                    Console.WriteLine("YES");
                }

            }
        }
    }
}

using System;
using System.Linq;
using CompLib.Util;
using System.Threading;
using System.IO;

public class Program
{

    public void Solve()
    {
        var sc = new Scanner();
#if !DEBUG
        System.Console.SetOut(new System.IO.StreamWriter(System.Console.OpenStandardOutput()) { AutoFlush = false });
#endif
        int t = sc.NextInt();
        for (int i = 0; i < t; i++)
        {
            Query(sc);
        }
        System.Console.Out.Flush();
    }

    void Query(Scanner sc)
    {
        int x = sc.NextInt();
        int[] a = sc.IntArray();

        var b = new bool[3];
        var k = new Queue<int>();
        k.Enqueue(x-1);

        while (k.Count > 0)
        {
            int q = k.Dequeue();
            if (a[q] != 0)
            {
                // Console.WriteLine($"d={q}");
                k.Enqueue(a[q] - 1);
                a[q] = 0;
            }
        }

        for (int i = 0; i < 3; i++)
        {
            if (a[i] != 0)
            {
                Console.WriteLine("NO");
                return;
            }
        }

        Console.WriteLine("YES");
    }

    public static void Main(string[] args) => new Program().Solve();
    // public static void Main(string[] args) => new Thread(new Program().Solve, 1 << 27).Start();
}

namespace CompLib.Util
{
    using System;
    using System.Linq;

    class Scanner
    {
        private string[] _line;
        private int _index;
        private const char Separator = ' ';

        public Scanner()
        {
            _line = new string[0];
            _index = 0;
        }

        public string Next()
        {
            if (_index >= _line.Length)
            {
                string s;
                do
                {
                    s = Console.ReadLine();
                } while (s.Length == 0);

                _line = s.Split(Separator);
                _index = 0;
            }

            return _line[_index++];
        }

        public string ReadLine()
        {
            _index = _line.Length;
            return Console.ReadLine();
        }

        public int NextInt() => int.Parse(Next());
        public long NextLong() => long.Parse(Next());
        public double NextDouble() => double.Parse(Next());
        public decimal NextDecimal() => decimal.Parse(Next());
        public char NextChar() => Next()[0];
        public char[] NextCharArray() => Next().ToCharArray();

        public string[] Array()
        {
            string s = Console.ReadLine();
            _line = s.Length == 0 ? new string[0] : s.Split(Separator);
            _index = _line.Length;
            return _line;
        }

        public int[] IntArray() => Array().Select(int.Parse).ToArray();
        public long[] LongArray() => Array().Select(long.Parse).ToArray();
        public double[] DoubleArray() => Array().Select(double.Parse).ToArray();
        public decimal[] DecimalArray() => Array().Select(decimal.Parse).ToArray();
    }
}

using System.Text;
using static System.Math;
using static System.Console;

var q = int.Parse(ReadLine()!);
var ansBuilder = new StringBuilder();

while (q-- > 0)
{
    var key = int.Parse(ReadLine()!);
    var inputs = ReadLine()!.Split(" ").Select(int.Parse).ToArray();
    var current = key - 1;
    var count = 0;
    while (current >= 0)
    {
        current = inputs[current] - 1;
        ++count;
    }

    ansBuilder.Append(count >= 3 ? "YES\n" : "NO\n");
}
WriteLine(ansBuilder.ToString());

using System;
using System.Linq;

int n = int.Parse(Console.ReadLine());

for (int i = 0; i < n; i++)
{
    int keyNum = int.Parse(Console.ReadLine());
    int[] doors = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
    int tryNumber = 1;
    while (true)
    {
        if (doors[keyNum - 1] == 0 || tryNumber == 3)
        {
            break;
        }

        keyNum = doors[keyNum - 1];
        tryNumber++;
    }

    if (tryNumber == 3)
    {
        Console.WriteLine("YES");
    }
    else
    {
        Console.WriteLine("NO");
    }
}

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;

namespace ConsoleApp
{
    public struct Vector
    {
        public double X;
        public double Y;
        public double Atan2 => Math.Atan2(Y, X);
        public double LengthSquared => (X * X) + (Y * Y);
        public double Length => Math.Sqrt(LengthSquared);

        public Vector(double x, double y)
        {
            X = x;
            Y = y;
        }

        public bool EqualsTo(Vector other, double epsilon = Compare.defaultEpsilon)
        {
            return Compare.Equal(this.X, other.X, epsilon) && Compare.Equal(this.Y, other.Y, epsilon);
        }
        public override string ToString()
        {
            return string.Format("{0:F3} {1:F3}", X, Y);
        }

        public static double DotProduct(Vector left, Vector right)
        {
            return (left.X * right.X) + (left.Y * right.Y);
        }
        public static double Determinant(Vector left, Vector right)
        {
            return (left.X * right.Y) - (left.Y * right.X);
        }
        public static double AngleBetween(Vector left, Vector right)
        {
            return Math.Acos(DotProduct(left, right) / (left.Length * right.Length));
        }
        public static Vector operator +(Vector p)
        {
            return p;
        }
        public static Vector operator -(Vector p)
        {
            return new Vector(-p.X, -p.Y);
        }
        public static Vector operator +(Vector left, Vector right)
        {
            return new Vector(left.X + right.X, left.Y + right.Y);
        }
        public static Vector operator -(Vector left, Vector right)
        {
            return left + -right;
        }
        public static Vector operator *(Vector v, double k)
        {
            return new Vector(v.X * k, v.Y * k);
        }
        public static Vector operator /(Vector v, double k)
        {
            return new Vector(v.X / k, v.Y / k);
        }
        public static bool operator ==(Vector left, Vector right)
        {
            return (left.X == right.X) && (left.Y == right.Y);
        }
        public static bool operator !=(Vector left, Vector right)
        {
            return !(left == right);
        }
    }
    public static class Compare
    {
        public const double defaultEpsilon = 1e-13;
        public static bool Equal(double a, double b, double epsilon = defaultEpsilon)
        {
            return Math.Abs(a - b) < epsilon;
        }
        public static bool Less(double a, double b, double epsilon = defaultEpsilon)
        {
            return (a < b) && !Equal(a, b, epsilon);
        }
        public static bool LessEqual(double a, double b, double epsilon = defaultEpsilon)
        {
            return (a < b) || Equal(a, b, epsilon);
        }
        public static bool Greater(double a, double b, double epsilon = defaultEpsilon)
        {
            return (a > b) && !Equal(a, b, epsilon);
        }
        public static bool GreaterEqual(double a, double b, double epsilon = defaultEpsilon)
        {
            return (a > b) || Equal(a, b, epsilon);
        }
    }
    public static class Algebra
    {
        private static void Swap(ref int a, ref int b)
        {
            int temp = a;
            a = b;
            b = temp;
        }
        private static void Swap(ref long a, ref long b)
        {
            long temp = a;
            a = b;
            b = temp;
        }

        public static int GCD(int a, int b)
        {
            while (b != 0)
            {
                a %= b;
                Swap(ref a, ref b);
            }

            return a;
        }
        public static long GCD(long a, long b)
        {
            while (b != 0)
            {
                a %= b;
                Swap(ref a, ref b);
            }

            return a;
        }
        public static int LCM(int a, int b)
        {
            return (a / GCD(a, b)) * b;
        }
        public static long LCM(long a, long b)
        {
            return (a / GCD(a, b)) * b;
        }
        public static bool IsPrime(int val)
        {
            if (val < 2)
            {
                return false;
            }

            for (int i = 2; i * i <= val; i++)
            {
                if (val % i == 0)
                {
                    return false;
                }
            }
            return true;
        }
        public static long QuickPow(int val, uint power)
        {
            long result = 1;

            while (power > 0)
            {
                if ((power & 1) == 1)
                {
                    result *= val;
                }

                val *= val;
                power >>= 1;
            }

            return result;
        }
    }
    public static class Geometry
    {
        public static List<Vector> GetConvexPolygon(List<Vector> points)
        {
            Vector bottomLeft = points[0];
            foreach (Vector point in points)
            {
                if (point.Y < bottomLeft.Y)
                {
                    bottomLeft = point;
                }
                else if (point.Y == bottomLeft.Y && point.X < bottomLeft.X)
                {
                    bottomLeft = point;
                }
            }

            List<Vector> temp = new List<Vector>();
            foreach (Vector point in points)
            {
                if (point == bottomLeft)
                {
                    continue;
                }

                temp.Add(point - bottomLeft);
            }
            temp.Sort(new VectorAtanComparer());

            Stack<Vector> polygon = new Stack<Vector>();
            polygon.Push(new Vector());

            foreach (Vector next in temp)
            {
                if (polygon.Count < 2)
                {
                    polygon.Push(next);
                    continue;
                }

                while (polygon.Count > 1)
                {
                    Vector current = polygon.Pop();
                    Vector previous = polygon.Peek();

                    if (Vector.Determinant(next - current, previous - current) > 0)
                    {
                        polygon.Push(current);
                        break;
                    }
                }
                polygon.Push(next);
            }

            List<Vector> result = new List<Vector>();
            result.Add(new Vector());
            result.AddRange(polygon);
            return result;
        }
    }
    public class VectorAtanComparer : IComparer<Vector>
    {
        public int Compare(Vector left, Vector right)
        {
            double a = left.Atan2;
            double b = right.Atan2;

            if (a < b)
            {
                return -1;
            }
            else if (a > b)
            {
                return 1;
            }
            else
            {
                a = left.LengthSquared;
                b = right.LengthSquared;

                if (a < b)
                {
                    return -1;
                }
                else if (a > b)
                {
                    return 1;
                }
                else
                {
                    return 0;
                }
            }
        }
    }

    public class Program
    {
        static Program()
        {
            CultureInfo cultureInfo = (CultureInfo)CultureInfo.CurrentCulture.Clone();
            cultureInfo.NumberFormat.NumberDecimalSeparator = ".";
            CultureInfo.CurrentCulture = cultureInfo;

            const bool useFiles = false;

            if (useFiles)
            {
                const bool useCustomFileNames = false;
                const string customFileName = "data";

                Console.SetIn(new StreamReader(useCustomFileNames ? customFileName + ".in" : "input.txt"));
                Console.SetOut(new StreamWriter(useCustomFileNames ? customFileName + ".out" : "output.txt"));
            }
        }
        public static string[] ReadStringData()
        {
            return Console.ReadLine()
                ?.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                .ToArray() ?? Array.Empty<string>();
        }
        public static int[] ReadIntData()
        {
            return Console.ReadLine()
                ?.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                .Select(str => int.Parse(str))
                .ToArray() ?? Array.Empty<int>();
        }
        public static long[] ReadLongData()
        {
            return Console.ReadLine()
                ?.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                .Select(str => long.Parse(str))
                .ToArray() ?? Array.Empty<long>();
        }
        public static double[] ReadDoubleData()
        {
            return Console.ReadLine()
                ?.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                .Select(str => double.Parse(str))
                .ToArray() ?? Array.Empty<double>();
        }
        public static void Main()
        {
            int testCases = int.Parse(Console.ReadLine());

            for (int z = 0; z < testCases; z++)
            {
                int x = int.Parse(Console.ReadLine()) - 1;

                int[] keys = ReadIntData().Select(val => val - 1).ToArray();

                bool[] isOpened = new bool[3];
                while (x != -1 && !isOpened[x])
                {
                    isOpened[x] = true;
                    x = keys[x];
                }

                Console.WriteLine(isOpened.All(val => val) ? "YES" : "NO");
            }

            Console.Out.Flush();
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CodeForces800
{
    internal static class Program
    {
        public static void Main()
        {
            var str = Console.ReadLine().Split(' ').Select(x => Int32.Parse(x.ToString())).ToList();
            var rep = str[0];
            for (var iter = 0; iter < rep; iter++)
            {
                str = Console.ReadLine().Split(' ').Select(x => Int32.Parse(x.ToString())).ToList();
                var n = str[0];
                str = Console.ReadLine().Split(' ').Select(x => Int32.Parse(x.ToString())).ToList();
                if (str[n - 1] == 0 || str[str[n - 1] - 1] == 0)
                    Console.WriteLine("NO");
                else
                    Console.WriteLine("YES");
            }
        }
    }
}

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

// ReSharper disable InconsistentNaming

namespace App
{
    [SuppressMessage("ReSharper", "SuggestVarOrType_BuiltInTypes")]
    public class Algo
    {
        private readonly StreamWriter _w;
        private readonly StreamReader _r;

        public Algo(StreamReader r, StreamWriter w)
        {
            _w = w;
            _r = r;
        }

        public void Run()
        {
            int t = _r.I();

            for (int i = 1; i <= t; i++)
            {
                Solve();
            }
        }

        private void Solve()
        {
            int k = _r.I();

            int[] doors = _r.II1(3);

            bool[] opened = new bool[4];

            while (k != 0)
            {
                opened[k] = true;
                k = doors[k];
            }

            _w.WriteYESNOLine(opened.Skip(1).All(r=>r));
        }

        class Row
        {
            public bool TryAdd(int floor, int p)
            {
                throw new NotImplementedException();
            }

            public int Min { get; }

            public int ValueUpTo(int i)
            {
                throw new NotImplementedException();
            }
        }

    }

    public static class Solution
    {
        public static void Main(string[] args)
        {
            var f = new Factory();
            var r = f.GetReader();
            var w = f.GetWriter();
            Algo p = new Algo(r, w);
            p.Run();
            w.Flush();

            f.Dispose();
        }
    }

    public interface IFactory
    {
        StreamWriter GetWriter();
        StreamReader GetReader();
        void Dispose();
    }

    public class Factory : IDisposable, IFactory
    {
        private StreamWriter _sw;
        private StreamReader _sr;

        public StreamWriter GetWriter()
        {
            return _sw = new StreamWriter(Console.OpenStandardOutput());
        }

        public StreamReader GetReader()
        {
            return _sr = new StreamReader(Console.OpenStandardInput());
        }

        public void Dispose()
        {
            _sw?.Dispose();
            _sr?.Dispose();
        }
    }

    public static class ReaderExtensions
    {
        static char[] _tokens = new char[4];

        public static ReadOnlySpan<char> NextToken(this StreamReader sr)
        {
            int size = 0;

            bool skipWhiteSpaceMode = true;
            while (true)
            {
                int nextChar = sr.Read();
                if (nextChar == -1)
                {
                    break;
                }

                char ch = (char) nextChar;
                if (char.IsWhiteSpace(ch))
                {
                    if (!skipWhiteSpaceMode)
                    {
                        if (ch == '\r' && (Environment.NewLine == "\r\n"))
                        {
                            sr.Read();
                        }

                        break;
                    }
                }
                else
                {
                    skipWhiteSpaceMode = false;
                    if (size == _tokens.Length)
                    {
                        char[] a2 = new char[_tokens.Length * 2];
                        Array.Copy(_tokens, a2, _tokens.Length);
                        _tokens = a2;
                    }

                    _tokens[size++] = ch;
                }
            }

            return new ReadOnlySpan<char>(_tokens, 0, size);
        }

        public static char C(this StreamReader sr)
        {
            while (true)
            {
                int nextChar = sr.Read();
                if (nextChar == -1)
                {
                    // End of stream reached
                    return (char) 0;
                }

                char ch = (char) nextChar;
                if (!char.IsWhiteSpace(ch))
                {
                    return ch;
                }
            }
        }

        public static int I(this StreamReader sr)
        {
            var token = new string(NextToken(sr));
            return int.Parse(token);
        }

        public static double D(this StreamReader sr, bool acceptAnyDecimalSeparator = true)
        {
            var token = NextToken(sr);
            if (acceptAnyDecimalSeparator)
            {
                var tokens = new string(token).Replace(',', '.');
                double result = double.Parse(tokens, CultureInfo.InvariantCulture);
                return result;
            }
            else
            {
                double result = double.Parse(token);
                return result;
            }
        }

        public static decimal M(this StreamReader sr, bool acceptAnyDecimalSeparator = true)
        {
            var token = NextToken(sr);
            if (acceptAnyDecimalSeparator)
            {
                var tokens = new string(token).Replace(',', '.');
                decimal result = decimal.Parse(tokens, CultureInfo.InvariantCulture);
                return result;
            }
            else
            {
                decimal result = decimal.Parse(token);
                return result;
            }
        }

        public static int[] II(this StreamReader r, int n)
        {
            int[] ret = new int[n];
            for (int i = 0; i < n; i++)
                ret[i] = r.I();

            return ret;
        }

        public static int[] II1(this StreamReader r, int n)
        {
            int[] ret = new int[n + 1];
            for (int i = 1; i < n + 1; i++)
                ret[i] = r.I();

            return ret;
        }

        public static int[] II2(this StreamReader r, int n)
        {
            int[] ret = new int[n + 2];
            for (int i = 2; i < n + 2; i++)
                ret[i] = r.I();

            return ret;
        }

        public static char[] CC(this StreamReader r, int n)
        {
            char[] ret = new char[n];
            for (int i = 0; i < n; i++)
                ret[i] = r.C();

            return ret;
        }

        public static int[] Digits(this StreamReader r, int n)
        {
            int[] ret = new int[n];
            for (int i = 0; i < n; i++)
                ret[i] = (int) (r.C() - (int) '0');

            return ret;
        }

        public static bool[] BB(this StreamReader r, int n)
        {
            bool[] ret = new bool[n];
            for (int i = 0; i < n; i++)
                ret[i] = r.C() == '1';

            return ret;
        }

        public static bool[] BB(this StreamReader r)
        {
            var token = r.NextToken();

            bool[] ret = new bool[token.Length];
            for (int i = 0; i < ret.Length; i++)
                ret[i] = token[i] == '1';

            return ret;
        }

        public static bool[] PlusesMinuses(this StreamReader r, int length)
        {
            bool[] ret = new bool[length];
            for (int i = 0; i < length; i++)
                ret[i] = r.C() == '+';

            return ret;
        }

        public static bool[] OnesZeroes(this StreamReader r, int length)
        {
            bool[] ret = new bool[length];
            for (int i = 0; i < length; i++)
                ret[i] = r.C() == '1';

            return ret;
        }

        public static Int16[] SS(this StreamReader r, int n)
        {
            Int16[] ret = new Int16[n];
            for (int i = 0; i < n; i++)
                ret[i] = Int16.Parse(r.NextToken());

            return ret;
        }

        public static long[] LL(this StreamReader r, int n)
        {
            long[] ret = new long[n];
            for (long i = 0; i < n; i++)
                ret[i] = long.Parse(r.NextToken());

            return ret;
        }

        public static long[] LL1(this StreamReader r, int n)
        {
            long[] ret = new long[n + 1];
            for (int i = 1; i < n + 1; i++)
                ret[i] = long.Parse(r.NextToken());

            return ret;
        }

        public static void WriteLine(this StreamWriter w, int i)
        {
            w.WriteLine(i.ToString());
        }

        public static void WriteLine(this StreamWriter w, char[] z)
        {
            w.WriteLine(new string(z));
        }

        public static void WriteYESNOLine(this StreamWriter w, bool b)
        {
            w.WriteLine(b ? "YES" : "NO");
        }

        public static void WriteBits(this StreamWriter w, BitArray bb)
        {
            foreach (bool b in bb)
            {
                w.Write(b ? '1' : '0');
            }

            w.WriteLine();
        }

        public static void WriteBits1(this StreamWriter w, BitArray bb)
        {
            bool first = true;
            foreach (bool b in bb)
            {
                if (first)
                {
                    first = false;
                    continue;
                }

                w.Write(b ? '1' : '0');
            }

            w.WriteLine();
        }

        public static void WriteChars1(this StreamWriter w, char[] cc)
        {
            foreach (char c in cc.Skip(1))
            {
                w.Write(c);
            }

            w.WriteLine();
        }

        public static void WriteNums1(this StreamWriter w, IEnumerable<int> nn)
        {
            w.WriteNums(nn.Skip(1));
        }

        public static void WriteNums(this StreamWriter w, IEnumerable<int> nn)
        {
            bool first = true;
            foreach (int n in nn)
            {
                if (first)
                {
                    first = false;
                }
                else
                {
                    w.Write(' ');
                }

                w.Write(n);
            }

            w.WriteLine();
        }

        public static void WriteNums(this StreamWriter w, IEnumerable<long> nn)
        {
            bool first = true;
            foreach (long n in nn)
            {
                if (first)
                {
                    first = false;
                }
                else
                {
                    w.Write(' ');
                }

                w.Write(n);
            }

            w.WriteLine();
        }
    }
}

using System;
using System.Linq;
using static System.Console;
namespace CodeFrorces
{
    class Program
    {
        static void Main()
        {
            for (int t = int.Parse(ReadLine()); t-- > 0;)
            {
                int x = int.Parse(ReadLine());
                int[] arr = Array.ConvertAll(ReadLine().Split(" "), int.Parse);
                WriteLine(arr[x - 1] == 0 || arr[arr[x - 1] - 1] == 0 ? "NO" : "YES");
            }
        }
    }
}

using System;
using System.Linq;
using static System.Console;
namespace CodeFrorces
{
    class Program
    {
        static void Main()
        {
            for (int t = int.Parse(ReadLine()); t-- > 0;)
            {
                int x = int.Parse(ReadLine());
                int[] arr = ReadLine().Split(" ").Select(int.Parse).ToArray();
                WriteLine(arr[x - 1] == 0 || arr[arr[x - 1] - 1] == 0 ? "NO" : "YES");
            }
        }
    }
}

using System;
using System.Linq;
using static System.Console;
namespace CodeFrorces
{
    class Program
    {
        static void Main()
        {
            for(int t = int.Parse(ReadLine()); t-- > 0;)
            {
                int x = int.Parse(ReadLine());
                int[] arr = ReadLine().Split(" ").Select(int.Parse).ToArray();
                if (arr[x - 1] == 0) { WriteLine("NO"); continue; }
                if (arr[arr[x-1]-1] == 0) { WriteLine("NO"); continue; }
                WriteLine("YES");
            }
        }
    }
}

using System;

namespace A.Three_Doors
{
    class Program
    {
        static void Main(string[] args)
        {
            int t = int.Parse(Console.ReadLine());
            for (int i = 0; i < t; i++)
            {
                int x = int.Parse(Console.ReadLine()) - 1;
                int[] doors = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);

                if (doors[x] == 0 || doors[doors[x] - 1] == 0)
                {
                    Console.WriteLine("NO");
                    continue;
                }
                Console.WriteLine("YES");
            }
        }
    }
}

using System;

namespace A.Three_Doors
{
    class Program
    {
        static void Main(string[] args)
        {
            int t = int.Parse(Console.ReadLine());
            for (int i = 0; i < t; i++)
            {
                int x = int.Parse(Console.ReadLine());
                int[] doors = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);

                if (doors[x - 1] == 0 || doors[doors[x - 1] - 1] == 0)
                {
                    Console.WriteLine("NO");
                    continue;
                }
                Console.WriteLine("YES");
            }
        }
    }
}

using System;

namespace ConsoleApp7
{
    class Program
    {
        static void Main(string[] args)
        {
            int t = int.Parse(Console.ReadLine());
            for (int i = 0; i < t; i++)
            {
                int x = int.Parse(Console.ReadLine());
                int[] doors = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);

                    if (doors[x - 1] == 0)
                    {
                        Console.WriteLine("NO");
                        continue;
                    }
                    if (doors[doors[x - 1] - 1] == 0)
                    {
                        Console.WriteLine("NO");
                        continue;
                    }
                    Console.WriteLine("YES");
            }
        }
    }
}

using System;

public class hello
{
    static void Main()
    {
        var t = int.Parse(Console.ReadLine().Trim());
        while (t-- > 0)
        {
            var x = int.Parse(Console.ReadLine().Trim());
            string[] line = Console.ReadLine().Trim().Split(' ');
            var a = Array.ConvertAll(line, int.Parse);
            getAns(x, a);
        }
    }
    static void getAns(int x, int[] a)
    {
        var k1 = a[x - 1];
        if (k1 == 0) { Console.WriteLine("NO"); return; }
        var k2 = a[k1 - 1];
        Console.WriteLine(k2 == 0? "NO":"YES");
    }
}

using System;
using static System.Console;
using System.Linq;
using System.Collections.Generic;

class Program
{
    static int NN => int.Parse(ReadLine());
    static int[] NList => ReadLine().Split().Select(int.Parse).ToArray();
    static int[][] NArr(int n) => Enumerable.Repeat(0, n).Select(_ => NList).ToArray();
    static void Main()
    {
        var t = NN;
        var res = new bool[t];
        for (var u = 0; u < t; ++u)
        {
            var x = NN;
            var d = NList;
            res[u] = Open(x, d);
        }
        WriteLine(string.Join("\n", res.Select(f => f ? "YES" : "NO")));
    }
    static bool Open(int x, int[] d)
    {
        if (d[x - 1] == 0) return false;
        if (d[d[x - 1] - 1] == 0) return false;
        return true;
    }
}

using System;

namespace CodeForces
{
    internal class ThreeDoors
    {
        public static void Main(string[] args)
        {
            int testcases = int.Parse(Console.ReadLine());

            for (int i = 0; i < testcases; i++)
            {
                int key = int.Parse(Console.ReadLine());

                int[] doors = new int[3];
                string[] split = Console.ReadLine().Split();

                for (int j = 0; j < 3; j++)
                {
                    doors[j] = int.Parse(split[j]);
                }

                TestPossible(key, doors);
            }
        }

        static void TestPossible(int key, int[] doors)
        {
            for (int i = 0; i < 2; i++)
            {
                key = doors[key - 1];
                if (key == 0)
                {
                    Console.WriteLine("no");
                    return;
                }
            }
            Console.WriteLine("yes");
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
	public static void Main()
	{
		int t = int.Parse(Console.ReadLine());

		while(t-- > 0)
		{
			int key = int.Parse(Console.ReadLine());
		    var input = Console.ReadLine().Split().ToList().Select(x => int.Parse(x)).ToList();
		    //int N = input[0];
		    //int K = input[1];
		    //int X = input[2];
		    //int Y = input[3];
			bool done = false;
			int count = 0;
			while(!done)
			{

				//go to door with key
				var x = input[key - 1];
				if(x == 0)
				 break;
				else{
					count++;
					key = x;
				}
				if(count == 2)
					done = true;
					if(count > 4)
					done = true;
			}
			if(done)
				Console.WriteLine("YES");
			else
				Console.WriteLine("NO");
			//Console.WriteLine(N);
			//Console.WriteLine(K);
			//Console.WriteLine(X);
			//Console.WriteLine(Y);

		}

	}
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    internal class Program
    {
        static void Main(string[] args)
        {

            int t = int.Parse(Console.ReadLine());
            for (int i = 0; i < t; i++)
            {
                int cnt = 0;
                int x = int.Parse(Console.ReadLine());
                string[] d = Console.ReadLine().Split(' ');
                for (int j = 0; j < 2; j++)
                {
                    if (d[x - 1] != "0")
                    {
                        int temp = int.Parse (d[x - 1]);
                        d[x-1] = "0";
                        cnt++;
                        x = temp;
                    }
                    else
                        break;

                }
                if (cnt==2)
                    Console.WriteLine("YES");
                else
                    Console.WriteLine("NO");
            }
            Console.ReadLine();
        }
    }
}

using System;
using System.Linq;
using System.Collections.Generic;

namespace kham
{
    class Program
    {
        static void Main(string[] args)
        {
            int t=int.Parse(Console.ReadLine());
            for (int te = 0; te < t; te++)
            {
                int key=int.Parse(Console.ReadLine())-1;
                int[] doors = Console.ReadLine().Split().Select(str => int.Parse(str)).ToArray();
                bool[] doors_opened=new bool[doors.Length];
                while (key!=-1)
                {
                    doors_opened[key]=true;
                    key= doors[key]-1;
                }
                if (!doors_opened.Any(d => !d))
                {
                    Console.WriteLine("YES");
                }
                else
                {
                    Console.WriteLine("NO");
                }

            }
        }
    }
}

using System;
using System.Linq;
using System.Text;
using System.Numerics;
using static System.Console;
using System.Collections.Generic;

using static CompLib.Algorithm;
using static CompLib.EMath;

namespace ProblemSolving.cs
{
    class MainClass
    {
        const int Mod = (int) (1e9 + 7);
        const int Def = (int) 1e9;

        static long[] OneLongLine => ReadLine().Trim().Split(' ').Select(long.Parse).ToArray();
        static int[] OneIntLine => ReadLine().Trim().Split(' ').Select(int.Parse).ToArray();
        static int[] OneCharLine => ReadLine().Trim().ToCharArray().Select(v => v - '0').ToArray();
        static long OneLong => long.Parse(ReadLine().Trim());
        static int OneInt => int.Parse(ReadLine().Trim());
        static string OneString => ReadLine().Trim();

        static void Solve()
        {
            int key = OneInt;
            var list = OneIntLine.ToList();
            int idx = list.IndexOf(0) + 1;

            if (list[key - 1] == 0 || list[list[key - 1] - 1] == 0)
            {
                WriteLine("NO");
            }
            else WriteLine("YES");

        }

        static bool Check(int[] arr)
        {
            return true;
        }

        static void Main()
        {
            int cases = OneInt;
            while (--cases >= 0)
            {
                Solve();
            }

            // Solve();
        }
    }
}

namespace CompLib
{
     public static class Algorithm
     {
         public static long LowerBound(long[] arr, long low, long high, long val)
         {
             if (low > high)
             {
                 return low;
             }

             long mid = low + (high - low) / 2;

             if (val <= arr[mid])
             {
                 return LowerBound(arr, low, mid - 1, val);
             }

             return LowerBound(arr, mid + 1, high, val);
         }

         public static long UpperBound(long[] arr, long low, long high, long val)
         {
             if (low > high || low == arr.Length)
             {
                 return low;
             }

             long mid = low + (high - low) / 2;

             if (val >= arr[mid])
             {
                 return UpperBound(arr, mid + 1, high, val);
             }

             return UpperBound(arr, low, mid - 1, val);
         }
     }

    public static class EMath
    {
        public static int Mod(int a, int m)
        {
            return (a % m + m) % m;
        }

        public static long Gcd(long a, long b)
        {
            long r;
            while (b != 0)
            {
                r = a % b;
                a = b;
                b = r;
            }

            return a;
        }

        public static long Lcm(long a, long b)
        {
            if (a > b)
            {
                return (a / Gcd(a, b)) * b;
            }

            return (b / Gcd(a, b)) * a;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Text;

namespace CF1
{
    class Program
    {
        static void Main(string[] args)
        {
            int t = Convert.ToInt32(Console.ReadLine());
            StringBuilder test = new StringBuilder();

            for (int x = 0; x < t; x++)
            {
                int n = Convert.ToInt32(Console.ReadLine()) - 1;
                string[] input = Console.ReadLine().Split(' ');
                bool one = false;
                bool two = false;
                bool three = false;

                switch (n + 1)
                {
                    case 1:
                        one = true;
                        break;
                    case 2:
                        two = true;
                        break;
                    case 3:
                        three = true;
                        break;
                }

                while (Int32.Parse(input[n]) != 0)
                {
                    switch (Int32.Parse(input[n]))
                    {
                        case 1:
                            one = true;
                            break;
                        case 2:
                            two = true;
                            break;
                        case 3:
                            three = true;
                            break;
                    }
                    n = Int32.Parse(input[n]) - 1;
                }

                if(one && two && three)
                {
                    test.AppendLine("YES");
                }
                else
                {
                    test.AppendLine("NO");
                }
            }

            Console.WriteLine(test.ToString());
            Console.ReadLine();
        }
    }
}

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace CodeForces
{
    class Program
    {
        static void Main(string[] args)
        {
            var t = Int32.Parse(Console.ReadLine());
            var res = new bool[t];
            for(var i = 0;i<t;i++)
            {
                var key = Int32.Parse(Console.ReadLine());
                var keysBehindDoor = Console.ReadLine().Split(' ').Select(item => Int32.Parse(item)).ToArray();
                res[i] = IsPossible(key, keysBehindDoor);
            }
            Console.WriteLine(string.Join('\n', res.Select(item => item ? "YES" : "NO")));
        }

        static bool IsPossible(int key, int[] keysBehindDoor)
        {
            if (keysBehindDoor[key-1] == 0)
            {
                return false;
            }
            return keysBehindDoor[keysBehindDoor[key-1]-1] != 0;
        }
    }
}

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace YKCodeForces
{
    class Program
    {
        static void Main(string[] args)
        {
            Solution s = new Solution();
            int t = int.Parse(Console.ReadLine());
            while (t > 0)
            {
                t--;
                s.Read();
                s.Solve();
            }
            Console.ReadLine();
        }

        class Solution
        {
            private int x;
            private int[] arr;

            public Solution()
            {

            }

            public void Read()
            {
                string s = Console.ReadLine();
                x = int.Parse(s);
                string[] inputArr = Console.ReadLine().Split(' ');
                arr = new int[3];
                for (int i = 0; i < 3; i++)
                {
                    arr[i] = int.Parse(inputArr[i]);
                }
            }

            public void Solve()
            {
                int cnt = 1;
                while (arr[x - 1] != 0)
                {
                    int nextKey = arr[x - 1];
                    arr[x - 1] = 0;
                    x = nextKey;
                    cnt++;
                }
                if (cnt == 3)
                {
                    Console.WriteLine("YES");
                }
                else
                {
                    Console.WriteLine("NO");
                }
            }
        }
    }
}

using System;
using System.Linq;
using System.Numerics;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using N = System.Int64;

static class Program
{
    static public void Main(string[] args)
    {
        Console.SetOut(new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false });
        var solver = new Solver();
        solver.Solve();
        Console.Out.Flush();
    }
}

public class Solver
{
    public void Solve()
    {
        int casecount = ri;
        for (int count = 0; count < casecount; count++)
        {
            int x = ri - 1;
            var a = new int[3] { ri - 1, ri - 1, ri - 1 };
            bool ans = true;
            for (int i = 0; i < 3; i++)
            {
                if (x == -1)
                {
                    ans = false;
                    break;
                }
                int t = a[x];
                a[x] = -1;
                x = t;
            }
            YN(ans);
        }
    }

    const long inf = (long)1 << 60;
    int ri { get { return (int)sc.Integer(); } }
    long rl { get { return sc.Integer(); } }
    double rd { get { return sc.Double(); } }
    string rs { get { return sc.Scan(); } }
    public StreamScanner sc = new StreamScanner(Console.OpenStandardInput());

    void WriteJoin<T>(string s, T[] t) { Console.WriteLine(string.Join(s, t)); }
    void WriteJoin<T>(string s, List<T> t) { Console.WriteLine(string.Join(s, t)); }
    void Write<T>(T t) { Console.WriteLine(t.ToString()); }
    void YN(bool t) { Console.WriteLine(t ? "YES" : "NO"); }
    void Yn(bool t) { Console.WriteLine(t ? "Yes" : "No"); }
    void yn(bool t) { Console.WriteLine(t ? "yes" : "no"); }
    void Swap(ref int x, ref int y) { x ^= y; y ^= x; x ^= y; }
    void Swap(ref N x, ref N y) { x ^= y; y ^= x; x ^= y; }
    void Swap<T>(ref T x, ref T y) { T t = y; y = x; x = t; }
}

public class StreamScanner
{
    public StreamScanner(Stream stream) { str = stream; }
    private readonly Stream str;
    private readonly byte[] buf = new byte[1024];
    private int len, ptr;
    public bool isEof = false;
    public bool IsEndOfStream { get { return isEof; } }
    private byte read()
    {
        if (isEof) throw new EndOfStreamException();
        if (ptr >= len)
        {
            ptr = 0;
            if ((len = str.Read(buf, 0, 1024)) <= 0) { isEof = true; return 0; }
        }
        return buf[ptr++];
    }
    public char Char()
    {
        byte b = 0;
        do b = read();
        while (b < 33 || 126 < b);
        return (char)b;
    }
    public string Scan()
    {
        var sb = new StringBuilder();
        for (var b = Char(); b >= 33 && b <= 126; b = (char)read()) sb.Append(b);
        return sb.ToString();
    }
    public long Integer()
    {
        long ret = 0; byte b = 0; var ng = false;
        do b = read();
        while (b != '-' && (b < '0' || '9' < b));
        if (b == '-') { ng = true; b = read(); }
        for (; true; b = read())
        {
            if (b < '0' || '9' < b) return ng ? -ret : ret;
            else ret = ret * 10 + b - '0';
        }
    }
    public double Double() { return double.Parse(Scan()); }
}

// Problem: 1709A - Three Doors
// Author: Gusztav Szmolik

using System;
using System.Text;

public class ThreeDoors {

    public static void Main () {
        StringBuilder ans = new StringBuilder ();
        byte t = byte.Parse (Console.ReadLine ());

        for (byte i = 0; i < t; i++) {
            byte x = byte.Parse (Console.ReadLine ());
            string[] parts = Console.ReadLine ().Split ();
            byte a = byte.Parse (parts[0]);
            byte b = byte.Parse (parts[1]);
            byte c = byte.Parse (parts[2]);
            byte[] doors = new byte[] { a,b,c };
            byte countDoor = 0;
            byte j = Convert.ToByte (x-1);
            bool processing = true;

            while (processing) {

                if (doors[j] == 255)
                    processing = false;

                else {
                    byte key = doors[j];
                    doors[j] = 255;
                    countDoor++;

                    if (countDoor == 3 || key == 0)
                        processing = false;

                    else
                        j = Convert.ToByte (key-1);
                }
            }

            ans.Append (countDoor == 3 ? "YES" : "NO");
            ans.AppendLine ();
        }

        Console.Write (ans);
    }
}

using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using static System.Console;
using System.Collections;

namespace leetcode
{
    class Program
    {
        static void Main(string[] args)
        {

            int t =  int.Parse(Console.ReadLine());
            while (t-- != 0)
            {
                Console.WriteLine(solver()?"YES":"NO");
            }
        }

        static long[] OneLongLine => ReadLine().Trim().Split(' ').Select(long.Parse).ToArray();
        static int[] OneIntLine => ReadLine().Trim().Split(' ').Select(int.Parse).ToArray();
        static int[] OneCharLine => ReadLine().Trim().ToCharArray().Select(v => v - '0').ToArray();
        static long OneLong => long.Parse(ReadLine().Trim());
        static int OneInt => int.Parse(ReadLine().Trim());

        static bool solver()
        {
            int a = OneInt;
            int[] b = OneIntLine;
            bool[] fa=new bool[3];
            for (int i = a-1; i < 3; i++)
            {
                if (i < 0) break;
                fa[i] = true;
                i = b[i] - 2;
            }
            return fa.All(x=>x==true);
        }

    }
}

using System;
using System.Collections.Generic;
using System.Linq;

namespace Compete2
{
    partial class MainClass
    {
        public static void Main(string[] args)
        {
            int count = int.Parse(Console.ReadLine());
            List<string> output = new List<string>();

            for (int z = 0; z < count; z++)
            {
                //Console.ReadLine();
                //var s = Console.ReadLine();
                var n = int.Parse(Console.ReadLine());
                var a = Console.ReadLine().Split(' ').Select(qw => long.Parse(qw)).ToList();
                //var b = Console.ReadLine().Split(' ').Select(qw => long.Parse(qw)).ToList();
                //var c = Console.ReadLine().Split(' ').Select(qw => long.Parse(qw)).ToList();
                //var b = long.Parse(Console.ReadLine());

                //long o = 0;
                bool can = true;

                if (a[n - 1] > 0)
                {
                    n = (int)a[n - 1];

                    if (a[n - 1] > 0)
                    {
                        n = (int)a[n - 1];
                    }
                    else
                        can = false;
                }
                else
                    can = false;

                if (can)
                    output.Add("YES");
                else
                    output.Add("NO");

                //output.Add(o.ToString());
                //output.Add(string.Join(" ", o));
            }

            output.ForEach(d => Console.WriteLine(d));
        }

    }
}

//CODE JAM
/*if (can)
    output.Add("Case #" + (z + 1).ToString() + ": " + string.Join(" ", o));
else
    output.Add("Case #" + (z + 1).ToString() + ": " + "IMPOSSIBLE");*/

//output.Add("Case #" + (z + 1).ToString() + ": " + o.ToString());

 static void Main(string[] args)
        {
            Console.WriteLine("Start");
            int testCases = Int32.Parse(Console.ReadLine());
            while (testCases != 0){
                int firstKey = Int32.Parse(Console.ReadLine()) - 1;
                int[] doorArray = Console.ReadLine().Split(' ').Select(s => Int32.Parse(s)).ToArray();

                Console.WriteLine(doorArray[firstKey] != 0 && doorArray[doorArray[firstKey] - 1] != 0 ? "YES" : "NO");
                testCases--;
            };
        }

using System;
using System.Linq;
using System.Collections.Generic;

namespace CodeForces_CS
{
    internal class Program
    {
        static void Main(string[] args)
        {
            int t = Convert.ToInt32(Console.ReadLine());

            while(t-- > 0)
            {
                int key = Convert.ToInt32(Console.ReadLine());

                string s = Console.ReadLine();
                int[] arr = s.Split(' ').Select(int.Parse).ToArray();

                int index = 0;

                while(true)
                {
                    key = arr[key - 1];
                    index++;
                    if (key == 0) break;

                }

                if (index != 3) Console.WriteLine("NO");
                else Console.WriteLine("YES");

                Console.WriteLine(index);
            }
        }
    }
}