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

namespace Problems
{
    class _8A
    {
        public static  void  Main()
        {
            var forward = "forward";
            var backward = "backward";
            var both = "both";
            var fantasy = "fantasy";
            var len = 25000;
            var stations = new string('a', len * 2) + new string('b', len*2);
            var a = new string('a', len);
            var b = new string('b', len);
            //var stations = Console.ReadLine();
            //var a = Console.ReadLine();
            //var b = Console.ReadLine();
            var forw = (IsSequencePossible(stations, a, b));
            //var back = (IsSequencePossible(Reverse(stations), a, b));
            var back = (IsRevSequencePossible(stations, a, b));

            if (forw && back)
            {
                Console.WriteLine(both);
            }
            else
            {
                if (forw) Console.WriteLine(forward);
                else if (back) Console.WriteLine(backward);
                else Console.WriteLine(fantasy);
            }

        }

        private static string Reverse(string s)
        {
            Console.WriteLine(" start Reverse " + DateTime.Now.Second + " " + DateTime.Now.Millisecond);
            string result = string.Empty;
            for (int i = s.Length - 1; i >= 0; i-- )
            {
                result += s[i];
            }
            //Console.WriteLine(" end Reverse " + DateTime.Now.Second + " " + DateTime.Now.Millisecond);
            return result;
        }

        private static bool IsSequencePossible(string stations, string a, string b)
        {

            var result = false;
            var ind = FindSubstring(stations, a);
            if (ind > -1)
            {
                Console.WriteLine(" start Substring " + DateTime.Now.Second + " "+ DateTime.Now.Millisecond);
                stations = stations.Substring(ind + a.Length);
                Console.WriteLine(" ebd Substring " + DateTime.Now.Second + " " + DateTime.Now.Millisecond);
                if (FindSubstring(stations, b) > -1)
                {
                    result = true;
                }
            }
            return result;
        }
        private static bool IsRevSequencePossible(string stations, string a, string b)
        {

            var result = false;
            var ind = FindRevSubstring(stations, a);
            if (ind > -1)
            {
                Console.WriteLine(" start Substring " + DateTime.Now.Second + " " + DateTime.Now.Millisecond);
                stations = stations.Substring(ind + a.Length);
                Console.WriteLine(" ebd Substring " + DateTime.Now.Second + " " + DateTime.Now.Millisecond);
                if (FindRevSubstring(stations, b) > -1)
                {
                    result = true;
                }
            }
            return result;
        }
        private static int FindSubstring(string s, string a)
        {
            Console.WriteLine(" start FindSubstring " + DateTime.Now.Second + " " + DateTime.Now.Millisecond);
            if (s.Length < a.Length) return -1;
            ulong x = 257;
            ulong xn = 1;
            for (int i = 1; i < a.Length; i++)
            {
                xn = xn * x;
            }

            ulong ha = 0;
            for (int i = 0; i < a.Length; i++)
            {
                ha = ha * x + a[i];
            }

            ulong hs = 0;
            for (int i = 0; i < a.Length; i++)
            {
                hs = hs * x + s[i];
            }

            if (hs == ha) return 0;

            for(int i = a.Length; i < s.Length; i++)
            {
                hs = (hs - xn*s[i - a.Length]) * x + s[i];
                if (hs == ha) return i-a.Length+1;
            }

            return -1;
        }

        private static int FindRevSubstring(string s, string a)
        {
            Console.WriteLine(" start FindSubstring " + DateTime.Now.Second + " " + DateTime.Now.Millisecond);
            if (s.Length < a.Length) return -1;
            ulong x = 257;
            ulong xn = 1;
            for (int i = 1; i < a.Length; i++)
            {
                xn = xn * x;
            }

            ulong ha = 0;
            for (int i = 0; i < a.Length; i++)
            {
                ha = ha * x + a[i];
            }

            ulong hs = 0;
            for (int i = s.Length-1; i >= 0 ; i--)
            {
                hs = hs * x + s[i];
            }

            if (hs == ha) return 0;

            for (int i = s.Length-1-a.Length; i >= 0; i--)
            {
                hs = (hs - xn * s[i + a.Length]) * x + s[i];
                if (hs == ha) return i + a.Length - 1;
            }

            return -1;
        }
    }
}

Peter likes to travel by train. He likes it so much that on the train he falls asleep. Once in summer Peter was going by train from city A to city B, and as usual, was sleeping. Then he woke up, started to look through the window and noticed that every railway station has a flag of a particular colour.The boy started to memorize the order of the flags' colours that he had seen. But soon he fell asleep again. Unfortunately, he didn't sleep long, he woke up and went on memorizing the colours. Then he fell asleep again, and that time he slept till the end of the journey.At the station he told his parents about what he was doing, and wrote two sequences of the colours that he had seen before and after his sleep, respectively.Peter's parents know that their son likes to fantasize. They give you the list of the flags' colours at the stations that the train passes sequentially on the way from A to B, and ask you to find out if Peter could see those sequences on the way from A to B, or from B to A. Remember, please, that Peter had two periods of wakefulness.Peter's parents put lowercase Latin letters for colours. The same letter stands for the same colour, different letters — for different colours.

The input data contains three lines. The first line contains a non-empty string, whose length does not exceed 105, the string consists of lowercase Latin letters — the flags' colours at the stations on the way from A to B. On the way from B to A the train passes the same stations, but in reverse order.  The second line contains the sequence, written by Peter during the first period of wakefulness. The third line contains the sequence, written during the second period of wakefulness. Both sequences are non-empty, consist of lowercase Latin letters, and the length of each does not exceed 100 letters. Each of the sequences is written in chronological order.

Output one of the four words without inverted commas:    «forward» — if Peter could see such sequences only on the way from A to B;  «backward» — if Peter could see such sequences on the way from B to A;  «both» — if Peter could see such sequences both on the way from A to B, and on the way from B to A;  «fantasy» — if Peter could not see such sequences.

NoteIt is assumed that the train moves all the time, so one flag cannot be seen twice. There are no flags at stations A and B.

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

namespace ProgrammingContest.Codeforces.Round8
{
    class A
    {
        public static int Check(string s, int start, string c)
        {
            for (int i = start; i < s.Length; i++)
            {
                bool ok = true;
                for (int j = 0; j < c.Length; j++)
                {
                    int k = i + j;
                    if (k >= s.Length || c[j] != s[k])
                    {
                        ok = false;
                        break;
                    }
                }
                if (ok) return i;
            }
            return -1;
        }

        public static bool Check(string s, string c1, string c2)
        {
#if false
            for (int i = Check(s, 0, c1); i < s.Length; i = Check(s, i+1, c1))
            {
                if (Check(s, i+1, c2) != -1)
                    return true;
            }
#endif
            int i = Check(s, 0, c1);
            if (i == -1) return false;
            return Check(s, i+c1.Length, c2) != -1;
        }

        public static void Main()
        {
            string s = Console.ReadLine();
            string c1 = Console.ReadLine();
            string c2 = Console.ReadLine();

            bool forward = Check(s, c1, c2);
            bool backward = Check(new string(s.Reverse().ToArray()), c1, c2);

            if (forward && backward)
            {
                Console.Write("both");
            }
            else if (forward)
            {
                Console.Write("forward");
            }
            else if (backward)
            {
                Console.Write("backward");
            }
            else
            {
                Console.Write("fantasy");
            }
        }
    }
}

[{'input': 'atob\r\na\r\nb\r\n', 'output': ['forward\r\n']}, {'input': 'aaacaaa\r\naca\r\naa\r\n', 'output': ['both\r\n']}, {'input': 'aaa\r\naa\r\naa\r\n', 'output': ['fantasy\r\n']}, {'input': 'astalavista\r\nastla\r\nlavista\r\n', 'output': ['fantasy\r\n']}, {'input': 'abacabadabacaba\r\nabacaba\r\nabacaba\r\n', 'output': ['both\r\n']}, {'input': 'a\r\na\r\na\r\n', 'output': ['fantasy\r\n']}, {'input': 'ab\r\nb\r\na\r\n', 'output': ['backward\r\n']}, {'input': 'aaa\r\naaaa\r\naaaa\r\n', 'output': ['fantasy\r\n']}, {'input': 'bbabbbbababbaabaabaa\r\nabb\r\nbaab\r\n', 'output': ['forward\r\n']}, {'input': 'bbbbbbbbbbbbbbbbbbbbbbbbb\r\nbbbb\r\nbbbbb\r\n', 'output': ['both\r\n']}, {'input': 'babaabababaaaababaabababaabababababababbababbbabbaabababaababbaabbababaababaaabababaabbaababaaababaa\r\nabaabababaa\r\nabaabbaa\r\n', 'output': ['forward\r\n']}, {'input': 'bbbbbbbbbbbbbbbbbbbbbbbbb\r\nbbbb\r\nbbbbb\r\n', 'output': ['both\r\n']}, {'input': 'aababaaababaabbaabababaaababaabababbaabbabaabababaabbabbbababbababababababaabababaababaaaabababaabab\r\nabaabababaa\r\nabaabbaa\r\n', 'output': ['backward\r\n']}, {'input': 'aaaa\r\naaa\r\naa\r\n', 'output': ['fantasy\r\n']}, {'input': 'zzzz\r\nzz\r\nzzz\r\n', 'output': ['fantasy\r\n']}, {'input': 'zzzz\r\nzzzz\r\nzzzz\r\n', 'output': ['fantasy\r\n']}, {'input': 'zzzz\r\nzz\r\nzz\r\n', 'output': ['both\r\n']}, {'input': 'aabaa\r\naab\r\nbaa\r\n', 'output': ['fantasy\r\n']}, {'input': 'aabaab\r\naba\r\nab\r\n', 'output': ['forward\r\n']}, {'input': 'aab\r\nb\r\naa\r\n', 'output': ['backward\r\n']}, {'input': 'abacaba\r\naca\r\nba\r\n', 'output': ['both\r\n']}]


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

namespace _217A
{
    class Struct
    {
        public Struct(int x1, int y1, int set1)
        {

            x = x1;
            y = y1;
            set = set1;
        }
        public int x;
        public int y;
        public int set;

