using System;
using System.IO;
using System.Linq;
using System.Text;

namespace CF {
    class Program {

        static int N;
        static int M;

        static void Main(string[] args) {

#if DEBUG
            TextReader reader = new StreamReader("../../input.txt");
            TextWriter writer = Console.Out;
#else
			TextReader reader = Console.In;
            TextWriter writer = Console.Out;
#endif

            var n = reader.Read<int>();
            var m = reader.Read<int>();

            var game1 = 0;
            if (n > 0) {
                N = n;
                M = m;
                game1 = PetyaAttempt(true);
            }
            var game2 = 0;
            if (m > 0) {
                N = n;
                M = m;
                game2 = PetyaAttempt(false);
            }

            var p = Math.Max(game1,game2);
            var v = Math.Max(0, n + m - 1 - p);

            Console.WriteLine("{0} {1}", p, v);

#if DEBUG
            Console.ReadKey();
#endif
        }

        private static int PetyaAttempt(bool first){
            if (first) N--;
            if (!first) M--;
            bool prevColor = first;
            bool petyaTurn = false;
            int petyaCount = 0;

            while (N+M > 0) {
                bool next = Step(petyaTurn, prevColor);
                petyaTurn = !petyaTurn;
                if (prevColor == next)
                    petyaCount++;
                if (next) N--;
                else M--;
                prevColor = next;
            }

            return petyaCount;
        }

        private static bool Step(bool isPetya, bool prevColor) {
            if (N == 0) {
                return false;
            }
            if (M == 0) {
                return true;
            }

            if (isPetya) {
                return prevColor;
            }
            return !prevColor;
        }

    }

    class Pair<T1, T2> {
        public Pair(T1 first, T2 second) {
            First = first;
            Second = second;
        }
        public T1 First { get; set; }
        public T2 Second { get; set; }
        public override string ToString() {
            return "{" + First + " " + Second + "}";
        }
    }

    static class ReaderExtensions {

        public static string ReadToken(this TextReader reader) {
            int val;
            var builder = new StringBuilder();
            while (true) {
                val = reader.Read();
                if (val == ' ' || val == -1){
                    if(builder.Length == 0) continue;
                    break;
                }
                if (val == 13) {
                    reader.Read();
                    if (builder.Length == 0) continue;
                    break;
                }
                builder.Append((char)val);
            }
            return builder.ToString();
        }

        public static T Read<T>(this TextReader reader) {
            return (T)Convert.ChangeType(reader.ReadToken(), typeof(T));
        }

        public static T[] ReadArr<T>(this TextReader reader) {
            return reader.ReadLine()
                .Split(' ').Select(str =>
                    (T)Convert.ChangeType(str, typeof(T))
                ).ToArray();
        }

    }

}


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

namespace G.GangUp
{
    internal static class Program
    {
        public static void Main(string[] args)
        {
            var nmkcd = Console.ReadLine().Split();
            var n = int.Parse(nmkcd[0]);
            var m = int.Parse(nmkcd[1]);
            var k = int.Parse(nmkcd[2]);
            var c = int.Parse(nmkcd[3]);
            var d = int.Parse(nmkcd[4]);

            var memberHomes = Console.ReadLine().Split().Select(int.Parse);
            var graph = ReadGraph(n, m, k);
            FindPathLengths(graph);

            var solver = new Solver(n, c, d);

            foreach (var memberHome in memberHomes)
                solver.AddDiscontentForMember(graph[memberHome]);

            Console.WriteLine(solver.Discontent);
        }

        private static GraphNode[] ReadGraph(int n, int m, int k)
        {
            var graph = new GraphNode[n + 1];
            for (var i = 1; i <= n; i++)
                graph[i] = new GraphNode(i, m);

            for (var i = 0; i < m; i++)
            {
                var xy = Console.ReadLine().Split();
                var x = graph[int.Parse(xy[0])];
                var y = graph[int.Parse(xy[1])];

                x.Edges.Add(new Edge() { Node = y, TimeInfo = new TimeInfo(k) });
                y.Edges.Add(new Edge() { Node = x, TimeInfo = new TimeInfo(k) });
            }

            return graph;
        }

        private static void FindPathLengths(GraphNode[] graph)
        {
            var queue = new Queue<GraphNode>(graph.Length);

            var node = graph[1];
            node.PathLength = 0;
            queue.Enqueue(node);

            while (queue.Count > 0)
            {
                node = queue.Dequeue();
                var newPathLength = node.PathLength + 1;

                foreach (var neighbour in node.Edges.Select(it => it.Node))
                {
                    if (neighbour.PathLength <= newPathLength)
                        continue;

                    neighbour.PathLength = newPathLength;
                    queue.Enqueue(neighbour);
                }
            }
        }
    }

    internal sealed class Solver
    {
        private readonly int _c, _d, _cPlusD;
        private readonly EdgeIndexWithTime[] _bestPath;

        private int _currentBestDiscontent, _bestPathLength;

        public Solver(int n, int c, int d)
        {
            _c = c;
            _d = d;
            _cPlusD = c + d;
            _bestPath = new EdgeIndexWithTime[n + 1];
        }

        public int Discontent { get; private set; }

        public void AddDiscontentForMember(GraphNode home)
        {
            _currentBestDiscontent = int.MaxValue;
            TryOptimize(home, 0, 0, 0);
            CommitBestPath(home);
            Discontent += _currentBestDiscontent;
        }

        private bool TryOptimize(GraphNode node, int time, int baseDiscontent, int bestPathIndex)
        {
            if (node.Id == 1)
            {
                if (baseDiscontent >= _currentBestDiscontent)
                    return false;

                _bestPathLength = bestPathIndex;
                _currentBestDiscontent = baseDiscontent;
                return true;
            }

            node.AlreadyInCurrentPath = true;

            var optimized = false;

            var nextBestPathIndex = bestPathIndex + 1;

            for (var idealContinuationDiscontent = baseDiscontent + node.PathLength * _cPlusD;
                idealContinuationDiscontent < _currentBestDiscontent;
                idealContinuationDiscontent += _c, ++time)
            {
                var nextTime = time + 1;
                baseDiscontent += _c;

                for (var edgeIndex = 0; edgeIndex < node.Edges.Count; edgeIndex++)
                {
                    var edge = node.Edges[edgeIndex];

                    var neighbour = edge.Node;
                    if (neighbour.AlreadyInCurrentPath)
                        continue;

                    var nextBaseDiscontent = baseDiscontent +
                                             CalculateDiscontentChange(edge.TimeInfo[time]);

                    if (!TryOptimize(neighbour, nextTime, nextBaseDiscontent, nextBestPathIndex))
                        continue;

                    _bestPath[bestPathIndex] = new EdgeIndexWithTime() {EdgeIndex = edgeIndex, Time = time};
                    optimized = true;
                }
            }

            node.AlreadyInCurrentPath = false;
            return optimized;
        }

        private void CommitBestPath(GraphNode current)
        {
            foreach (var edgeIndexWithTime in _bestPath.Take(_bestPathLength))
            {
                var edge = current.Edges[edgeIndexWithTime.EdgeIndex];
                ++edge.TimeInfo[edgeIndexWithTime.Time];
                current = edge.Node;
            }
        }

        private int CalculateDiscontentChange(int peopleWalkingTheSameTime)
        {
            var oldDiscontentD = peopleWalkingTheSameTime * peopleWalkingTheSameTime * _d;
            ++peopleWalkingTheSameTime;
            var newDiscontentD = peopleWalkingTheSameTime * peopleWalkingTheSameTime * _d;
            return newDiscontentD - oldDiscontentD;
        }

        private struct EdgeIndexWithTime
        {
            public int EdgeIndex { get; set; }
            public int Time { get; set; }
        }
    }

    internal sealed class GraphNode : IEquatable<GraphNode>
    {
        public GraphNode(int id, int m)
        {
            Id = id;
            Edges = new List<Edge>(m);
        }

        public int Id { get; }

        public int PathLength { get; set; } = 1000;

        public bool AlreadyInCurrentPath { get; set; }

        public List<Edge> Edges { get; }

        public bool Equals(GraphNode other) => Id == other?.Id;

        public override bool Equals(object obj) => obj is GraphNode graphNode && graphNode.Id == Id;

        public override int GetHashCode() => Id;
    }

    internal struct TimeInfo
    {
        private readonly Dictionary<int, int> _peopleCounts;

        public TimeInfo(int capacity) { _peopleCounts = new Dictionary<int, int>(capacity); }

        public int this[int time]
        {
            get
            {
                _peopleCounts.TryGetValue(time, out var peopleCount);
                return peopleCount;
            }

            set => _peopleCounts[time] = value;
        }
    }

    internal struct Edge
    {
        public GraphNode Node;
        public TimeInfo TimeInfo;
    }
}


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

namespace Codeforces
{

    class Program
    {
        public static readonly int MOD = Convert.ToInt32(1e9 + 7);
        public static readonly int oo = Convert.ToInt32(1e9);
        public static readonly long OO = Convert.ToInt64(1e18);

        static void Main(string[] args)
        {
            int weights = int.Parse(Console.ReadLine());
            int[] masses = Console.ReadLine().Split(' ').Select(s => int.Parse(s)).ToArray();
            int[] cnt = new int[101];
            foreach (int mass in masses)
            {
                cnt[mass]++;
            }

            if (masses.Select(mass => mass > 0).Count() <= 2)
            {
                Console.WriteLine(weights);
                return;
            }

            int[,] C = new int[101, 101];
            C[0, 0] = 1;
            for (int i = 1; i <= 100; i++)
            {
                C[i, 0] = C[i, i] = 1;
                for (int j = 1; j < i; j++)
                {
                    C[i, j] = (C[i - 1, j] + C[i - 1, j - 1]) % MOD;
                }
            }

            int sum = masses.Sum();
            int[,] ways = new int[weights + 1, sum + 1];
            ///
            /// dp(i, j, k) = dp(i - 1, j - 1, k - masses[j])
            ///

            ways[0, 0] = 1;
            for (int i = 0; i < weights; i++)
            {
                int[,] nways = new int[weights + 1, sum + 1];
                nways[0, 0] = 1;
                for (int j = 1; j <= i + 1; j++)
                {
                    for (int k = sum; k > 0; k--)
                    {
                        nways[j, k] = ways[j, k];
                        if (k >= masses[i])
                        {
                            nways[j, k] = (nways[j, k] + ways[j - 1, k - masses[i]]) % MOD;
                        }
                    }
                }

                ways = nways;
            }

            int ans = 1;
            for (int i = 1; i <= 100; i++)
            {
                if (cnt[i] > 0)
                {
                    for (int j = i; j <= sum; j += i)
                    {
                        if (j / i <= weights && ways[j / i, j] > 0 && ways[j / i, j] == C[cnt[i], j / i])
                        {
                            ans = Math.Max(ans, j / i);
                        }
                    }
                }
            }

            Console.WriteLine(ans);

        }

    }

}


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

