import java.io.*;

import java.util.*;

// 32 +

import static java.lang.Math.*;

import static java.util.Arrays.*;

public class cf1304f1 {

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

        int n = rni(), m = ni(), k = ni(), animals[][] = new int[n][m];

        for (int i = 0; i < n; ++i) {

            r();

            for (int j = 0; j < m; ++j) {

                animals[i][j] = ni();

            }

        }

        long sum[][] = new long[n][m + 1];

        for (int i = 0; i < n; ++i) {

            for (int j = 0; j < m; ++j) {

                sum[i][j + 1] = sum[i][j] + animals[i][j];

            }

        }

        sgt dp = new sgt(m - k + 1, Math::max, LMIN);

        for (int i = 0; i < n; ++i) {

            sgt ndp = new sgt(m - k + 1, Math::max, LMIN);

            long[] point_qry = new long[m - k + 1];

            for (int j = 0; j <= m - k; ++j) {

                point_qry[j] = dp.qry(j, j + 1);

            }

            for (int j = 0; j <= m - k; ++j) {

                long cnt = sum[i][j + k] - sum[i][j];

                if (i < n - 1){

                    cnt += sum[i + 1][j + k] - sum[i + 1][j];

                }

                if (i == 0) {

                    ndp.upd(j, dp.qry(0, m - k + 1) + cnt);

                } else {

                    ndp.upd(j, dp.qry(0, j - k) + cnt);

                    ndp.upd(j, dp.qry(j + k, m - k + 1) + cnt);

                    long upd = 0;

                    for (int l = max(0, j - k); l < min(j + k, m - k + 1); ++l) {

                        upd = max(upd, point_qry[l] - max(0, min(sum[i][l + k] - sum[i][j], sum[i][j + k] - sum[i][l])) + cnt);

                    }

                    ndp.upd(j, upd);

                }

            }

            dp = ndp;

        }

        prln(dp.qry(0, m - k + 1));

        close();

    }

    @FunctionalInterface

    interface LongOperator {

        long merge(long a, long b);

    }

    static class sgt {

        LongOperator upd_op, qry_op;

        int n;

        long sgt[], id;

        sgt(int sz, LongOperator operator, long identity) {

            n = sz;

            sgt = new long[4 * n + 5];

            upd_op = qry_op = operator;

            id = identity;

        }

        sgt(int sz, LongOperator update_operator, LongOperator query_operator, long identity) {

            n = sz;

            sgt = new long[4 * n + 5];

            upd_op = update_operator;

            qry_op = query_operator;

            id = identity;

        }

        sgt(long[] a, LongOperator operator, long identity) {

            n = a.length;

            sgt = new long[4 * n + 5];

            upd_op = qry_op = operator;

            id = identity;

            build(1, a, 0, n - 1);

        }

        sgt(long[] a, LongOperator update_operator, LongOperator query_operator, long identity) {

            n = a.length;

            sgt = new long[4 * n + 5];

            upd_op = update_operator;

            qry_op = query_operator;

            id = identity;

            build(1, a, 0, n - 1);

        }

        void set(int i, long x) {

            set(1, i, x, 0, n - 1);

        }

        void upd(int i, long x) {

            upd(1, i, x, 0, n - 1);

        }

        long qry(int l, int r) {

            return qry(1, l, r - 1, 0, n - 1);

        }

        void set(int node, int i, long x, int l, int r) {

            if (l == r) {

                sgt[node] = x;

            } else {

                int m = l + (r - l) / 2;

                if (i <= m) {

                    set(node << 1, i, x, l, m);

                } else {

                    set(node << 1 | 1, i, x, m + 1, r);

                }

                pull(node);

            }

        }

        void upd(int node, int i, long x, int l, int r) {

            if (l == r) {

                sgt[node] = upd_op.merge(sgt[node], x);

            } else {

                int m = l + (r - l) / 2;

                if (i <= m) {

                    upd(node << 1, i, x, l, m);

                } else {

                    upd(node << 1 | 1, i, x, m + 1, r);

                }

                pull(node);

            }

        }

        long qry(int node, int i, int j, int l, int r) {

            if (r < i || j < l) {

                return id;

            } else if (i <= l && r <= j) {

                return sgt[node];

            } else {

                int m = l + (r - l) / 2;

                return qry_op.merge(qry(node << 1, i, j, l, m), qry(node << 1 | 1, i, j, m + 1, r));

            }

        }

        void build(int node, long[] a, int l, int r) {

            if (l == r) {

                sgt[node] = a[l];

            } else {

                int m = l + (r - l) / 2;

                build(node << 1, a, l, m);

                build(node << 1 | 1, a, m + 1, r);

                pull(node);

            }

        }

        void pull(int node) {

            sgt[node] = qry_op.merge(sgt[node << 1], sgt[node << 1 | 1]);

        }

    }

    static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in));

    static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out));

    static StringTokenizer input;

    static Random __rand = new Random();

    // references

    // IBIG = 1e9 + 7

    // IMAX ~= 2e9

    // LMAX ~= 9e18

    // constants

    static final int IBIG = 1000000007;

    static final int IMAX = 2147483647;

    static final int IMIN = -2147483648;

    static final long LMAX = 9223372036854775807L;

    static final long LMIN = -9223372036854775808L;

    // math util

    static int minof(int a, int b, int c) {return min(a, min(b, c));}

    static int minof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;}

    static long minof(long a, long b, long c) {return min(a, min(b, c));}

    static long minof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;}

    static int maxof(int a, int b, int c) {return max(a, max(b, c));}

    static int maxof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;}

    static long maxof(long a, long b, long c) {return max(a, max(b, c));}

    static long maxof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;}

    static int powi(int a, int b) {if (a == 0) return 0; int ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}

    static long powl(long a, int b) {if (a == 0) return 0; long ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}

    static int fli(double d) {return (int) d;}

    static int cei(double d) {return (int) ceil(d);}

    static long fll(double d) {return (long) d;}

    static long cel(double d) {return (long) ceil(d);}

    static int gcf(int a, int b) {return b == 0 ? a : gcf(b, a % b);}

    static long gcf(long a, long b) {return b == 0 ? a : gcf(b, a % b);}

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

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

    static int randInt(int min, int max) {return __rand.nextInt(max - min + 1) + min;}

    static long mix(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);}

    // array util

    static void reverse(int[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}

    static void reverse(long[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}

    static void reverse(double[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}

    static void reverse(char[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}

    static void shuffle(int[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}

    static void shuffle(long[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}

    static void shuffle(double[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}

    static void rsort(int[] a) {shuffle(a); sort(a);}

    static void rsort(long[] a) {shuffle(a); sort(a);}

    static void rsort(double[] a) {shuffle(a); sort(a);}

    static int[] copy(int[] a) {int[] ans = new int[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}

    static long[] copy(long[] a) {long[] ans = new long[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}

    static double[] copy(double[] a) {double[] ans = new double[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}

    static char[] copy(char[] a) {char[] ans = new char[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}

    // graph util

    static List<List<Integer>> g(int n) {List<List<Integer>> g = new ArrayList<>(); for (int i = 0; i < n; ++i) g.add(new ArrayList<>()); return g;}

    static List<Set<Integer>> sg(int n) {List<Set<Integer>> g = new ArrayList<>(); for (int i = 0; i < n; ++i) g.add(new HashSet<>()); return g;}

    static void c(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v); g.get(v).add(u);}

    static void cto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v);}

    static void dc(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v); g.get(v).remove(u);}

    static void dcto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v);}

    // input

    static void r() throws IOException {input = new StringTokenizer(rline());}

    static int ri() throws IOException {return Integer.parseInt(rline());}

    static long rl() throws IOException {return Long.parseLong(rline());}

    static double rd() throws IOException {return Double.parseDouble(rline());}

    static int[] ria(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni(); return a;}

    static int[] riam1(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni() - 1; return a;}

    static long[] rla(int n) throws IOException {long[] a = new long[n]; r(); for (int i = 0; i < n; ++i) a[i] = nl(); return a;}

    static double[] rda(int n) throws IOException {double[] a = new double[n]; r(); for (int i = 0; i < n; ++i) a[i] = nd(); return a;}

    static char[] rcha() throws IOException {return rline().toCharArray();}

    static String rline() throws IOException {return __in.readLine();}

    static String n() {return input.nextToken();}

    static int rni() throws IOException {r(); return ni();}

    static int ni() {return Integer.parseInt(n());}

    static long rnl() throws IOException {r(); return nl();}

    static long nl() {return Long.parseLong(n());}

    static double rnd() throws IOException {r(); return nd();}

    static double nd() {return Double.parseDouble(n());}

    static List<List<Integer>> rg(int n, int m) throws IOException {List<List<Integer>> g = g(n); for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;}

    static void rg(List<List<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);}

    static List<List<Integer>> rdg(int n, int m) throws IOException {List<List<Integer>> g = g(n); for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;}

    static void rdg(List<List<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);}

    static List<Set<Integer>> rsg(int n, int m) throws IOException {List<Set<Integer>> g = sg(n); for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;}

    static void rsg(List<Set<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);}

    static List<Set<Integer>> rdsg(int n, int m) throws IOException {List<Set<Integer>> g = sg(n); for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;}

    static void rdsg(List<Set<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);}

    // output

    static void pr(int i) {__out.print(i);}

    static void prln(int i) {__out.println(i);}

    static void pr(long l) {__out.print(l);}

    static void prln(long l) {__out.println(l);}

    static void pr(double d) {__out.print(d);}

    static void prln(double d) {__out.println(d);}

    static void pr(char c) {__out.print(c);}

    static void prln(char c) {__out.println(c);}

    static void pr(char[] s) {__out.print(new String(s));}

    static void prln(char[] s) {__out.println(new String(s));}

    static void pr(String s) {__out.print(s);}

    static void prln(String s) {__out.println(s);}

    static void pr(Object o) {__out.print(o);}

    static void prln(Object o) {__out.println(o);}

    static void prln() {__out.println();}

    static void pryes() {prln("yes");}

    static void pry() {prln("Yes");}

    static void prY() {prln("YES");}

    static void prno() {prln("no");}

    static void prn() {prln("No");}

    static void prN() {prln("NO");}

    static void pryesno(boolean b) {prln(b ? "yes" : "no");};

    static void pryn(boolean b) {prln(b ? "Yes" : "No");}

    static void prYN(boolean b) {prln(b ? "YES" : "NO");}

    static void prln(int... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();}

    static void prln(long... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();}

    static void prln(double... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();}

    static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for (int i = 0; i < n; pr(iter.next()), pr(' '), ++i); if (n >= 0) prln(iter.next()); else prln();}

    static void h() {prln("hlfd"); flush();}

    static void flush() {__out.flush();}

    static void close() {__out.close();}

}