        public override string ToString()
        {
            return x + " " + y + " " + set;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            int n = int.Parse(Console.ReadLine());
            var list = new List<Struct>();

            int id = 0;

            for (int i = 0; i < n; i++)
            {
                //Console.WriteLine("Точка №"+i);
                var strArr = Console.ReadLine().Split(' ');
                int x = int.Parse(strArr[0]);
                int y = int.Parse(strArr[1]);
                var setValue = list.Where(s => s.x == x ^ s.y == y).Select(s => s.set);
                var setElems = list.Where(s => setValue.Contains(s.set));
                foreach (var item in setElems)
                {
                    item.set = id;
                }
                list.Add(new Struct(x, y, id));
                id++;
                //foreach (var item in list)
                //{
                //    Console.WriteLine(item.ToString());
                //}
            }
            Console.WriteLine(list.Select(s=>s.set).Distinct().Count()-1);
        }
    }
}

Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created.We assume that Bajtek can only heap up snow drifts at integer coordinates.

The first line of input contains a single integer n (1 ≤ n ≤ 100) — the number of snow drifts. Each of the following n lines contains two integers xi and yi (1 ≤ xi, yi ≤ 1000) — the coordinates of the i-th snow drift. Note that the north direction coinсides with the direction of Oy axis, so the east direction coinсides with the direction of the Ox axis. All snow drift's locations are distinct.

Output the minimal number of snow drifts that need to be created in order for Bajtek to be able to reach any snow drift from any other one.

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

namespace _217A
{
    class Struct
    {
        public Struct(int x1, int y1, int set1)
        {

            x = x1;
            y = y1;
            set = set1;
        }
        public int x;
        public int y;
        public int set;

        public override string ToString()
        {
            return x + " " + y + " " + set;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            int n = int.Parse(Console.ReadLine());
            var list = new List<Struct>();

            int id = 0;

            for (int i = 0; i < n; i++)
            {
                //Console.WriteLine("Точка №"+i);
                var strArr = Console.ReadLine().Split(' ');
                int x = int.Parse(strArr[0]);
                int y = int.Parse(strArr[1]);
                var setValue = list.Where(s => s.x == x ^ s.y == y).Select(s => s.set).ToArray();
                var setElems = list.Where(s => setValue.Contains(s.set)).ToArray();
                foreach (var item in setElems)
                {
                    item.set = id;
                }
                list.Add(new Struct(x, y, id));
                id++;
                //foreach (var item in list)
                //{
                //    Console.WriteLine(item.ToString());
                //}
            }
            Console.WriteLine(list.Select(s=>s.set).Distinct().Count()-1);
        }
    }
}


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

namespace _192B
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = Convert.ToInt32(Console.ReadLine());
            int[] k = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();

            int countDay = 0;
            int countTile = 0;
                while (countTile <= n)
                {
                    if (countTile == n - 1)
                    {
                        countDay++;
                        countTile = 0;
                    }

                    if (k[0] > countDay && countTile + 2 < n && k[countTile + 2] > countDay)
                        countTile += 2;
                    else if (k[0] > countDay && countTile + 1 < n && k[countTile + 1] > countDay)
                        countTile += 1;
                    else if (n == 1)
                        continue;
                    else
                        break;
                    }

                Console.WriteLine(countDay);
            }
        }
    }

In Berland the opposition is going to arrange mass walking on the boulevard. The boulevard consists of n tiles that are lain in a row and are numbered from 1 to n from right to left. The opposition should start walking on the tile number 1 and the finish on the tile number n. During the walk it is allowed to move from right to left between adjacent tiles in a row, and jump over a tile. More formally, if you are standing on the tile number i (i < n - 1), you can reach the tiles number i + 1 or the tile number i + 2 from it (if you stand on the tile number n - 1, you can only reach tile number n). We can assume that all the opposition movements occur instantaneously.In order to thwart an opposition rally, the Berland bloody regime organized the rain. The tiles on the boulevard are of poor quality and they are rapidly destroyed in the rain. We know that the i-th tile is destroyed after ai days of rain (on day ai tile isn't destroyed yet, and on day ai + 1 it is already destroyed). Of course, no one is allowed to walk on the destroyed tiles! So the walk of the opposition is considered thwarted, if either the tile number 1 is broken, or the tile number n is broken, or it is impossible to reach the tile number n from the tile number 1 if we can walk on undestroyed tiles.The opposition wants to gather more supporters for their walk. Therefore, the more time they have to pack, the better. Help the opposition to calculate how much time they still have and tell us for how many days the walk from the tile number 1 to the tile number n will be possible.

The first line contains integer n (1 ≤ n ≤ 103) — the boulevard's length in tiles. The second line contains n space-separated integers ai — the number of days after which the i-th tile gets destroyed (1 ≤ ai ≤ 103).

Print a single number — the sought number of days.

NoteIn the first sample the second tile gets destroyed after day three, and the only path left is 1 → 3 → 4. After day five there is a two-tile gap between the first and the last tile, you can't jump over it.In the second sample path 1 → 3 → 5 is available up to day five, inclusive. On day six the last tile is destroyed and the walk is thwarted.

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

namespace Codeforces192B
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = Convert.ToInt32(Console.ReadLine());
            int[] k = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();

            int countDay = 0;
            int countTile = 0;

            if (n == 1)
            {
                countDay = k[0];
            }
            else
            {
                while (countTile <= n)
                {
                    if (countTile == n - 1)
                    {
                        countDay++;
                        countTile = 0;
                    }

                    if (k[0] > countDay && countTile + 2 < n && k[countTile + 2] > countDay)
                        countTile += 2;
                    else if (k[0] > countDay && countTile + 1 < n && k[countTile + 1] > countDay)
                        countTile += 1;
                    else
                        break;
                }
            }
            Console.WriteLine(countDay);
        }
    }
}


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(sr, sw);
				//Console.ReadKey();
			}
		}
	}

	internal class Task
	{
		public void Solve(InputReader sr, TextWriter sw)
		{
			var input = sr.ReadArray(Int32.Parse);
			var n = input[0];
			var m = input[1];
			var costs = sr.ReadArray(Int32.Parse);
			var dict = new Dictionary<int, HashSet<int>>();
			for (var i = 0; i < m; i++) {
				input = sr.ReadArray(Int32.Parse);
				if (!dict.ContainsKey(input[0])) {
					dict.Add(input[0], new HashSet<int>());
				}
				dict[input[0]].Add(input[1]);
				if (!dict.ContainsKey(input[1])) {
					dict.Add(input[1], new HashSet<int>());
				}
				dict[input[1]].Add(input[0]);
			}
			var maxCost = -1;
			for (var i = 1; i <= n; i++) {
				for (var j = 1; j <= n; j++) {
					if (dict.ContainsKey(i) && dict[i].Contains(j)) {
						for (var k = 1; k <= n; k++) {
							if (i != j && i != k && j != k) {
								if (dict[i].Contains(k) && dict[j].Contains(k)) {
									var curr = costs[i - 1] + costs[j - 1] + costs[k - 1];
									if (curr > maxCost) {
										maxCost = curr;
									}
								}
							}
						}
					}
				}
			}

			sw.WriteLine(maxCost);
		}
	}
}

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);
	}
}

A little boy Gerald entered a clothes shop and found out something very unpleasant: not all clothes turns out to match. For example, Gerald noticed that he looks rather ridiculous in a smoking suit and a baseball cap.Overall the shop sells n clothing items, and exactly m pairs of clothing items match. Each item has its price, represented by an integer number of rubles. Gerald wants to buy three clothing items so that they matched each other. Besides, he wants to spend as little money as possible. Find the least possible sum he can spend.

The first input file line contains integers n and m — the total number of clothing items in the shop and the total number of matching pairs of clothing items (). Next line contains n integers ai (1 ≤ ai ≤ 106) — the prices of the clothing items in rubles. Next m lines each contain a pair of space-separated integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi). Each such pair of numbers means that the ui-th and the vi-th clothing items match each other. It is guaranteed that in each pair ui and vi are distinct and all the unordered pairs (ui, vi) are different.

Print the only number — the least possible sum in rubles that Gerald will have to pay in the shop. If the shop has no three clothing items that would match each other, print "-1" (without the quotes).

NoteIn the first test there only are three pieces of clothing and they all match each other. Thus, there is only one way — to buy the 3 pieces of clothing; in this case he spends 6 roubles.The second test only has three pieces of clothing as well, yet Gerald can't buy them because the first piece of clothing does not match the third one. Thus, there are no three matching pieces of clothing. The answer is -1.In the third example there are 4 pieces of clothing, but Gerald can't buy any 3 of them simultaneously. The answer is -1.

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

class Solution
{
    static int Main(string[] args)
    {
        var q = Console.ReadLine().Split().Select(int.Parse).ToList();
        var n = q[0]; var m = q[1];

        int[] p = new int[9999];
        var d = Console.ReadLine().Split().Select(int.Parse).ToArray();
        for (int i = 0; i < n; i++)
            p[i + 1] = d[i];

        bool[,] g = new bool[9999, 9999];
        for (int i = 0; i < m; i++)
        {
            string e = Console.ReadLine();
            int x = int.Parse(e.Split()[0]);
            int y = int.Parse(e.Split()[1]);
            g[x, y] = true;
            g[y, x] = true;
        }
        int a = int.MaxValue;
        for (int i = 1; i <= n; i++)
            for (int j = i + 1; j <= n; j++)
                for (int k = j + 1; k <= n; k++)
                    if (g[i, j] && g[j, k] && g[k, i])
                        a = Math.Min(a, p[i] + p[j] + p[k]);
        if (a == int.MaxValue)
            Console.WriteLine(-1);
        else
            Console.WriteLine(a);

        Console.Read();
        return 0;
    }
}


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