namespace ConsoleApplication1
{
    public static class MainClass
    {
        const int BufferSize = (1 << 10) * 10;

        const int Module = 1000000007;

        static readonly StreamReader Reader = new StreamReader(Console.OpenStandardInput(BufferSize), Encoding.ASCII, false, BufferSize);
        static readonly StreamWriter Writer = new StreamWriter(Console.OpenStandardOutput(BufferSize), Encoding.ASCII, BufferSize);

        static void Main(string[] args)
        {
            //var thread = new Thread(Solve) {Priority = ThreadPriority.Highest};
            //thread.Start();
            Solve();
            //Console.ReadKey();
        }

        static void Solve()
        {
            var n = NextNumber();
            var k = NextLongNumber();

            var func = new long[n + 1];
            func[0] = 1;
            func[1] = 1;

            for (var i = 2; i <= n; i++)
            {
                func[i] = func[i - 1] + func[i - 2];
            }

            for (var i = 1; i <= n; i++)
            {
                if (k > func[n - i])
                {
                    k -= func[n - i];

                    Writer.Write("{0} {1} ", i + 1, i);
                    i++;
                }
                else
                {
                    Writer.Write("{0} ", i);
                }
            }

            Writer.Flush();
        }

        static void ReverseArray(ref int[] array, int left, int right)
        {
            if (right < left) return;

            var middle = left + (right - left) / 2;
            for (var i = left; i <= middle; i++)
            {
                Swap(ref array[i], ref array[right + left - i]);
            }
        }

        static void Swap<T>(ref T firstElement, ref T secondElement)
        {
            var temp = firstElement;
            firstElement = secondElement;
            secondElement = temp;
        }

        static void Swap<T>(IList<T> collection, int firstIndex, int secondIndex)
        {
            var temp = collection[firstIndex];
            collection[firstIndex] = collection[secondIndex];
            collection[secondIndex] = temp;
        }

        static int GCD(int firstNumber, int secondNumber)
        {
            return secondNumber == 0 ? firstNumber : GCD(secondNumber, firstNumber % secondNumber);
        }

        static int NextNumber()
        {
            var resultNumber = 0;
            var isNegative = false;
            int symbol;

            do
            {
                symbol = Reader.Read();
                switch (symbol)
                {
                    case '-':
                        isNegative = true;
                        break;
                    case '.':
                        return 1;
                    case -1:
                        return isNegative ? -resultNumber : resultNumber;
                }

                if (symbol >= 'a' && symbol <= 'z')
                {
                    return -1;
                }
            } while (symbol < '0' || symbol > '9');

            resultNumber = symbol - '0';
            while (true)
            {
                symbol = Reader.Read();
                if (symbol < '0' || symbol > '9')
                {
                    return isNegative ? -resultNumber : resultNumber;
                }

                resultNumber *= 10;
                resultNumber += symbol - '0';
            }
        }

        static long NextLongNumber()
        {
            var resultNumber = 0L;
            var isNegative = false;
            int symbol;

            do
            {
                symbol = Reader.Read();
                switch (symbol)
                {
                    case '-':
                        isNegative = true;
                        break;
                    case '.':
                        return 1;
                    case -1:
                        return isNegative ? -resultNumber : resultNumber;
                }

                if (symbol >= 'a' && symbol <= 'z')
                {
                    return -1;
                }
            } while (symbol < '0' || symbol > '9');

            resultNumber = (long)symbol - '0';
            while (true)
            {
                symbol = Reader.Read();
                if (symbol < '0' || symbol > '9')
                {
                    return isNegative ? -resultNumber : resultNumber;
                }

                resultNumber *= 10L;
                resultNumber += (long)symbol - '0';
            }
        }

        static int ReadNumber()
        {
            return int.Parse(Reader.ReadLine());
        }

        static long ReadLongNumber()
        {
            return long.Parse(Reader.ReadLine());
        }

        static int[] ReadArray()
        {
            var inputLine = Reader.ReadLine().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            var resultArray = new int[inputLine.Length];
            for (var i = 0; i < inputLine.Length; i++)
            {
                resultArray[i] = int.Parse(inputLine[i]);
            }

            return resultArray;
        }
    }
}


//Rextester.Program.Main is the entry point for your code. Don't change it.
//Compiler version 4.0.30319.17929 for Microsoft (R) .NET Framework 4.5

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

namespace Rextester
{
    public class Program
    {
        public static long[] fibo = new long[52];
        public static void Main(string[] args)
        {
            fibo[0] = 1;
            fibo[1] = 2;
            for (var i = 2; i < 52; i++) fibo[i] = fibo[i-1] + fibo[i-2];

            var arg = Console.ReadLine().Split(' ');
            var amount = int.Parse(arg[0]);
            var num = long.Parse(arg[1]);
            var r = Solve(amount, num - 1, 1);

            Console.WriteLine(String.Join(" ", r));
        }

        public static List<int> Solve(int amount, long num, int start) {
            var r = new List<int>();
            if (amount == 0) return r;
            var end = start;
            while (amount > 1 && num - fibo[amount-2] >= 0) {
                num -= fibo[amount-2];
                end++;
                amount--;
            }

            for (var curr = end; curr >= start; curr--) r.Add(curr);

            r.AddRange(Solve(amount-1, num, end+1));
            return r;
        }
    }
}


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

namespace Brauzer
{
    class Program
    {
        private static int CalculateTime(int n,int pos,int l, int r)
        {
            if (l == 1 && r == n) return 0;
            int count = 0;
            if (l > 1 && r < n) count += r - l;
            if (pos >= l && pos <= r)
            {
                if (l == 1)
                    count += r - pos+1;
                else
                    if (r == n) count += pos - l+1; else count += Math.Min(r - pos, pos - l)+2;
                return count;
            }

            if (pos < l || (pos == l && l > 1))
            {
                count += l - pos+1;
                if (r < n) count++;
                return count;
            }

            if (pos > r || (pos == r && r < n))
            {
                count += pos - r+1;
                if (l > 1) count++;
            }

            return count;
        }

        static void Main(string[] args)
        {
            string[] s = Console.ReadLine().Split();

            int n = int.Parse(s[0]);
            int pos = int.Parse(s[1]);
            int l = int.Parse(s[2]);
            int r = int.Parse(s[3]);

            Console.Write(CalculateTime(n,pos,l,r));

        }
    }
}


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

class Solver
{
    public void Solve()
    {
        var ss = Console.ReadLine().Split(' ');
        int n = int.Parse(ss[0]);
        int m = int.Parse(ss[1]);
        int k = int.Parse(ss[2]);

        int[,][] d = new int[n,m][];
        for (int p = 0; p < n; p++)
        {
            Console.ReadLine();
            for (int i = 0; i < m; i++)
            {
                ss = Console.ReadLine().Split(' ');
                d[p, i] = new int[3];
                d[p,i][0] = int.Parse(ss[0]);
                d[p, i][1] = int.Parse(ss[1]);
                d[p, i][2] = int.Parse(ss[2]);
            }
        }

        int max = 0;
        for (int p1 = 0; p1 < n; p1++)
        {
            for (int p2 = 0; p2 < n; p2++)
            {
                var list = new List<KeyValuePair<int,int>>();
                for (int i = 0; i < m; i++)
                {
                    var kv = new KeyValuePair<int,int>( d[p2,i][1]-d[p1,i][0],i );
                    list.Add(kv);
                }
                list.Sort(delegate(KeyValuePair<int,int>kv1,KeyValuePair<int,int>kv2){
                    return -(kv1.Key-kv2.Key);
                });

                int q = k;
                int prof = 0;
                foreach(var v in list)
                {
                    if (v.Key <= 0)
                        break;
                    if (q == 0)
                        break;
                    int qq = Math.Min(q,d[p1,v.Value][2]);
                    prof+=(v.Key* qq);
                    q -= qq;
                }

                max = Math.Max(max, prof);
            }
        }
        Console.WriteLine(max);
    }

#if !DEBUG
    static void Main(string[] args)
    {
        new Solver().Solve();
    }
#endif
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Numerics;
using E = System.Linq.Enumerable;

namespace Prob13 {
    class Program {
        protected IOHelper io;

        public Program(string inputFile, string outputFile) {
            io = new IOHelper(inputFile, outputFile, Encoding.Default);

            long n = long.Parse(io.NextToken());
            n %= 360;
            if (n < 0) n += 360;
            io.WriteLine((n-45 + 89) / 90);

            io.Dispose();
        }

        static void Main(string[] args) {
            Program myProgram = new Program(null, null);
        }
    }

    class IOHelper : IDisposable {
        public StreamReader reader;
        public StreamWriter writer;

        public IOHelper(string inputFile, string outputFile, Encoding encoding) {
            if (inputFile == null)
                reader = new StreamReader(Console.OpenStandardInput(), encoding);
            else
                reader = new StreamReader(inputFile, encoding);

            if (outputFile == null)
                writer = new StreamWriter(Console.OpenStandardOutput(), encoding);
            else
                writer = new StreamWriter(outputFile, false, encoding);

            curLine = new string[] { };
            curTokenIdx = 0;
        }

        string[] curLine;
        int curTokenIdx;

        char[] whiteSpaces = new char[] { ' ', '\t', '\r', '\n' };

        public bool hasNext() {
            if (curTokenIdx >= curLine.Length) {
                //Read next line
                string line = reader.ReadLine();
                if (line != null)
                    curLine = line.Split(whiteSpaces, StringSplitOptions.RemoveEmptyEntries);
                else
                    curLine = new string[] { };
                curTokenIdx = 0;
            }

            return curTokenIdx < curLine.Length;
        }

        public string NextToken() {
            return hasNext() ? curLine[curTokenIdx++] : null;
        }

        public int NextInt() {
            return int.Parse(NextToken());
        }