E. Sleeping Scheduletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVova had a pretty weird sleeping schedule. There are hh hours in a day. Vova will sleep exactly nn times. The ii-th time he will sleep exactly after aiai hours from the time he woke up. You can assume that Vova woke up exactly at the beginning of this story (the initial time is 00). Each time Vova sleeps exactly one day (in other words, hh hours).Vova thinks that the ii-th sleeping time is good if he starts to sleep between hours ll and rr inclusive.Vova can control himself and before the ii-th time can choose between two options: go to sleep after aiai hours or after ai−1ai−1 hours.Your task is to say the maximum number of good sleeping times Vova can obtain if he acts optimally.InputThe first line of the input contains four integers n,h,ln,h,l and rr (1≤n≤2000,3≤h≤2000,0≤l≤r<h1≤n≤2000,3≤h≤2000,0≤l≤r<h) — the number of times Vova goes to sleep, the number of hours in a day and the segment of the good sleeping time.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai<h1≤ai<h), where aiai is the number of hours after which Vova goes to sleep the ii-th time.OutputPrint one integer — the maximum number of good sleeping times Vova can obtain if he acts optimally.ExampleInputCopy7 24 21 23
16 17 14 20 20 11 22
OutputCopy3
NoteThe maximum number of good times in the example is 33.The story starts from t=0t=0. Then Vova goes to sleep after a1−1a1−1 hours, now the time is 1515. This time is not good. Then Vova goes to sleep after a2−1a2−1 hours, now the time is 15+16=715+16=7. This time is also not good. Then Vova goes to sleep after a3a3 hours, now the time is 7+14=217+14=21. This time is good. Then Vova goes to sleep after a4−1a4−1 hours, now the time is 21+19=1621+19=16. This time is not good. Then Vova goes to sleep after a5a5 hours, now the time is 16+20=1216+20=12. This time is not good. Then Vova goes to sleep after a6a6 hours, now the time is 12+11=2312+11=23. This time is good. Then Vova goes to sleep after a7a7 hours, now the time is 23+22=2123+22=21. This time is also good.

/*

  It's always like another kick for me to make sure I get what I want to get done,

  because honestly you never know.

*/

import java.util.*;

import java.io.*;

import static java.lang.Math.*;

public class Main extends PrintWriter {

      Main() { super(System.out); }

      static boolean cases = false;

      // Solution

      int l, h, r, a[];

      int dp[][];

      void solve() {

	    int n = sc.nextInt();

	    h = sc.nextInt();

	    l = sc.nextInt();

	    r = sc.nextInt();

	    a = sc.readIntArray(n);

	    this.dp = new int[n + 1][h + 1];

	    for (int i = n - 1; i >= 0; i--) {

		  for (int j = h; j >= 0; j--) {

			int d1 = (j + a[i]) % h;

			int d2 = (j + (a[i] - 1)) % h;

			if (d1 >= l && d1 <= r) {

			      dp[i][j] = max(dp[i][j], 1 + dp[i + 1][d1]);

			} else dp[i][j] = max(dp[i][j], dp[i + 1][d1]);

			if (d2 >= l && d2 <= r) {

			      dp[i][j] = max(dp[i][j], 1 + dp[i + 1][d2]);

			} else dp[i][j] = max(dp[i][j], dp[i + 1][d2]);

		  }

	    }

	    System.out.println(dp[0][0]);

      }

      void sort(int[] a) {

	    ArrayList<Integer> l = new ArrayList<>();

	    for (int i : a) l.add(i);

	    Collections.sort(l);

	    for (int i = 0; i < a.length; i++) a[i] = l.get(i);

      }

      public static void main(String[] args) {

	    Main obj = new Main();

	    int c = 1;

	    for (int t = (cases ? sc.nextInt() : 0); t > 1; t--, c++) obj.solve();

	    obj.solve();

	    obj.flush();

      }

      static class FastScanner {

	    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

	    StringTokenizer st = new StringTokenizer("");

	    String next() {

		  while (!st.hasMoreTokens()) try {

			st = new StringTokenizer(br.readLine());

		  } catch (IOException e) {

			e.printStackTrace();

		  }

		  return st.nextToken();

	    }

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

	    int[] readIntArray(int n) {

		  int[] a = new int[n];

		  for (int i = 0; i < n; i++) a[i] = nextInt();

		  return a;

	    }

	    char[] readCharArray(int n) {

		  char a[] = new char[n];

		  String s = sc.next();

		  for (int i = 0; i < n; i++) { a[i] = s.charAt(i); }

		  return a;

	    }

	    long[] readLongArray(int n) {

		  long[] a = new long[n];

		  for (int i = 0; i < n; i++) a[i] = nextLong();

		  return a;

	    }

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

      }

      final int ima = Integer.MAX_VALUE;

      final int imi = Integer.MIN_VALUE;

      final long lma = Long.MAX_VALUE;

      final long lmi = Long.MIN_VALUE;

      static final long mod = (long) 1e9 + 7;

      private static final FastScanner sc = new FastScanner();

      private PrintWriter out = new PrintWriter(System.out);

}


C. Ayoub's functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAyoub thinks that he is a very smart person; so he created a function f(s)f(s), where ss is a binary string (a string which contains only symbols "0" and "1"). The function f(s)f(s) is equal to the number of substrings in the string ss that contains at least one symbol, that is equal to "1".More formally, f(s)f(s) is equal to the number of pairs of integers (l,r)(l,r), such that 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of string ss), such that at least one of the symbols sl,sl+1,…,srsl,sl+1,…,sr is equal to "1". For example, if s=s="01010" then f(s)=12f(s)=12, because there are 1212 such pairs (l,r)(l,r): (1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5)(1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5).Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers nn and mm and asked him this problem. For all binary strings ss of length nn which contains exactly mm symbols equal to "1", find the maximum value of f(s)f(s).Mahmoud couldn't solve the problem so he asked you for help. Can you help him? InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1051≤t≤105)  — the number of test cases. The description of the test cases follows.The only line for each test case contains two integers nn, mm (1≤n≤1091≤n≤109, 0≤m≤n0≤m≤n) — the length of the string and the number of symbols equal to "1" in it.OutputFor every test case print one integer number — the maximum value of f(s)f(s) over all strings ss of length nn, which has exactly mm symbols, equal to "1".ExampleInputCopy5
3 1
3 2
3 3
4 0
5 2
OutputCopy4
5
6
0
12
NoteIn the first test case; there exists only 33 strings of length 33, which has exactly 11 symbol, equal to "1". These strings are: s1=s1="100", s2=s2="010", s3=s3="001". The values of ff for them are: f(s1)=3,f(s2)=4,f(s3)=3f(s1)=3,f(s2)=4,f(s3)=3, so the maximum value is 44 and the answer is 44.In the second test case, the string ss with the maximum value is "101".In the third test case, the string ss with the maximum value is "111".In the fourth test case, the only string ss of length 44, which has exactly 00 symbols, equal to "1" is "0000" and the value of ff for that string is 00, so the answer is 00.In the fifth test case, the string ss with the maximum value is "01010" and it is described as an example in the problem statement.