namespace _34A
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = Convert.ToInt32(Console.ReadLine());
            int[] container = Console.ReadLine().Split().Select(int.Parse).ToArray();
            int helper = 0,ans=999999;
            int index1 = 0, index2 = 0;
            for(int i=1;i<n;i++)
            {
                helper = Math.Abs(container[i] - container[i - 1]);
                if (helper<ans)
                {
                    ans = helper;
                    index1 = i;
                    index2 = i - 1;
                }
            }
            int final = Math.Abs(container[0] - container[n - 1]);
            if(final<ans)
            {
                index1 = 1;
                index2 = n - 1;
            }

            Console.WriteLine("{0} {1}", index1+1, index2+1);
        }
    }
}

n soldiers stand in a circle. For each soldier his height ai is known. A reconnaissance unit can be made of such two neighbouring soldiers, whose heights difference is minimal, i.e. |ai - aj| is minimal. So each of them will be less noticeable with the other. Output any pair of soldiers that can form a reconnaissance unit.

The first line contains integer n (2 ≤ n ≤ 100) — amount of soldiers. Then follow the heights of the soldiers in their order in the circle — n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 1000). The soldier heights are given in clockwise or counterclockwise direction.

Output two integers — indexes of neighbouring soldiers, who should form a reconnaissance unit. If there are many optimum solutions, output any of them. Remember, that the soldiers stand in a circle.

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

namespace Contest
{
    class Program
    {

        static void Main(string[] args)
        {
            var n = int.Parse(Console.ReadLine());
            var s = Console.ReadLine().Split(' ').Select(ss => int.Parse(ss)).ToArray();
            int c = 0;
            int max = int.MaxValue;
            int maxn = 0;
            for (; ; )
            {
                var ct = c % n;
                var nt = (c + 1) % n;
                if (Math.Abs(s[ct] - s[nt]) < max)
                {
                    max = Math.Abs(s[ct] - s[nt]);
                    maxn = ct;
                }
                if (nt == 0) break;
                c++;
            }
            Console.WriteLine("{0} {1}", maxn % n+1, (maxn + 1) % n+1);
        }
    }
}


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

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            string s1 = Console.ReadLine();

            int n = int.Parse(s1.Split(' ')[0]) - 1;
            int m = int.Parse(s1.Split(' ')[1]) - 1;

            int min = m;

            if (n < m)
            {
                min = n;
                n = m;
                m = min;
            }

            byte[] poss = new byte[min + 1];

            for (int i = 0; i < poss.Length; i++)
                poss[i] = 1;

            for (int i = 0; i <= min; i++)
            {
                if (poss[i] == 1)
                {
                    int y = i;
                    int dy = 2 * n % (2 * m);

                    do
                    {
                        y += dy;
                        dy *= Convert.ToInt32(Math.Pow((-1.0), Convert.ToDouble(((y - 1) / m) % 2)));
                        y = (Math.Abs(y) / m) % 2 * m + Convert.ToInt32(Math.Pow((-1.0), Convert.ToDouble(((Math.Abs(y) - 1) / m) % 2))) * Math.Abs(y % m);
                        //dy *= Convert.ToInt32(Math.Pow((-1.0), Convert.ToDouble(((y - 1) / m) % 2 - 1)));
                        if (poss[y] == 1 && y != i)
                            poss[y] = 0;
                    } while (y != i);
                }
            }

            int cou = 0;

            for (int i = 0; i < poss.Length; i++)
                if (poss[i] == 1)
                    cou++;

            Console.WriteLine(cou.ToString());

            Console.ReadKey();
        }

    }
}

Let's imagine: there is a chess piece billiard ball. Its movements resemble the ones of a bishop chess piece. The only difference is that when a billiard ball hits the board's border, it can reflect from it and continue moving.More formally, first one of four diagonal directions is chosen and the billiard ball moves in that direction. When it reaches the square located on the board's edge, the billiard ball reflects from it; it changes the direction of its movement by 90 degrees and continues moving. Specifically, having reached a corner square, the billiard ball is reflected twice and starts to move the opposite way. While it moves, the billiard ball can make an infinite number of reflections. At any square of its trajectory the billiard ball can stop and on that the move is considered completed.  It is considered that one billiard ball a beats another billiard ball b if a can reach a point where b is located.You are suggested to find the maximal number of billiard balls, that pairwise do not beat each other and that can be positioned on a chessboard n × m in size.

The first line contains two integers n and m (2 ≤ n, m ≤ 106).

Print a single number, the maximum possible number of billiard balls that do not pairwise beat each other. Please do not use the %lld specificator to read or write 64-bit numbers in C++. It is preferred to use cin (also you may use the %I64d specificator).

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

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            string s1 = Console.ReadLine();

            int n = int.Parse(s1.Split(' ')[0]) - 1;
            int m = int.Parse(s1.Split(' ')[1]) - 1;

            int min = m;

            if (n < m)
            {
                min = n;
                n = m;
                m = min;
            }

            byte[] poss = new byte[min + 1];

            for (int i = 0; i < poss.Length; i++)
                poss[i] = 1;

            for (int i = 0; i <= min; i++)
            {
                if (poss[i] == 1)
                {
                    int y = i;
                    int dy = 2 * n % (2 * m);

                    do
                    {
                        y += dy;
                        int k = 0;
                        if (y <0) k = -1;
                        else k = 1;
                        dy *= k * Convert.ToInt32(Math.Pow((-1.0), Convert.ToDouble(((Math.Abs(y) - 1) / m) % 2)));
                        y = (Math.Abs(y) / m) % 2 * m + Convert.ToInt32(Math.Pow((-1.0), Convert.ToDouble(((Math.Abs(y) - 1) / m) % 2))) * Math.Abs(y % m);
                        //dy *= Convert.ToInt32(Math.Pow((-1.0), Convert.ToDouble(((y - 1) / m) % 2 - 1)));
                        if (poss[y] == 1 && y != i)
                            poss[y] = 0;
                    } while (!((y == i && dy >= 0) || (y == 0)));
                }
            }

            int cou = 0;

            for (int i = 0; i < poss.Length; i++)
                if (poss[i] == 1)
                    cou++;

            Console.WriteLine(cou.ToString());

            Console.ReadKey();
        }

    }
}


using System;
using System.Collections.Generic;

public class Program {
    private int n;
    private int[] numbers;

    public void Solve() {
        string[] data;
        data = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        n = int.Parse(data[1]);
        data = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        numbers = new int[data.Length];
        for (int i = 0; i < n; ++i)
            numbers[i] = int.Parse(data[i]);
        Console.WriteLine(computeMinCost());
    }

    private int computeMinCost() {
        Array.Sort(numbers);
        if (numbers.Length > 0 && numbers[0] == 1)
            return 1;
        else if (n >= limit)
            return -1;
        int cost = 0, index = 0;
        foreach (int prime in primes) {
            if (prime >= n)
                break;
            while (index < numbers.Length && numbers[index] < prime)
                ++index;
            if (index == numbers.Length || numbers[index] != prime)
                return -1;
            ++cost;
        }
        return cost;
    }

    private static int limit = 1299744;
    private static bool[] isPrime;
    private static List<int> primes;

    private static void computePrimes() {
        isPrime = new bool[limit];
        for (int i = 2; i < limit; ++i)
            isPrime[i] = true;
        primes = new List<int>();
        for (int i = 2; i < limit; ++i) {
            if (isPrime[i])
                primes.Add(i);
            foreach (int prime in primes) {
                if (i * prime >= limit)
                    break;
                isPrime[i * prime] = false;
                if (i % prime == 0)
                    break;
            }
        }
    }

    public static void Main() {
        computePrimes();
        new Program().Solve();
    }
}

Vasya plays The Elder Trolls III: Morrowindows. He has a huge list of items in the inventory, however, there is no limits on the size of things. Vasya does not know the total amount of items but he is sure that are not more than x and not less than 2 items in his inventory. A new patch for the game appeared to view inventory in n different modes. Displaying in mode i is a partition of all inventory items on pages, each of which (except for maybe the last one) shows exactly ai items. In addition, each mode shows how many pages bi is in a complete list. Great! Perhaps this information will be enough for Vasya to find the required number. Moreover, it is very interesting, what is the fewest number of modes in which Vasya can see inventory to determine the number of items in it?Vasya cannot use the information that was received while looking on inventory in some mode for selection of next actions. I. e. Vasya chooses some set of modes first, and then sees all the results and determines the size.Knowing the number of ai, x and assuming that Vasya is very smart, check whether he can uniquely determine the number of items in his inventory, and how many modes he will need to do that if he knows numbers ai, x and he is able to know number bi after viewing items in mode i.

The first line contains two integers n and x (0 ≤ n ≤ 105, 2 ≤ x ≤ 109). The second line contains integers ai (1 ≤ ai ≤ 109). Some numbers among all ai may be equal.

Output the fewest amount of modes required to uniquely determine amount of items in the inventory. If there is no solution output  - 1.

NoteIn the second example Vasya is not able to determine items count uniquely because 3 items, as well as 4 items, can be displayed on two pages.

using System;
using System.Collections.Generic;

public class Program {
    private int n;
    private int[] numbers;

    public void Solve() {
        string[] data;
        data = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        n = int.Parse(data[1]);
        data = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        numbers = new int[data.Length];
        for (int i = 0; i < numbers.Length; ++i)
            numbers[i] = int.Parse(data[i]);
        Console.WriteLine(computeMinCost());
    }

    private int computeMinCost() {
        Array.Sort(numbers);
        if (numbers.Length > 0 && numbers[0] == 1)
            return n == 2 ? 0 : 1;
        else if (n >= limit)
            return -1;
        int cost = 0, index = 0;
        foreach (int prime in primes) {
            if (prime >= n)
                break;
            while (index < numbers.Length && numbers[index] < prime)
                ++index;
            if (index == numbers.Length || numbers[index] != prime)
                return -1;
            ++cost;
        }
        return cost;
    }

    private static int limit = 1299744;
    private static bool[] isPrime;
    private static List<int> primes;

    private static void computePrimes() {
        isPrime = new bool[limit];
        for (int i = 2; i < limit; ++i)
            isPrime[i] = true;
        primes = new List<int>();
        for (int i = 2; i < limit; ++i) {
            if (isPrime[i])
                primes.Add(i);
            foreach (int prime in primes) {
                if (i * prime >= limit)
                    break;
                isPrime[i * prime] = false;
                if (i % prime == 0)
                    break;
            }
        }
    }