        public double NextDouble() {
            string tkn = NextToken();
            return double.Parse(tkn, System.Globalization.CultureInfo.InvariantCulture);
        }

        public void Write(double val, int precision) {
            writer.Write(val.ToString("F" + precision, System.Globalization.CultureInfo.InvariantCulture));
        }

        public void Write(object stringToWrite) {
            writer.Write(stringToWrite);
        }

        public void WriteLine(double val, int precision) {
            writer.WriteLine(val.ToString("F" + precision, System.Globalization.CultureInfo.InvariantCulture));
        }

        public void WriteLine(object stringToWrite) {
            writer.WriteLine(stringToWrite);
        }

        public void Dispose() {
            try {
                if (reader != null) {
                    reader.Dispose();
                }
                if (writer != null) {
                    writer.Flush();
                    writer.Dispose();
                }
            } catch { };
        }

        public void Flush() {
            if (writer != null) {
                writer.Flush();
            }
        }
    }
}


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

namespace _630M_Turn
{
    class Program
    {
        static void Main(string[] args)
        {
            long x = long.Parse(Console.ReadLine());

            if (Math.Abs(x) > 360)
                x %= 360;
            if (x < 0)
                x += 360;
            if (x <= 45 || x >= 315 )
                Console.WriteLine("0");
            else if (x > 45 && x <= 135)
                Console.WriteLine("1");
            else if (x > 135 && x <= 225)
                Console.WriteLine("2");
            else
                Console.WriteLine("3");
        }
    }
}


using System;
using System.Linq;
using System.Collections.Generic;
using Debug = System.Diagnostics.Debug;
using StringBuilder = System.Text.StringBuilder;
using System.Numerics;
using Point = System.Numerics.Complex;
using Number = System.Int64;
namespace Program
{
    public class Solver
    {
        public void Solve()
        {
            var n = sc.Integer();
            var m = sc.Integer();
            var dist = Enumerate(n, x => new int[n]);
            for (int i = 0; i < n; i++)
                for (int j = i + 1; j < n; j++)
                    dist[i][j] = dist[j][i] = 10000000;
            var G = Enumerate(n, x => new List<int>());
            for (int i = 0; i < m; i++)
            {
                var f = sc.Integer() - 1;
                var t = sc.Integer() - 1;
                G[f].Add(t);
                G[t].Add(f);
                dist[f][t] = dist[t][f] = 1;
            }
            for (int k = 0; k < n; k++)
                for (int i = 0; i < n; i++)
                    for (int j = 0; j < n; j++)
                        dist[i][j] = Math.Min(dist[i][j], dist[i][k] + dist[k][j]);

            var vs = Enumerate(n, x => Enumerate(n, y => new List<int>()));
            for (int i = 0; i < n; i++)
                for (int j = 0; j < n; j++)
                {
                    var x = dist[i][j];
                    vs[i][x].Add(j);
                }
            var max = 1.0 / n;

            //必ず n 個
            for (int f = 0; f < n; f++)
            {
                var psum = 0.0;
                //全体でn個
                for (int d = 0; d < n; d++)
                {

                    var cnt = vs[f][d].Count;
                    if (cnt == 0) continue;
                    var x = 1.0 / n;

                    var p = new double[n];
                    //合計で m 個
                    //ここまででO(N(N+M))
                    var vv = new List<int>();
                    foreach (var v in vs[f][d])
                        foreach (var to in G[v]) { p[to] += 1.0 / (n * G[v].Count); vv.Add(to); }
                    vv = vv.Distinct().ToList();
                    psum += Math.Max(x, solve(n, p, vv, dist));
                }
                max = Math.Max(max, psum);
            }
            IO.Printer.Out.WriteLine(max);
        }
        double solve(int n, double[] p, List<int> vs, int[][] d)
        {
            var ret = 0.0;
            var r = new double[n];
            for (int f = 0; f < n; f++)
            {
                var z = 0.0;
                foreach (var v in vs)
                {
                    var x = d[f][v];
                    r[x] = Math.Max(r[x], p[v]);
                }
                foreach (var v in vs)
                {
                    var x = d[f][v];
                    z += r[x];
                    r[x] = 0;
                }

                ret = Math.Max(ret, z);
            }
            return ret;
        }
        public IO.StreamScanner sc = new IO.StreamScanner(Console.OpenStandardInput());
        static T[] Enumerate<T>(int n, Func<int, T> f) { var a = new T[n]; for (int i = 0; i < n; ++i) a[i] = f(i); return a; }
        static public void Swap<T>(ref T a, ref T b) { var tmp = a; a = b; b = tmp; }
    }
}

#region main
static class Ex
{
    static public string AsString(this IEnumerable<char> ie) { return new string(System.Linq.Enumerable.ToArray(ie)); }
    static public string AsJoinedString<T>(this IEnumerable<T> ie, string st = " ") { return string.Join(st, ie); }
    static public void Main()
    {
        var solver = new Program.Solver();
        solver.Solve();
        Program.IO.Printer.Out.Flush();
    }
}
#endregion
#region Ex
namespace Program.IO
{
    using System.IO;
    using System.Text;
    using System.Globalization;
    public class Printer: StreamWriter
    {
        static Printer() { Out = new Printer(Console.OpenStandardOutput()) { AutoFlush = false }; }
        public static Printer Out { get; set; }
        public override IFormatProvider FormatProvider { get { return CultureInfo.InvariantCulture; } }
        public Printer(System.IO.Stream stream) : base(stream, new UTF8Encoding(false, true)) { }
        public Printer(System.IO.Stream stream, Encoding encoding) : base(stream, encoding) { }
        public void Write<T>(string format, T[] source) { base.Write(format, source.OfType<object>().ToArray()); }
        public void WriteLine<T>(string format, T[] source) { base.WriteLine(format, source.OfType<object>().ToArray()); }
    }
    public class StreamScanner
    {
        public StreamScanner(Stream stream) { str = stream; }
        public readonly Stream str;
        private readonly byte[] buf = new byte[1024];
        private int len, ptr;
        public bool isEof = false;
        public bool IsEndOfStream { get { return isEof; } }
        private byte read()
        {
            if (isEof) return 0;
            if (ptr >= len) { ptr = 0; if ((len = str.Read(buf, 0, 1024)) <= 0) { isEof = true; return 0; } }
            return buf[ptr++];
        }
        public char Char() { byte b = 0; do b = read(); while ((b < 33 || 126 < b) && !isEof); return (char)b; }

        public string Scan()
        {
            var sb = new StringBuilder();
            for (var b = Char(); b >= 33 && b <= 126; b = (char)read())
                sb.Append(b);
            return sb.ToString();
        }
        public string ScanLine()
        {
            var sb = new StringBuilder();
            for (var b = Char(); b != '\n'; b = (char)read())
                if (b == 0) break;
                else if (b != '\r') sb.Append(b);
            return sb.ToString();
        }
        public long Long()
        {
            if (isEof) return long.MinValue;
            long ret = 0; byte b = 0; var ng = false;
            do b = read();
            while (b != 0 && b != '-' && (b < '0' || '9' < b));
            if (b == 0) return long.MinValue;
            if (b == '-') { ng = true; b = read(); }
            for (; true; b = read())
            {
                if (b < '0' || '9' < b)
                    return ng ? -ret : ret;
                else ret = ret * 10 + b - '0';
            }
        }
        public int Integer() { return (isEof) ? int.MinValue : (int)Long(); }
        public double Double() { var s = Scan(); return s != "" ? double.Parse(s, CultureInfo.InvariantCulture) : double.NaN; }
        private T[] enumerate<T>(int n, Func<T> f)
        {
            var a = new T[n];
            for (int i = 0; i < n; ++i) a[i] = f();
            return a;
        }

