using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// Управление общими сведениями о сборке осуществляется с помощью
// набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения,
// связанные со сборкой.

// Параметр ComVisible со значением FALSE делает типы в сборке невидимыми
// для COM-компонентов.  Если требуется обратиться к типу в этой сборке через
// COM, задайте атрибуту ComVisible значение TRUE для этого типа.

// Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM

// Сведения о версии сборки состоят из следующих четырех значений:
//
//      Основной номер версии
//      Дополнительный номер версии
//   Номер сборки
//      Редакция
//
// Можно задать все значения или принять номера сборки и редакции по умолчанию
// используя "*", как показано ниже:
// [assembly: AssemblyVersion("1.0.*")]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Numerics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OJ
{
    public partial class Program
    {
        public static List<List<int>> genBitmasks(int n)
        {
            List<List<int>> res = new List<List<int>>();
            int maxPow = (1 << n);
            for (int i = 0; i < maxPow; i++)
            {
                List<int> l = new List<int>();
                for (int j = 0; j < n; j++)
                {
                    l.Add((i >> j) % 2);
                }
                res.Add(l);
            }
            return res;
        }

        public static int gray_code(int n)
        {
            return n ^ (n >> 1);
        }

        public static int count_bits(int n)
        {
            int res = 0;
            for (; n > 0; n >>= 1)
                res += n & 1;
            return res;
        }

        public static List<List<int>> genCombinations(int n, int k)
        {
            List<List<int>> res = new List<List<int>>();
            for (int i = 0; i < (1 << n); ++i)
            {
                int cur = i;
                if (count_bits(cur) == k)
                {
                    List<int> l = new List<int>();
                    for (int j = 0; j < n; ++j)
                    {
                        if ((cur >> j) % 2 == 1)
                        {
                            l.Add(j + 1);
                        }
                    }
                    res.Add(l);
                }
            }
            return res;
        }

        static double polygoneSquare(List<Tuple<double, double>> fig)
        {
            double res = 0;
            for (int i = 0; i < fig.Count; i++)
            {
                Tuple<double, double> p1 = i > 0 ? fig[i - 1] : fig[fig.Count - 1];
                Tuple<double, double> p2 = fig[i];
                double add = (p1.Item1 - p2.Item1) * (p1.Item2 + p2.Item2);
                res += add;
            }
            return Math.Abs(res) / 2.0;
        }

        public static int fact(int n)
        {
            return n == 1 ? 1 : n * fact(n - 1);
        }

        public static List<List<int>> genPermutations(int n)
        {
            List<List<int>> res = new List<List<int>>();
            List<int> current = new List<int>();
            for (int i = 0; i < n; i++)
            {
                current.Add(i + 1);
            }

            int numberOfPerms = fact(n);

            {
                List<int> newList = new List<int>();
                newList.AddRange(current);
                res.Add(newList);
            }

            for (int i = 0; i < numberOfPerms - 1; i++)
            {
                int j = n - 2;
                while (j != -1 && current[j] > current[j + 1]) j--;
                int k = n - 1;
                while (current[j] > current[k]) k--;
                {
                    int temp = current[j];
                    current[j] = current[k];
                    current[k] = temp;
                }

                int l = j + 1, r = n - 1;
                while (l < r)
                {
                    int temp = current[l];
                    current[l] = current[r];
                    current[r] = temp;
                    l++;
                    r--;
                }

                List<int> newList = new List<int>();
                newList.AddRange(current);
                res.Add(newList);
            }

            return res;
        }

        public static long C(int n, int k, long[] fs, long mod)
        {
            long nfact = fs[n];
            long nkFact = fs[n - k];
            long kFact = fs[k];

            long invnkFact = inv(nkFact, mod);
            long invkFact = inv(kFact, mod);

            long res = nfact;
            res = (res * invnkFact) % mod;
            res = (res * invkFact) % mod;
            return res;
        }

        public static long[] modFactorials(int maxN, long mod)
        {
            long[] factorials = new long[maxN+1];
            factorials[0] = 1;
            for (int i = 1; i <= maxN; i++)
            {
                factorials[i] = (factorials[i - 1] * i) % mod;
            }
            return factorials;
        }
    }
}

namespace OJ
{
    public partial class Program
    {
        public static int SolveDPInt(DP<int> dp, params int[] args) {
            return 0;
        }

        public class DP<T>
        {
            public class MultyArray<E>
            {
                int n;
                int[] lens;
                E[] array;
                int[] ks;

                public MultyArray(params int[] lens)
                {
                    n = lens.Length;

                    this.lens = new int[n];
                    for (int i = 0; i < n; i++)
                    {
                        this.lens[i] = lens[i] + 1;
                    }

                    ks = new int[n + 1];
                    int prod = 1;
                    for (int i = 0; i < n; i++)
                    {
                        ks[i] = prod;
                        prod *= this.lens[i];
                    }
                    ks[n] = prod;

                    array = new E[prod];
                }

                public int index(params int[] args)
                {
                    int q = args.Length;
                    int res = 0;
                    for (int i = 0; i < q; i++)
                    {
                        res += args[i] * ks[i];
                    }

                    return res;
                }

                public E get(params int[] args)
                {
                    return array[index(args)];
                }

                public void set(E value, params int[] args)
                {
                    array[index(args)] = value;
                }

                public int _index(params int[] args)
                {
                    int q = args.Length;

                    int res = 0;
                    for (int i = 0; i < q; i++)
                    {
                        res += (args[i] + (lens[i] >> 1)) * ks[i];
                    }

                    /*
                    if (q == 2)
                    {
                        return (args[0] + (lens[0] << 1)) * ks[0] + (args[1] + (lens[1] >> 1)) * ks[1];
                    }

                    if(q == 1){
                        return (args[0] + (lens[0] >> 1)) * ks[0];
                    }

                    if (q == 3)
                    {
                        return (args[0] + (lens[0] >> 1)) * ks[0] + (args[1] + (lens[1] >> 1)) * ks[1] + (args[2] + (lens[2] >> 1)) * ks[2];
                    }

                    if (q == 4)
                    {
                        return (args[0] + (lens[0] >> 1)) * ks[0] + (args[1] + (lens[1] >> 1)) * ks[1] + (args[2] + (lens[2] >> 1)) * ks[2] + (args[3] + (lens[3] >> 1)) * ks[3];
                    }
                     * */

                    return res;
                }

                public E _get(params int[] args)
                {
                    return array[_index(args)];
                }

                public void _set(E value, params int[] args)
                {
                    array[_index(args)] = value;
                }

                public override string ToString()
                {
                    StringBuilder res = new StringBuilder();
                    return res.ToString();
                }
            }

            public delegate T Solve(DP<T> dp, params int[] args);

            public MultyArray<T> array;
            public MultyArray<bool> exist;
            public int[] lens;
            public int[] ks;

            private Solve solve;