import java.awt.MultipleGradientPaint.ColorSpaceType;

import java.io.*;

import java.sql.PreparedStatement;

import java.util.*;

public class cp {

	static int mod=998244353;//(int)1e9+7;

//	static  Reader sc=new Reader();

	static FastReader sc=new FastReader(System.in);

	static int[] sp;

	static int size=(int)1e6;

	static int[] arInt;

	static long[] arLong;

	static long ans;

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

		long tc=sc.nextLong();

//		Scanner sc=new Scanner(System.in);

//			int tc=1;

//			print_int(pre);

//			primeSet=new HashSet<>();

//			primeCnt=new int[(int)1e9];

//			sieveOfEratosthenes((int)1e9);

//			factorial(mod);

//			InverseofNumber(mod);

//			InverseofFactorial(mod);

			while(tc-->0)

			{

				long n=sc.nextLong();

				long m=sc.nextLong();

				long ans=n*(n+1)/2;

				long zero=(n-m);

				long grps=m+1;

				long k=zero/grps;

				ans-=(k*(k+1)/2)*grps;

				ans-=(k+1)*(zero%grps);

				out.println(ans);

			}

//			System.out.flush();

			out.flush();

			out.close();

			System.gc();

	}

	/*

	   ...SOLUTION ENDS HERE...........SOLUTION ENDS HERE...

 */

	static class Node{

		int a;

		ArrayList<Pair> adj;

		public Node(int a) {

			this.a=a;

			this.adj=new ArrayList<>();

		}

	}

	static void dijkstra(Node[] g,int dist[],int parent[],int src)

	{

		Arrays.fill(dist, int_max);

		Arrays.fill(parent, -1);

		boolean vis[]=new boolean[dist.length];

//		vis[1]=true;

		PriorityQueue<Pair> q=new PriorityQueue<>();

		q.add(new Pair(1, 0));

		dist[1]=0;

		while(!q.isEmpty())

		{

			Pair curr=q.poll();

			vis[curr.x]=true;

			for(Pair edge:g[curr.x].adj)

			{

				if (vis[edge.x]) {

					continue;

				}

				if (dist[edge.x]>dist[curr.x]+edge.y) {

					dist[edge.x]=dist[curr.x]+edge.y;

					parent[edge.x]=curr.x;

					q.add(new Pair(edge.x, dist[edge.x]));

				}

			}

		}

	}

	static void mapping(int a[])

	{

		Pair[] temp=new Pair[a.length];

		for (int i = 0; i < temp.length; i++) {

			temp[i]=new Pair(a[i], i);

		}

		Arrays.sort(temp);

		int k=0;

		for (int i = 0; i < temp.length; i++) {

			a[temp[i].y]=k++;

		}

	}

	static boolean palin(String s)

	{

		for(int i=0;i<s.length()/2;i++)

			if(s.charAt(i)!=s.charAt(s.length()-i-1))

				return false;

		return true;

	}

	static class temp implements Comparable<temp>{

		int x;

		int y;

		int sec;

		public temp(int x,int y,int l) {

			// TODO Auto-generated constructor stub

			this.x=x;

			this.y=y;

			this.sec=l;

		}

		@Override

		public int compareTo(cp.temp o) {

			// TODO Auto-generated method stub

			return this.sec-o.sec;

		}

	}

//	static class Node{

//		int x;

//		int y;

//		ArrayList<Integer> edges;

//		public Node(int x,int y) {

//			// TODO Auto-generated constructor stub

//			this.x=x;

//			this.y=y;

//			this.edges=new ArrayList<>();

//		}

//	}

	static int lis(int arr[],int n)

	{

		int ans=0;

		int dp[]=new int[n+1];

		Arrays.fill(dp, int_max);

		dp[0]=int_min;

		for(int i=0;i<n;i++)

		{

			int j=UpperBound(dp,arr[i]);

			if(dp[j-1]<=arr[i] && arr[i]<dp[j])

				dp[j]=arr[i];

		}

		for(int i=0;i<=n;i++)

		{

			if(dp[i]<int_max)

				ans=i;

		}

		return ans;

	}

	static long get(long n)

	{

		return n*(n+1)/2L;

	}

	static boolean go(ArrayList<Pair> caves,int k)

	{

		for(Pair each:caves)

		{

			if(k<=each.x)

				return false;

			k+=each.y;

		}

		return true;

	}

	static String revString(String s)

	{

		char arr[]=s.toCharArray();

		int n=s.length();

		for(int i=0;i<n/2;i++)

		{

			char temp=arr[i];

			arr[i]=arr[n-i-1];

			arr[n-i-1]=temp;

		}

		return String.valueOf(arr);

	}