        public char[] Char(int n) { return enumerate(n, Char); }
        public string[] Scan(int n) { return enumerate(n, Scan); }
        public double[] Double(int n) { return enumerate(n, Double); }
        public int[] Integer(int n) { return enumerate(n, Integer); }
        public long[] Long(int n) { return enumerate(n, Long); }
    }
}
#endregion


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//неправильный ответ на тесте 12
namespace F
{
    class Program
    {
        class tree
        {
            public long ves;
            public int nn;//индек первого элемента
            public int nk;//индек последнего элемента
            public tree l;
            public tree r;
            public tree p;
            public tree(int[] m, int i1, int ik, tree p1)
            {
                if (i1 == ik)
                {
                    nn = i1;
                    nk = ik;
                    l = null;
                    r = null;
                    ves = m[i1];
                    wt[i1] = this;
                }
                else
                {
                    int s = (ik + i1 + 1) / 2/*+ (ik - i1) % 2*/;
                    nn = i1;
                    nk = ik;
                    l = new tree(m, i1, s - 1, this);
                    r = new tree(m, s, ik, this);
                    ves = l.ves + r.ves;
                }
                p = p1;
            }

        }
        static long FindVes(tree t1, tree tn)
        {
            long ves = 0;
            int x1 = t1.nn;
            int y1 = tn.nk;
            if (y1 < x1) return 0;
            tree ti = wt[x1];
            while (ti.nk < y1) ti = ti.p;
            ves = (long)ti.ves;
            tree tiv = ti;
            while (ti.nn < x1)
            {
                if (ti.r.nn <= x1)
                {
                    ves = ves - (long)ti.l.ves;
                    ti = ti.r;
                }
                else
                {
                    ti = ti.l;
                }
            }
            ti = tiv;
            while (ti.nk > y1)
            {
                if (ti.l.nk >= y1)
                {
                    ves = ves - (long)ti.r.ves;
                    ti = ti.l;
                }
                else
                {
                    ti = ti.r;
                }
            }
            return ves;
        }
        static tree[] wt;
        static void Main(string[] args)
        {
            TextReader sr = Console.In;
            //StreamReader sr = new StreamReader("in7.txt");
            string[] s = sr.ReadLine().Split();
            int n = Convert.ToInt32(s[0]);
            int q = Convert.ToInt32(s[1]);
            s = sr.ReadLine().Split();
            string[] s1 = sr.ReadLine().Split();
            int[] a = new int[n];
            int[] w = new int[n];
            for (int i = 0; i < n; i++)
            {
                a[i] = Convert.ToInt32(s[i]);
                w[i] = Convert.ToInt32(s1[i]);
            }
            //решение
            wt = new tree[n];
            tree t1 = new tree(w, 0, n - 1, null);
            int x, y;
            tree ti;
            List<int> res = new List<int>();
            for (int i = 0; i < q; i++)
            {
                s = sr.ReadLine().Split();
                x = Convert.ToInt32(s[0]);
                y = Convert.ToInt32(s[1]);
                if (x < 0)
                {
                    int delta = y - w[-1 - x];
                    w[-1 - x] = y;
                    ti = wt[-1 - x];
                    while (ti != null)
                    {
                        ti.ves = ti.ves + delta;
                        ti = ti.p;
                    }
                }
                else
                {
                    if (x == y)
                    {
                        res.Add(0);
                    }
                    else if ((y - x) == (a[y - 1] - a[x - 1]))
                    {
                        res.Add(0);
                    }
                    else if ((y - x) == 1)
                    {
                        if (w[x-1] > w[y-1])
                        {
                            res.Add((int)(((long)(a[y-1]- a[x - 1] - 1)* (long)w[y - 1])% (long)(1000000007)));
                        }
                        else
                        {
                            res.Add((int)(((long)(a[y - 1] - a[x - 1] - 1) * (long)w[x - 1]) % (long)(1000000007)));
                        }
                    }
                    else
                    {
                        //найти вес отрезка
                        int x1 = x - 1;
                        int y1 = y - 1;
                        long ves = FindVes(wt[x1], wt[y1]);
                        long vl, vr,vv;
                        int iis, iiss;
                        int iisll=x1, iislr=y1;
                        iis = (x1 + y1 + 1) / 2;
                        vl = FindVes(wt[x1], wt[iis - 1]);
                        vr = FindVes(wt[iis + 1],wt[y1] );
                        while (true)
                        {
                            if ((vl + w[iis] > vr) && (vr + w[iis] > vl)) break;
                            if (vl + w[iis] == vr) {
                                if (w[iis] >= w[iis + 1]) break;
                                else
                                {
                                    iis++;
                                    break;
                                }
                            }
                            if (vr + w[iis] == vl)
                            {
                                if (w[iis] >= w[iis - 1]) break;
                                else
                                {
                                    iis--;
                                    break;
                                }
                            }
                            if ((vl + w[iis]) >(vr + w[iis]))
                            {
                                iiss = (iisll + iis) / 2;
                                vv= FindVes(wt[iiss + 1], wt[iis- 1]);
                                vl =vl-vv- w[iiss];
                                vr =vr+vv+ w[iis];
                                iislr = iis;
                                iis = iiss;
                            }
                            else
                            {
                                iiss = (iislr + iis + 1) / 2;
                                vv = FindVes(wt[iis + 1], wt[iiss - 1]);
                                vl = vl + vv + w[iis];
                                vr = vr - vv - w[iiss];
                                iisll = iis;
                                iis = iiss;
                            }
                        }
                        long r = 0;
                        for (int j = x1; j < iis; j++)
                        {
                            r = (r + ((long)w[j] * (long)(a[iis] - a[j] - (iis-j)))) % 1000000007;
                        }
                        for (int j = iis+1; j <=y1; j++)
                        {
                            r = (r + ((long)w[j] * (long)(a[j] - a[iis] - (j-iis)))) % 1000000007;
                        }
                        res.Add((int)r);
                    }
                }
            }
            Console.WriteLine(string.Join("\n", res));
        }
    }
}


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

namespace F
{
    class Program
    {
        class tree
        {
            public long ves;
            public int nn;//индек первого элемента
            public int nk;//индек последнего элемента
            public tree l;
            public tree r;
            public tree p;
            public tree(int[] m, int i1, int ik, tree p1)
            {
                if (i1 == ik)
                {
                    nn = i1;
                    nk = ik;
                    l = null;
                    r = null;
                    ves = m[i1];
                    wt[i1] = this;
                }
                else
                {
                    int s = (ik + i1 + 1) / 2/*+ (ik - i1) % 2*/;
                    nn = i1;
                    nk = ik;
                    l = new tree(m, i1, s - 1, this);
                    r = new tree(m, s, ik, this);
                    ves = l.ves + r.ves;
                }
                p = p1;
            }

        }
        static long FindVes(tree t1, tree tn)
        {
            long ves = 0;
            int x1 = t1.nn;
            int y1 = tn.nk;
            if (y1 < x1) return 0;
            tree ti = wt[x1];
            while (ti.nk < y1) ti = ti.p;
            ves = (long)ti.ves;
            tree tiv = ti;
            while (ti.nn < x1)
            {
                if (ti.r.nn <= x1)
                {
                    ves = ves - (long)ti.l.ves;
                    ti = ti.r;
                }
                else
                {
                    ti = ti.l;
                }
            }
            ti = tiv;
            while (ti.nk > y1)
            {
                if (ti.l.nk >= y1)
                {
                    ves = ves - (long)ti.r.ves;
                    ti = ti.l;
                }
                else
                {
                    ti = ti.r;
                }
            }
            return ves;
        }
        static tree[] wt;
        static void Main(string[] args)
        {
            TextReader sr = Console.In;
            //StreamReader sr = new StreamReader("in1.txt");
            string[] s = sr.ReadLine().Split();
            int n = Convert.ToInt32(s[0]);
            int q = Convert.ToInt32(s[1]);
            s = sr.ReadLine().Split();
            string[] s1 = sr.ReadLine().Split();
            int[] a = new int[n];
            int[] w = new int[n];
            for (int i = 0; i < n; i++)
            {
                a[i] = Convert.ToInt32(s[i]);
                w[i] = Convert.ToInt32(s1[i]);
            }
            //решение
            wt = new tree[n];
            tree t1 = new tree(w, 0, n - 1, null);
            int x, y;
            tree ti;
            List<int> res = new List<int>();
            for (int i = 0; i < q; i++)
            {
                s = sr.ReadLine().Split();
                x = Convert.ToInt32(s[0]);
                y = Convert.ToInt32(s[1]);
                if (x < 0)
                {
                    int delta = y - w[-1 - x];
                    w[-1 - x] = y;
                    ti = wt[-1 - x];
                    while (ti != null)
                    {
                        ti.ves = ti.ves + delta;
                        ti = ti.p;
                    }
                }
                else
                {
                    if (x == y)
                    {
                        res.Add(0);
                    }
                    else if ((y - x) == (a[y - 1] - a[x - 1]))
                    {
                        res.Add(0);
                    }
                    else if ((y - x) == 1)
                    {
                        if (w[x-1] > w[y-1])
                        {
                            res.Add((int)(((long)(a[y-1]- a[x - 1] - 1)* (long)w[y - 1])% (long)(1000000007)));
                        }
                        else
                        {
                            res.Add((int)(((long)(a[y - 1] - a[x - 1] - 1) * (long)w[x - 1]) % (long)(1000000007)));
                        }
                    }
                    else
                    {
                        //найти вес отрезка
                        int x1 = x - 1;
                        int y1 = y - 1;
                        long ves = FindVes(wt[x1], wt[y1]);
                        long vl, vr,vv;
                        int iis,iiss;
                        iis = (x1 + y1 + 1) / 2;
                        vl = FindVes(wt[x1], wt[iis - 1]);
                        vr = FindVes(wt[iis + 1],wt[y1] );
                        while (true)
                        {
                            if ((vl + w[iis] > vr) && (vr + w[iis] > vl)) break;
                            if ((vl + w[iis] == vr) && (w[iis] >= w[iis+1])) break;
                            if ((vr + w[iis] == vl) && (w[iis] >= w[iis - 1])) break;
                            if ((vl + w[iis]) >(vr + w[iis]))
                            {
                                iiss = (x1 + iis + 1) / 2;
                                vv= FindVes(wt[iiss + 1], wt[iis- 1]);
                                vl =vl-vv- w[iiss];
                                vr =vr+vv+ w[iis];
                                iis = iiss;
                            }
                            else
                            {
                                iiss = (y1 + iis + 1) / 2;
                                vv = FindVes(wt[iis + 1], wt[iiss - 1]);
                                vl = vl + vv + w[iis];
                                vr = vr - vv - w[iiss];
                                iis = iiss;
                            }
                        }
                        long r = 0;
                        for (int j = x1; j < iis; j++)
                        {
                            r = (r + ((long)w[j] * (long)(a[iis] - a[j] - (iis-j)))) % 1000000007;
                        }
                        for (int j = iis+1; j <=y1; j++)
                        {
                            r = (r + ((long)w[j] * (long)(a[j] - a[iis] - (j-iis)))) % 1000000007;
                        }
                        res.Add((int)r);
                    }
                }
            }
            Console.WriteLine(string.Join("\n", res));
        }
    }
}


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

namespace F
{
    class Program
    {
        static Tree[] wt;
        class Tree
        {
            public long ves;
            public long ves_;
            public int nn;//индек первого элемента
            public int nk;//индек последнего элемента
            public Tree l;
            public Tree r;
            public Tree p;
            public Tree(int[] m, int[] a, int i1, int ik, Tree p1)
            {
                nn = i1;
                nk = ik;
                if (i1 == ik)
                {
                    l = null;
                    r = null;
                    ves = m[i1];
                    ves_ = ((long)(a[i1] - i1) * (long)m[i1]) % (long)(1000000007);
                    wt[i1] = this;
                }
                else
                {
                    int s = (ik + i1 + 1) / 2;
                    l = new Tree(m, a, i1, s - 1, this);
                    r = new Tree(m, a, s, ik, this);
                    ves = l.ves + r.ves;
                    ves_ = (l.ves_ + r.ves_) % (long)(1000000007);
                }
                p = p1;
            }
        }

        static long FindVes(Tree t1, Tree tn, bool t)//t=true ves;t=false ves_;
        {
            long ves = 0;
            int x1 = t1.nn;
            int y1 = tn.nk;
            if (y1 < x1) return 0;
            Tree ti = wt[x1];
            long sub = 0;
            while (ti.nk < y1)
            {
                if (ti.p.r == ti && ti.p.l!=null)
                {
                    if (t) sub = sub + ti.p.l.ves;
                    else sub = (sub + ti.p.l.ves_) % (long)(1000000007);
                }
                ti = ti.p;
            }
            if (t) ves = (long)ti.ves;
            else ves = (long)ti.ves_;
            if (t) ves =ves-sub;
            else ves =(ves-sub+ +(long)(1000000007)) % (long)(1000000007);
            //Tree tiv = ti;
            //while (ti.nn < x1)
            //{
            //    if (ti.r.nn <= x1)
            //    {
            //        if (t) ves = ves - (long)ti.l.ves;
            //        else ves = (ves - (long)ti.l.ves_ + (long)(1000000007)) % (long)(1000000007);
            //        ti = ti.r;
            //    }
            //    else
            //    {
            //        ti = ti.l;
            //    }
            //}
            //ti = tiv;
            while (ti.nk > y1)
            {
                if (ti.l.nk >= y1)
                {
                    if (t) ves = ves - (long)ti.r.ves;
                    else ves = (ves - (long)ti.r.ves_ + (long)(1000000007)) % (long)(1000000007);
                    ti = ti.l;
                }
                else
                {
                    ti = ti.r;
                }
            }
            return ves;
        }