            public DP(Solve solve, params int[] lens)
            {
                this.lens = lens;

                ks = new int[lens.Length + 1];
                int prod = 1;
                for (int i = 0; i < lens.Length; i++)
                {
                    ks[i] = prod;
                    prod *= this.lens[i] + 1;
                }
                ks[lens.Length] = prod;

                int[] newLens = new int[lens.Length];
                for (int i = 0; i < newLens.Length; i++)
                {
                    newLens[i] = lens[i] * 2;
                }

                this.array = new MultyArray<T>(newLens);
                this.exist = new MultyArray<bool>(newLens);

                this.solve = solve;
            }

            public T dp(params int[] args)
            {
                if (exist._get(args))
                {
                    return array._get(args);
                }
                T value = solve(this, args);
                array._set(value, args);
                exist._set(true, args);
                return value;
            }

            public int[] indexToArgs(int index)
            {
                int[] res = new int[lens.Length];
                for (int i = 0; i < lens.Length; i++)
                {
                    res[i] = (index / ks[i]) % (lens[i] + 1);
                }
                return res;
            }

            public int index(params int[] args)
            {
                int q = args.Length;
                int res = 0;
                for (int i = 0; i < q; i++)
                {
                    res += args[i] * ks[i];
                }

                return res;
            }

            public T run(params int[] args)
            {
                int maxIndex = index(args);

                for (int i = 0; i <= maxIndex; i++)
                {
                    int[] a = indexToArgs(i);
                    dp(a);
                }

                return dp(args);
            }
        }
    }
}

namespace OJ
{
    public partial class Program
    {
        public static void print(List<int> obj)
        {
            Console.Write("{");
            for (int i = 0; i < obj.Count; i++)
            {
                print(obj[i]);
            }
            Console.Write("}");
        }

        public static void print(ValueType obj)
        {
            Console.Write(obj + " ");
        }

        public static void print(string obj)
        {
            Console.Write(obj + " ");
        }

        public static void print(Type obj)
        {
            Console.Write(obj + " ");
        }

        public static void print(Array obj)
        {
            Console.Write("[");
            for (int i = 0; i < obj.Length; i++)
            {
                print(obj.GetValue(i));
            }
            Console.Write("]");
        }

        public static void print(List<int[]> obj)
        {
            Console.WriteLine("{");
            for (int i = 0; i < obj.Count; i++)
            {
                print(obj[i]);
                Console.WriteLine();
            }
            Console.Write("}");
        }

        public static void print(List<string> obj)
        {
            Console.WriteLine("{");
            for (int i = 0; i < obj.Count; i++)
            {
                print(obj[i]);
                Console.WriteLine();
            }
            Console.Write("}");
        }

        public static void print(List<List<int>> obj)
        {
            Console.WriteLine("{");
            for (int i = 0; i < obj.Count; i++)
            {
                print(obj[i]);
                Console.WriteLine();
            }
            Console.Write("}");
        }

        public static void print(object obj)
        {
            Console.Write(obj);
            Console.Write(" ");
        }

        public static void println(List<int> obj)
        {
            print(obj);
            Console.WriteLine();
        }

        public static void println(ValueType obj)
        {
            print(obj);
            Console.WriteLine();
        }

        public static void println(string obj)
        {
            print(obj);
            Console.WriteLine();
        }

        public static void println(Type obj)
        {
            print(obj);
            Console.WriteLine();
        }

        public static void println(Array obj)
        {
            print(obj);
            Console.WriteLine();
        }

        public static void println(List<int[]> obj)
        {
            print(obj);
            Console.WriteLine();
        }

        public static void println(List<string> obj)
        {
            print(obj);
            Console.WriteLine();
        }

        public static void println(List<List<int>> obj)
        {
            print(obj);
            Console.WriteLine();
        }

        public static void println(object obj)
        {
            Console.Write(obj);
            Console.Write(" ");
        }

        public class Scanner
        {
            List<string> array = new List<string>();
            int pos = 0;

            public Scanner(string text)
            {
                string[] sss = text.Split('\n');
                for (int i = 0; i < sss.Length; i++ )
                {
                    array.AddRange(sss[i].Split(' '));
                }
            }

            public Scanner()
            {
                while (true)
                {
                    string next = Console.ReadLine();
                    if (next != null && next.Length > 0)
                    {
                        array.AddRange(next.Split(' '));
                    }
                    else
                    {
                        break;
                    }
                }
            }

            public int nextInt()
            {
                if (pos == array.Count)
                {
                    throw new ArgumentException("Arguments are gone");
                }
                int res = Int32.Parse(array[pos]);
                pos++;
                return res;
            }

            public long nextLong()
            {
                if (pos == array.Count)
                {
                    throw new ArgumentException("Arguments are gone");
                }
                long res = Int64.Parse(array[pos]);
                pos++;
                return res;
            }

            public string nextString()
            {
                if (pos == array.Count)
                {
                    throw new ArgumentException("Arguments are gone");
                }
                string res = array[pos];
                pos++;
                return res;
            }

            public char nextChar()
            {
                if (pos == array.Count)
                {
                    throw new ArgumentException("Arguments are gone");
                }
                char res = array[pos][0];
                pos++;
                return res;
            }

            public double nextDouble()
            {
                if (pos == array.Count)
                {
                    throw new ArgumentException("Arguments are gone");
                }
                double res = Double.Parse(array[pos]);
                pos++;
                return res;
            }

            public List<int> nextArray(int n)
            {
                List<int> res = new List<int>();
                for (int i = 0; i < n; i++)
                {
                    res.Add(nextInt());
                }
                return res;
            }

            public List<double> nextArrayDouble(int n)
            {
                List<double> res = new List<double>();
                for (int i = 0; i < n; i++)
                {
                    res.Add(nextDouble());
                }
                return res;
            }

            public List<string> nextArrayString(int n)
            {
                List<string> res = new List<string>();
                for (int i = 0; i < n; i++)
                {
                    res.Add(nextString());
                }
                return res;
            }
        }
    }
}

namespace OJ
{
    public partial class Program
    {
        public static int gcd(int a, int b)
        {
            if (b == 0)
            {
                return a;
            }
            else
            {
                return gcd(b, a % b);
            }
        }

        public static bool[] sieve(int bound)
        {
            bool[] array = new bool[bound + 1];
            for (int i = 2; i * i <= bound; i++)
            {
                if (!array[i])
                {
                    for (int j = i + i; j <= bound; j += i)
                    {
                        array[j] = true;
                    }
                }
            }
            return array;
        }

        public static long inv(long a, long mod)
        {
            long r = powmod(a, mod - 2, mod);
            return r;
        }

        public static List<int> sieveList(int bound)
        {
            bool[] array = new bool[bound + 1];
            for (int i = 2; i * i <= bound; i++)
            {
                if (!array[i])
                {
                    for (int j = i + i; j <= bound; j += i)
                    {
                        array[j] = true;
                    }
                }
            }

            List<int> a = new List<int>();
            for (int i = 2; i < bound + 1; i++)
            {
                if (!array[i])
                {
                    a.Add(i);
                }
            }

            return a;
        }