    public static void Main() {
        computePrimes();
        new Program().Solve();
    }
}


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

namespace D
{
    class Program
    {
        class AR
        {
            public long max, sum, maxl, maxr;
        }

        static void Main(string[] args)
        {
            string[] line = Console.ReadLine().Split(' ');
            int n = int.Parse(line[0]);
            int m = int.Parse(line[1]);

            AR[] ar = new AR[n];

            for (int i = 0; i < n; i++)
            {
                line = Console.ReadLine().Split(' ');
                int size = int.Parse(line[0]);
                int[] a = new int[size];
                for (int j = 0; j < size; j++)
                    a[j] = int.Parse(line[j + 1]);

                ar[i] = new AR();

                //// max
                //long max = int.MinValue;
                //for (int j = 0; j < size; j++)
                //    max = Math.Max(max, a[j]);
                //ar[i].max = max;

                long sum = 0;
                for (int j = 0; j < size; j++)
                    sum += a[j];
                ar[i].sum = sum;

                int p = 0;
                long max = long.MinValue;

                while (p < size && a[p] < 0)
                    p++;

                if (p == size)
                {
                    for (int j = 0; j < size; j++)
                        max = Math.Max(max, a[j]);
                    ar[i].max = max;
                }
                else
                {
                    long cs = max = a[p];
                    for (int q = p + 1; q < size; q++)
                    {
                        if (a[q] + cs > 0)
                        {
                            cs += a[q];
                            max = Math.Max(max, cs);
                        }
                        else
                            cs = 0;
                    }
                    ar[i].max = max;
                }

                long maxl = 0, suml = 0;
                for (int j = 0; j < size; j++)
                {
                    suml += a[j];
                    maxl = Math.Max(maxl, suml);
                }

                long maxr = 0, sumr = 0;
                for (int j = size - 1; j >= 0; j--)
                {
                    sumr += a[j];
                    maxr = Math.Max(maxr, sumr);
                }

                ar[i].maxl = maxl;
                ar[i].maxr = maxr;
            }

            int[] lg = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);

            long[] DPe = new long[m + 1];
            long[] DPc = new long[m + 1];
            long[] DPs = new long[m + 1];

            DPe[0] = long.MinValue;
            DPc[0] = long.MinValue;
            DPs[0] = ar[lg[0] - 1].maxr;

            for (int i = 1; i < m; i++)
            {
                int idx = lg[i] - 1;
                if (i > 1)
                {
                    DPe[i] = Math.Max(DPc[i - 1], DPs[i - 1]) + ar[idx].maxl;
                    DPc[i] = Math.Max(DPc[i - 1], DPs[i - 1]) + ar[idx].sum;
                }
                else
                {
                    DPe[i] = DPs[i - 1] + ar[idx].maxl;
                    DPc[i] = DPs[i - 1] + ar[idx].sum;
                }
                DPs[i] = ar[idx].maxr;
            }

            long best = long.MinValue;
            for (int i = 0; i < m; i++)
                best = Math.Max(best, ar[lg[i] - 1].max);

            //best = Math.Max(best, ar[lg[0] - 1].maxr);

            for (int i = 1; i < m; i++)
            {
                best = Math.Max(best, DPe[i]);
                //best = Math.Max(best, DPc[i]);
                //best = Math.Max(best, DPs[i]);
            }

            Console.WriteLine(best);

        }
    }
}

Ahmed and Mostafa used to compete together in many programming contests for several years. Their coach Fegla asked them to solve one challenging problem, of course Ahmed was able to solve it but Mostafa couldn't.This problem is similar to a standard problem but it has a different format and constraints.In the standard problem you are given an array of integers, and you have to find one or more consecutive elements in this array where their sum is the maximum possible sum.But in this problem you are given n small arrays, and you will create one big array from the concatenation of one or more instances of the small arrays (each small array could occur more than once). The big array will be given as an array of indexes (1-based) of the small arrays, and the concatenation should be done in the same order as in this array. Then you should apply the standard problem mentioned above on the resulting big array.For example let's suppose that the small arrays are {1, 6, -2}, {3, 3} and {-5, 1}. And the indexes in the big array are {2, 3, 1, 3}. So the actual values in the big array after formatting it as concatenation of the small arrays will be {3, 3, -5, 1, 1, 6, -2, -5, 1}. In this example the maximum sum is 9.Can you help Mostafa solve this problem?

The first line contains two integers n and m, n is the number of the small arrays (1 ≤ n ≤ 50), and m is the number of indexes in the big array (1 ≤ m ≤ 250000). Then follow n lines, the i-th line starts with one integer l which is the size of the i-th array (1 ≤ l ≤ 5000), followed by l integers each one will be greater than or equal -1000 and less than or equal 1000. The last line contains m integers which are the indexes in the big array, and you should concatenate the small arrays in the same order, and each index will be greater than or equal to 1 and less than or equal to n. The small arrays are numbered from 1 to n in the same order as given in the input. Some of the given small arrays may not be used in big array. Note, that the array is very big. So if you try to build it straightforwardly, you will probably get time or/and memory limit exceeded.

Print one line containing the maximum sum in the big array after formatting it as described above. You must choose at least one element for the sum, i. e. it cannot be empty. Please, do not use %lld specificator to write 64-bit integers in C++. It is preferred to use cout (also you may use %I64d).

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

namespace ProgrammingContest.Codeforces.Round67
{
    class D
    {
        static int[] ReadInts() { return Array.ConvertAll(Console.ReadLine().Split(' '), sss => int.Parse(sss)); }
        static long[] ReadILongs() { return Array.ConvertAll(Console.ReadLine().Split(' '), sss => long.Parse(sss)); }

        public static void Main()
        {
            var xs = ReadInts();
            int n = xs[0],
                m = xs[1];
            var ys = new long[n][];
            var len = new int[n];
            var sum = new long[n];
            var minsum = new long[n];
            var minsum2 = new long[n];
            var maxsum = new long[n];
            var maxsum2 = new long[n];
            for (int i = 0; i < n; i++)
            {
                ys[i] = ReadILongs();
                len[i] = (int)ys[i][0];
                maxsum2[i] = int.MinValue;
                for (int j = 1; j <= len[i]; j++)
                {
                    sum[i] += ys[i][j];

                    if (maxsum2[i] < sum[i] - minsum[i])
                        maxsum2[i] = sum[i] - minsum[i];

                    if (j == 1 || maxsum[i] < sum[i])
                    {
                        if(j > 1) minsum2[i] = minsum[i];
                        maxsum[i] = sum[i];
                    }

                    if (minsum[i] > sum[i])
                        minsum[i] = sum[i];
                }
            }
            xs = ReadInts();
            long min = 0, now = 0, res = long.MinValue;
            for (int i = 0; i < m; i++)
            {
                int j = xs[i] - 1;
                min = Math.Min(now + minsum2[j], min);
                res = Math.Max(now + maxsum[j] - min, res);
                res = Math.Max(maxsum2[j], res);
                min = Math.Min(now + minsum[j], min);
                now += sum[j];
                //Console.WriteLine("{0}: {1} {2} {3} {4}", i, res, min, max, now);
            }
            Console.WriteLine(res);
        }
    }
}


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

namespace pro
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = int.Parse(Console.ReadLine());
            int[] x = new int[n];
            int[] y = new int[n];
            for (int i = 0; i < n; i++)
            {
                string[] sp = Console.ReadLine().Split();
                x[i] = int.Parse(sp[0]);
                y[i] = int.Parse(sp[1]);
            }
            Int64 L = x[0], R = x[1];
            if (L > R)
            {
                Int64 tmp = L;
                L = R;
                R = L;
            }
            for (int i = 0; i < n; i++)
            {
                int j = (i + 1) % n;
                Int64 a = y[j] - y[i];
                Int64 b = x[i] - x[j];
                Int64 c = - a * x[i] - b * y[i];
                if (a == 0)
                {
                    if (i != 0 && b * (x[0] - x[1]) > 0)
                    {
                        L = R + 1;
                        break;
                    }
                    continue;
                }
                double loc = ((double)-b * y[1] - c) / a;
                //Console.WriteLine("i = " + i + " loc = " + loc + " a = " + a);
                if (a > 0)
                {
                    Int64 v = (Int64)(loc + 1 - 1e-7);
                    if (L < v) L = v;
                }else
                {
                    Int64 v = (Int64)(loc + 1e-7);
                    if (R > v) R = v;
                }
            }
            Console.WriteLine(R - L + 1);
        }
    }
}

In the town of Aalam-Aara (meaning the Light of the Earth), previously there was no crime, no criminals but as the time progressed, sins started creeping into the hearts of once righteous people. Seeking solution to the problem, some of the elders found that as long as the corrupted part of population was kept away from the uncorrupted part, the crimes could be stopped. So, they are trying to set up a compound where they can keep the corrupted people. To ensure that the criminals don't escape the compound, a watchtower needs to be set up, so that they can be watched.Since the people of Aalam-Aara aren't very rich, they met up with a merchant from some rich town who agreed to sell them a land-plot which has already a straight line fence AB along which a few points are set up where they can put up a watchtower. Your task is to help them find out the number of points on that fence where the tower can be put up, so that all the criminals can be watched from there. Only one watchtower can be set up. A criminal is watchable from the watchtower if the line of visibility from the watchtower to him doesn't cross the plot-edges at any point between him and the tower i.e. as shown in figure 1 below, points X, Y, C and A are visible from point B but the points E and D are not.    Figure 1     Figure 2 Assume that the land plot is in the shape of a polygon and coordinate axes have been setup such that the fence AB is parallel to x-axis and the points where the watchtower can be set up are the integer points on the line. For example, in given figure 2, watchtower can be setup on any of five integer points on AB i.e. (4, 8), (5, 8), (6, 8), (7, 8) or (8, 8). You can assume that no three consecutive points are collinear and all the corner points other than A and B, lie towards same side of fence AB. The given polygon doesn't contain self-intersections.