        static void Main(string[] args)
        {
            TextReader sr = Console.In;
            //StreamReader sr = new StreamReader("in1.txt");
            string[] s = sr.ReadLine().Split();
            int n = Convert.ToInt32(s[0]);
            int q = Convert.ToInt32(s[1]);
            s = sr.ReadLine().Split();
            string[] s1 = sr.ReadLine().Split();
            int[] a = new int[n];
            int[] w = new int[n];
            for (int i = 0; i < n; i++)
            {
                a[i] = Convert.ToInt32(s[i]);
                w[i] = Convert.ToInt32(s1[i]);
            }
            //решение
            wt = new Tree[n];
            Tree t1 = new Tree(w, a, 0, n - 1, null);

            int ll;
            int rr;
            int id, nw;
            bool zapros1;
            Tree ti;
            List<int> res = new List<int>();
            for (int i = 0; i < q; i++)
            {
                s = sr.ReadLine().Split();
                ll = Convert.ToInt32(s[0]);
                if (ll < 0) zapros1 = true; else zapros1 = false;
                id = -1 - ll;
                ll--;
                nw = Convert.ToInt32(s[1]);
                rr = nw - 1;
                if (zapros1)
                {
                    ti = wt[id];
                    long delta = (long)nw - ti.ves;
                    long delta_ = (((long)(a[id] - id) * (long)nw)) % (long)(1000000007) - ti.ves_;
                    w[id] = nw;
                    while (ti != null)
                    {
                        ti.ves = ti.ves + delta;
                        ti.ves_ = (ti.ves_ + delta_ + (long)(1000000007)) % (long)(1000000007);
                        ti = ti.p;
                    }
                }
                else
                {
                    if (ll == rr)
                    {
                        res.Add(0);
                    }
                    else if ((rr - ll) == (a[rr] - a[ll]))
                    {
                        res.Add(0);
                    }
                    else if ((rr - ll) == 1)
                    {
                        if (w[ll] > w[rr])
                        {
                            res.Add((int)(((long)(a[rr] - a[ll] - 1) * (long)w[rr]) % (long)(1000000007)));
                        }
                        else
                        {
                            res.Add((int)(((long)(a[rr] - a[ll] - 1) * (long)w[ll]) % (long)(1000000007)));
                        }
                    }
                    else
                    {
                        //найти вес отрезка
                        long ves = FindVes(wt[ll], wt[rr], true);
                        long vl, vr, vv;
                        int iis, iiss;
                        int iisll = ll, iislr = rr;
                        iis = (ll + rr + 1) / 2;
                        vl = FindVes(wt[ll], wt[iis - 1], true);
                        vr = FindVes(wt[iis + 1], wt[rr], true);
                        while (true)
                        {
                            if ((vl + w[iis] > vr) && (vr + w[iis] > vl)) break;
                            if (vl + w[iis] == vr)
                            {
                                if (w[iis] < w[iis + 1]) iis++;
                                break;
                            }
                            if (vr + w[iis] == vl)
                            {
                                if (w[iis] < w[iis - 1]) iis--;
                                break;
                            }
                            if ((vl) > (vr))
                            {
                                iiss = (iisll + iis) / 2;
                                vv = FindVes(wt[iiss + 1], wt[iis - 1], true);
                                vl = vl - vv - w[iiss];
                                vr = vr + vv + w[iis];
                                iislr = iis;
                                iis = iiss;
                            }
                            else
                            {
                                iiss = (iislr + iis + 1) / 2;
                                vv = FindVes(wt[iis + 1], wt[iiss - 1], true);
                                vl = vl + vv + w[iis];
                                vr = vr - vv - w[iiss];
                                iisll = iis;
                                iis = iiss;
                            }
                        }
                        long r = 0;
                        if (iis > ll)
                        {
                            r = (r - (FindVes(wt[ll], wt[iis - 1], false) % (long)(1000000007)) + (long)(1000000007)) % (long)(1000000007);
                            r = (r + (long)(a[iis] - iis) * (FindVes(wt[ll], wt[iis - 1], true) % (long)(1000000007))) % (long)(1000000007);

                        }
                        if (iis < rr)
                        {
                            r = (r + (FindVes(wt[iis + 1], wt[rr], false)) % (long)(1000000007)) % (long)(1000000007);
                            r = (r - (long)(a[iis] - iis) * (FindVes(wt[iis + 1], wt[rr], true) % (long)(1000000007)) % (long)(1000000007) + (long)(1000000007)) % (long)(1000000007);
                        }
                        res.Add((int)r);
                    }
                }
            }
            Console.WriteLine(string.Join("\n", res));
        }
    }
}


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

namespace ConsoleApp
{
    class Program
    {
        const double DefaultEpsilon = 1e-18;

        struct Vector
        {
            public double X;
            public double Y;

            public Vector(double x, double y)
            {
                X = x;
                Y = y;
            }
            public Vector(double angle)
            {
                X = Math.Cos(angle);
                Y = Math.Sin(angle);
            }

            public double Hypot()
            {
                return Math.Sqrt((X * X) + (Y * Y));
            }
            public double HypotSquared()
            {
                return (X * X) + (Y * Y);
            }
            public Vector RotateClockwise(double angle)
            {
                double cos = Math.Cos(angle);
                double sin = Math.Sin(angle);

                return new Vector(X * cos + Y * sin, X * -sin + Y * cos);
            }
            public Vector Perpendicular()
            {
                return new Vector(-Y, X);
            }
            public bool IsEqual(Vector vector, double epsilon = DefaultEpsilon)
            {
                return Equal(this.X, vector.X, epsilon) && Equal(this.Y, vector.Y, epsilon);
            }

            public static Vector operator +(Vector a)
            {
                return a;
            }
            public static Vector operator -(Vector a)
            {
                return new Vector(-a.X, -a.Y);
            }
            public static Vector operator +(Vector a, Vector b)
            {
                return new Vector(a.X + b.X, a.Y + b.Y);
            }
            public static Vector operator -(Vector a, Vector b)
            {
                return new Vector(a.X - b.X, a.Y - b.Y);
            }
            public static double Determinant(Vector a, Vector b)
            {
                return (a.X * b.Y) - (a.Y * b.X);
            }
            public static double DotProduct(Vector a, Vector b)
            {
                return (a.X * b.X) + (a.Y * b.Y);
            }
        }
        struct Line
        {
            public double A;
            public double B;
            public double C;

            public double slopeY => -A / B; // y = f'(x)
            public double slopeX => -B / A; // x = f'(y)

            public Line(Vector p1, Vector p2)
            {
                A = p2.Y - p1.Y;
                B = p1.X - p2.X;
                C = p2.X * p1.Y - p1.X * p2.Y;
            }
        }
        struct Segment
        {
            public Vector Left;
            public Vector Right;

            public Segment(Vector left, Vector right)
            {
                Left = left;
                Right = right;
            }

            public Line GetLine()
            {
                return new Line(Left, Right);
            }
            public bool IsOnTheSegment(Vector point, double epsilon = DefaultEpsilon)
            {
                Vector v1 = point - Left;
                Vector v2 = point - Right;
                double det = Vector.Determinant(v1, v2);
                double dotProd = Vector.DotProduct(v1, v2);

                return Equal(det, 0, epsilon) && LessOrEqual(dotProd, 0, epsilon);
            }
        }

        static Program()
        {
            // Comment this before submitting (in case of strandard input)
            //Console.SetIn(new StreamReader("input.txt"));
            //Console.SetOut(new StreamWriter("output.txt"));
        }
        static void Main()
        {
            //int testCases = int.Parse(Console.ReadLine());
            //for (int z = 0; z < testCases; z++)
            //{

            //}

            int[] data = ReadIntData();
            int n = data[0];
            int m = data[1];
            int k = data[2];
            int r = data[3];
            int c = data[4];

            data = ReadIntData();
            int ax = data[0];
            int ay = data[1];
            int bx = data[2];
            int by = data[3];

            if (ax > bx)
            {
                Swap(ref ax, ref bx);
            }
            if (ay > by)
            {
                Swap(ref ay, ref by);
            }

            //int dx = bx - ax;
            //int dy = by - ay;

            long total = (long)n * m;
            total -= (long)r * c;
            //total += (long)(ax - bx + r) * (ay - by + c);

            Console.WriteLine(PowQuick(k, total, 1_000_000_007));

            Console.Out.Close();
        }