        public static List<int[]> factorize(int n, List<int> primeList)
        {
            List<int[]> res = new List<int[]>();
            for (int j = 0; j < primeList.Count; j++)
            {
                int i = primeList[j];
                if (n % i == 0)
                {
                    int[] comp = new int[] { i, 1 };
                    n /= i;
                    while (n % i == 0)
                    {
                        comp[1] = comp[1] + 1;
                        n /= i;
                    }
                    res.Add(comp);
                }
            }

            if (n > 1)
            {
                res.Add(new int[] { n, 1 });
            }
            return res;
        }

        public static List<int[]> factorize(int n)
        {
            List<int[]> res = new List<int[]>();
            int sqrt = (int)Math.Sqrt(n)+1;
            for (int j = 2; j < sqrt; j++)
            {
                if (n % j == 0)
                {
                    int[] comp = new int[] { j, 1 };
                    n /= j;
                    while (n % j == 0)
                    {
                        comp[1] = comp[1] + 1;
                        n /= j;
                    }
                    res.Add(comp);
                }
            }

            if (n > 1)
            {
                res.Add(new int[] { n, 1 });
            }
            return res;
        }

        public static List<int> genDivisors(int n)
        {
            List<int> res = new List<int>();
            int root = (int)(Math.Sqrt(n) + 1);
            for (int i = 1; i < root; i++)
            {
                if (n % i == 0)
                {
                    if (n / i != i)
                    {
                        res.Add(i);
                        res.Add(n / i);
                    }
                    else
                    {
                        res.Add(i);
                    }
                }
            }
            return res;
        }

    }
}

namespace OJ
{
    public partial class Program
    {
        //public static Scanner sc = new Scanner(File.ReadAllText("input.txt"));
        public static Scanner sc = new Scanner();

        static int rank(char a)
        {
            if(a == '6'){
                return 6;
            }

            if (a == '7')
            {
                return 7;
            }

            if (a == '8')
            {
                return 8;
            }

            if (a == '9')
            {
                return 9;
            }

            if (a == 'T')
            {
                return 10;
            }

            if (a == 'J')
            {
                return 11;
            }

            if (a == 'Q')
            {
                return 12;
            }

            if (a == 'K')
            {
                return 13;
            }

            if (a == 'A')
            {
                return 14;
            }

            return -1;
        }

        static void Main(string[] args)
        {
            string koz = sc.nextString();
            string a = sc.nextString();
            string b = sc.nextString();

            if(a[1] == koz[0]){
                if(b[1] != koz[1]){
                    Console.WriteLine( "YES");
                }
                else
                {
                    if(rank(a[0]) > rank(b[0])){
                        Console.WriteLine("YES");
                    }
                    else
                    {
                        Console.WriteLine("NO");
                    }
                }
            }
            else{
                if(a[1] == b[1]){
                    if (rank(a[0]) > rank(b[0]))
                    {
                        Console.WriteLine("YES");
                    }
                    else
                    {
                        Console.WriteLine("NO");
                    }
                }
                else
                {
                    Console.WriteLine("NO");
                }
            }
        }
    }
}

namespace OJ
{
    public partial class Program
    {
        public static T min<T>(T first, params T[] array) where T : IComparable
        {
            T res = first;
            for (int i = 0; i < array.Length; i++)
            {
                if (array[i].CompareTo(res) < 0)
                {
                    res = array[i];
                }
            }
            return res;
        }

        public static T max<T>(T first, params T[] array) where T : IComparable
        {
            T res = first;
            for (int i = 0; i < array.Length; i++)
            {
                if (array[i].CompareTo(res) > 0)
                {
                    res = array[i];
                }
            }
            return res;
        }

        public static long pow(long a, long n)
        {
            long res = 1;
            while (n > 0)
            {
                if (n % 2 == 1)
                    res = (a * res);
                a = (a * a);
                n >>= 1;
            }
            return res;
        }

        public static long powmod(long a, long n, long mod)
        {
            long res = 1;
            while (n>0)
            {
                if (n % 2 == 1)
                    res = (a * res) % mod;
                a = (a * a) % mod;
                n >>= 1;
            }
            return res;
        }
    }
}


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

namespace Game
{
    class Card
    {
        public string ValueCard { get; set; }
        public string LearCard { get; set; }
        public bool Trump { get; set; }

        public static bool Calculation(Card card1, Card card2, string trump)
        {
            bool status = false;

            //присвоение статуса "козырь"
            if (card1.LearCard == trump)
                card1.Trump = true;
            if (card2.LearCard == trump)
                card2.Trump = true;

            //вариант 1
            //если первая козырь, а вторая нет, то
            if (card1.Trump == true && card2.Trump == false)
            {
                status = true;
            }
            //вариант 2
            //если вторая козырь, а первая нет, то
            if (card1.Trump == false && card2.Trump == true)
            {
                status = false;
            }

            //вариант 3
            //если карты не козыри, а первая другой масти

            if (card1.Trump == false && card2.Trump == false)
            {
                if (card1.LearCard != card2.LearCard)
                    status = false;
            }

            //если масти одинаковы
            if (card1.LearCard == card2.LearCard)
            {
                int ind1 =  card1.GetCoefficient();
                int ind2 = card2.GetCoefficient();

                if (card1.GetCoefficient() > card2.GetCoefficient())
                {
                    status = true;
                }
            }
            return status;
        }