//	Fuction return the number of set bits in n

	static int SetBits(int n)

	{

		int cnt=0;

		while(n>0)

		{

			if((n&1)==1)

			{

				cnt++;

			}

			n=n>>1;

		}

		return cnt;

	}

	static boolean isPowerOfTwo(int n)

    {

        return (int)(Math.ceil((Math.log(n) / Math.log(2))))

            == (int)(Math.floor(((Math.log(n) / Math.log(2)))));

    }

	static void arrInt(int n) throws IOException

	{

		arInt=new int[n];

		for (int i = 0; i < arInt.length; i++) {

			arInt[i]=sc.nextInt();

		}

	}

	static void arrLong(int n) throws IOException

	{

		arLong=new long[n];

		for (int i = 0; i < arLong.length; i++) {

			arLong[i]=sc.nextLong();

		}

	}

	static ArrayList<Integer> add(int id,int c)

	{

		ArrayList<Integer> newArr=new ArrayList<>();

		for(int i=0;i<id;i++)

			newArr.add(arInt[i]);

		newArr.add(c);

		for(int i=id;i<arInt.length;i++)

		{

			newArr.add(arInt[i]);

		}

		return newArr;

	}

	    // function to find first index >= y

    static int upper(ArrayList<Integer> arr, int n, int x)

    {

    	int l = 0, h = n - 1;

        while (h-l>1)

        {

            int mid = (l + h) / 2;

            if (arr.get(mid) <= x)

                l=mid+1;

            else

            {

            	h=mid;

            }

        }

        if(arr.get(l)>x)

        {

        	return l;

        }

        if(arr.get(h)>x)

        	return h;

        return -1;

    }

    static int upper(ArrayList<Long> arr, int n, long x)

    {

    	int l = 0, h = n - 1;

    	while (h-l>1)

    	{

    		int mid = (l + h) / 2;

    		if (arr.get(mid) <= x)

    			l=mid+1;

    		else

    		{

    			h=mid;

    		}

    	}

    	if(arr.get(l)>x)

    	{

    		return l;

    	}

    	if(arr.get(h)>x)

    		return h;

    	return -1;

    }

	static int lower(ArrayList<Integer> arr, int n, int x)

    {

        int l = 0, h = n - 1;

        while (h-l>1)

        {

            int mid = (l + h) / 2;

            if (arr.get(mid) < x)

                l=mid+1;

            else

            {

            	h=mid;

            }

        }

        if(arr.get(l)>=x)

        {

        	return l;

        }

        if(arr.get(h)>=x)

        	return h;

        return -1;

    }

	static int N = (int)2e5+5;

	// Array to store inverse of 1 to N

	static long[] factorialNumInverse = new long[N + 1];

	// Array to precompute inverse of 1! to N!

	static long[] naturalNumInverse = new long[N + 1];

	// Array to store factorial of first N numbers

	static long[] fact = new long[N + 1];

	// Function to precompute inverse of numbers

	public static void InverseofNumber(int p)

	{

	    naturalNumInverse[0] = naturalNumInverse[1] = 1;

	    for(int i = 2; i <= N; i++)

	        naturalNumInverse[i] = naturalNumInverse[p % i] *

	                                 (long)(p - p / i) % p;

	}

	// Function to precompute inverse of factorials

	public static void InverseofFactorial(int p)

	{

	    factorialNumInverse[0] = factorialNumInverse[1] = 1;

	    // Precompute inverse of natural numbers

	    for(int i = 2; i <= N; i++)

	        factorialNumInverse[i] = (naturalNumInverse[i] *

	                           factorialNumInverse[i - 1]) % p;

	}

	// Function to calculate factorial of 1 to N

	public static void factorial(int p)

	{

	    fact[0] = 1;

	    // Precompute factorials

	    for(int i = 1; i <= N; i++)

	    {

	        fact[i] = (fact[i - 1] * (long)i) % p;

	    }

	}

	// Function to return nCr % p in O(1) time

	public static long Binomial(int N, int R, int p)

	{

	    // n C r = n!*inverse(r!)*inverse((n-r)!)

	    long ans = ((fact[N] * factorialNumInverse[R]) %

	                       p * factorialNumInverse[N - R]) % p;

	    return ans;

	}

	static String tr(String s)

	{

		int now = 0;

		while (now + 1 < s.length() && s.charAt(now)== '0')

			++now;

		return s.substring(now);

	}

	static boolean isPrime(long n)

    {

        // Corner cases

        if (n <= 1)

            return false;

        if (n <= 3)

            return true;

        // This is checked so that we can skip

        // middle five numbers in below loop

        if (n % 2 == 0 || n % 3 == 0)

            return false;

        for (int i = 5; i * i <= n; i = i + 6)

            if (n % i == 0 || n % (i + 2) == 0)

                return false;

        return true;

    }

	static ArrayList<Integer> commDiv(int a, int b)

    {

        // find gcd of a, b

        int n = gcd(a, b);

        // Count divisors of n.

        ArrayList<Integer> Div=new ArrayList<>();

        for (int i = 1; i <= Math.sqrt(n); i++) {

            // if 'i' is factor of n

            if (n % i == 0) {

                // check if divisors are equal

                if (n / i == i)

                    Div.add(i);

                else

                {

                	Div.add(i);

                	Div.add(n/i);

                }

            }

        }

        return Div;

    }

	static HashSet<Integer> factors(int x)

	{

		HashSet<Integer> a=new HashSet<Integer>();

		for(int i=2;i*i<=x;i++)

		{

			if(x%i==0)

			{

				a.add(i);

				a.add(x/i);

			}

		}

		return a;

	}

	static void primeFactors(int n,HashSet<Integer> factors)

    {

        // Print the number of 2s that divide n

        while (n%2==0)

        {

            factors.add(2);

            n /= 2;

        }

        // n must be odd at this point.  So we can

        // skip one element (Note i = i +2)

        for (int i = 3; i <= Math.sqrt(n); i+= 2)

        {

            // While i divides n, print i and divide n

            while (n%i == 0)

            {

               factors.add(i);

                n /= i;

            }

        }

        // This condition is to handle the case when

        // n is a prime number greater than 2

        if (n > 2)

            factors.add(n);

    }

	static class Tuple{

		int a;

		int b;

		int c;

		public Tuple(int a,int b,int c) {

			this.a=a;

			this.b=b;

			this.c=c;

		}

	}

	//function to find prime factors of n

	static HashMap<Long,Long> findFactors(long n2)

	{

		HashMap<Long,Long> ans=new HashMap<>();

		if(n2%2==0)

		{

			ans.put(2L, 0L);

//			cnt++;

			while((n2&1)==0)

			{

				n2=n2>>1;

				ans.put(2L, ans.get(2L)+1);

//

			}

		}

		for(long i=3;i*i<=n2;i+=2)

		{

			if(n2%i==0)

			{

				ans.put((long)i, 0L);

//				cnt++;

				while(n2%i==0)

				{

					n2=n2/i;

					ans.put((long)i, ans.get((long)i)+1);

				}

			}

		}

		if(n2!=1)

		{

			ans.put(n2, ans.getOrDefault(n2, (long) 0)+1);

		}

		return ans;

	}

	//fenwick tree implementaion

	static class fwt

	{

		int n;

		long BITree[];

		fwt(int n)

		{

			this.n=n;

			BITree=new long[n+1];

		}

		fwt(int arr[], int n)

		{

			this.n=n;

			BITree=new long[n+1];

			for(int i = 0; i < n; i++)

			updateBIT(n, i, arr[i]);

		 }

		   long getSum(int index)

		   {

		       long sum = 0;

		       index = index + 1;

		       while(index>0)

		       {

		           sum += BITree[index];

		           index -= index & (-index);

		       }

		       return sum;

		   }

		   void updateBIT(int n, int index,int val)

		   {

		       index = index + 1;

		       while(index <= n)

		       {

			       BITree[index] += val;

			       index += index & (-index);

		       }

		   }

		   long sum(int l, int r) {

		        return getSum(r) - getSum(l - 1);

		   }

		   void print()

		   {

			    for(int i=0;i<n;i++)

			    out.print(getSum(i)+" ");

			    out.println();

		   }

	}

	static class sparseTable{

		int n;

		long[][]dp;

		int log2[];

		int P;

		void buildTable(long[] arr)

		{

			n=arr.length;

			P=(int)Math.floor(Math.log(n)/Math.log(2));

			log2=new int[n+1];

			log2[0]=log2[1]=0;

			for(int i=2;i<=n;i++)

			{

				log2[i]=log2[i/2]+1;

			}

			dp=new long[P+1][n];

			for(int i=0;i<n;i++)

			{

				dp[0][i]=arr[i];

			}

			for(int p=1;p<=P;p++)

			{

				for(int i=0;i+(1<<p)<=n;i++)

				{

					long left=dp[p-1][i];

					long right=dp[p-1][i+(1<<(p-1))];

					dp[p][i]=Math.min(left, right);

				}

			}

		}

		long maxQuery(int l,int r)

		{

			int len=r-l+1;

			int p=(int)Math.floor(log2[len]);

			long left=dp[p][l];

			long right=dp[p][r-(1<<p)+1];

			return Math.min(left,right);

		}

	}

	//Function to find number of set bits

	static int setBitNumber(long n)

    {

        if (n == 0)

            return 0;

        int msb = 0;

        n = n / 2;

        while (n != 0) {

            n = n / 2;

            msb++;

        }

        return msb;

    }

	static int getFirstSetBitPos(long n)

    {

        return (int)((Math.log10(n & -n)) / Math.log10(2)) + 1;

    }

	static ArrayList<Integer> primes;

	static HashSet<Integer> primeSet;

	static boolean prime[];

	static int primeCnt[];

	static void sieveOfEratosthenes(int n)

    {

       prime= new boolean[n + 1];

        for (int i = 2; i <= n; i++)

            prime[i] = true;

        for (int p = 2; p * p <= n; p++)

        {

            // If prime[p] is not changed, then it is a

            // prime

            if (prime[p] == true)

            {

                // Update all multiples of p

                for (int i = p * p; i <= n; i += p)

                    prime[i] = false;

            }

        }

        // Print all prime numbers

        for (int i = 2; i <= n; i++)

        {

            if (prime[i] == true)

               primeCnt[i]=primeCnt[i-1]+1;

        }

    }

	static long mod(long a, long b) {

		  long c = a % b;

		  return (c < 0) ? c + b : c;

		}

	static void swap(long arr[],int i,int j)

	{

		long temp=arr[i];

		arr[i]=arr[j];

		arr[j]=temp;

	}

	static boolean util(int a,int b,int c)

	{

		if(b>a)util(b, a, c);

		while(c>=a)

		{

			c-=a;

			if(c%b==0)

				return true;

		}

		return (c%b==0);

	}

	static void flag(boolean flag)

	   {

	       out.println(flag ? "YES" : "NO");

	       out.flush();

	   }

	static void print(int a[])

	  {

	     int n=a.length;

	     for(int i=0;i<n;i++)

	       {

	          out.print(a[i]+" ");

	       }

	     out.println();

	     out.flush();

	  }

	static void print(long a[])

	  {

	     int n=a.length;

	     for(int i=0;i<n;i++)

	       {

	          out.print(a[i]+" ");

	       }

	     out.println();

	     out.flush();

	  }

	static void print_int(ArrayList<Integer> al)

	  {

	     int si=al.size();

	     for(int i=0;i<si;i++)

	       {

	          out.print(al.get(i)+" ");

	       }

	     out.println();

	     out.flush();

	  }

	static void print_long(ArrayList<Long> al)

	  {

	     int si=al.size();

	     for(int i=0;i<si;i++)

	       {

	          out.print(al.get(i)+" ");

	       }

	     out.println();

	     out.flush();

	  }

	static void printYesNo(boolean condition)

	{

		if (condition) {

			out.println("YES");

		}

		else {

			out.println("NO");

		}

	}

	static int LowerBound(int a[], int x)

	 { // x is the target value or key

	  int l=-1,r=a.length;

	  while(l+1<r) {

	    int m=(l+r)>>>1;

	    if(a[m]>=x) r=m;

	    else l=m;

	  }

	  return r;

	}

	static int lowerIndex(int arr[], int n, int x)

    {

        int l = 0, h = n - 1;

        while (l<=h)

        {

            int mid = (l + h) / 2;

            if (arr[mid] >= x)

                h = mid -1 ;

            else

                l = mid + 1;

        }

        return l;

    }

	    // function to find last index <= y

    static int upperIndex(int arr[], int n, int y)

    {

        int l = 0, h = n - 1;

        while (l <= h)

        {

            int mid = (l + h) / 2;

            if (arr[mid] <= y)

                l = mid + 1;

            else

                h = mid - 1;

        }

        return h;

    }

    static int upperIndex(long arr[], int n, long y)

    {

    	int l = 0, h = n - 1;

    	while (l <= h)

    	{

    		int mid = (l + h) / 2;

    		if (arr[mid] <= y)

    			l = mid + 1;

    		else

    			h = mid - 1;

    	}

    	return h;

    }

	 static int UpperBound(int a[], int x)

	  {// x is the key or target value

	    int l=-1,r=a.length;

	    while(l+1<r) {

	       int m=(l+r)>>>1;

	       if(a[m]<=x) l=m;

	       else r=m;

	    }

	    return l+1;

	 }

	 static int UpperBound(long a[], long x)

	 {// x is the key or target value

		 int l=-1,r=a.length;

		 while(l+1<r) {

			 int m=(l+r)>>>1;

	       if(a[m]<=x) l=m;

	       else r=m;

		 }

		 return l+1;

	 }

	 static class DisjointUnionSets

	 {

	    int[] rank, parent;

	    int n;

	    // Constructor

	    public DisjointUnionSets(int n)

	    {

	        rank = new int[n];

	        parent = new int[n];

	        this.n = n;

	        makeSet();

	    }

	    // Creates n sets with single item in each

	    void makeSet()

	    {

	        for (int i = 0; i < n; i++)

	            parent[i] = i;

	    }

	    int find(int x)

	    {

	        if (parent[x] != x) {

	            parent[x] = find(parent[x]);

	        }

	        return parent[x];

	    }

	    // Unites the set that includes x and the set

	    // that includes x

	    void union(int x, int y)

	    {

	        int xRoot = find(x), yRoot = find(y);

	        if (xRoot == yRoot)

	            return;

	        if (rank[xRoot] < rank[yRoot])

	            parent[xRoot] = yRoot;

	        else if (rank[yRoot] < rank[xRoot])

	         parent[yRoot] = xRoot;

	        else // if ranks are the same

	        {

	         parent[yRoot] = xRoot;

	            rank[xRoot] = rank[xRoot] + 1;

	        }

//	        if(xRoot!=yRoot)

//	        	parent[y]=x;

	    }

	    int connectedComponents()

	    {

	    	int cnt=0;

	    	for(int i=0;i<n;i++)

	    	{

	    		if(parent[i]==i)

	    			cnt++;

	    	}

	    	return cnt;

	    }

	 }