        static bool Equal(double a, double b, double epsilon = DefaultEpsilon)
        {
            return Math.Abs(a - b) < epsilon;
        }
        static bool Greater(double a, double b, double epsilon = DefaultEpsilon)
        {
            return (a > b) && !Equal(a, b, epsilon);
        }
        static bool Less(double a, double b, double epsilon = DefaultEpsilon)
        {
            return (a < b) && !Equal(a, b, epsilon);
        }
        static bool GreaterOrEqual(double a, double b, double epsilon = DefaultEpsilon)
        {
            return (a > b) || Equal(a, b, epsilon);
        }
        static bool LessOrEqual(double a, double b, double epsilon = DefaultEpsilon)
        {
            return (a < b) || Equal(a, b, epsilon);
        }
        static double DegToRad(double angle)
        {
            return (angle / 180) * Math.PI;
        }
        static long LCM(long a, long b)
        {
            return (a / GCD(a, b)) * b;
        }
        static long GCD(long a, long b)
        {
            while (a != 0)
            {
                b %= a;
                Swap(ref a, ref b);
            }

            return b;
        }
        static long PowQuick(long b, long p)
        {
            long exp = b;
            long res = 1;

            while (p > 0)
            {
                if ((p % 2) == 1)
                {
                    res *= exp;
                }

                exp *= exp;
                p /= 2;
            }

            return res;
        }
        static long PowQuick(long b, long p, long mod)
        {
            long exp = b;
            long res = 1;

            while (p > 0)
            {
                if ((p % 2) == 1)
                {
                    res *= exp;
                    res %= mod;
                }

                exp *= exp;
                exp %= mod;
                p /= 2;
            }

            return res;
        }
        static uint BitCount(uint a)
        {
            a = ((a >> 1) & 0x55555555u) + (a & 0x55555555u);
            a = ((a >> 2) & 0x33333333u) + (a & 0x33333333u);
            a = ((a >> 4) & 0x0F0F0F0Fu) + (a & 0x0F0F0F0Fu);
            a = ((a >> 8) & 0x00FF00FFu) + (a & 0x00FF00FFu);
            a = ((a >> 16) & 0x0000FFFFu) + (a & 0x0000FFFFu);
            return a;
        }
        static bool AreAlmostEqual(double a, double b, double epsilon)
        {
            return Math.Abs(a - b) < epsilon;
        }
        static int Binary(int[] array, int val)
        {
            return Binary(array, val, 0, array.Length);
        }
        static int Binary(int[] array, int val, int left, int right)
        {
            if (val < array[0])
            {
                return 0;
            }

            while (right - left > 1)
            {
                int mid = (right + left) / 2;

                if (array[mid] <= val)
                {
                    left = mid;
                }
                else
                {
                    right = mid;
                }
            }

            return right;
        }
        static void Swap(ref int a, ref int b)
        {
            int temp = a;
            a = b;
            b = temp;
        }
        static void Swap(ref long a, ref long b)
        {
            long temp = a;
            a = b;
            b = temp;
        }
        static double[] ReadDoubleData(TextReader input)
        {
            return input.ReadLine()
                .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                .Select(val => double.Parse(val))
                .ToArray();
        }
        static double[] ReadDoubleData()
        {
            return ReadDoubleData(Console.In);
        }
        static int[] ReadIntData(TextReader input)
        {
            return input.ReadLine()
                .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                .Select(val => int.Parse(val))
                .ToArray();
        }
        static int[] ReadIntData()
        {
            return ReadIntData(Console.In);
        }
        static long[] ReadLongData(TextReader input)
        {
            return input.ReadLine()
                .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                .Select(val => long.Parse(val))
                .ToArray();
        }
        static long[] ReadLongData()
        {
            return ReadLongData(Console.In);
        }
    }
}


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

public class taskD
{
    public class MyReader
    {
        private TextReader instream;

        public int[] ReadIntArray()
        {
            string inp = instream.ReadLine().Trim();
            string[] spl = inp.Split(' ');

            int[] a = new int[spl.Length];
            for (int i = 0; i < a.Length; i++)
                a[i] = int.Parse(spl[i]);
            return a;
        }

        public long[] ReadLongArray()
        {
            string inp = instream.ReadLine().Trim();
            string[] spl = inp.Split(' ');

            long[] a = new long[spl.Length];
            for (int i = 0; i < a.Length; i++)
                a[i] = long.Parse(spl[i]);
            return a;
        }

        public double[] ReadDoubleArray()
        {
            string inp = instream.ReadLine().Trim();
            string[] spl = inp.Split(' ');

            double[] a = new double[spl.Length];

            System.Globalization.NumberFormatInfo nfi = new System.Globalization.NumberFormatInfo();
            nfi.NumberDecimalSeparator = ".";
            for (int i = 0; i < a.Length; i++)
                a[i] = double.Parse(spl[i], nfi);
            return a;
        }

        public int ReadInt()
        {
            return int.Parse(instream.ReadLine());
        }

        public long ReadLong()
        {
            return long.Parse(instream.ReadLine());
        }

        public void SetInStream(TextReader textReader)
        {
            this.instream = textReader;
        }

        internal string ReadLine()
        {
            return instream.ReadLine();
        }
    }

    static void Main(string[] args)
    {
        MyReader instream = new MyReader();
        instream.SetInStream(Console.In);

        TextWriter outstream = Console.Out;

        solve(instream, outstream);

    }

    private static void solve(MyReader instream, TextWriter outstream)
    {
        int[] nmk = instream.ReadIntArray();
        int n = nmk[0];
        int m = nmk[1];
        int k = nmk[2];

        int[] r = new int[n];
        int[] g = new int[n];

        bool rfree = false;
        bool gfree = false;

        for (int i = 0; i < n; i++)
        {
            string line = instream.ReadLine();

            int rpos = -1;
            int gpos = -1;

            int rcnt = 0;
            int gcnt = 0;
            for (int j = 0; j < line.Length; j++)
            {
                if (line[j] == 'R') { rpos = j; rcnt++; }
                if (line[j] == 'G') { gpos = j; gcnt++; }
            }

            if (rpos < 0 && (gpos >= 0 && (gcnt==1 || n>2)))
                gfree = true;
            else if ((rpos >= 0 && (rcnt==1 || n>2)) && gpos < 0)
                rfree = true;
            else
            {
                if (gpos>=0 && rpos>=0 && gpos > rpos)
                {
                    gpos = m - gpos - 1;
                    rpos = m - rpos - 1;
                }
            }
            r[i] = rpos;
            g[i] = gpos;
        }

        if (m == 1)
        {
            outstream.WriteLine("Second");
            return;
        }

        if (rfree && gfree)
        {
            outstream.WriteLine("Draw");
            return;
        }
        if (gfree)
        {
            outstream.WriteLine("First");
            return;
        }
        if (rfree)
        {
            outstream.WriteLine("Second");
            return;
        }

        int odd = 0;
        for (int i = 0; i < n; i++)
        {
            if (r[i] >= 0 && g[i] >= 0)
            {
                int dist = r[i] - g[i] - 1;

                if (dist % 2 == 1) odd++;
            }
        }

        if (odd % (k + 1) != 0)
            outstream.WriteLine("First");
        else
            outstream.WriteLine("Second");
    }

}


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

namespace Round356e
{
    class Program : ProgramBase
    {
        private const long commonMod = 1000000007;

        static void Main(string[] args)
        {
            var p = new Program();
            var x = p.Get();
            p.Out(x);
        }

        object Get()
        {
            checked
            {
                var wa = Stopwatch.StartNew();
                //FileName = "input";
                var n = ReadIntToken();
                var k = ReadIntToken();
                var table = new bool[n, n];
                for (int i = 0; i < n; i++)
                {
                    var input = Read();
                    for (int j = 0; j < n; j++)
                        table[i, j] = input[j] == '.';
                }
                Cell[,] cells;
                int componentCount;
                BFS(table, out cells, out componentCount);
                var ccWeights = new int[componentCount + 1];
                for (int i = 0; i < n; i++)
                {
                    for (int j = 0; j < n; j++)
                    {
                        if (cells[i, j].CCNumber > 0)
                            ccWeights[cells[i, j].CCNumber]++;
                    }
                }
                var max = int.MinValue;
                var memory = new bool[componentCount + 1];
                for (int z = 0; z < n - k + 1; z++)
                {
                    //Console.WriteLine(z + " " + wa.Elapsed);
                    var activeField = new int[k, k];
                    var ccStats = new int[componentCount + 1];
                    var sumOfInternal = 0;
                    var blockedCount = 0;
                    for (int i = z; i < z + k; i++)
                    {
                        for (int j = 0; j < k; j++)
                        {
                            var cc = cells[i, j].CCNumber;
                            if (cc > 0)
                            {
                                if (ccStats[cc] == 0)
                                    sumOfInternal += ccWeights[cc];
                                ccStats[cc] += 1;
                            }
                            else
                                blockedCount++;
                        }
                    }

                    var max2 = Math.Max(max, Sum(GetNeighboursCcs(z, 0, k, n, cells, memory), ccStats, ccWeights) + sumOfInternal + blockedCount);
                    if (max2 > max)
                        max = max2;

                    for (int w = 1; w < n - k + 1; w++)
                    {
                        for (int i = 0; i < k; i++)
                        {
                            var ccNumber = cells[z + i, w - 1].CCNumber;
                            if (ccNumber > 0)
                            {
                                ccStats[ccNumber]--;
                                if (ccStats[ccNumber] == 0)
                                    sumOfInternal -= ccWeights[ccNumber];
                            }
                            else
                                blockedCount--;

                            ccNumber = cells[z + i, w + k - 1].CCNumber;
                            if (ccNumber > 0)
                            {
                                if (ccStats[ccNumber] == 0)
                                    sumOfInternal += ccWeights[ccNumber];
                                ccStats[ccNumber]++;
                            }
                            else
                                blockedCount++;
                        }
                        max2 = Math.Max(max, Sum(GetNeighboursCcs(z, w, k, n, cells, memory), ccStats, ccWeights) + sumOfInternal + blockedCount);
                        if (max2 > max)
                            max = max2;
                    }
                }
                if (!string.IsNullOrEmpty(FileName))
                    Console.WriteLine(wa.Elapsed);
                return max;
                //return here
            }
        }

        int Sum(List<int> list, int[] set, int[] weights)
        {
            var sum = 0;
            foreach (var cc in list)
                if (set[cc] == 0)
                    sum += weights[cc];
            return sum;
        }

        List<int> GetNeighboursCcs(int i, int j, int k, int n, Cell[,] cells, bool[] memory)
        {
            var result = new List<int>();
            if (i > 0)
                //.Concat(Enumerable.Range(0, k).Select(x => Struct.Create(i + k, j + x)))
                //.Concat(Enumerable.Range(0, k).Select(x => Struct.Create(i + x, j - 1)))
                //.Concat(Enumerable.Range(0, k).Select(x => Struct.Create(i + x, j + k))))
                for (var x = 0; x < k; x++)
                {
                    var cc = cells[i - 1, j + x].CCNumber;
                    if (cc > 0 && !memory[cc])
                    {
                        result.Add(cc);
                        memory[cc] = true;
                    }
                }
            if (i + k < n)
                for (var x = 0; x < k; x++)
                {
                    var cc = cells[i + k, j + x].CCNumber;
                    if (cc > 0 && !memory[cc])
                    {
                        result.Add(cc);
                        memory[cc] = true;
                    }
                }
            if (j > 0)
                for (var x = 0; x < k; x++)
                {
                    var cc = cells[i + x, j - 1].CCNumber;
                    if (cc > 0 && !memory[cc])
                    {
                        result.Add(cc);
                        memory[cc] = true;
                    }
                }
            if (j + k < n)
                for (var x = 0; x < k; x++)
                {
                    var cc = cells[i + x, j + k].CCNumber;
                    if (cc > 0 && !memory[cc])
                    {
                        result.Add(cc);
                        memory[cc] = true;
                    }
                }
            foreach (var cc in result)
            {
                memory[cc] = false;
            }
            return result;
        }