        public  int GetCoefficient()
        {
            int coef = new int();
            switch (this.ValueCard)
            {
                case "6": coef = 1;
                    break;
                case "7": coef = 2;
                    break;
                case "8": coef = 3;
                    break;
                case "9": coef = 4;
                    break;
                case "10": coef = 5;
                    break;
                case "В": coef = 6;
                    break;
                case "Д": coef = 7;
                    break;
                case "К": coef = 8;
                    break;
                case "Т": coef = 9;
                    break;
                default:
                    break;
            }
            return coef;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            bool work = true;

            while (work == true)
            {

               // Console.Write("Введите масть козыря одной заглавной буквой.\r\nКрести, вини, черви, буби - К, В, Ч, Б - соответственно.\r\nКозырь: ");
                //масть
                string learTrump = Console.ReadLine();

                //Console.WriteLine("\r\nВведите достоинство карт.\r\nНапример, король червей - КЧ, восмёрка крестей - 8К");
                //Console.Write("Карта №1: ");
                string strCard1 = Console.ReadLine();//карта 1

               // Console.Write("Карта №2: ");
                string strCard2 = Console.ReadLine();//карта 2

                Card card1 = new Card { ValueCard = strCard1[0].ToString(), LearCard = strCard1[1].ToString() };
                Card card2 = new Card { ValueCard = strCard2[0].ToString(), LearCard = strCard2[1].ToString() };

                bool result = Card.Calculation(card1, card2, learTrump);

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


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

namespace Game
{
    class Card
    {
        public string ValueCard { get; set; }
        public string LearCard { get; set; }
        public bool Trump { get; set; }

        public static bool Calculation(Card card1, Card card2, string trump)
        {
            bool status = false;

            //присвоение статуса "козырь"
            if (card1.LearCard == trump)
                card1.Trump = true;
            if (card2.LearCard == trump)
                card2.Trump = true;

            //вариант 1
            //если первая козырь, а вторая нет, то
            if (card1.Trump == true && card2.Trump == false)
            {
                status = true;
            }
            //вариант 2
            //если вторая козырь, а первая нет, то
            if (card1.Trump == false && card2.Trump == true)
            {
                status = false;
            }

            //вариант 3
            //если карты не козыри, а первая другой масти

            if (card1.Trump == false && card2.Trump == false)
            {
                if (card1.LearCard != card2.LearCard)
                    status = false;
            }

            //если масти одинаковы
            if (card1.LearCard == card2.LearCard)
            {
                int ind1 = card1.GetCoefficient();
                int ind2 = card2.GetCoefficient();

                if (card1.GetCoefficient() > card2.GetCoefficient())
                {
                    status = true;
                }
            }
            return status;
        }

        public int GetCoefficient()
        {
            int coef = new int();
            switch (this.ValueCard)
            {
                case "6": coef = 1;
                    break;
                case "7": coef = 2;
                    break;
                case "8": coef = 3;
                    break;
                case "9": coef = 4;
                    break;
                case "10": coef = 5;
                    break;
                case "В": coef = 6;
                    break;
                case "Д": coef = 7;
                    break;
                case "К": coef = 8;
                    break;
                case "Т": coef = 9;
                    break;
                default:
                    break;
            }
            return coef;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            bool work = true;

            while (work == true)
            {

                // Console.Write("Введите масть козыря одной заглавной буквой.\r\nКрести, вини, черви, буби - К, В, Ч, Б - соответственно.\r\nКозырь: ");
                //масть

                string learTrump = Console.ReadLine();

                //Console.WriteLine("\r\nВведите достоинство карт.\r\nНапример, король червей - КЧ, восмёрка крестей - 8К");
                //Console.Write("Карта №1: ");

                string cards = Console.ReadLine();
                int indexProbel = cards.IndexOf(' ');
                int indexPospeProbela = cards.Length - indexProbel - 1;
                string strCard1 = cards.Substring(0, indexProbel);

                // Console.Write("Карта №2: ");
                string strCard2 = cards.Substring(indexProbel + 1, indexPospeProbela);

                Card card1;
                Card card2;

                if (strCard1.Length == 3)
                {
                    card1 = new Card { ValueCard = strCard1[0].ToString() +strCard1[1].ToString() , LearCard = strCard1[2].ToString() };
                }
                else
                {
                    card1 = new Card { ValueCard = strCard1[0].ToString(), LearCard = strCard1[1].ToString() };
                }

                if (strCard2.Length == 3)
                {
                    card2 = new Card { ValueCard = strCard2[0].ToString() + strCard2[1].ToString(), LearCard = strCard2[2].ToString() };
                }
                else
                {
                    card2 = new Card { ValueCard = strCard2[0].ToString(), LearCard = strCard2[1].ToString() };
                }

                bool result = Card.Calculation(card1, card2, learTrump);

                if (result)
                    Console.WriteLine("YES");
                else
                    Console.WriteLine("NO");

            }
        }


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

namespace ConsoleApplication1
{

    class Program
    {

        static void Main(string[] args)
        {
            long[] s = Console.ReadLine().Split().Select(long.Parse).ToArray();
            long n = s[0], m = s[1], k = s[2], ans = 0, mod = 1000000009,z=0, er=n-m ;
            bool b = false;
            for (long i = 1; i <= n; i++)
            {
                z++;
                if (i == (n - k * er + 1))
                    b = true;
                if (z < k)
                {
                    ans=(ans+1)%mod;
                }
                else
                {
                    if (b == true)
                    {
                        z = 0;
                    }
                    else
                    {
                        ans = (ans + 1) * 2%mod;
                        z = 0;
                    }
                }
            }
            if (m == 0) ans = 0;
            Console.WriteLine(ans%mod);
           // Console.Read();
        }
    }


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

namespace K.Factorization
{
    class Program
    {
        static void Main(string[] args)
        {
            var input = Console.ReadLine().Split(' ').Select(s => int.Parse(s)).ToArray();
            List<int> primeNumbers = new List<int>();
            var number = input[0];
            var factors = input[1];

            for (int b = 2; number > 1; b++)
            {
                if (number % b == 0)
                {
                    while (number % b == 0)
                    {
                        number /= b;
                        primeNumbers.Add(b);
                    }
                }
            }

            if (primeNumbers.Count() < factors) Console.WriteLine(-1);
            else
            {
                StringBuilder message = new StringBuilder();
                for (int i = 0; i < factors - 1; i++)
                {
                    message.Append(primeNumbers[i] + " ");
                    primeNumbers.RemoveAt(i);
                }
                message.Append(primeNumbers.Aggregate(1, (accum, current) => accum * current));
                Console.WriteLine(message.ToString());
            }
        }
    }
}


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

namespace Codeforces_Round_353__Div_2_
{
    static class B
    {
        public static void Solve()
        {
            int n = ReadInt();
            int a = ReadInt();
            int b = ReadInt();
            int c = ReadInt();
            int d = ReadInt();
            int[] sums = new[] {a + b, a + c, c + d, b + d};
            int maxSum = 0;
            int minSum = n + n;
            for (int i = 0; i < 4; i++)
            {
                if (sums[i] > maxSum)
                    maxSum = sums[i];
                if (sums[i] < minSum)
                    minSum = sums[i];
            }
            int numOfQuads = 0;
            for (int middleNum = 1; middleNum <= n; middleNum++)
            {
                for (int i = 1; i <= n; i++)
                {
                    int maxSumWithRest = maxSum + middleNum + i;
                    if (maxSumWithRest - (minSum + middleNum) <= n)
                    {
                        numOfQuads++;
                    }
                    else
                    {
                        break;
                    }
                }
            }
            Write(numOfQuads);

            //int[] ar = new[] {a, b, d, c};
            //int maxnum = 0;
            //int maxnumpair = 0;
            //int num1 = 0;
            //int num2 = 0;
            //for (int i = 0; i < 4; i++)
            //{
            //    if (ar[i] > maxnum)
            //    {
            //        maxnum = ar[i];
            //        num1 = i;
            //    }

            //}
            //if (num1 == 0)
            //{
            //    if (ar[(num1 + 1)%4] > ar[3])
            //    {
            //        maxnumpair = maxnum + ar[(num1 + 1)%4];
            //        num2 = (num1 + 1)%4;
            //    }
            //    else
            //    {
            //        maxnumpair = maxnum + ar[3];
            //        num2 = ar[3];
            //    }
            //}
            //else
            //{
            //    if (ar[(num1 + 1) % 4] > ar[num1-1])
            //    {
            //        maxnumpair = maxnum + ar[(num1 + 1) % 4];
            //        num2 = (num1 + 1)%4;
            //    }
            //    else
            //    {
            //        maxnumpair = maxnum + ar[num1-1];
            //        num2 = num1 - 1;
            //    }
            //}
            //int middleNum = 1;
            //while (true)
            //{
            //    for (int i = 1; i < n; i++)
            //    {
            //        int sum = maxnumpair + middleNum + i;
            //    }
            //    middleNum++;
            //}

        }

        #region -- Main --

        private static TextReader reader;
        private static TextWriter writer;

        static void Main()
        {
#if DEBUG
            reader = new StreamReader("..\\..\\input.txt");
            //reader = new StreamReader(Console.OpenStandardInput());
            writer = Console.Out;
            //writer = new StreamWriter("..\\..\\output.txt");
#else
        reader = new StreamReader(Console.OpenStandardInput());
        writer = new StreamWriter(Console.OpenStandardOutput());
        //reader = new StreamReader("input.txt");
        //writer = new StreamWriter("output.txt");
#endif
            try
            {
                //var thread = new Thread(new Solver().Solve, 1024 * 1024 * 128);
                //thread.Start();
                //thread.Join();
                Solve();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
#if DEBUG
#else
            throw;
#endif
            }
            reader.Close();
            writer.Close();
        }

        #endregion

        #region -- Read / Write --

        private static Queue<string> currentLineTokens = new Queue<string>();

        private static string[] ReadAndSplitLine()
        {
            return reader.ReadLine().Split(new[] { ' ', '\t', }, StringSplitOptions.RemoveEmptyEntries);
        }

        public static string ReadToken()
        {
            while (currentLineTokens.Count == 0) currentLineTokens = new Queue<string>(ReadAndSplitLine());
            return currentLineTokens.Dequeue();
        }

        public static int ReadInt()
        {
            return int.Parse(ReadToken());
        }

        public static long ReadLong()
        {
            return long.Parse(ReadToken());
        }

        public static double ReadDouble()
        {
            return double.Parse(ReadToken(), CultureInfo.InvariantCulture);
        }

        public static int[] ReadIntArray()
        {
            return ReadAndSplitLine().Select(int.Parse).ToArray();
        }

        public static long[] ReadLongArray()
        {
            return ReadAndSplitLine().Select(long.Parse).ToArray();
        }

        public static double[] ReadDoubleArray()
        {
            return ReadAndSplitLine().Select(s => double.Parse(s, CultureInfo.InvariantCulture)).ToArray();
        }

        public static int[][] ReadIntMatrix(int numberOfRows)
        {
            int[][] matrix = new int[numberOfRows][];
            for (int i = 0; i < numberOfRows; i++) matrix[i] = ReadIntArray();
            return matrix;
        }

        public static int[][] ReadAndTransposeIntMatrix(int numberOfRows)
        {
            int[][] matrix = ReadIntMatrix(numberOfRows);
            int[][] ret = new int[matrix[0].Length][];
            for (int i = 0; i < ret.Length; i++)
            {
                ret[i] = new int[numberOfRows];
                for (int j = 0; j < numberOfRows; j++) ret[i][j] = matrix[j][i];
            }
            return ret;
        }

        public static string[] ReadLines(int quantity)
        {
            string[] lines = new string[quantity];
            for (int i = 0; i < quantity; i++) lines[i] = reader.ReadLine().Trim();
            return lines;
        }

        public static void WriteArray<T>(IEnumerable<T> array)
        {
            writer.WriteLine(string.Join(" ", array));
        }

        public static void Write(params object[] array)
        {
            WriteArray(array);
        }
        public static void WriteLines<T>(IEnumerable<T> array)
        {
            foreach (var a in array) writer.WriteLine(a);
        }
        private class SDictionary<TKey, TValue> : Dictionary<TKey, TValue>
        {
            public new TValue this[TKey key]
            {
                get { return ContainsKey(key) ? base[key] : default(TValue); }
                set { base[key] = value; }
            }
        }
        private static T[] Init<T>(int size) where T : new()
        {
            var ret = new T[size];
            for (int i = 0; i < size; i++) ret[i] = new T();
            return ret;
        }
        #endregion
    }
}


using System;
using System.Linq;

namespace CSharp
{
    class _322B
    {
        public static void Main()
        {
            var flowers = Console.ReadLine().Split().Select(token => int.Parse(token)).ToArray();
            var remainders = flowers.Select(count => count % 3).OrderBy(r => r).ToArray();

            if (remainders.Distinct().Count() == 1)
            {
                Console.WriteLine(flowers.Sum() / 3);
            }
            else if (remainders[1] == 2)
            {
                Console.WriteLine(Math.Sign(flowers.First(count => count % 3 == 0)) + flowers.Sum(count => count / 3));
            }
            else if (remainders[0] == 0)
            {
                Console.WriteLine(flowers.Sum(count => count / 3));
            }
            else
            {
                Console.WriteLine(flowers.Sum() / 3);
            }
        }
    }
}


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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var n = int.Parse(Console.ReadLine());
            var cntPrimes = n/2 + 1;
            var isNotPrime = new bool[cntPrimes];
            isNotPrime[0] = true;
            isNotPrime[1] = true;
            var primes = new List<int>();
            for (int i = 2; i < cntPrimes; i++)
            {
                if(isNotPrime[i])
                    continue;
                primes.Add(i);
                for (int j = i * i; j < cntPrimes; j += i)
                    isNotPrime[j] = true;
            }

            var res = 0;
            for (int i = 6; i <= n; i++)
            {
                var cnt = 0;
                for (int j = 0; j < primes.Count; j++)
                {
                    if (i%primes[j] == 0)
                        cnt++;
                    if(cnt > 2)
                        break;
                }

                if (cnt == 2)
                    res++;
            }

            Console.WriteLine(res);
        }
    }
}


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

namespace TaskB
{
    class Program
    {
        static void Main(string[] args)
        {
            var arr = Console.ReadLine().Split(' ').Select(x => Convert.ToInt32(x)).ToArray();
            var n = arr[0];
            var m = arr[1];
            var k = arr[2];

            k = Math.Min(k, n + 1 - k);

            var kol = n;
            var kolFrodo = 1;

            int i = 1;

            while (kol < m && i <= k)
            {
                kolFrodo ++;
                kol = kol + 2 * i - 1;
                i++;
            }

            //слева закончили или подушки закончились
            if (kol == m)
            {
                Console.Write(kolFrodo);
                return;
            }

            if (kol > m)
            {
                kolFrodo--;
                Console.Write(kolFrodo);
                return;
            }

            //kol < m, идем вправо
            i = 1;
            while (kol < m && i  <= n - 2 * k + 1)
            {
                kolFrodo++;
                kol = kol + 2*k + i - 1;
                i++;
            }

            //справа закончили или подушки закончились
            if (kol == m)
            {
                Console.Write(kolFrodo);
                return;
            }

            if (kol > m)
            {
                kolFrodo--;
                Console.Write(kolFrodo);
                return;
            }

            //kol < m, теперь добавляем константно по n штук
            while (kol + n <= m)
            {
                kolFrodo++;
                kol = kol + n;
            }

            Console.Write(kolFrodo);
        }
    }
}


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

namespace AprilFools
{
    internal class Program
    {
        private const string TestIn = @"..\..\In\Text.in";
        private const string TestOut = @"..\..\In\Text.out";

        private static void Solve()
        {
            var nums = ReadIntArray();
            var n = nums[0];
            var k = nums[1];
            var nk = n - k;
            var nmul = nk;
            var kmul = k;

            // factorial n
            long kf = kmul;
            while (--k > 1)
            {
                kf *= kmul;
                kf = kf%1000000007;
            }

            long nkp = nk;
            while (--nk > 0)
            {
                nkp *= nmul;
                nkp = nkp%1000000007;
            }

            Console.WriteLine(((nkp * kf) % 1000000007));
        }

        public static string Multiply(string source, int multiplier)
        {
            StringBuilder sb = new StringBuilder(multiplier * source.Length);
            for (int i = 0; i < multiplier; i++)
            {
                sb.Append(source);
            }

            return sb.ToString();
        }

        private static void Main()
        {
            if (Debugger.IsAttached)
            {
                Console.SetIn(new StreamReader(TestIn));
                Console.SetOut(new StreamWriter(TestOut));
            }

            Solve();

            if (Debugger.IsAttached)
            {
                Console.In.Close();
                Console.Out.Close();
                Console.SetIn(new StreamReader(Console.OpenStandardInput()));
                //Console.ReadLine();
            }
        }

        #region Reader

        private static string Read()
        {
            return Console.ReadLine();
        }

        private static string[] ReadArray()
        {
            return Console.ReadLine().Split(' ');
        }

        private static List<int> ReadIntArray()
        {
            var input = Console.ReadLine().Split(' ').Select(Int32.Parse).ToList();
            return input;
        }

        private static int ReadInt()
        {
            return Int32.Parse(Console.ReadLine());
        }

        private static long ReadLong()
        {
            return long.Parse(Console.ReadLine());
        }

        private static int ReadNextInt(string[] input, int index)
        {
            return Int32.Parse(input[index]);
        }

        #endregion
    }
}


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

namespace Codeforces
{
    internal static class Program
    {
        private const string test = "D1";

        private static void Solve()
        {
            int n,k;
            Read(out n, out k);
            long res = k-1;
            var mod = 1000000007;
            for (int i = 1; i <= k-1; i++)
            {
                res *= k;
                res %= mod;
            }
            for (int i = 1; i <= n-k; i++)
            {
                res *= n-k;
                res %= mod;
            }
            WriteLine(res);
        }

        private static void Main()
        {
            if (Debugger.IsAttached)
            {
                Console.SetIn(new StreamReader(String.Format(@"..\..\..\..\Tests\{0}.in", test)));
            }

            Solve();

            if (Debugger.IsAttached)
            {
                Console.In.Close();
                Console.SetIn(new StreamReader(Console.OpenStandardInput()));
                Console.ReadLine();
            }
        }

        private static int[] SortIndexs<T>(this IEnumerable<T> source) where T : IComparable
        {
            var array = source == null ? new List<T>() : source.ToList();
            var n = array.Count;
            var res = Enumerable.Range(0, n).ToArray();
            Array.Sort(res, (a, b) => array[a].CompareTo(array[b]));
            return res;
        }

        #region Reader

        private static string Read()
        {
            return Console.ReadLine();
        }

        private static void Read<T>(out T a1, out T a2)
        {
            var input = ReadArray();
            a1 = (T)Convert.ChangeType(input[0], typeof(T));
            a2 = (T)Convert.ChangeType(input[1], typeof(T));
        }

        private static void Read<T>(out T a1, out T a2, out T a3)
        {
            var input = ReadArray();
            a1 = (T)Convert.ChangeType(input[0], typeof(T));
            a2 = (T)Convert.ChangeType(input[1], typeof(T));
            a3 = (T)Convert.ChangeType(input[2], typeof(T));
        }

        private static void Read<T>(out T a1, out T a2, out T a3, out T a4)
        {
            var input = ReadArray();
            a1 = (T)Convert.ChangeType(input[0], typeof(T));
            a2 = (T)Convert.ChangeType(input[1], typeof(T));
            a3 = (T)Convert.ChangeType(input[2], typeof(T));
            a4 = (T)Convert.ChangeType(input[3], typeof(T));
        }

        private static void Read<T>(out T a1, out T a2, out T a3, out T a4, out T a5)
        {
            var input = ReadArray();
            a1 = (T)Convert.ChangeType(input[0], typeof(T));
            a2 = (T)Convert.ChangeType(input[1], typeof(T));
            a3 = (T)Convert.ChangeType(input[2], typeof(T));
            a4 = (T)Convert.ChangeType(input[3], typeof(T));
            a5 = (T)Convert.ChangeType(input[4], typeof(T));
        }

        private static void Read<T>(out T a1, out T a2, out T a3, out T a4, out T a5, out T a6)
        {
            var input = ReadArray();
            a1 = (T)Convert.ChangeType(input[0], typeof(T));
            a2 = (T)Convert.ChangeType(input[1], typeof(T));
            a3 = (T)Convert.ChangeType(input[2], typeof(T));
            a4 = (T)Convert.ChangeType(input[3], typeof(T));
            a5 = (T)Convert.ChangeType(input[4], typeof(T));
            a6 = (T)Convert.ChangeType(input[5], typeof(T));
        }

        private static int ReadInt()
        {
            return Int32.Parse(Read());
        }

        private static long ReadLong()
        {
            return long.Parse(Read());
        }

        private static double ReadDouble()
        {
            return double.Parse(Read(), CultureInfo.InvariantCulture);
        }

        private static T Read<T>()
        {
            return (T)Convert.ChangeType(Read(), typeof(T));
        }

        private static string[] ReadArray()
        {
            var readLine = Console.ReadLine();
            if (readLine != null)
                return readLine.Split(' ');

            throw new ArgumentException();
        }

        private static List<int> ReadIntArray()
        {
            return ReadArray().Select(Int32.Parse).ToList();
        }

        private static List<long> ReadLongArray()
        {
            return ReadArray().Select(long.Parse).ToList();
        }

        private static List<double> ReadDoubleArray()
        {
            return ReadArray().Select(d => double.Parse(d, CultureInfo.InvariantCulture)).ToList();
        }

        private static List<T> ReadArray<T>()
        {
            return ReadArray().Select(x => (T)Convert.ChangeType(x, typeof(T))).ToList();
        }

        private static void WriteLine(double value)
        {
            Console.WriteLine(value.ToString(CultureInfo.InvariantCulture));
        }

        private static void WriteLine(double value, string stringFormat)
        {
            Console.WriteLine(value.ToString(stringFormat, CultureInfo.InvariantCulture));
        }

        private static void WriteLine<T>(T value)
        {
            Console.WriteLine(value);
        }

        private static void Write(double value)
        {
            Console.Write(value.ToString(CultureInfo.InvariantCulture));
        }

        private static void Write(double value, string stringFormat)
        {
            Console.Write(value.ToString(stringFormat, CultureInfo.InvariantCulture));
        }

        private static void Write<T>(T value)
        {
            Console.Write(value);
        }

        #endregion
    }
}


using System;

namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args)
        {
            UInt64 n = UInt64.Parse(Console.ReadLine());
            UInt64 sum = n + (n - 1);
            UInt64 result = 0;

            char[] bad = { '0', '1', '2', '3', '4', '5', '6', '7', '8' };
            if (sum.ToString().IndexOfAny(bad) == -1)
                result = 1;
            else
            {
                UInt64 count = (UInt64)sum.ToString().Length;
                string devt = "";
                for (UInt64 i = 0; i < count - 1; i++)
                    devt += "9";
                for (int i = 0; i < 9; i++)
                {
                    UInt64 curent = UInt64.Parse(i.ToString() + devt);
                    if (curent <= (n + 1))
                        result += (curent / 2);
                    else if (!(curent > n + (n - 1)))
                        result += ((n-(curent-n))/2+1);
                }
            }
            Console.WriteLine(result);
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
using Pair = System.IComparable;
using Point = System.Tuple<int, int>;

public class Solution : Helper
{
    public Solution()
    {
        // http://codeforces.com/contest/899/problem/D
        var n = readInt32();
        long ans = 0;
        //
        if (n < 5)
        {
            ans = n * (n - 1) / 2;
        }
        else
        {
            var bs = bestSum(n);
            var str = bs.ToString();
            var f = str[0] - '0';
            if (f == 9)
            {
                ans = cp(bs, n);
            }
            else
            {
                range(1, f).each(h =>
                {
                    ans += cp(int.Parse(str.Replace(
                        f.ToString(),
                        h.ToString()
                        )), n);
                });
            }
        }
        //
        Console.WriteLine(ans);
    }
    //
    int cp(int sum, int n)
    {
        var a = sum / 2 + 1;
        var b = sum - 1;
        return count(a, Math.Min(b, n));
    }
    int count(int left, int right)
    {
        if (left > right) return 0;
        return (int)(right - left + 1);
    }
    int bestSum(int n)
    {
        var a = n + n - 1;
        var b = a.ToString();
        var c = b[0] - '0';
        var l = b.Length;
        var nines = b.Reverse().TakeWhile(x => x == '9').Count();
        if (nines >= l - 1)
            return a;
        return int.Parse((c - 1) + new string('9', l - 1));
    }
}

#region Core helper library
[DebuggerNonUserCode]
static partial class Extension
{
    internal static IEnumerable<T> each<T>(this IEnumerable<T> stream, Action<T> act) { foreach (var elem in stream) act(elem); return stream; }
    internal static IEnumerable<KeyValuePair<int, T>> kvp<T>(this IEnumerable<T> stream) { return stream.Select((elem, idx) => new KeyValuePair<int, T>(idx, elem)); }
    internal static IEnumerable<T> each<T>(this IEnumerable<T> stream, Action<T, int> act) { stream.kvp().each(kvp => act(kvp.Value, kvp.Key)); return stream; }
    internal static IEnumerable<int> indexIndices<T>(this IList<T> list) { return Helper.range(0, list.Count - 1); }
    internal static TValue? getOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key) where TValue : struct
    { TValue ans; if (dict.TryGetValue(key, out ans)) return ans; return null; }
    internal static T? FirstOrNullable<T>(this IEnumerable<T> stream) where T : struct { foreach (var val in stream) return val; return null; }
    internal static List<T> list<T>(this IEnumerable<T> stream, int capacity) { var ans = new List<T>(capacity); ans.AddRange(stream); return ans; }
}
[DebuggerNonUserCode]
public partial class Helper
{
    internal const int DEFAULT_BUFFER_SIZE = 4194304;
    internal static void fail(string reason = "ASSERTION FAILED") { throw new ApplicationException(reason); }
    internal static void debug(string reason) { Debug.Fail(reason); }
    internal static IEnumerable<int> range(int left, int right) { for (var i = left; i <= right; i++) yield return i; }
    internal static int? explainSearchIndex(int rawIndex) { if (rawIndex < 0) return null; return rawIndex; }
    internal static Pair pair<T1, T2>(T1 value1, T2 value2) { return Tuple.Create(value1, value2); }
}
#endregion

// additional plugable library
public partial class Helper
{
    #region STDIO
#if !DEBUG
    static void Main() { new Solution(); }
#endif
    static void eof() { throw new System.IO.EndOfStreamException(); }
    internal static string readLine_TRIM()
    { while (true) { var ans = Console.ReadLine(); if (ans == null) eof(); ans = ans.Trim(); if (ans.Any()) return ans; } }
    static IEnumerable<char> stream() { while (true) { var iread = Console.Read(); if (iread < 0) break; yield return (char)iread; } }
    static bool isWhitespace(char c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t'; }
    internal static string readString_TRIM(int maxCapacity)
    {
        var sb = new System.Text.StringBuilder(maxCapacity, maxCapacity);
        var iter = stream().SkipWhile(isWhitespace).TakeWhile(c => !isWhitespace(c));
        foreach (var c in iter) sb.Append(c);
        if (sb.Length == 0) eof(); return sb.ToString();
    }
    internal static long readLong64() { return long.Parse(readString_TRIM(21)); }
    internal static int readInt32() { return Convert.ToInt32(readLong64()); }
    #endregion
}
static partial class Extension
{

}


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

namespace CF317
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var sr = new InputReader(Console.In);
            //var sr = new InputReader(new StreamReader("input.txt"));
            var task = new Task();
            using (var sw = Console.Out)
            //using (var sw = new StreamWriter("output.txt"))
            {
                task.Solve(1, sr, sw);
                //Console.ReadKey();
            }
        }
    }