The first line of the test case will consist of the number of vertices n (3 ≤ n ≤ 1000). Next n lines will contain the coordinates of the vertices in the clockwise order of the polygon. On the i-th line are integers xi and yi (0 ≤ xi, yi ≤ 106) separated by a space. The endpoints of the fence AB are the first two points, (x1, y1) and (x2, y2).

Output consists of a single line containing the number of points where the watchtower can be set up.

NoteFigure 2 shows the first test case. All the points in the figure are watchable from any point on fence AB. Since, AB has 5 integer coordinates, so answer is 5.For case two, fence CD and DE are not completely visible, thus answer is 0.

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

namespace pro
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = int.Parse(Console.ReadLine());
            int[] x = new int[n];
            int[] y = new int[n];
            for (int i = 0; i < n; i++)
            {
                string[] sp = Console.ReadLine().Split();
                x[i] = int.Parse(sp[0]);
                y[i] = int.Parse(sp[1]);
            }
            Int64 L = x[0], R = x[1];
            if (L > R)
            {
                Int64 tmp = L;
                L = R;
                R = tmp;
            }
            for (int i = 0; i < n; i++)
            {
                int j = (i + 1) % n;
                Int64 a = y[j] - y[i];
                Int64 b = x[i] - x[j];
                Int64 c = - a * x[i] - b * y[i];
                if (a == 0)
                {
                    if (i != 0 && b * (x[0] - x[1]) > 0)
                    {
                        L = R + 1;
                        break;
                    }
                    continue;
                }
                Int64 s = -b * y[1] - c;
                if (a > 0)
                {
                    Int64 v = s / a;
                    if (v*a < s) v++;
                    if (L < v) L = v;
                }else
                {
                    Int64 v = s / a;
                    if (v*a < s) v--;
                    if (R > v) R = v;
                }
            }
            int ans = (int)(R - L + 1);
            if (ans < 0) ans = 0;
            Console.WriteLine(ans);
        }
    }
}


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

class ProblemC {
    static string inputFileName = "../../input.txt";
    static StreamReader fileReader;
    static string[] inputTokens;
    static int curInputTokenIndex;
    static string NextToken() {
        string ret = "";
        while (ret == "") {
            if (inputTokens == null || curInputTokenIndex >= inputTokens.Length) {
                string line;
                if (Type.GetType("HaitaoLocal") != null) {
                    if (fileReader == null) {
                        fileReader = new StreamReader(inputFileName);
                    }
                    line = fileReader.ReadLine();
                    if (line == null) {
                        throw new Exception("Error: out of input tokens!");
                    }
                } else {
                    line = Console.ReadLine();
                }
                inputTokens = line.Split();
                curInputTokenIndex = 0;
            }
            ret = inputTokens[curInputTokenIndex++];
        }
        return ret;
    }
    static int ReadInt() {
        return Int32.Parse(NextToken());
    }
    static string ReadString() {
        return NextToken();
    }
    static long ReadLong() {
        return Int64.Parse(NextToken());
    }
    static int[] ReadIntArray(int length) {
        int[] ret = new int[length];
        for (int i = 0; i < length; i++) {
            ret[i] = ReadInt();
        }
        return ret;
    }
    static string[] ReadStringArray(int length) {
        string[] ret = new string[length];
        for (int i = 0; i < length; i++) {
            ret[i] = ReadString();
        }
        return ret;
    }
    static long[] ReadLongArray(int length) {
        long[] ret = new long[length];
        for (int i = 0; i < length; i++) {
            ret[i] = ReadLong();
        }
        return ret;
    }
    static string DoubleToString(double d) {
        return d.ToString(new CultureInfo("en-US"));
    }

    public static void Main(string[] args) {

        int N = ReadInt();
        int[] ar = ReadIntArray(N);
        for (int i = 0; i < N; i++) ar[i]--;
        int[,] dp = new int[2*N+1,N];
        for(int k=0; k<=2*N; k++) {
            for(int i=0; i<N; i++) {
                if (k == 0) dp[k, i] = 1;
                else if (k == 1) dp[k, i] = ar[i];
                else dp[k, i] = ar[dp[k - 1, i]];
            }
        }

        int ans = 0;
        for (int k = 1; k <= N; k++) {
            bool flag = true;
            for (int i = 0; i < N; i++) {
                if (dp[2 * k, i] != dp[k, i]) flag = false;
            }
            if (flag) {ans = k; break;}
        }

            Console.WriteLine(ans);

    }
}

Some time ago Leonid have known about idempotent functions. Idempotent function defined on a set {1, 2, ..., n} is such function , that for any  the formula g(g(x)) = g(x) holds.Let's denote as f(k)(x) the function f applied k times to the value x. More formally, f(1)(x) = f(x), f(k)(x) = f(f(k - 1)(x)) for each k > 1.You are given some function . Your task is to find minimum positive integer k such that function f(k)(x) is idempotent.

In the first line of the input there is a single integer n (1 ≤ n ≤ 200) — the size of function f domain. In the second line follow f(1), f(2), ..., f(n) (1 ≤ f(i) ≤ n for each 1 ≤ i ≤ n), the values of a function.

Output minimum k such that function f(k)(x) is idempotent.

NoteIn the first sample test function f(x) = f(1)(x) is already idempotent since f(f(1)) = f(1) = 1, f(f(2)) = f(2) = 2, f(f(3)) = f(3) = 2, f(f(4)) = f(4) = 4.In the second sample test:   function f(x) = f(1)(x) isn't idempotent because f(f(1)) = 3 but f(1) = 2;  function f(x) = f(2)(x) is idempotent since for any x it is true that f(2)(x) = 3, so it is also true that f(2)(f(2)(x)) = 3. In the third sample test:   function f(x) = f(1)(x) isn't idempotent because f(f(1)) = 3 but f(1) = 2;  function f(f(x)) = f(2)(x) isn't idempotent because f(2)(f(2)(1)) = 2 but f(2)(1) = 3;  function f(f(f(x))) = f(3)(x) is idempotent since it is identity function: f(3)(x) = x for any  meaning that the formula f(3)(f(3)(x)) = f(3)(x) also holds.

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

class ProblemC {
    static string inputFileName = "../../input.txt";
    static StreamReader fileReader;
    static string[] inputTokens;
    static int curInputTokenIndex;
    static string NextToken() {
        string ret = "";
        while (ret == "") {
            if (inputTokens == null || curInputTokenIndex >= inputTokens.Length) {
                string line;
                if (Type.GetType("HaitaoLocal") != null) {
                    if (fileReader == null) {
                        fileReader = new StreamReader(inputFileName);
                    }
                    line = fileReader.ReadLine();
                    if (line == null) {
                        throw new Exception("Error: out of input tokens!");
                    }
                } else {
                    line = Console.ReadLine();
                }
                inputTokens = line.Split();
                curInputTokenIndex = 0;
            }
            ret = inputTokens[curInputTokenIndex++];
        }
        return ret;
    }
    static int ReadInt() {
        return Int32.Parse(NextToken());
    }
    static string ReadString() {
        return NextToken();
    }
    static long ReadLong() {
        return Int64.Parse(NextToken());
    }
    static int[] ReadIntArray(int length) {
        int[] ret = new int[length];
        for (int i = 0; i < length; i++) {
            ret[i] = ReadInt();
        }
        return ret;
    }
    static string[] ReadStringArray(int length) {
        string[] ret = new string[length];
        for (int i = 0; i < length; i++) {
            ret[i] = ReadString();
        }
        return ret;
    }
    static long[] ReadLongArray(int length) {
        long[] ret = new long[length];
        for (int i = 0; i < length; i++) {
            ret[i] = ReadLong();
        }
        return ret;
    }
    static string DoubleToString(double d) {
        return d.ToString(new CultureInfo("en-US"));
    }

    public static void Main(string[] args) {

        int N = ReadInt();
        int[] ar = ReadIntArray(N);
        for (int i = 0; i < N; i++) ar[i]--;
        int[,] dp = new int[2 * N + 1, N];
        for (int k = 0; k <= 2 * N; k++) {
            for (int i = 0; i < N; i++) {
                if (k == 0) dp[k, i] = 1;
                else if (k == 1) dp[k, i] = ar[i];
                else dp[k, i] = ar[dp[k - 1, i]];
            }
        }
        int[] cycle = new int[N];

        for (int i = 0; i < N; i++) {
            cycle[i] = -1;
        }
        for (int i = 0; i < N; i++) {
            for (int k = 1; k <= N; k++) {
                if (dp[k, i] == i) { cycle[i] = k; break; }
            }
        }
        long lc = 1;
        for (int i = 0; i < N; i++) {
            //Console.WriteLine(i + " " + cycle[i]);
            if (cycle[i] != -1) lc = lcm(lc, cycle[i]);
        }
        long ans = -1;
        if (lc < N) {
            for (int k = 1; k <= N; k++) {
                bool flag = true;
                for (int i = 0; i < N; i++) {
                    if (dp[2 * k, i] != dp[k, i]) flag = false;
                }
                if (flag) { ans = k; break; }
            }
        }
        if (ans == -1) {
            ans = 0;
            while (ans < N) ans += lc;
        }

        Console.WriteLine(ans);

    }

    static long gcf(long a, long b) {
        while (b != 0) {
            long temp = b;
            b = a % b;
            a = temp;
        }
        return a;
    }

    static long lcm(long a, long b) {
        return (a / gcf(a, b)) * b;
    }
}


#if DEBUG
using System.Reflection;
using System.Threading.Tasks;
#endif

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

namespace _347c
{
    class Program
    {
        static string _inputFilename = "input.txt";
        static string _outputFilename = "output.txt";
        static bool _useFileInput = false;

        static void Main(string[] args)
        {
            StreamWriter file = null;
#if DEBUG
			Console.SetIn(getInput());
#else
            if (_useFileInput)
            {
                Console.SetIn(File.OpenText(_inputFilename));
                file = new StreamWriter(_outputFilename);
                Console.SetOut(file);
            }
#endif

            try
            {
                solution();
            }
            finally
            {
                if (_useFileInput)
                {
                    file.Close();
                }
            }
        }