        void BFS(bool[,] input, out Cell[,] cells, out int componentCount)
        {
            var n = input.GetLength(0);
            cells = new Cell[n, n];
            var visited = new bool[n, n];
            var componentIndex = 0;
            for (int i = 0; i < n; i++)
                for (int j = 0; j < n; j++)
                    if (!visited[i, j] && input[i, j])
                        BFS(i, j, cells, input, visited, ++componentIndex);
            componentCount = componentIndex;
        }

        void BFS(int i, int j, Cell[,] cells, bool[,] input, bool[,] visited, int ccIndex)
        {
            var n = input.GetLength(0);
            visited[i, j] = true;
            cells[i, j].CCNumber = ccIndex;
            var neighbours = new[] { Struct.Create(i + 1, j), Struct.Create(i - 1, j), Struct.Create(i, j + 1), Struct.Create(i, j - 1) };
            foreach (var c in neighbours.Where(x => x.Item1 >= 0 && x.Item1 < n && x.Item2 >= 0 && x.Item2 < n && !visited[x.Item1, x.Item2] && input[x.Item1, x.Item2]))
                BFS(c.Item1, c.Item2, cells, input, visited, ccIndex);
        }

        struct Cell
        {
            public int CCNumber { get; set; }
        }

        public static class Struct
        {
            public static Pair<T1, T2> Create<T1, T2>(T1 item1, T2 item2)
            {
                return new Pair<T1, T2> { Item1 = item1, Item2 = item2 };
            }
        }

        public struct Pair<T1, T2>
        {
            public T1 Item1 { get; set; }
            public T2 Item2 { get; set; }
        }

        class Automata
        {
            bool[] terminals;
            public int sigma;
            public int len;
            public int[,] jumps;

            public void Create()
            {
                var a = ReadInts();
                len = a[0];
                sigma = a[2];
                var ts = ReadInts();
                terminals = new bool[len];
                for (int i = 0; i < ts.Length; i++)
                    terminals[ts[i]] = true;
                jumps = new int[len, sigma];
                for (int i = 0; i < len * sigma; i++)
                {
                    var b = Console.ReadLine().Split(' ');
                    jumps[Convert.ToInt32(b[0]), b[1][0] - 'a'] = Convert.ToInt32(b[2]);
                }
            }
            protected int[] ReadInts()
            {
                return Console.ReadLine().Split(' ').Select(x => Convert.ToInt32(x)).ToArray();
            }

            public bool IsTerminal(int s)
            {
                return terminals[s];
            }
        }
    }

    abstract class ProgramBase
    {
        bool? prod = null;
        StreamReader f;
        Queue<string> tokens;
        protected string FileName { get; set; }

        protected string Read()
        {
            if (f == null)
                f = string.IsNullOrEmpty(FileName)
                    ? new StreamReader(Console.OpenStandardInput())
                    : new StreamReader((GetProd() ? "" : "c:\\dev\\") + FileName);
            return f.ReadLine();
        }

        protected int ReadInt()
        {
            return int.Parse(Read());
        }

        protected int ReadIntToken()
        {
            if (tokens == null || tokens.Count == 0)
                tokens = new Queue<string>(Read().Split(' '));
            return int.Parse(tokens.Dequeue());
        }

        protected int[] ReadInts()
        {
            var tokens = Read().Split(' ');
            var result = new int[tokens.Length];
            for (int i = 0; i < tokens.Length; i++)
                result[i] = int.Parse(tokens[i]);
            return result;
        }

        protected long ReadLongToken()
        {
            if (tokens == null || tokens.Count == 0)
                tokens = new Queue<string>(Read().Split(' '));
            return long.Parse(tokens.Dequeue());
        }

        protected long ReadLong()
        {
            return Convert.ToInt64(Read());
        }

        protected long[] ReadLongs()
        {
            var tokens = Read().Split(' ');
            var result = new long[tokens.Length];
            for (int i = 0; i < tokens.Length; i++)
                result[i] = long.Parse(tokens[i]);
            return result;
        }

        public void Out(object r)
        {
            if (string.IsNullOrEmpty(FileName))
                Console.WriteLine(r);
            else if (GetProd())
                File.WriteAllText(FileName, r.ToString());
            else
                Console.WriteLine(r);
        }

        private bool GetProd()
        {

            if (!prod.HasValue)
                try
                {
                    prod = Environment.MachineName != "RENADEEN-W7";
                }
                catch (Exception)
                {
                    prod = true;
                }
            return prod.Value;
        }
    }

    public static class Huj
    {
        public static T MinBy<T>(this IEnumerable<T> source, Func<T, double> func) where T : class
        {
            T result = null;
            var min = double.MaxValue;
            foreach (var item in source)
            {
                var current = func(item);
                if (min > current)
                {
                    min = current;
                    result = item;
                }
            }
            return result;
        }

        public static T MaxBy<T>(this IEnumerable<T> source, Func<T, double> func, T defaultValue = default(T))
        {
            T result = defaultValue;
            var max = double.MinValue;
            foreach (var item in source)
            {
                var current = func(item);
                if (max < current)
                {
                    max = current;
                    result = item;
                }
            }
            return result;
        }

        public static string JoinStrings(this IEnumerable<string> source, string delimeter)
        {
            return string.Join(delimeter, source.ToArray());
        }

        public static string JoinStrings(this IEnumerable<int> source, string delimeter)
        {
            return source.Select(x => x.ToString()).JoinStrings(delimeter);
        }
    }
}


using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Linq;
using System.Globalization;
using System.Threading;
using System.Web.Script.Serialization;
using System.Numerics;

class Program
{/*
    public class Point
    {
        public int X;
        public int Y;

        public Point(int x, int y)
        {
            this.X = x;
            this.Y = y;
        }

        public static Point operator +(Point a, Point b)
        {
            return new Point(a.X + b.X, a.Y + b.Y);
        }

        public static Point operator -(Point a, Point b)
        {
            return new Point(a.X - b.X, a.Y - b.Y);
        }

        public double Dist()
        {
            return Math.Sqrt(this.DistRoot());
        }

        public long DistRoot()
        {
            return this.X * (long)this.X + this.Y * (long)this.Y;
        }

        public override string ToString()
        {
            return this.X + " " + this.Y;
        }
    }

    public class Segment
    {
        public Point A;
        public Point B;

        public Segment(Point a, Point b)
        {
            this.A = a;
            this.B = b;
        }

        public double Dist()
        {
            return (this.A - this.B).Dist();
        }

        public long DistRoot()
        {
            return (this.A - this.B).DistRoot();
        }
    }

    private static Point ReadPoint()
    {
        return new Point(ReadInt(), ReadInt());
    }

    public static long ScalarProduct(Point a, Point b)
    {
        return a.X * (long)b.Y - b.X * (long)a.Y;
    }

    public static bool OnLine(Segment line, Point p)
    {
        var v1 = line.B - line.A;
        var v2 = p - line.A;

        if (v2.X == 0 && v2.Y == 0) return true;
        if (v2.X == v1.X && v2.Y == v1.Y) return true;
        if (ScalarProduct(v1, v2) != 0) return false;

        if (v2.DistRoot() > v1.DistRoot()) return false;

        if (v1.X != 0 && v2.X != 0)
        {
            return (v1.X > 0) == (v2.X > 0);
        }

        if (v1.Y != 0 && v2.Y != 0)
        {
            return (v1.Y > 0) == (v2.Y > 0);
        }

        throw new NotSupportedException("wtf?");
    }

    public static bool Crossed(Segment a, Segment b)
    {
        var sp1 = ScalarProduct(a.B - a.A, b.A - a.A);
        var sp2 = ScalarProduct(a.B - a.A, b.B - a.A);
        if (sp1 < 0 && sp2 < 0) return false;
        if (sp1 > 0 && sp2 > 0) return false;

        var sp3 = ScalarProduct(b.B - b.A, a.A - b.A);
        var sp4 = ScalarProduct(b.B - b.A, a.B - b.A);
        if (sp3 < 0 && sp4 < 0) return false;
        if (sp3 > 0 && sp4 > 0) return false;

        return true;
    }

    public static bool CrossedNoTouch(Segment a, Segment b)
    {
        var sp1 = ScalarProduct(a.B - a.A, b.A - a.A);
        var sp2 = ScalarProduct(a.B - a.A, b.B - a.A);
        if (sp1 <= 0 && sp2 <= 0) return false;
        if (sp1 >= 0 && sp2 >= 0) return false;

        var sp3 = ScalarProduct(b.B - b.A, a.A - b.A);
        var sp4 = ScalarProduct(b.B - b.A, a.B - b.A);
        if (sp3 <= 0 && sp4 <= 0) return false;
        if (sp3 >= 0 && sp4 >= 0) return false;

        return true;
    }

    private static double Solve(Point s, Point t, Point a, Point b, Point c)
    {
        var st = new Segment(s, t);
        var ab = new Segment(a, b);
        var bc = new Segment(b, c);
        var ac = new Segment(a, c);

        if (ScalarProduct(b - a, c - a) == 0)
        {
            var q = ab;
            if (q.Dist() < bc.Dist()) q = bc;
            if (q.Dist() < ac.Dist()) q = ac;

            if (Crossed(q, st))
            {
                var d1 = (q.A - s).Dist() + (q.A - t).Dist();
                var d2 = (q.B - s).Dist() + (q.B - t).Dist();
                return Math.Min(d1, d2);
            }

            return (s - t).Dist();
        }

        if (!Crossed(ab, st) && !Crossed(bc, st))
        {
            return (s - t).Dist();
        }

        p[0] = s;
        p[1] = t;
        p[2] = a;
        p[3] = b;
        p[4] = c;

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

        Go(0, 0);

        return d[1];
    }

    private static Point[] p = new Point[5];
    private static double[] d = new double[5];
    private static void Go(int pos, double dist)
    {
        if (d[pos] < dist) return;
        d[pos] = dist;
        if (pos == 1) return;

    }*/