    internal class Task
    {
        public void Solve(int testNumber, InputReader sr, TextWriter sw)
        {
            var input = sr.ReadArray(Int32.Parse);
            var n = input[0];
            var q = input[1];
            var array = new Tuple<string, char>[q];
            for (var i = 0; i < q; i++)
            {
                var next = sr.NextSplitStrings();
                array[i] = new Tuple<string, char>(next[0], next[1][0]);
            }
            var count = 0;
            var list = new HashSet<char>();
            for (var i = 0; i < q; i++)
            {
                if (array[i].Item2 == 'a')
                {
                    list.Add(array[i].Item1[0]);
                    if (n == 2)
                    {
                        count++;
                    }
                }
            }
            HashSet<char> newList = null;
            for (var i = 3; i <= n; i++)
            {
                newList = new HashSet<char>();
                foreach (var item in list)
                {
                    for (var j = 0; j < q; j++)
                    {
                        if (array[j].Item2 == item)
                        {
                            newList.Add(array[j].Item1[0]);
                            if (i == n)
                            {
                                count++;
                            }
                        }
                    }
                }
                list = newList;
            }
            sw.WriteLine(count);
        }
    }

    internal class InputReader : IDisposable
    {
        private bool isDispose;
        private readonly TextReader sr;

        public InputReader(TextReader stream)
        {
            sr = stream;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        public string NextString()
        {
            var result = sr.ReadLine();
            return result;
        }

        public int NextInt32()
        {
            return Int32.Parse(NextString());
        }

        public long NextInt64()
        {
            return Int64.Parse(NextString());
        }

        public string[] NextSplitStrings()
        {
            return NextString()
                .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        }

        public T[] ReadArray<T>(Func<string, CultureInfo, T> func)
        {
            return NextSplitStrings()
                .Select(s => func(s, CultureInfo.InvariantCulture))
                .ToArray();
        }

        public T[] ReadArrayFromString<T>(Func<string, CultureInfo, T> func, string str)
        {
            return
                str.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                    .Select(s => func(s, CultureInfo.InvariantCulture))
                    .ToArray();
        }

        protected void Dispose(bool dispose)
        {
            if (!isDispose)
            {
                if (dispose)
                    sr.Close();
                isDispose = true;
            }
        }

        ~InputReader()
        {
            Dispose(false);
        }
    }
}


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

// (づ°ω°)づﾐe★゜・。。・゜゜・。。・゜☆゜・。。・゜゜・。。・゜
public class Solver
{
    string[] a;
    char[] b;
    int m;