        static void solution()
        {
            #region SOLUTION
            var n = readInt();
            for (int i = 0; i < n; i++)
            {
                var next = Console.ReadLine().Split('\'').ToArray();
                var val = next[1];
                if (val.Length == 1)
                {
                    var d = int.Parse(val);
                    if (d == 9)
                    {
                        Console.WriteLine(1989);
                    }
                    else
                    {
                        Console.WriteLine("199{0}", val);
                    }
                }
                else if (val == "99")
                {
                    Console.WriteLine("1999");
                }
                else if (val.Length == 2)
                {
                    Console.WriteLine("20{0}", val);
                }
                else if (val.Length == 3)
                {
                    Console.WriteLine("2{0}", val);
                }
                else
                {
                    var last = val.Substring(val.Length - 4, 4);
                    var dc = int.Parse(last);
                    if (dc >= 1000 && dc <= 2999)
                    {
                        var si = true;
                        var any = false;
                        for (int j = 0; j < val.Length - 4; j++)
                        {
                            any = true;
                            if (val[j] != '1')
                            {
                                si = false;
                            }
                        }

                        if (si || !any)
                        {
                            Console.WriteLine("1{0}", val);
                        }
                        else
                        {
                            Console.WriteLine("{0}", val);
                        }
                    }
                    else
                    {
                        Console.WriteLine("{0}", val);
                    }
                }
            }

            //var n = readInt();
            //var m = readInt();

            //var a = readIntArray();
            //var b = readIntArray();
            #endregion
        }

        static int readInt()
        {
            return int.Parse(Console.ReadLine());
        }

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

        static int[] readIntArray()
        {
            return Console.ReadLine().Split(' ').Where(i => !string.IsNullOrEmpty(i)).Select(i => int.Parse(i)).ToArray();
        }

        static long[] readLongArray()
        {
            return Console.ReadLine().Split(' ').Where(i => !string.IsNullOrEmpty(i)).Select(i => long.Parse(i)).ToArray();
        }

#if DEBUG
		static StreamReader getInput()
		{
			var resName = Assembly.GetCallingAssembly().GetManifestResourceNames()[0];
			var resource = Assembly.GetCallingAssembly().GetManifestResourceStream(resName);

			return new StreamReader(resource);
		}
#endif
    }
}

International Abbreviation Olympiad takes place annually starting from 1989. Each year the competition receives an abbreviation of form IAO'y, where y stands for some number of consequent last digits of the current year. Organizers always pick an abbreviation with non-empty string y that has never been used before. Among all such valid abbreviations they choose the shortest one and announce it to be the abbreviation of this year's competition.For example, the first three Olympiads (years 1989, 1990 and 1991, respectively) received the abbreviations IAO'9, IAO'0 and IAO'1, while the competition in 2015 received an abbreviation IAO'15, as IAO'5 has been already used in 1995.You are given a list of abbreviations. For each of them determine the year it stands for.

The first line of the input contains a single integer n (1 ≤ n ≤ 1000) — the number of abbreviations to process.  Then n lines follow, each containing a single abbreviation. It's guaranteed that each abbreviation contains at most nine digits.

For each abbreviation given in the input, find the year of the corresponding Olympiad.

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

namespace chall_cs
{
    class Program
    {
        static int N, pos_1, pos_2;
        static long add, target, answer;
        static string phr, abbr;

        static void Main(string[] args)
        {
            N = Convert.ToInt32(Console.ReadLine());

            for (int i = 0; i < N; ++i)
            {
                phr = Console.ReadLine();
                abbr = "";

                for (int j = 4; j < phr.Length; ++j)
                    abbr += phr[j];

                answer = 1988;
                add = 1;
                pos_1 = 1;
                pos_2 = abbr.Length - 1;

                while (pos_2 >= 0)
                {
                    while (true)
                    {
                        answer += add;

                        if (take_dig(answer, pos_1) == abbr[pos_2] - '0')
                            break;
                    }

                    pos_2 -= 1;
                    pos_1 += 1;
                    add *= 10;
                }

                Console.WriteLine(answer);
            }

            //Console.ReadKey();
        }

        static long take_dig(long value, int pos)
        {
            while(value > 0)
            {
                if (pos == 1)
                    break;

                pos -= 1;
                value /= 10;
            }

            return value % 10;
        }
    }
}


#if DEBUG
using System.Reflection;
using System.Threading.Tasks;
#endif

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

namespace _44d
{
    class Program
    {
        static string _inputFilename = "input.txt";
        static string _outputFilename = "output.txt";
        static bool _useFileInput = false;

        static void Main(string[] args)
        {
            StreamWriter file = null;
#if DEBUG
			Console.SetIn(getInput());
#else
            if (_useFileInput)
            {
                Console.SetIn(File.OpenText(_inputFilename));
                file = new StreamWriter(_outputFilename);
                Console.SetOut(file);
            }
#endif

            try
            {
                solution();
            }
            finally
            {
                if (_useFileInput)
                {
                    file.Close();
                }
            }
        }

        static void add(long pattern, int right, int n, HashSet<long> vs)
        {
            //vs.Inte
            vs.IntersectWith(generate(pattern, right, n));
        }

        static IEnumerable<long> generate(long pattern, int right, int n)
        {
            var vs = Enumerable.Range(1, right).ToArray();

            yield return NewMethod(pattern, right, vs, n);

            while (true)
            {
                var can = false;
                for (int i = right - 1; i >= 0; i--)
                {
                    var max = n - (right - 1 - i);
                    if (vs[i] < max)
                    {
                        vs[i]++;
                        for (int j = i + 1; j < right; j++)
                        {
                            vs[j] = vs[j - 1] + 1;
                        }

                        long sb = NewMethod(pattern, right, vs, n);

                        yield return sb;
                        can = true;
                        break;
                    }
                }

                if (!can)
                {
                    break;
                }
            }

        }

        private static long NewMethod(long pattern, int right, int[] vs, int n)
        {
            var sb = 0L;
            for (int j = 0; j < n; j++)
            {
                sb |= (~((1L << j) & pattern));
            }

            for (int j = 0; j < right; j++)
            {
                sb &= ~(1L << (vs[j] - 1));
                sb |= (1L << (vs[j] - 1)) & pattern;
                //sb[vs[j] - 1] = pattern[vs[j] - 1];
            }

            return sb;
        }

        static void solution()
        {
            #region SOLUTION
            var d = readIntArray();
            var n = d[0];
            var m = d[1];
            var inter = new HashSet<long>();

            for (int i = 0; i < m; i++)
            {
                var next = Console.ReadLine().Split(' ').ToArray();
                var line = next[0];
                var ct = int.Parse(next[1]);

                var pattern = 0L;
                for (int j = 0; j < n; j++)
                {
                    if (line[j] == '1')
                    {
                        pattern |= (1L << j);
                    }
                }

                if (i == 0)
                {
                    var c = generate(pattern, ct, n).ToArray();
                    //foreach (var item in c)
                    //{
                    //    for (int j = 0; j < n; j++)
                    //    {
                    //        Console.Write(((1L << j) & item) != 0 ? '1' : '0');
                    //    }

                    //    Console.WriteLine();
                    //}

                    inter.UnionWith(generate(pattern, ct, n));
                }
                else
                {
                    add(pattern, ct, n, inter);
                }
            }

            Console.WriteLine(inter.Count);

            //var n = readInt();
            //var m = readInt();

            //var a = readIntArray();
            //var b = readIntArray();
            #endregion
        }

        static int readInt()
        {
            return int.Parse(Console.ReadLine());
        }

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

        static int[] readIntArray()
        {
            return Console.ReadLine().Split(' ').Where(i => !string.IsNullOrEmpty(i)).Select(i => int.Parse(i)).ToArray();
        }

        static long[] readLongArray()
        {
            return Console.ReadLine().Split(' ').Where(i => !string.IsNullOrEmpty(i)).Select(i => long.Parse(i)).ToArray();
        }

#if DEBUG
		static StreamReader getInput()
		{
			var resName = Assembly.GetCallingAssembly().GetManifestResourceNames()[0];
			var resource = Assembly.GetCallingAssembly().GetManifestResourceStream(resName);

			return new StreamReader(resource);
		}
#endif
    }
}

Vasya tries to break in a safe. He knows that a code consists of n numbers, and every number is a 0 or a 1. Vasya has made m attempts to enter the code. After each attempt the system told him in how many position stand the right numbers. It is not said in which positions the wrong numbers stand. Vasya has been so unlucky that he hasn’t entered the code where would be more than 5 correct numbers. Now Vasya is completely bewildered: he thinks there’s a mistake in the system and it is self-contradictory. Help Vasya — calculate how many possible code variants are left that do not contradict the previous system responses.

The first input line contains two integers n and m (6 ≤ n ≤ 35, 1 ≤ m ≤ 10) which represent the number of numbers in the code and the number of attempts made by Vasya. Then follow m lines, each containing space-separated si and ci which correspondingly indicate Vasya’s attempt (a line containing n numbers which are 0 or 1) and the system’s response (an integer from 0 to 5 inclusively).

Print the single number which indicates how many possible code variants that do not contradict the m system responses are left.

#if DEBUG
using System.Reflection;
using System.Threading.Tasks;
#endif

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

namespace _44d
{
    class Program
    {
        static string _inputFilename = "input.txt";
        static string _outputFilename = "output.txt";
        static bool _useFileInput = false;

        static void Main(string[] args)
        {
            StreamWriter file = null;
#if DEBUG
			Console.SetIn(getInput());
#else
            if (_useFileInput)
            {
                Console.SetIn(File.OpenText(_inputFilename));
                file = new StreamWriter(_outputFilename);
                Console.SetOut(file);
            }
#endif

            try
            {
                solution();
            }
            finally
            {
                if (_useFileInput)
                {
                    file.Close();
                }
            }
        }

        static void add(long pattern, int right, int n, HashSet<long> vs)
        {
            //vs.Inte
            vs.IntersectWith(generate(pattern, right, n));
        }