    private static void Main(string[] args)
    {
        /*
        PushTestData(@"
1
0 0 0 10 -10 20 0 1 10 20
0 0 0 10 -10 20 1 1 10 20
0 0 0 10 -10 20 -1 1 10 20

0 0 0 10 -10 1 0 1 10 1
0 0 0 10 -10 1 1 1 10 1
0 0 0 10 -10 1 -1 1 10 1

");

        int n = ReadInt();
        double[] answer = new double[n];
        for (int i = 0; i < n; i++)
        {
            var s = ReadPoint();
            var t = ReadPoint();
            var a = ReadPoint();
            var b = ReadPoint();
            var c = ReadPoint();

            answer[i] = Solve(s, t, a, b, c);
        }

        Console.WriteLine(string.Join(Environment.NewLine, answer));*/

        n = ReadInt();
        k = ReadInt();
        map = new int[n, n];
        sum = new int[n, n];
        sid = new int[n, n];
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                map[i, j] = ReadCh();

        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
            {
                int d = 1 - map[i, j];
                if (i > 0) d += sum[i - 1, j];
                if (j > 0) d += sum[i, j - 1];
                if (i > 0 && j > 0) d -= sum[i - 1, j - 1];
                sum[i, j] = d;
            }

        int nextId = 1;
        segmentSize = new int[n * n + 1];
        markedSegments = new int[n * n + 1];
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                if (map[i, j] + sid[i, j] == 0)
                {
                    MarkSegment(i, j, nextId);
                    nextId++;
                }

        int ep = k < n ? k : k - 1;
        for (int i = 0; i <= ep; i++)
            for (int j = 0; j <= ep; j++)
                AddItem(sid[i, j], 1);

        if (k < n)
            AddItem(sid[k, k], -1);

        CalculateAnswer(0, 0);
        for (int i = 0; i <= n - k; i++)
        {
            if (i % 2 == 0)
                for (int j = 0; j < n - k; j++)
                {
                    MoveRight(i, j);
                    CalculateAnswer(i, j + 1);
                }

            if (i % 2 == 1)
                for (int j = n - k; j > 0; j--)
                {
                    MoveLeft(i, j);
                    CalculateAnswer(i, j - 1);
                }

            if (i < n - k)
            {
                int j = n - k - (i % 2) * (n - k);
                MoveDown(i, j);
                CalculateAnswer(i + 1, j);
            }
        }

        Console.WriteLine(answer);
    }

    private static void MoveRight(int i, int j, int delta = 1)
    {
        if (i > 0 && j >= 0) AddItem(sid[i - 1, j], -delta);
        if (i + k < n && j >= 0) AddItem(sid[i + k, j], -delta);
        if (j > 0)
            for (int ii = 0; ii < k; ii++) AddItem(sid[i + ii, j - 1], -delta);

        j += k;
        if (i > 0 && j < n) AddItem(sid[i - 1, j], delta);
        if (i + k < n && j < n) AddItem(sid[i + k, j], delta);
        if (j + 1 < n)
            for (int ii = 0; ii < k; ii++) AddItem(sid[i + ii, j + 1], delta);
    }

    private static void MoveLeft(int i, int j)
    {
        MoveRight(i, j - 1, -1);
    }

    private static void MoveDown(int i, int j)
    {
        if (i > 0)
            for (int jj = 0; jj < k; jj++)
                AddItem(sid[i - 1, j + jj], -1);
        if (j > 0) AddItem(sid[i, j - 1], -1);
        if (j + k < n) AddItem(sid[i, j + k], -1);

        i += k;
        if (i + 1 < n)
            for (int jj = 0; jj < k; jj++)
                AddItem(sid[i + 1, j + jj], 1);

        if (j > 0) AddItem(sid[i, j - 1], 1);
        if (j + k < n) AddItem(sid[i, j + k], 1);

    }

    private static void AddItem(int segmentId, int delta)
    {
        if (segmentId <= 0) return;
        int before = markedSegments[segmentId];
        markedSegments[segmentId] += delta;

        if (before == 0) totalSegmentsSize += segmentSize[segmentId];
        if (markedSegments[segmentId] == 0) totalSegmentsSize -= segmentSize[segmentId];
    }

    private static int totalSegmentsSize;
    private static int answer = 0;
    private static int n, k;
    private static int[,] map, sum, sid;
    private static int[] segmentSize, markedSegments;
    private static void MarkSegment(int i, int j, int id)
    {
        if (i < 0 || j < 0 || i >= n || j >= n) return;
        if (map[i, j] == 1) return;
        if (sid[i, j] > 0) return;
        sid[i, j] = id;
        segmentSize[id]++;

        MarkSegment(i - 1, j, id);
        MarkSegment(i + 1, j, id);
        MarkSegment(i, j - 1, id);
        MarkSegment(i, j + 1, id);
    }

    private static int GetCountInside(int i, int j)
    {
        int ans = sum[i + k - 1, j + k - 1];
        if (i > 0) ans -= sum[i - 1, j + k - 1];
        if (j > 0) ans -= sum[i + k - 1, j - 1];
        if (i > 0 && j > 0) ans += sum[i - 1, j - 1];

        return k * k - ans;
    }

    private static void CalculateAnswer(int i, int j)
    {
        int newAnswer = totalSegmentsSize + GetCountInside(i, j);
        answer = Math.Max(answer, newAnswer);
    }

    private static int ReadCh()
    {
        while (true)
        {
            int ans = consoleReader.Read();
            if (ans == 'X') return 1;
            if (ans == '.') return 0;
        }
    }

    private static List<int>[] ReadGraph(int n, int m)
    {
        List<int>[] g = new List<int>[n];
        for (int i = 0; i < n; i++) g[i] = new List<int>();
        for (int i = 0; i < m; i++)
        {
            int a = ReadInt() - 1;
            int b = ReadInt() - 1;

            g[a].Add(b);
            g[b].Add(a);
        }

        return g;
    }

    private static int[,] ReadGraphAsMatrix(int n, int m)
    {
        int[,] matrix = new int[n + 1, n + 1];
        for (int i = 0; i < m; i++)
        {
            int a = ReadInt();
            int b = ReadInt();
            matrix[a, b] = matrix[b, a] = 1;
        }

        return matrix;
    }

    private static void Sort(ref int a, ref int b)
    {
        if (a > b) Swap(ref a, ref b);
    }

    private static void Swap(ref int a, ref int b)
    {
        int tmp = a;
        a = b;
        b = tmp;
    }

    private const int BufferSize = 1 << 16;
    private static StreamReader consoleReader;
    private static MemoryStream testData;

    private static int ReadInt()
    {
        int ans = 0;
        int mul = 1;
        do
        {
            ans = consoleReader.Read();
            if (ans == -1)
                return 0;
            if (ans == '-') mul = -1;
        } while (ans < '0' || ans > '9');

        ans -= '0';
        while (true)
        {
            int chr = consoleReader.Read();
            if (chr < '0' || chr > '9')
                return ans * mul;
            ans = ans * 10 + chr - '0';
        }
    }

    private static ulong ReadULong()
    {
        ulong ans = 0;
        int chr;
        do
        {
            chr = consoleReader.Read();
            if (chr == -1)
                return 0;
        } while (chr < '0' || chr > '9');

        ans = (uint)(chr - '0');
        while (true)
        {
            chr = consoleReader.Read();
            if (chr < '0' || chr > '9')
                return ans;
            ans = ans * 10 + (uint)(chr - '0');
        }
    }

    private static long ReadLong()
    {
        long ans = 0;
        int mul = 1;
        do
        {
            ans = consoleReader.Read();
            if (ans == -1)
                return 0;
            if (ans == '-') mul = -1;
        } while (ans < '0' || ans > '9');

        ans -= '0';
        while (true)
        {
            int chr = consoleReader.Read();
            if (chr < '0' || chr > '9')
                return ans * mul;
            ans = ans * 10 + chr - '0';
        }
    }

    private static int[] ReadIntArray(int n)
    {
        int[] ans = new int[n];
        for (int i = 0; i < n; i++)
            ans[i] = ReadInt();
        return ans;
    }

    private static long[] ReadLongArray(int n)
    {
        long[] ans = new long[n];
        for (int i = 0; i < n; i++)
            ans[i] = ReadLong();
        return ans;
    }

    private static char[] ReadString()
    {
        int ans;

        do
        {
            ans = consoleReader.Read();
        } while (!((ans >= 'a' && ans <= 'z') || (ans >= 'A' && ans <= 'Z')));

        List<char> s = new List<char>();
        do
        {
            s.Add((char)ans);
            ans = consoleReader.Read();
        } while ((ans >= 'a' && ans <= 'z') || (ans >= 'A' && ans <= 'Z'));

        return s.ToArray();
    }

    private static char[] ReadString(int n)
    {
        int ans;

        do
        {
            ans = consoleReader.Read();
        } while (!((ans >= 'a' && ans <= 'z') || (ans >= 'A' && ans <= 'Z')));

        char[] s = new char[n];
        int pos = 0;
        do
        {
            s[pos++] = (char)ans;
            if (pos == n) break;
            ans = consoleReader.Read();
        } while ((ans >= 'a' && ans <= 'z') || (ans >= 'A' && ans <= 'Z'));

        return s;
    }

    private static char ReadLetter()
    {
        while (true)
        {
            int ans = consoleReader.Read();
            if ((ans >= 'a' && ans <= 'z') || (ans >= 'A' && ans <= 'Z'))
                return (char)ans;
        }
    }

    private static char ReadDigit()
    {
        while (true)
        {
            int ans = consoleReader.Read();
            if (ans >= '0' && ans <= '9')
                return (char)ans;
        }
    }

    private static int ReadDigitInt()
    {
        return ReadDigit() - (int)'0';
    }

    private static char ReadAnyChar()
    {
        return (char)consoleReader.Read();
    }

    private static string DoubleToString(double x)
    {
        return x.ToString(CultureInfo.InvariantCulture);
    }

    static Program()
    {
        //Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
        consoleReader = new StreamReader(Console.OpenStandardInput(BufferSize), Encoding.ASCII, false, BufferSize);
    }

    private static void PushTestData(string data)
    {
#if !ONLINE_JUDGE
        if (testData == null)
        {
            testData = new MemoryStream();
            consoleReader = new StreamReader(testData);
        }

        var pos = testData.Position;
        var bytes = Encoding.UTF8.GetBytes(data);
        testData.Write(bytes, 0, bytes.Length);
        testData.Flush();
        testData.Position = pos;
#endif
    }
}