    Dictionary<string, bool> mem = new Dictionary<string,bool>();
    bool Fun(string s)
    {
        if (s.Length == 1)
            return s[0] == 'a';
        if (mem.ContainsKey(s))
            return mem[s];

        bool ret = false;
        for (int i = 0; !ret && i < m; i++)
            if (a[i][0] == s[0] && a[i][1] == s[1])
                ret |= Fun(b[i] + s.Substring(2));
        return mem[s] = ret;
    }

    public void Solve()
    {
        int n = ReadInt();
        m = ReadInt();

        a = new string[m];
        b = new char[m];
        for (int i = 0; i < m; i++)
        {
            a[i] = ReadToken();
            b[i] = ReadToken()[0];
        }

        int ans = 0;
        var v = Enumerable.Repeat('a', n).ToArray();
        while (true)
        {
            if (Fun(new string(v)))
                ans++;
            v[n - 1]++;
            for (int i = n - 1; i > 0; i--)
                if (v[i] == 'g')
                {
                    v[i - 1]++;
                    v[i] = 'a';
                }
            if (v.All(vv => vv == 'f'))
                break;
        }

        Write(ans);
    }

    #region Main

    protected static TextReader reader;
    protected static TextWriter writer;
    static void Main()
    {
#if DEBUG
        reader = new StreamReader("..\\..\\input.txt");
        //reader = new StreamReader(Console.OpenStandardInput());
        writer = Console.Out;
        //writer = new StreamWriter("..\\..\\output.txt");
#else
        reader = new StreamReader(Console.OpenStandardInput());
        writer = new StreamWriter(Console.OpenStandardOutput());
        //reader = new StreamReader("input.txt");
        //writer = new StreamWriter("output.txt");
#endif
        try
        {
            //var thread = new Thread(new Solver().Solve, 1024 * 1024 * 128);
            //thread.Start();
            //thread.Join();
            new Solver().Solve();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
#if DEBUG
#else
            throw;
#endif
        }
        reader.Close();
        writer.Close();
    }