        static IEnumerable<long> generate(long pattern, int right, int n)
        {
            var vs = Enumerable.Range(1, right).ToArray();

            yield return NewMethod(pattern, right, vs, n);

            while (true)
            {
                var can = false;
                for (int i = right - 1; i >= 0; i--)
                {
                    var max = n - (right - 1 - i);
                    if (vs[i] < max)
                    {
                        vs[i]++;
                        for (int j = i + 1; j < right; j++)
                        {
                            vs[j] = vs[j - 1] + 1;
                        }

                        var sb = NewMethod(pattern, right, vs, n);

                        yield return sb;
                        can = true;
                        break;
                    }
                }

                if (!can)
                {
                    break;
                }
            }

        }

        private static long NewMethod(long pattern, int right, int[] vs, int n)
        {
            //var init = getVal(pattern, n);

            var sb = 0L;
            for (int j = 0; j < n; j++)
            {
                //var ff = getVal((~((1L << j) & pattern)), n);
                sb |= (((1L << j) & pattern));
                sb ^= (1L << j);
            }

            //var after = getVal(sb, n);

            for (int j = 0; j < right; j++)
            {
                sb &= ~(1L << (vs[j] - 1));
                sb |= (1L << (vs[j] - 1)) & pattern;
                //sb[vs[j] - 1] = pattern[vs[j] - 1];
            }

            //var res = getVal(sb, n);
            //return res;
            return sb;
        }

        static string getVal(long a, int n)
        {
            var sb = new StringBuilder();
            for (int j = 0; j < n; j++)
            {
                sb.Append(((1L << j) & a) != 0 ? '1' : '0');
            }

            return sb.ToString();
        }

        static void solution()
        {
            #region SOLUTION
            var d = readIntArray();
            var n = d[0];
            var m = d[1];
            var inter = new HashSet<long>();

            for (int i = 0; i < m; i++)
            {
                var next = Console.ReadLine().Split(' ').ToArray();
                var line = next[0];
                var ct = int.Parse(next[1]);

                var pattern = 0L;
                for (int j = 0; j < n; j++)
                {
                    if (line[j] == '1')
                    {
                        pattern |= (1L << j);
                    }
                }

                if (i == 0)
                {
                    var c = generate(pattern, ct, n).ToArray();
                    //var c2 = generate(pattern, ct, n).ToArray();
                    //foreach (var item in c)
                    //{
                    //    for (int j = 0; j < n; j++)
                    //    {
                    //        Console.Write(((1L << j) & item) != 0 ? '1' : '0');
                    //    }

                    //    Console.WriteLine();
                    //}

                    inter.UnionWith(c);
                }
                else
                {
                    add(pattern, ct, n, inter);
                }
            }

            Console.WriteLine(inter.Count);

            //var n = readInt();
            //var m = readInt();

            //var a = readIntArray();
            //var b = readIntArray();
            #endregion
        }

        static int readInt()
        {
            return int.Parse(Console.ReadLine());
        }

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

        static int[] readIntArray()
        {
            return Console.ReadLine().Split(' ').Where(i => !string.IsNullOrEmpty(i)).Select(i => int.Parse(i)).ToArray();
        }

        static long[] readLongArray()
        {
            return Console.ReadLine().Split(' ').Where(i => !string.IsNullOrEmpty(i)).Select(i => long.Parse(i)).ToArray();
        }

#if DEBUG
		static StreamReader getInput()
		{
			var resName = Assembly.GetCallingAssembly().GetManifestResourceNames()[0];
			var resource = Assembly.GetCallingAssembly().GetManifestResourceStream(resName);

			return new StreamReader(resource);
		}
#endif
    }
}


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

class Program
{
    long[,] dp;
    long[] allLucky;
    long[] p10;
    int K;
    const long mod = 1000000007;
    void solve()
    {
        int Q = nextInt();
        K = nextInt();
        Do();
        for (int step = 1; step <= Q; step++)
        {
            string s = nextString();
            string t = nextString();
            long res = getStricklySmaller(t);
            res -= getStricklySmaller(s);
            if (isLucky(t))
                res++;
            res += mod;
            res %= mod;
            println(res);
        }

    }

    private long getStricklySmaller(string s)
    {
        int prev = -1;
        int d = 1001;
        long res = 0;
        for (int i = 0; i < s.Length; i++)
        {
            for (int cur = 0; cur < s[i] - '0'; cur++)
            {
                if (cur == 0 && i == 0)
                    continue;
                int nd = d;
                if ((cur == 4 || cur == 7) && prev != -1)
                    nd = Math.Min(nd, i - prev);
                if (nd <= K)
                    res += p10[s.Length - 1 - i];
                else
                {
                    int nprev = i-prev;
                    if (prev == -1)
                        nprev = 1001;
                    if (cur == 4 || cur == 7)
                        nprev = 0;
                    res += dp[nprev, s.Length - 1 - i];
                }
                res %= mod;
            }
            if (s[i] == '4' || s[i] == '7')
            {
                if (prev != -1)
                {
                    d = Math.Min(d, i - prev);
                }
                prev = i;
            }
        }
        for (int i = 1; i < s.Length; i++)
            res = (res + allLucky[i]) % mod;
        return res;
    }
    void Do()
    {
        dp = new long[1002, 1002];
        allLucky = new long[1002];
        p10 = new long[1002];
        for (int i = 0; i < p10.Length; i++)
        {
            p10[i] = (i == 0) ? 1 : 10 * p10[i - 1] % mod;
        }
        for (int digits = 0; digits < p10.Length; digits++)
            for (int prev = 0; prev < p10.Length; prev++)
            {
                if (digits > 0)
                {
                    long cur = 0;
                    //if lucky
                    if (prev <= K - 1)
                    {
                        cur += 2*p10[digits - 1];
                    }
                    else
                    {

                        cur += dp[0, digits - 1];
                    }
                    //end od luck
                    //not lucky
                    cur += 8*dp[Math.Min(1001, prev + 1), digits - 1];
                    //end of not lucky
                    dp[prev, digits] = cur % mod;
                }
            }
        for (int digits = 2; digits < p10.Length; digits++)
        {
            for (int first = 1; first <= 9; first++)
            {
                int prev = 1001;
                if (first == 4 || first == 7)
                {
                    prev = 0;
                }
                allLucky[digits] = (allLucky[digits] + dp[prev, digits - 1]) % mod;
            }
        }

    }
    bool isLucky(string s)
    {
        int prev = -1;
        int d = 1001;
        for (int i = 0; i < s.Length; i++)
        {
            if (s[i] == '4' || s[i] == '7')
            {
                if (prev != -1)
                {
                    d = Math.Min(d, i - prev);
                }
                prev = i;
            }
        }
        return d <= K;
    }

    ////////////
    private void println(int[] ar)
    {
        for (int i = 0; i < ar.Length; i++)
        {
            if (i == ar.Length - 1)
                println(ar[i]);
            else
                print(ar[i] + " ");
        }
    }
    private void println(int[] ar, bool add)
    {
        int A = 0;
        if (add)
            A++;
        for (int i = 0; i < ar.Length; i++)
        {
            if (i == ar.Length - 1)
                println(ar[i] + A);
            else
                print((ar[i] + A) + " ");
        }
    }

    private void println(string Stringst)
    {
        Console.WriteLine(Stringst);
    }
    private void println(char charnum)
    {
        Console.WriteLine(charnum);
    }
    private void println(int Intnum)
    {
        Console.WriteLine(Intnum);
    }
    private void println(long Longnum)
    {
        Console.WriteLine(Longnum);
    }
    private void println(double Doublenum)
    {
        string s = Doublenum.ToString(CultureInfo.InvariantCulture);
        Console.WriteLine(s);
    }

    private void print(string Stringst)
    {
        Console.Write(Stringst);
    }
    private void print(int Intnum)
    {
        Console.Write(Intnum);
    }
    private void print(char charnum)
    {
        Console.Write(charnum);
    }
    private void print(long Longnum)
    {
        Console.Write(Longnum);
    }
    private void print(double Doublenum)
    {
        Console.Write(Doublenum);
    }

    string[] inputLine = new string[0];
    int inputInd = 0;
    string nextLine()
    {
        return Console.ReadLine();
    }
    void readInput()
    {
        if (inputInd != inputLine.Length)
            throw new Exception();
        inputInd = 0;
        inputLine = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        if (inputLine.Length == 0)
            readInput();

    }
    int nextInt()
    {
        return int.Parse(nextString());
    }
    long nextLong()
    {
        return long.Parse(nextString());
    }
    double nextDouble()
    {
        return double.Parse(nextString());
    }
    string nextString()
    {
        if (inputInd == inputLine.Length)
            readInput();
        return inputLine[inputInd++];
    }
    static void Main(string[] args)
    {
        Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
        new Program().solve();
    }
}

Petya likes horse racing very much. Horses numbered from l to r take part in the races. Petya wants to evaluate the probability of victory; for some reason, to do that he needs to know the amount of nearly lucky horses' numbers. A nearly lucky number is an integer number that has at least two lucky digits the distance between which does not exceed k. Petya learned from some of his mates from Lviv that lucky digits are digits 4 and 7. The distance between the digits is the absolute difference between their positions in the number of a horse. For example, if k = 2, then numbers 412395497, 404, 4070400000070004007 are nearly lucky and numbers 4, 4123954997, 4007000040070004007 are not.Petya prepared t intervals [li, ri] and invented number k, common for all of them. Your task is to find how many nearly happy numbers there are in each of these segments. Since the answers can be quite large, output them modulo 1000000007 (109 + 7).

The first line contains two integers t and k (1 ≤ t, k ≤ 1000) — the number of segments and the distance between the numbers correspondingly. Next t lines contain pairs of integers li and ri (1 ≤ l ≤ r ≤ 101000). All numbers are given without the leading zeroes. Numbers in each line are separated by exactly one space character.

Output t lines. In each line print one integer — the answer for the corresponding segment modulo 1000000007 (109 + 7).

NoteIn the first sample, the four nearly lucky numbers are 44, 47, 74, 77.In the second sample, only 74 and 77 are in the given segment.

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