//	static class Graph

//	  {

//	        int v;

//	        ArrayList<Integer> list[];

//	        Graph(int v)

//	        {

//	            this.v=v;

//	            list=new ArrayList[v+1];

//	            for(int i=1;i<=v;i++)

//	                list[i]=new ArrayList<Integer>();

//	        }

//	        void addEdge(int a, int b)

//	        {

//	            this.list[a].add(b);

//	        }

//

//

//

//	    }

	 static class Pair implements Comparable<Pair>

	    {

	       int x;

	       int y;

	       Pair(int x,int y)

	        {

	           this.x=x;

	           this.y=y;

	        }

		@Override

		public int compareTo(Pair o) {

			// TODO Auto-generated method stub

			return this.y-o.y;

		}

	    }

	 static class PairL implements Comparable<PairL>

	 {

		 long x;

		 long y;

		 PairL(long x,long y)

		 {

			 this.x=x;

			 this.y=y;

		 }

		 @Override

		 public int compareTo(PairL o) {

			 // TODO Auto-generated method stub

			 return (this.y>o.y)?1:-1;

		 }

	 }

	static long sum_array(int a[])

	 {

	    int n=a.length;

	    long sum=0;

	    for(int i=0;i<n;i++)

	     sum+=a[i];

	    return sum;

	 }

	static long sum_array(long a[])

	 {

	    int n=a.length;

	    long sum=0;

	    for(int i=0;i<n;i++)

	     sum+=a[i];

	    return sum;

	 }

	 static void sort(int[] a)

	   {

			ArrayList<Integer> l=new ArrayList<>();

			for (int i:a) l.add(i);

			Collections.sort(l);

			for (int i=0; i<a.length; i++) a[i]=l.get(i);

		}

	static void sort(long[] a)

	   {

			ArrayList<Long> l=new ArrayList<>();

			for (long i:a) l.add(i);

			Collections.sort(l);

			for (int i=0; i<a.length; i++) a[i]=l.get(i);

		}

	static void reverse_array(int a[])

	 {

	    int n=a.length;

	    int i,t;

	    for (i = 0; i < n / 2; i++) {

	            t = a[i];

	            a[i] = a[n - i - 1];

	            a[n - i - 1] = t;

	        }

	 }

	static void reverse_array(long a[])

	 {

	    int n=a.length;

	    int i; long t;

	    for (i = 0; i < n / 2; i++) {

	            t = a[i];

	            a[i] = a[n - i - 1];

	            a[n - i - 1] = t;

	        }

	 }

//	 static long modInverse(long a, long m)

//		    {

//		        long g = gcd(a, m);

//

//		          return   power(a, m - 2, m);

//

//		    }

	static long power(long x, long y)

	 {

	   long res = 1;

	   x = x % mod;

	   if (x == 0)

	     return 0;

	   while (y > 0)

	   {

	    if ((y & 1) != 0)

	    res = (res * x) % mod;

	    y = y >> 1; // y = y/2

	    x = (x * x) % mod;

	   }

	   return res;

	 }

	static int power(int x, int y)

	{

		int res = 1;

		x = x % mod;

		if (x == 0)

			return 0;

		while (y > 0)

		{

			if ((y & 1) != 0)

				res = (res * x) % mod;

			y = y >> 1; // y = y/2

	    x = (x * x) % mod;

		}

		return res;

	}

	static long gcd(long a, long b)

	    {

	        if (a == 0)

	            return b;

	         //cnt+=a/b;

	        return gcd(b%a,a);

	    }

	static int gcd(int a, int b)

	    {

	        if (a == 0)

	            return b;

	        return gcd(b%a, a);

	    }

	   static class FastReader{

	        byte[] buf = new byte[2048];

	        int index, total;

	        InputStream in;

	        FastReader(InputStream is) {

	            in = is;

	        }

	        int scan() throws IOException {

	            if (index >= total) {

	                index = 0;

	                total = in.read(buf);

	                if (total <= 0) {

	                    return -1;

	                }

	            }

	            return buf[index++];

	        }

	        String next() throws IOException {

	            int c;

	            for (c = scan(); c <= 32; c = scan());

	            StringBuilder sb = new StringBuilder();

	            for (; c > 32; c = scan()) {

	                sb.append((char) c);

	            }

	            return sb.toString();

	        }

	        int nextInt() throws IOException {

	            int c, val = 0;

	            for (c = scan(); c <= 32; c = scan());

	            boolean neg = c == '-';

	            if (c == '-' || c == '+') {

	                c = scan();

	            }

	            for (; c >= '0' && c <= '9'; c = scan()) {

	                val = (val << 3) + (val << 1) + (c & 15);

	            }

	            return neg ? -val : val;

	        }

	        long nextLong() throws IOException {

	            int c;

	            long val = 0;

	            for (c = scan(); c <= 32; c = scan());

	            boolean neg = c == '-';

	            if (c == '-' || c == '+') {

	                c = scan();

	            }

	            for (; c >= '0' && c <= '9'; c = scan()) {

	                val = (val << 3) + (val << 1) + (c & 15);

	            }

	            return neg ? -val : val;

	        }

	    }

	    static class Reader

	    {

	        final private int BUFFER_SIZE = 1 << 16;

	        private DataInputStream din;

	        private byte[] buffer;

	        private int bufferPointer, bytesRead;

	        public Reader()

	        {

	            din = new DataInputStream(System.in);

	            buffer = new byte[BUFFER_SIZE];

	            bufferPointer = bytesRead = 0;

	        }

	        public Reader(String file_name) throws IOException

	        {

	            din = new DataInputStream(new FileInputStream(file_name));

	            buffer = new byte[BUFFER_SIZE];

	            bufferPointer = bytesRead = 0;

	        }

	        public String readLine() throws IOException

	        {

	            byte[] buf = new byte[64]; // line length

	            int cnt = 0, c;

	            while ((c = read()) != -1)

	            {

	                if (c == '\n')

	                    break;

	                buf[cnt++] = (byte) c;

	            }

	            return new String(buf, 0, cnt);

	        }

	        public int nextInt() throws IOException

	        {

	            int ret = 0;

	            byte c = read();

	            while (c <= ' ')

	                c = read();

	            boolean neg = (c == '-');

	            if (neg)

	                c = read();

	            do

	            {

	                ret = ret * 10 + c - '0';

	            }  while ((c = read()) >= '0' && c <= '9');

	            if (neg)

	                return -ret;

	            return ret;

	        }

	        public long nextLong() throws IOException

	        {

	            long ret = 0;

	            byte c = read();

	            while (c <= ' ')

	                c = read();

	            boolean neg = (c == '-');

	            if (neg)

	                c = read();

	            do {

	                ret = ret * 10 + c - '0';

	            }

	            while ((c = read()) >= '0' && c <= '9');

	            if (neg)

	                return -ret;

	            return ret;

	        }

	        public double nextDouble() throws IOException

	        {

	            double ret = 0, div = 1;

	            byte c = read();

	            while (c <= ' ')

	                c = read();

	            boolean neg = (c == '-');

	            if (neg)

	                c = read();

	            do {

	                ret = ret * 10 + c - '0';

	            }

	            while ((c = read()) >= '0' && c <= '9');

	            if (c == '.')

	            {

	                while ((c = read()) >= '0' && c <= '9')

	                {

	                    ret += (c - '0') / (div *= 10);

	                }

	            }

	            if (neg)

	                return -ret;

	            return ret;

	        }

	        private void fillBuffer() throws IOException

	        {

	            bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);

	            if (bytesRead == -1)

	                buffer[0] = -1;

	        }

	        private byte read() throws IOException

	        {

	            if (bufferPointer == bytesRead)

	                fillBuffer();

	            return buffer[bufferPointer++];

	        }

	        public void close() throws IOException

	        {

	            if (din == null)

	                return;

	            din.close();

	        }

	    }

	  static  PrintWriter out=new PrintWriter(System.out);

	  static int int_max=Integer.MAX_VALUE;

	  static int int_min=Integer.MIN_VALUE;

	  static long long_max=Long.MAX_VALUE;

	  static long long_min=Long.MIN_VALUE;

}