    #endregion

    #region Read / Write
    private static Queue<string> currentLineTokens = new Queue<string>();
    private static string[] ReadAndSplitLine() { return reader.ReadLine().Split(new[] { ' ', '\t', }, StringSplitOptions.RemoveEmptyEntries); }
    public static string ReadToken() { while (currentLineTokens.Count == 0)currentLineTokens = new Queue<string>(ReadAndSplitLine()); return currentLineTokens.Dequeue(); }
    public static int ReadInt() { return int.Parse(ReadToken()); }
    public static long ReadLong() { return long.Parse(ReadToken()); }
    public static double ReadDouble() { return double.Parse(ReadToken(), CultureInfo.InvariantCulture); }
    public static int[] ReadIntArray() { return ReadAndSplitLine().Select(int.Parse).ToArray(); }
    public static long[] ReadLongArray() { return ReadAndSplitLine().Select(long.Parse).ToArray(); }
    public static double[] ReadDoubleArray() { return ReadAndSplitLine().Select(s => double.Parse(s, CultureInfo.InvariantCulture)).ToArray(); }
    public static int[][] ReadIntMatrix(int numberOfRows) { int[][] matrix = new int[numberOfRows][]; for (int i = 0; i < numberOfRows; i++)matrix[i] = ReadIntArray(); return matrix; }
    public static int[][] ReadAndTransposeIntMatrix(int numberOfRows)
    {
        int[][] matrix = ReadIntMatrix(numberOfRows); int[][] ret = new int[matrix[0].Length][];
        for (int i = 0; i < ret.Length; i++) { ret[i] = new int[numberOfRows]; for (int j = 0; j < numberOfRows; j++)ret[i][j] = matrix[j][i]; } return ret;
    }
    public static string[] ReadLines(int quantity) { string[] lines = new string[quantity]; for (int i = 0; i < quantity; i++)lines[i] = reader.ReadLine().Trim(); return lines; }
    public static void WriteArray<T>(IEnumerable<T> array) { writer.WriteLine(string.Join(" ", array)); }
    public static void Write(params object[] array) { WriteArray(array); }
    public static void WriteLines<T>(IEnumerable<T> array) { foreach (var a in array)writer.WriteLine(a); }
    private class SDictionary<TKey, TValue> : Dictionary<TKey, TValue>
    {
        public new TValue this[TKey key]
        {
            get { return ContainsKey(key) ? base[key] : default(TValue); }
            set { base[key] = value; }
        }
    }
    private static T[] Init<T>(int size) where T : new() { var ret = new T[size]; for (int i = 0; i < size; i++)ret[i] = new T(); return ret; }
    #endregion
}