class Program
{
    long[,] dp;
    long[] allLucky;
    long[] p10;
    int K;
    const long mod = 1000000007;
    void solve()
    {
        int Q = nextInt();
        K = nextInt();
        Do();
        for (int step = 1; step <= Q; step++)
        {
            string s = nextString();
            string t = nextString();
            long res = getStricklySmaller(t);
            res -= getStricklySmaller(s);
            if (isLucky(t))
                res++;
            res += mod;
            res %= mod;
            println(res);
        }

    }

    private long getStricklySmaller(string s)
    {
        int prev = -1;
        int d = 1001;
        long res = 0;
        for (int i = 0; i < s.Length; i++)
        {
            for (int cur = 0; cur < s[i] - '0'; cur++)
            {
                if (cur == 0 && i == 0)
                    continue;
                int nd = d;
                if ((cur == 4 || cur == 7) && prev != -1)
                    nd = Math.Min(nd, i - prev);
                if (nd <= K)
                    res += p10[s.Length - 1 - i];
                else
                {
                    int nprev = i-prev;
                    if (prev == -1)
                        nprev = 1001;
                    if (cur == 4 || cur == 7)
                        nprev = 0;
                    res += dp[nprev, s.Length - 1 - i];
                }
                res %= mod;
            }
            if (s[i] == '4' || s[i] == '7')
            {
                if (prev != -1)
                {
                    d = Math.Min(d, i - prev);
                }
                prev = i;
            }
        }
        for (int i = 1; i < s.Length; i++)
            res = (res + allLucky[i]) % mod;
        return res;
    }
    void Do()
    {
        dp = new long[1002, 1002];
        allLucky = new long[1002];
        p10 = new long[1002];
        for (int i = 0; i < p10.Length; i++)
        {
            p10[i] = (i == 0) ? 1 : 10 * p10[i - 1] % mod;
        }
        for (int digits = 0; digits < p10.Length; digits++)
            for (int prev = 0; prev < p10.Length; prev++)
            {
                if (digits > 0)
                {
                    long cur = 0;
                    //if lucky
                    if (prev <= K - 1)
                    {
                        cur += 2*p10[digits - 1];
                    }
                    else
                    {

                        cur += 2*dp[0, digits - 1];
                    }
                    //end od luck
                    //not lucky
                    cur += 8*dp[Math.Min(1001, prev + 1), digits - 1];
                    //end of not lucky
                    dp[prev, digits] = cur % mod;
                }
            }
        for (int digits = 2; digits < p10.Length; digits++)
        {
            for (int first = 1; first <= 9; first++)
            {
                int prev = 1001;
                if (first == 4 || first == 7)
                {
                    prev = 0;
                }
                allLucky[digits] = (allLucky[digits] + dp[prev, digits - 1]) % mod;
            }
        }

    }
    bool isLucky(string s)
    {
        int prev = -1;
        int d = 1001;
        for (int i = 0; i < s.Length; i++)
        {
            if (s[i] == '4' || s[i] == '7')
            {
                if (prev != -1)
                {
                    d = Math.Min(d, i - prev);
                }
                prev = i;
            }
        }
        return d <= K;
    }

    ////////////
    private void println(int[] ar)
    {
        for (int i = 0; i < ar.Length; i++)
        {
            if (i == ar.Length - 1)
                println(ar[i]);
            else
                print(ar[i] + " ");
        }
    }
    private void println(int[] ar, bool add)
    {
        int A = 0;
        if (add)
            A++;
        for (int i = 0; i < ar.Length; i++)
        {
            if (i == ar.Length - 1)
                println(ar[i] + A);
            else
                print((ar[i] + A) + " ");
        }
    }

    private void println(string Stringst)
    {
        Console.WriteLine(Stringst);
    }
    private void println(char charnum)
    {
        Console.WriteLine(charnum);
    }
    private void println(int Intnum)
    {
        Console.WriteLine(Intnum);
    }
    private void println(long Longnum)
    {
        Console.WriteLine(Longnum);
    }
    private void println(double Doublenum)
    {
        string s = Doublenum.ToString(CultureInfo.InvariantCulture);
        Console.WriteLine(s);
    }

    private void print(string Stringst)
    {
        Console.Write(Stringst);
    }
    private void print(int Intnum)
    {
        Console.Write(Intnum);
    }
    private void print(char charnum)
    {
        Console.Write(charnum);
    }
    private void print(long Longnum)
    {
        Console.Write(Longnum);
    }
    private void print(double Doublenum)
    {
        Console.Write(Doublenum);
    }

    string[] inputLine = new string[0];
    int inputInd = 0;
    string nextLine()
    {
        return Console.ReadLine();
    }
    void readInput()
    {
        if (inputInd != inputLine.Length)
            throw new Exception();
        inputInd = 0;
        inputLine = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        if (inputLine.Length == 0)
            readInput();

    }
    int nextInt()
    {
        return int.Parse(nextString());
    }
    long nextLong()
    {
        return long.Parse(nextString());
    }
    double nextDouble()
    {
        return double.Parse(nextString());
    }
    string nextString()
    {
        if (inputInd == inputLine.Length)
            readInput();
        return inputLine[inputInd++];
    }
    static void Main(string[] args)
    {
        Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
        new Program().solve();
    }
}


using System;
using System.Collections.Generic;

class Program
{
    const long inf = int.MaxValue;
	void solve()
	{

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

        long b = 0;
        long c=0;
        foreach (char ch in s[2])
        {
            c = (10 * c + ch - '0');
        }
        foreach (char ch in s[0])
            b = (10 * b + ch - '0') % c;
        long ret = 1;
        long p = b;
        char[] t = s[1].ToCharArray();
        for (int i = t.Length - 1; i >= 0; i--)
        {
            if (t[i] == '0')
                t[i] = '9';
            else
            {
                t[i]--;
                break;
            }
        }
        for (int i = t.Length - 1; i >= 0; i--)
        {
            long np = 1;
            for (int j = 0; j < t[i] - '0'; j++)
                np = (np * p) % c;
            ret *= np;
            ret %= c;
            for (int j = t[i] - '0'; j <= '9'; j++)
                np = (p * np) % c;
            p = np;
        }
        ret = ret * (b - 1 + c) % c;
        if (ret == 0)
            ret = c;
        println(ret);

	}

    ////////////

    private void println(string Stringst)
    {
        Console.WriteLine(Stringst);
    }
    private void println(int Intnum)
    {
        Console.WriteLine(Intnum);
    }
    private void println(long Longnum)
    {
        Console.WriteLine(Longnum);
    }
    private void println(double Doublenum)
    {
        Console.WriteLine(Doublenum);
    }

    private void print(string Stringst)
    {
        Console.Write(Stringst);
    }
    private void print(int Intnum)
    {
        Console.Write(Intnum);
    }
    private void print(long Longnum)
    {
        Console.Write(Longnum);
    }
    private void print(double Doublenum)
    {
        Console.Write(Doublenum);
    }

    string[] inputLine = new string[0];
    int inputInd = 0;
    string nextLine()
    {
        return Console.ReadLine();
    }
    void readInput()
    {
        if (inputInd != inputLine.Length)
            throw new Exception();
        inputInd = 0;
        inputLine = Console.ReadLine().Split(new char[]{' '},StringSplitOptions.RemoveEmptyEntries);
        if (inputLine.Length == 0)
            readInput();

    }
    int nextInt()
    {
        if (inputInd == inputLine.Length)
            readInput();
        return int.Parse(inputLine[inputInd++]);
    }
    long nextLong()
    {
        if (inputInd == inputLine.Length)
            readInput();
        return long.Parse(inputLine[inputInd++]);
    }
    double nextDouble()
    {
        if (inputInd == inputLine.Length)
            readInput();
        return double.Parse(inputLine[inputInd++]);
    }
    string nextString()
    {
        if (inputInd == inputLine.Length)
            readInput();
        return inputLine[inputInd++];
    }
    static void Main(string[] args)
    {
        new Program().solve();
    }
}

Nick is attracted by everything unconventional. He doesn't like decimal number system any more, and he decided to study other number systems. A number system with base b caught his attention. Before he starts studying it, he wants to write in his notepad all the numbers of length n without leading zeros in this number system. Each page in Nick's notepad has enough space for c numbers exactly. Nick writes every suitable number only once, starting with the first clean page and leaving no clean spaces. Nick never writes number 0 as he has unpleasant memories about zero divide.Would you help Nick find out how many numbers will be written on the last page.

The only input line contains three space-separated integers b, n and c (2 ≤ b < 10106, 1 ≤ n < 10106, 1 ≤ c ≤ 109). You may consider that Nick has infinite patience, endless amount of paper and representations of digits as characters. The numbers doesn't contain leading zeros.

In the only line output the amount of numbers written on the same page as the last number.

NoteIn both samples there are exactly 4 numbers of length 3 in binary number system. In the first sample Nick writes 3 numbers on the first page and 1 on the second page. In the second sample all the 4 numbers can be written on the first page.

using System;
using System.Diagnostics;
using System.Collections.Generic;

namespace A
{
    class Program
    {
        public static void Main(string[] argv)
        {
            String[] s = Console.ReadLine().Split(' ');
            String b = s[0];
            String n = s[1];
            long c = long.Parse(s[2]);
            long bb = 0;
            foreach(char i in b){
                bb = (bb*10 + (int)(i - '0' ))%c;
            }
            long tbb = (bb + c - 1) % c;
            long ret = 1;
            long ki = bb;
            bool isan = true;
            for (int i = n.Length - 1; i >= 0; i--)
            {
                int nn = (int)(n[i]-'0');
                if (isan == true)
                {
                    if (nn == 0)
                    {
                        nn = 9;
                    }
                    else
                    {
                        nn--;
                        isan = false;
                    }
                }
                for (int j = 0; j < nn; j++)
                {
                    ret = (ret * ki) % c;
                }
                long nki = 1;
                for (int j = 0; j < 10; j++)
                {
                    nki = (nki * ki) % c;
                }
                ki = nki;
            }
            //Console.WriteLine(tbb + " " + ret + " " + bb);
            long count = (tbb * ret) % c;
            if (count == 0) count = c;
            Console.WriteLine(count);
        }
    }
}