import java.io.*;

import java.util.*;

public class CF1562C extends PrintWriter {

	CF1562C() { super(System.out); }

	public static Scanner sc = new Scanner(System.in);

	public static void main(String[] $) {

		CF1562C o = new CF1562C(); o.main(); o.flush();

	}

	static long calculate(long p, long q)

{

    long mod = 1000000007, expo;

    expo = mod - 2;

    // Loop to find the value

    // until the expo is not zero

    while (expo != 0)

    {

        // Multiply p with q

        // if expo is odd

        if ((expo & 1) == 1)

        {

            p = (p * q) % mod;

        }

        q = (q * q) % mod;

        // Reduce the value of

        // expo by 2

        expo >>= 1;

    }

    return p;

}

 static String longestPalSubstr(String str)

    {

        // The result (length of LPS)

        int maxLength = 1;

        int start = 0;

        int len = str.length();

        int low, high;

        // One by one consider every

        // character as center

        // point of even and length

        // palindromes

        for (int i = 1; i < len; ++i) {

            // Find the longest even

            // length palindrome with

            // center points as i-1 and i.

            low = i - 1;

            high = i;

            while (low >= 0 && high < len

                   && str.charAt(low)

                          == str.charAt(high)) {

                --low;

                ++high;

            }

              // Move back to the last possible valid palindrom substring

            // as that will anyway be the longest from above loop

            ++low; --high;

            if (str.charAt(low) == str.charAt(high) && high - low + 1 > maxLength) {

                start = low;

                maxLength = high - low + 1;

            }

            // Find the longest odd length

            // palindrome with center point as i

            low = i - 1;

            high = i + 1;

            while (low >= 0 && high < len

                   && str.charAt(low)

                          == str.charAt(high)) {

                --low;

                ++high;

            }

              // Move back to the last possible valid palindrom substring

            // as that will anyway be the longest from above loop

            ++low; --high;

            if (str.charAt(low) == str.charAt(high) && high - low + 1 > maxLength) {

                start = low;

                maxLength = high - low + 1;

            }

        }

        return str.substring(start, start + maxLength - 1);

    }

long check(long a){

                 long ret=0;

                 for(long k=2;(k*k*k)<=a;k++){

                  ret=ret+(a/(k*k*k));

                 }

                 return ret;

}

/*public static int getFirstSetBitPos(int n)

	{

		return (int)((Math.log10(n & -n)) / Math.log10(2)) + 1;

	}

	public static int bfsq(int n, int m, HashMap<Integer,ArrayList<Integer>>h,boolean v ){

	                 v[n]=true;

	                 if(n==m)

	                 return 1;

	                 else

	                 {

	                                  int a=h.get(n).get(0);

	                                  int b=h.get(n).get(1);

	                                  if(b>m)

	                                  return(m-n);

	                                  else

	                                  {

	                                                   int a1=bfsq(a,m,h,v);

	                                                   int b1=bfsq(b,m,h,v);

	                                                   return 1+Math.min(a1,b1);

	                                  }

	                 }

	}*/

	static long nCr(int n, int r)

{    return fact(n) / (fact(r) *

                  fact(n - r));

}

// Returns factorial of n

static long fact(long n)

{

    long res = 1;

    for (long i = 2; i <= n; i++)

        res = res * i;

    return res;

}

/*void bfs(int src, HashMap<Integer,ArrayList<Integer,Integer>>h,int deg, boolean v[] ){

                 a[src]=deg;

                 Queue<Integer>= new LinkedList<Integer>();

                 q.add(src);

                 while(!q.isEmpty()){

                                  (int a:h.get(src)){

                                                   if()

                                  }

                 }

}*/

	 /*   void dfs(int root, int par, HashMap<Integer,ArrayList<Integer>>h,int dp[], int child[]) {

     dp[root]=0;

    child[root]=1;

     for(int x: h.get(root)){

         if(x == par) continue;

         dfs(x,root,h,in,dp);

         child[root]+=child[x];

     }

     ArrayList<Integer> mine= new ArrayList<Integer>();

         for(int x: h.get(root)) {

             if(x == par) continue;

             mine.add(x);

         }

         if(mine.size() >=2){

int y= Math.max(child[mine.get(0)] - 1 + dp[mine.get(1)] , child[mine.get(1)] -1 + dp[mine.get(0)]);

         dp[root]=y;}

else if(mine.size() == 1)

         dp[root]=child[mine.get(0)] - 1;

 }

	   */

class Pair implements Comparable<Pair>{

		int i;

		int j;

	Pair (int a, int b){

		i = a;

	j = b;

	}

	public int compareTo(Pair A){

		return (int)(this.i-A.i);

	}}

/*static class Pair {

        int i;

        int j;

        Pair() {

        }

        Pair(int i, int j) {

            this.i = i;

            this.j = j;

        }

    }*/

          public int[] check(String s) {

             int ans[]= new int[2];

        int maxans = 0;

        int dp[] = new int[s.length()];

        for (int i = 1; i < s.length(); i++) {

            if (s.charAt(i) == ')') {

                if (s.charAt(i - 1) == '(') {

                    dp[i] = (i >= 2 ? dp[i - 2] : 0) + 2;

                } else if (i - dp[i - 1] > 0 && s.charAt(i - dp[i - 1] - 1) == '(') {

                    dp[i] = dp[i - 1] + ((i - dp[i - 1]) >= 2 ? dp[i - dp[i - 1] - 2] : 0) + 2;

                }

                if(dp[i]==maxans)

            ans[1]=ans[1]+1;

            if(dp[i]>maxans){

            ans[0]=dp[i];

            ans[1]=1;

                    maxans = Math.max(maxans, dp[i]);}

            }

        }

        if(ans[0]==0)

        ans[1]=1;

        return ans;

    }

 void main() {

int g=sc.nextInt();

for(int w=0;w<g;w++){

long n=sc.nextLong();

long m=sc.nextLong();

	long ans =n *(n + 1) / 2;

	long z = n - m;

	long k = z / (m + 1);

	ans -= (m + 1)*k*(k + 1)/2;

	ans -= (z%(m + 1))*(k + 1);

	println(ans); }

    }

}


C. Yet Another Walking Robottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot on a coordinate plane. Initially; the robot is located at the point (0,0)(0,0). Its path is described as a string ss of length nn consisting of characters 'L', 'R', 'U', 'D'.Each of these characters corresponds to some move:   'L' (left): means that the robot moves from the point (x,y)(x,y) to the point (x−1,y)(x−1,y);  'R' (right): means that the robot moves from the point (x,y)(x,y) to the point (x+1,y)(x+1,y);  'U' (up): means that the robot moves from the point (x,y)(x,y) to the point (x,y+1)(x,y+1);  'D' (down): means that the robot moves from the point (x,y)(x,y) to the point (x,y−1)(x,y−1). The company that created this robot asked you to optimize the path of the robot somehow. To do this, you can remove any non-empty substring of the path. But this company doesn't want their customers to notice the change in the robot behavior. It means that if before the optimization the robot ended its path at the point (xe,ye)(xe,ye), then after optimization (i.e. removing some single substring from ss) the robot also ends its path at the point (xe,ye)(xe,ye).This optimization is a low-budget project so you need to remove the shortest possible non-empty substring to optimize the robot's path such that the endpoint of his path doesn't change. It is possible that you can't optimize the path. Also, it is possible that after the optimization the target path is an empty string (i.e. deleted substring is the whole string ss).Recall that the substring of ss is such string that can be obtained from ss by removing some amount of characters (possibly, zero) from the prefix and some amount of characters (possibly, zero) from the suffix. For example, the substrings of "LURLLR" are "LU", "LR", "LURLLR", "URL", but not "RR" and "UL".You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The next 2t2t lines describe test cases. Each test case is given on two lines. The first line of the test case contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of the robot's path. The second line of the test case contains one string ss consisting of nn characters 'L', 'R', 'U', 'D' — the robot's path.It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105).OutputFor each test case, print the answer on it. If you cannot remove such non-empty substring that the endpoint of the robot's path doesn't change, print -1. Otherwise, print two integers ll and rr such that 1≤l≤r≤n1≤l≤r≤n — endpoints of the substring you remove. The value r−l+1r−l+1 should be minimum possible. If there are several answers, print any of them.ExampleInputCopy4
4
LRUD
4
LURD
5
RRUDU
5
LLDDR
OutputCopy1 2
1 4
3 4
-1

import static java.lang.Math.max;

import static java.lang.Math.min;

import static java.lang.Math.abs;

import java.util.*;

import java.io.*;

import java.math.*;

public class C_Yet_Another_Walking_Robot {

    static long mod = Long.MAX_VALUE;

    public static void main(String[] args) {

        OutputStream outputStream = System.out;

        PrintWriter out = new PrintWriter(outputStream);

        FastReader f = new FastReader();

        int t = f.nextInt();

        while(t-- > 0){

            solve(f, out);

        }

        out.close();

    }

    public static void solve(FastReader f, PrintWriter out) {

        int n = f.nextInt();

        String s = f.nextLine();

        HashMap<String, Integer> hm = new HashMap<>();

        int ansL = -1;

        int ansR = -1;

        int x = 0;

        int y = 0;

        hm.put(x+":"+y, 0);

        for(int i = 0; i < n; i++) {

            if(s.charAt(i) == 'U') {

                y++;

            } else if(s.charAt(i) == 'D') {

                y--;

            } else if(s.charAt(i) == 'L') {

                x--;

            } else {

                x++;

            }

            String pos = x + ":" + y;

            if(hm.containsKey(pos)) {

                int sInd = hm.get(pos)+1;

                int eInd = i+1;

                if((ansL == -1 && ansR == -1) || (eInd-sInd+1 < ansR-ansL+1)) {

                    ansL = sInd;

                    ansR = eInd;

                }

            }

            hm.put(pos, i+1);

        }

        if(ansL == -1 && ansR == -1) {

            out.println(-1);

        } else {

            out.println(ansL + " " + ansR);

        }

    }

    // Sort an array

    public static void sort(int arr[]) {

        ArrayList<Integer> al = new ArrayList<>();

        for(int i: arr) {

            al.add(i);

        }

        Collections.sort(al);

        for(int i = 0; i < arr.length; i++) {

            arr[i] = al.get(i);

        }

    }

    // Find all divisors of n

    public static void allDivisors(int n) {

        for(int i = 1; i*i <= n; i++) {

            if(n%i == 0) {

                System.out.println(i + " ");

                if(i != n/i) {

                    System.out.println(n/i + " ");

                }

            }

        }

    }

    // Check if n is prime or not

    public static boolean isPrime(int n) {

        if(n < 1) return false;

        if(n == 2 || n == 3) return true;

        if(n % 2 == 0 || n % 3 == 0) return false;

        for(int i = 5; i*i <= n; i += 6) {

            if(n % i == 0 || n % (i+2) == 0) {

                return false;

            }

        }

        return true;

    }

    // Find gcd of a and b

    public static long gcd(long a, long b) {

        long dividend = a > b ? a : b;

        long divisor =  a < b ? a : b;

        while(divisor > 0) {

            long reminder = dividend % divisor;

            dividend = divisor;

            divisor = reminder;

        }

        return dividend;

    }

    // Find lcm of a and b

    public static long lcm(long a, long b) {

        long lcm = gcd(a, b);

        long hcf = (a * b) / lcm;

        return hcf;

    }

    // Find factorial in O(n) time

    public static long fact(int n) {

        long res = 1;

        for(int i = 2; i <= n; i++) {

            res = res * i;

        }

        return res;

    }

    // Find power in O(logb) time

    public static long power(long a, long b) {

        long res = 1;

        while(b > 0) {

            if((b&1) == 1) {

                res = (res * a)%mod;

            }

            a = (a * a)%mod;

            b >>= 1;

        }

        return res;

    }

    // Find nCr

    public static long nCr(int n, int r) {

        if(r < 0 || r > n) {

            return 0;

        }

        long ans = fact(n) / (fact(r) * fact(n-r));

        return ans;

    }

    // Find nPr

    public static long nPr(int n, int r) {

        if(r < 0 || r > n) {

            return 0;

        }

        long ans = fact(n) / fact(r);

        return ans;

    }

    // sort all characters of a string

    public static String sortString(String inputString) {

        char tempArray[] = inputString.toCharArray();

        Arrays.sort(tempArray);

        return new String(tempArray);

    }

    // User defined class for fast I/O

    static class FastReader {

        BufferedReader br;

        StringTokenizer st;

        public FastReader() {

            br = new BufferedReader(new InputStreamReader(System.in));

        }

        String next() {

            while (st == null || !st.hasMoreElements()) {

                try {

                    st = new StringTokenizer(br.readLine());

                }

                catch (IOException e) {

                    e.printStackTrace();

                }

            }

            return st.nextToken();

        }

        boolean hasNext() {

            if (st != null && st.hasMoreTokens()) {

                return true;

            }

            String tmp;

            try {

                br.mark(1000);

                tmp = br.readLine();

                if (tmp == null) {

                    return false;

                }

                br.reset();

            } catch (IOException e) {

                return false;

            }

            return true;

        }

        int nextInt() {

            return Integer.parseInt(next());

        }

        long nextLong() {

            return Long.parseLong(next());

        }

        double nextDouble() {

            return Double.parseDouble(next());

        }

        float nextFloat() {

            return Float.parseFloat(next());

        }

        boolean nextBoolean() {

            return Boolean.parseBoolean(next());

        }

        String nextLine() {

            String str = "";

            try {

                str = br.readLine();

            }

            catch (IOException e) {

                e.printStackTrace();

            }

            return str;

        }

        int[] nextArray(int n) {

            int[] a = new int[n];

            for(int i=0; i<n; i++) {

                a[i] = nextInt();

            }

            return a;

        }

    }

}

/**

Dec  Char                           Dec  Char     Dec  Char     Dec  Char

---------                           ---------     ---------     ----------

  0  NUL (null)                      32  SPACE     64  @         96  `

  1  SOH (start of heading)          33  !         65  A         97  a

  2  STX (start of text)             34  "         66  B         98  b

  3  ETX (end of text)               35  #         67  C         99  c

  4  EOT (end of transmission)       36  $         68  D        100  d

  5  ENQ (enquiry)                   37  %         69  E        101  e

  6  ACK (acknowledge)               38  &         70  F        102  f

  7  BEL (bell)                      39  '         71  G        103  g

  8  BS  (backspace)                 40  (         72  H        104  h

  9  TAB (horizontal tab)            41  )         73  I        105  i

 10  LF  (NL line feed, new line)    42  *         74  J        106  j

 11  VT  (vertical tab)              43  +         75  K        107  k

 12  FF  (NP form feed, new page)    44  ,         76  L        108  l

 13  CR  (carriage return)           45  -         77  M        109  m

 14  SO  (shift out)                 46  .         78  N        110  n

 15  SI  (shift in)                  47  /         79  O        111  o

 16  DLE (data link escape)          48  0         80  P        112  p

 17  DC1 (device control 1)          49  1         81  Q        113  q

 18  DC2 (device control 2)          50  2         82  R        114  r

 19  DC3 (device control 3)          51  3         83  S        115  s

 20  DC4 (device control 4)          52  4         84  T        116  t

 21  NAK (negative acknowledge)      53  5         85  U        117  u

 22  SYN (synchronous idle)          54  6         86  V        118  v

 23  ETB (end of trans. block)       55  7         87  W        119  w

 24  CAN (cancel)                    56  8         88  X        120  x

 25  EM  (end of medium)             57  9         89  Y        121  y

 26  SUB (substitute)                58  :         90  Z        122  z

 27  ESC (escape)                    59  ;         91  [        123  {

 28  FS  (file separator)            60  <         92  \        124  |

 29  GS  (group separator)           61  =         93  ]        125  }

 30  RS  (record separator)          62  >         94  ^        126  ~

 31  US  (unit separator)            63  ?         95  _        127  DEL

 */

// (a/b)%mod == (a * moduloInverse(b)) % mod;

// moduloInverse(b) = power(b, mod-2);


D. Cow and Fieldstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is out grazing on the farm; which consists of nn fields connected by mm bidirectional roads. She is currently at field 11, and will return to her home at field nn at the end of the day.The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has kk special fields and he has decided to install the road between two different special fields. He may add the road between two special fields that already had a road directly connecting them.After the road is added, Bessie will return home on the shortest path from field 11 to field nn. Since Bessie needs more exercise, Farmer John must maximize the length of this shortest path. Help him!InputThe first line contains integers nn, mm, and kk (2≤n≤2⋅1052≤n≤2⋅105, n−1≤m≤2⋅105n−1≤m≤2⋅105, 2≤k≤n2≤k≤n)  — the number of fields on the farm, the number of roads, and the number of special fields. The second line contains kk integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n)  — the special fields. All aiai are distinct.The ii-th of the following mm lines contains integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), representing a bidirectional road between fields xixi and yiyi. It is guaranteed that one can reach any field from every other field. It is also guaranteed that for any pair of fields there is at most one road connecting them.OutputOutput one integer, the maximum possible length of the shortest path from field 11 to nn after Farmer John installs one road optimally.ExamplesInputCopy5 5 3
1 3 5
1 2
2 3
3 4
3 5
2 4
OutputCopy3
InputCopy5 4 2
2 4
1 2
2 3
3 4
4 5
OutputCopy3
NoteThe graph for the first example is shown below. The special fields are denoted by red. It is optimal for Farmer John to add a road between fields 33 and 55, and the resulting shortest path from 11 to 55 is length 33.   The graph for the second example is shown below. Farmer John must add a road between fields 22 and 44, and the resulting shortest path from 11 to 55 is length 33.

/*

        "Everything in the universe is balanced. Every disappointment

                you face in life will be balanced by something good for you!

                        Keep going, never give up."

                        Just have Patience + 1...

*/

import java.util.*;

import java.lang.*;

import java.io.*;

public class Solution {

    static int MAX = 200005, INF = 1000000007;

    static Map<Integer, List<Integer>> graph = new HashMap<>();

    static int[][] shortestDistance = new int[2][MAX];

    public static void main(String[] args) throws java.lang.Exception {

        out = new PrintWriter(new BufferedOutputStream(System.out));

        sc = new FastReader();

        int test = 1;

        for (int t = 0; t < test; t++) {

            solve();

        }

        out.close();

    }

    private static void solve() {

        int n = sc.nextInt();

        int m = sc.nextInt();

        int k = sc.nextInt();

        for (int i = 0; i < 2; i++) {

            Arrays.fill(shortestDistance[i], INF);

        }

        List<Integer> specialNodes = new ArrayList<>();

        for (int i = 0; i < k; i++) {

            int node = sc.nextInt();

            specialNodes.add(node);

        }

        for (int i = 1; i <= n; i++) {

            graph.put(i, new ArrayList<>());

        }

        for (int i = 0; i < m; i++) {

            int u = sc.nextInt();

            int v = sc.nextInt();

            graph.get(u).add(v);

            graph.get(v).add(u);

        }

        bfs(1, 0);

        bfs(n, 1);

        specialNodes.sort(Comparator.comparingInt(a -> (shortestDistance[0][a] - shortestDistance[1][a])));

        int maxShortestPath = 0, maxSpecialDistanceFromStart = -INF;

        for (int node : specialNodes) {

            maxShortestPath = Math.max(maxShortestPath, maxSpecialDistanceFromStart + shortestDistance[1][node]);

            maxSpecialDistanceFromStart = Math.max(maxSpecialDistanceFromStart, shortestDistance[0][node]);

        }

        maxShortestPath++; // special edge length

        out.println(Math.min(maxShortestPath, shortestDistance[0][n]));

    }

    private static void bfs(int startNode, int index) {

        Queue<Integer> q = new LinkedList<>();

        shortestDistance[index][startNode] = 0;

        q.add(startNode);

        while (!q.isEmpty()) {

            int currNode = q.poll();

            for (int adjacentNode : graph.get(currNode)) {

                if (shortestDistance[index][adjacentNode] > shortestDistance[index][currNode] + 1) {

                    shortestDistance[index][adjacentNode] = shortestDistance[index][currNode] + 1;

                    q.add(adjacentNode);

                }

            }

        }

    }

    public static FastReader sc;

    public static PrintWriter out;

    static class FastReader

    {

        BufferedReader br;

        StringTokenizer str;

        public FastReader()

        {

            br = new BufferedReader(new

                    InputStreamReader(System.in));

        }

        String next()

        {

            while (str == null || !str.hasMoreElements())

            {

                try

                {

                    str = new StringTokenizer(br.readLine());

                }

                catch (IOException  lastMonthOfVacation)

                {

                    lastMonthOfVacation.printStackTrace();

                }

            }

            return str.nextToken();

        }

        int nextInt()

        {

            return Integer.parseInt(next());

        }

        long nextLong()

        {

            return Long.parseLong(next());

        }

        double nextDouble()

        {

            return Double.parseDouble(next());

        }

        String nextLine()

        {

            String str = "";

            try

            {

                str = br.readLine();

            }

            catch (IOException lastMonthOfVacation)

            {

                lastMonthOfVacation.printStackTrace();

            }

            return str;

        }

    }

}


E. Obtain a Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular matrix of size n×mn×m consisting of integers from 11 to 2⋅1052⋅105.In one move, you can:  choose any element of the matrix and change its value to any integer between 11 and n⋅mn⋅m, inclusive;  take any column and shift it one cell up cyclically (see the example of such cyclic shift below). A cyclic shift is an operation such that you choose some jj (1≤j≤m1≤j≤m) and set a1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,ja1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,j simultaneously.  Example of cyclic shift of the first column You want to perform the minimum number of moves to make this matrix look like this:  In other words, the goal is to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (i.e. ai,j=(i−1)⋅m+jai,j=(i−1)⋅m+j) with the minimum number of moves performed.InputThe first line of the input contains two integers nn and mm (1≤n,m≤2⋅105,n⋅m≤2⋅1051≤n,m≤2⋅105,n⋅m≤2⋅105) — the size of the matrix.The next nn lines contain mm integers each. The number at the line ii and position jj is ai,jai,j (1≤ai,j≤2⋅1051≤ai,j≤2⋅105).OutputPrint one integer — the minimum number of moves required to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (ai,j=(i−1)m+jai,j=(i−1)m+j).ExamplesInputCopy3 3
3 2 1
1 2 3
4 5 6
OutputCopy6
InputCopy4 3
1 2 3
4 5 6
7 8 9
10 11 12
OutputCopy0
InputCopy3 4
1 6 3 4
5 10 7 8
9 2 11 12
OutputCopy2
NoteIn the first example; you can set a1,1:=7,a1,2:=8a1,1:=7,a1,2:=8 and a1,3:=9a1,3:=9 then shift the first, the second and the third columns cyclically, so the answer is 66. It can be shown that you cannot achieve a better answer.In the second example, the matrix is already good so the answer is 00.In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 22.

import java.io.*;

import java.util.*;

public class E{

	static int n,m;

	static int[][] g;

	static int[][] t;

	static void dbg(int[][] cur) {

		for (int[] x: cur) {

			for (int y: x) out.print(y + " ");

			out.println();

		}

	}

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

		// br = new BufferedReader(new FileReader(".in"));

		// out = new PrintWriter(new FileWriter(".out"));

		//new Thread(null, new (), "peepee", 1<<28).start();

		n = readInt();

		m = readInt();

		g = new int[n][m];

		t = new int[n][m];

		int b = 1;

		for (int i =0 ; i < n; i++) {

			for (int j = 0; j < m; j++) {

				t[i][j] = b++;

				g[i][j] = readInt();

			}

		}

		long cost = 0;

		for (int i = 0; i < m; i++) {

			long v = solve(i);

			//System.out.println(v);

			cost += v;

		}

		out.println(cost);

		out.close();

	}

	static void dbg(long[] a) {

		for (long x: a) out.print(x + " ");

		out.println();

	}

	static long solve(int col) {

		long[] r = new long[n];

		long[] r2 = new long[n];

		HashMap<Long, List<Integer>>hm = new HashMap<Long, List<Integer>>();

		for (int i = 0; i < n; i++) {

			r[i] = g[i][col];

			r2[i] = t[i][col];

			if (!hm.containsKey(r2[i])) {

				hm.put(r2[i], new ArrayList<Integer>());

			}

			hm.get(r2[i]).add(i);

		}

		long ans = 2*n;

		long[] cycles = new long[n]; // I cycled i times.

		for (int i = 0; i < n; i++) {

			if (!hm.containsKey(r[i])) continue;

			for (int x: hm.get(r[i])) {

				// X IS FROM R2 (the correct)

				// I IS FROM R1. (ours)

				if (i >= x) cycles[i-x]++;

				else {

					int newR2Pos = x-n;

					//System.out.println("We saw it at r2 pos " + x + " but our r pos is " + i );

					cycles[i-newR2Pos]++;

				}

			}

		}

		for (int i= 0 ; i < n; i++) {

			long tans = i+n-cycles[i];

			ans = Long.min(ans, tans);

		}

		//System.out.println(ans);

		return ans;

	}

	static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

	static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));

	static StringTokenizer st = new StringTokenizer("");

	static String read() throws IOException{return st.hasMoreTokens() ? st.nextToken():(st = new StringTokenizer(br.readLine())).nextToken();}

	static int readInt() throws IOException{return Integer.parseInt(read());}

	static long readLong() throws IOException{return Long.parseLong(read());}

	static double readDouble() throws IOException{return Double.parseDouble(read());}

}