Problem: There is a directed graph with N vertices numbered 1 to N and M edges. The i-th edge is directed from Vertex A_i to Vertex B_i, and there are C_i coins placed along that edge. Additionally, there is a button on Vertex N.

We will play a game on this graph. You start the game on Vertex 1 with zero coins, and head for Vertex N by traversing the edges while collecting coins. It takes one minute to traverse an edge, and you can collect the coins placed along the edge each time you traverse it. As usual in games, even if you traverse an edge once and collect the coins, the same number of coins will reappear next time you traverse that edge, which you can collect again.

When you reach Vertex N, you can end the game by pressing the button. (You can also choose to leave Vertex N without pressing the button and continue traveling.) However, when you end the game, you will be asked to pay T \times P coins, where T is the number of minutes elapsed since the start of the game. If you have less than T \times P coins, you will have to pay all of your coins instead.

Your score will be the number of coins you have after this payment. Determine if there exists a maximum value of the score that can be obtained. If the answer is yes, find that maximum value.

Constraints

* 2 \leq N \leq 2500
* 1 \leq M \leq 5000
* 1 \leq A_i, B_i \leq N
* 1 \leq C_i \leq 10^5
* 0 \leq P \leq 10^5
* All values in input are integers.
* Vertex N can be reached from Vertex 1.

Input

Input is given from Standard Input in the following format:


N M P
A_1 B_1 C_1
:
A_M B_M C_M


Output

If there exists a maximum value of the score that can be obtained, print that maximum value; otherwise, print `-1`.

Examples

Input

3 3 10
1 2 20
2 3 30
1 3 45


Output

35


Input

2 2 10
1 2 100
2 2 100


Output

-1


Input

4 5 10
1 2 1
1 4 1
3 4 1
2 2 100
3 3 100


Output

0

Solution (in JAVA):

Solution:

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.IntStream;
import java.util.stream.LongStream;

/**
 * https://kenkoooo.com/atcoder/#/contest/show/44c3c2cb-a601-4307-a097-a2e5705d84be
 */
public class Main {

    public Main() throws IOException {
    }

    public static void main(String[] args) throws IOException {
        new Main().solve();
    }

    //    private final InputStream in = Files.newInputStream(Paths.get("C:\\Users\\ryo.suzuki\\Downloads\\02.txt"));
    private final InputStream in = System.in;
    private final PrintWriter out = new PrintWriter(System.out);
    private final byte[] buffer = new byte[1024];
    private int ptr = 0;
    private int buflen = 0;

    private void solve() throws IOException {
        try {
//            solveA();
//            solveB();
//            solveC();
//            solveD();
//            solveE();
            solveF();
        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.flush();
                out.close();
            }
        }

    }

    // mods
    long MOD = (long) Math.pow(10, 9) + 7;

    /**
     * https://atcoder.jp/contests/agc002/tasks/agc002_a
     * A - Range Product
     */
    private void solveA() {
        int a = nextInt();
        int b = nextInt();
        if (a < 0 && b > 0 || a == 0 || b == 0) {
            out.println("Zero");
        } else if (a > 0 && b > 0) {
            out.println("Positive");
        } else if (a < 0) {
            if ((b - a) % 2 == 0)
                out.println("Negative");
            else
                out.println("Positive");
        }
    }

    /**
     * https://atcoder.jp/contests/agc012/tasks/agc012_a
     * A - AtCoder Group Contest
     */
    private void solveB() {
        int n = nextInt();
        int[] a = IntStream.range(0, 3 * n).map(i -> nextInt()).sorted().toArray();
        long sum = 0;
        for (int i = n; i < 3 * n; i += 2) {
            sum += a[i];
        }
        out.println(sum);
    }

    /**
     * https://atcoder.jp/contests/agc007/tasks/agc007_a
     * A - Shik and Stone
     */
    private void solveC() {
        int h = nextInt();
        int w = nextInt();
        char[][] a = IntStream.range(0, h).mapToObj(i -> next().toCharArray()).toArray(char[][]::new);
        if (a[0][0] == '.') {
            out.println("Impoissible");
            return;
        }
        Queue<SimplePair> queue = new ArrayDeque<SimplePair>();
        queue.add(new SimplePair(0, 0));
        int[] dx = new int[]{-1, 0, 1, 0};
        int[] dy = new int[]{0, -1, 0, 1};
        while (!queue.isEmpty()) {
            int cnt = queue.size();
            for (int i = 0; i < cnt; i++) {
                SimplePair pair = queue.poll();
                int inCnt = 0;
                int outCnt = 0;
                for (int j = 0; j < 4; j++) {
                    int wx = (int) (dx[j] + pair.v);
                    int wy = (int) (dy[j] + pair.k);
                    if (wx < 0 || wx >= w || wy < 0 || wy >= h || a[wy][wx] == '.')
                        continue;
                    if (j < 2) {
                        inCnt++;
                    } else {
                        outCnt++;
                        queue.add(new SimplePair(wy, wx));
                    }
                }
                if (inCnt > 1 || outCnt > 1) {
                    out.println("Impossible");
                    return;
                }
            }
            if (queue.size() > 1) {
                out.println("Impossible");
                return;
            }
        }
        out.println("Possible");
    }

    /**
     * https://atcoder.jp/contests/abc142/tasks/abc142_d
     * D - Disjoint Set of Common Divisors
     * <p>
     * https://drken1215.hatenablog.com/entry/2019/10/03/175800
     */
    private void solveD() {
        long a = nextLong();
        Map<Long, Long> aSet = new HashMap<Long, Long>();
        for (long i = 2; i * i <= a; i++) {
            if (a % i != 0)
                continue;
            long cnt = 0;
            while (a % i == 0) {
                a /= i;
                cnt++;
            }
            aSet.put(i, cnt);
        }
        if (a != 1)
            aSet.put(a, 1L);
        long b = nextLong();
        Map<Long, Long> bSet = new HashMap<Long, Long>();
        for (long i = 2; i * i <= b; i++) {
            if (b % i != 0)
                continue;
            long cnt = 0;
            while (b % i == 0) {
                b /= i;
                cnt++;
            }
            bSet.put(i, cnt);
        }
        if (b != 1)
            bSet.put(b, 1L);

        long res = aSet.keySet().stream().filter(i -> bSet.containsKey(i)).count();

        out.println(res + 1);
    }

    /**
     * https://atcoder.jp/contests/abc134/tasks/abc134_e
     * E - Sequence Decomposing
     * <p>
     * upper_boudで調べる
     * 速い
     */
    private void solveE() {
        int n = nextInt();
        int[] a = IntStream.range(0, n).map(i -> -nextInt()).toArray();
        List<Integer> memo = new ArrayList<Integer>();
        for (int item : a) {
            if (memo.size() == 0) {
                memo.add(item);
                continue;
            }

            int idx = bst(memo, item);
            if (idx == memo.size()) {
                memo.add(item);
            } else if (idx == -1) {
                memo.add(0, item);
            } else {
                memo.set(idx, item);
            }
        }
        out.println(memo.size());
    }

    private int bst(List<Integer> memo, int item) {
        int left = -1;
        int right = memo.size();
        while (right - left > 1) {
            int mid = left + (right - left) / 2;
            if (item < memo.get(mid))
                right = mid;
            else
                left = mid;
        }
        return right;
    }

    /**
     * https://atcoder.jp/contests/abc134/tasks/abc134_e
     * E - Sequence Decomposing
     * 愚直にBSTして場所にsetする。
     * 遅い
     */
    private void solveESlow() {
        int n = nextInt();
        int[] a = IntStream.range(0, n).map(i -> nextInt()).toArray();
        List<Integer> memo = new ArrayList<Integer>();
        for (int item : a) {
            if (memo.size() == 0) {
                memo.add(item);
                continue;
            }

            int idx = bstSlow(memo, item);
            if (idx == memo.size()) {
                memo.add(item);
            } else if (idx == -1) {
                memo.add(0, item);
            } else {
                memo.set(idx, item);
            }
        }
        out.println(memo.size());
    }

    private int bstSlow(List<Integer> memo, int item) {
        int left = -1;
        int right = memo.size();
        while (right - left > 1) {
            int mid = left + (right - left) / 2;
            if (item <= memo.get(mid))
                right = mid;
            else
                left = mid;
        }
        return left;
    }

    /**
     * https://atcoder.jp/contests/abc137/tasks/abc137_e
     * E - Coins Respawn
     * <p>
     * 有向グラフの最短経路問題（負閉路有）
     * Bellman-Ford法
     */
    private void solveF() {
        int n = nextInt();
        int m = nextInt();
        int p = nextInt();
        /*
        最初からcost-pをしておく
            →最後に合計するのではない
         cost-pを負に変換する
            →最長経路問題から、最短経路問題へ問題を読み替えている
              辺を負にすることによって、最大→最小へ変化させている
         */
        int[][] abc = IntStream.range(0, m).mapToObj(i -> new int[]{nextInt() - 1, nextInt() - 1, -(nextInt() - p)}).toArray(int[][]::new);
        BellmanFord bellmanFord = new BellmanFord(n);
        Map<Integer, List<Integer>> edges = new HashMap<Integer, List<Integer>>();
        Map<Integer, List<Integer>> reverseEdges = new HashMap<Integer, List<Integer>>();
        for (int[] item : abc) {
            bellmanFord.addEdge(item[0], item[1], item[2]);
            edges.put(item[0], edges.getOrDefault(item[0], new ArrayList<Integer>()));
            edges.get(item[0]).add(item[1]);
            reverseEdges.put(item[1], reverseEdges.getOrDefault(item[1], new ArrayList<Integer>()));
            reverseEdges.get(item[1]).add(item[0]);
        }
        boolean[] from1ToN = new boolean[n];
        dfs(from1ToN, edges, 0);
        boolean[] fromNTo1 = new boolean[n];
        dfs(fromNTo1, reverseEdges, n - 1);
        for (int i = 0; i < n; i++) {
            from1ToN[i] = (from1ToN[i] && fromNTo1[i]);
        }

        try {
            bellmanFord.shortestPath(0, from1ToN);
            out.println(Long.max(-bellmanFord.distance[n - 1], 0));
        } catch (Exception e) {
//            e.printStackTrace();
            out.println(-1);
        }
    }

    private void dfs(boolean[] fromTo, Map<Integer, List<Integer>> edges, int n) {
        if (fromTo[n])
            return;
        fromTo[n] = true;
        for (int item : edges.getOrDefault(n, new ArrayList<Integer>())) {
            dfs(fromTo, edges, item);
        }
    }

    private static class BellmanFord {
        static boolean debug = false;

        static class Edge {
            int from, to, cost;

            public Edge(int from, int to, int cost) {
                this.from = from;
                this.to = to;
                this.cost = cost;
            }

            public String toString() {
                return "edge[" + from + ", " + to + ", " + cost + "]";
            }
        }

        final int MAX_V;
        List<Edge> edges;
        int[] distance;

        public BellmanFord(int n) {
            MAX_V = n;
            edges = new ArrayList<Edge>();
            distance = new int[n];
        }

        public void addEdge(int from, int to, int cost) {
            edges.add(new Edge(from, to, cost));
        }

        public void shortestPath(int src, boolean[] canUseEdges) {
            for (int i = 0; i < distance.length; i++)
                distance[i] = Integer.MAX_VALUE;
            distance[src] = 0;
            int count = 0;
            boolean updated = true;
            while (updated) {
                updated = false;
                for (Edge e : edges) {
                    if (canUseEdges[e.to] && distance[e.from] != Integer.MAX_VALUE
                            && distance[e.to] > distance[e.from] + e.cost) {
                        distance[e.to] = distance[e.from] + e.cost;
                        updated = true;
                        if (count == MAX_V - 1)
                            throw new RuntimeException("negative loop");
                    }
                }
                count++;
            }
        }
    }

    static final long CONST_INF = Long.MAX_VALUE / 4;


    private static class VectorCalculation {
        /**
         * 点Pと線(AB)の距離
         *
         * @param p
         * @param a
         * @param b
         * @return
         */
        private double distanceDotAndLine(DoublePair p, DoublePair a, DoublePair b) {
            DoublePair ab = new DoublePair(b.x - a.x, b.y - a.y);
            DoublePair ap = new DoublePair(p.x - a.x, p.y - a.y);

            // ベクトルAB、APの外積の絶対値が平行四辺形Dの面積になる
            double d = Math.abs(crossVector(ab, ap));

            double l = distanceVertex(a, b); // AB間の距離

            double h = d / l;
            return h;
        }

        /**
         * 2点間距離
         *
         * @param p1
         * @param p2
         * @return
         */
        private double distanceVertex(DoublePair p1, DoublePair p2) {
            double dx = p1.x - p2.x;
            double dy = p1.y - p2.y;
            return Math.sqrt(dx * dx + dy * dy);
        }

        /**
         * ベクトル外積
         *
         * @param vl
         * @param vr
         * @return
         */
        private double crossVector(DoublePair vl, DoublePair vr) {
            return vl.x * vr.y - vl.y * vr.x;
        }
    }

    private static class DoublePair implements Comparable<DoublePair> {
        double x;
        double y;

        public DoublePair(double k, double v) {
            this.x = k;
            this.y = v;
        }

        public int compareTo(DoublePair pair) {
            return Double.compare(this.y, pair.y);
        }
    }

    private static class SimplePair implements Comparable<SimplePair> {
        long k;
        long v;

        public SimplePair(int k, int v) {
            this.k = k;
            this.v = v;
        }

        public SimplePair(long k, long v) {
            this.k = k;
            this.v = v;
        }

        public int compareTo(SimplePair pair) {
            return Long.compare(this.v, pair.v);
        }
    }


    private static class SimpleGraphNode {
        private int n;
        private Map<Integer, Integer> childs;

        public SimpleGraphNode(int n) {
            this.n = n;
            childs = new HashMap<Integer, Integer>();
        }

        public void addChild(int child, int d) {
            this.childs.put(child, d);
        }
    }

    private static class SimpleGraph {

        private Map<Integer, SimpleGraphNode> graph;

        public SimpleGraph(int[][] list) {
            graph = new HashMap<Integer, SimpleGraphNode>();
            Arrays.stream(list).forEach(l -> {
                int a = l[0];
                int b = l[1];
                int d = l[2];
                graph.put(a, graph.getOrDefault(a, new SimpleGraphNode(a)));
                graph.get(a).addChild(b, d);
                graph.put(b, graph.getOrDefault(b, new SimpleGraphNode(b)));
                graph.get(b).addChild(a, d);
            });
        }

        public SimpleGraphNode getNode(int i) {
            return graph.getOrDefault(i, new SimpleGraphNode(-1));
        }

    }

    private static class GraphNode {
        private long n;
        private Map<Long, SimplePair> childs;

        public GraphNode(long n) {
            this.n = n;
            childs = new TreeMap<Long, SimplePair>();
        }

        /**
         * not update
         *
         * @param child
         * @param d
         */
        public void addChild(long child, long d) {
            this.childs.put(child, this.childs.getOrDefault(child, new SimplePair(child, d)));
        }

        public SimplePair getChild(long child) {
            return this.childs.getOrDefault(child, new SimplePair(child, CONST_INF));
        }
    }

    private static class Graph {

        private Map<Long, GraphNode> graph;
        int n;

        /**
         * @param n    頂点数
         * @param list
         */
        public Graph(int n, int[][] list) {
            this.n = n;
            graph = new HashMap<Long, GraphNode>();
            /*
            隣接行列作成
            0-indexed
             */
            Arrays.stream(list).forEach(l -> {
                long a = l[0] - 1;
                long b = l[1] - 1;
                long d = l[2];
                graph.put(a, graph.getOrDefault(a, new GraphNode(a)));
                graph.get(a).addChild(b, d);
                graph.put(b, graph.getOrDefault(b, new GraphNode(b)));
                graph.get(b).addChild(a, d);
            });
            /*
            たどり着けない場所はCONST_INFで埋める
            自分へはCOST=0でたどり着ける
             */
            for (long i = 0; i < n; i++) {
                graph.put(i, graph.getOrDefault(i, new GraphNode(i)));
                GraphNode node = graph.get(i);
                for (int j = 0; j < n; j++) {
                    if (i == j)
                        node.addChild(j, 0L);
                    else
                        node.addChild(j, CONST_INF);
                }
            }
        }

        /**
         * ワーシャルフロイド
         */
        public void warshallFloyd() {
            for (long k = 0; k < n; k++) {
                for (long i = 0; i < n; i++) {
                    for (long j = 0; j < n; j++) {
                        long min = Math.min(graph.get(i).getChild(j).v, graph.get(i).getChild(k).v + graph.get(k).getChild(j).v);
                        graph.get(i).getChild(j).v = min;
                    }
                }
            }
        }

        public void partialUpdateAndWarshallFloyd(long x, long y, long w) {
            if (graph.get(x).getChild(y).v > w)
                graph.get(x).getChild(y).v = graph.get(y).getChild(x).v = w;
            long[] l = {x, y};
            for (long k : l) {
                for (long i = 0; i < n; i++) {
                    for (long j = 0; j < n; j++) {
                        if (graph.get(i).getChild(j).v > graph.get(i).getChild(k).v + graph.get(k).getChild(j).v) {
                            graph.get(i).getChild(j).v = graph.get(i).getChild(k).v + graph.get(k).getChild(j).v;
                        }
                    }
                }
            }
        }

        /**
         * 2点間の距離
         *
         * @param from
         * @param to
         * @return
         */
        public long getDistance(long from, long to) {
            return graph.get(from).getChild(to).v;
        }

    }

    public long calcSimpleCombination(long n, long m, long CONST_MOD) {
        long mole = 1;
        for (long i = 1; i <= n + m; i++) {
            mole *= i;
            mole %= CONST_MOD;
        }
        long deno = 1;
        for (long i = 1; i <= n; i++) {
            deno *= i;
            deno %= CONST_MOD;
        }
        for (int i = 1; i <= m; i++) {
            deno *= i;
            deno %= CONST_MOD;
        }
        deno = modInverse(deno, CONST_MOD);
        return (mole * deno) % CONST_MOD;
    }

    long abs(double x) {
        return (long) Math.abs(x);
    }

    long round(double x) {
        return Math.round(x);
    }

    long floor(double x) {
        return (long) Math.floor(x);
    }

    long ceil(double x) {
        return (long) Math.ceil(x);
    }

    double sqrt(double x) {
        return Math.sqrt(x);
    }

    double pow(double x, double y) {
        return Math.pow(x, y);
    }

    long pow(long x, long y) {
        return (long) Math.pow(x, y);
    }

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

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

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

    public long lcmMod(long... ab) {

        Map<Long, Long> ps = new HashMap<Long, Long>();

        for (int abl = 0; abl < ab.length; abl++) {
            long target = ab[abl];
            long l = target;
            for (long p = 2; p * p <= l; p++) {
                long cnt = 0;
                while (target > 1 && target % p == 0) {
                    cnt++;
                    target /= p;
                }
                if (cnt == 0)
                    continue;
                ps.put(p, Long.max(cnt, ps.getOrDefault(p, 0L)));
            }
            if (target > 1)
                ps.put(target, Long.max(1, ps.getOrDefault(target, 0L)));
        }
        long res = 1L;
        for (Map.Entry<Long, Long> e : ps.entrySet()) {
            res *= powMod(e.getKey(), e.getValue());
            res %= MOD;
        }
        return res;
    }

    int upperToInt(char a) {
        return a - 'A';
    }

    int lowerToInt(char a) {
        return a - 'a';
    }

    int numToInt(char a) {
        return a - '0';
    }

    int charToInt(char a) {
        return a >= 'a' ? lowerToInt(a) : a >= 'A' ? upperToInt(a) : numToInt(a);
    }

    char intToUpper(int a) {
        return (char) (a + 'A');
    }

    char intToLower(int a) {
        return (char) (a + 'a');
    }

    char intToNum(int a) {
        return (char) (a + '0');
    }

    void reverse(String array[]) {
        String reversed[] = new String[array.length];
        for (int i = 0; i < array.length; i++) {
            reversed[array.length - i - 1] = array[i];
        }
        for (int i = 0; i < array.length; i++) {
            array[i] = reversed[i];
        }
    }

    void reverse(int array[]) {
        int reversed[] = new int[array.length];
        for (int i = 0; i < array.length; i++) {
            reversed[array.length - i - 1] = array[i];
        }
        for (int i = 0; i < array.length; i++) {
            array[i] = reversed[i];
        }
    }

    void reverse(long array[]) {
        long reversed[] = new long[array.length];
        for (int i = 0; i < array.length; i++) {
            reversed[array.length - i - 1] = array[i];
        }
        for (int i = 0; i < array.length; i++) {
            array[i] = reversed[i];
        }
    }

    void reverse(double array[]) {
        double reversed[] = new double[array.length];
        for (int i = 0; i < array.length; i++) {
            reversed[array.length - i - 1] = array[i];
        }
        for (int i = 0; i < array.length; i++) {
            array[i] = reversed[i];
        }
    }

    void reverse(boolean array[]) {
        boolean reversed[] = new boolean[array.length];
        for (int i = 0; i < array.length; i++) {
            reversed[array.length - i - 1] = array[i];
        }
        for (int i = 0; i < array.length; i++) {
            array[i] = reversed[i];
        }
    }

    void fill(int array[][], int x) {
        for (int a[] : array) {
            Arrays.fill(a, x);
        }
    }

    void fill(long array[][], long x) {
        for (long a[] : array) {
            Arrays.fill(a, x);
        }
    }

    void fill(double array[][], double x) {
        for (double a[] : array) {
            Arrays.fill(a, x);
        }
    }

    void fill(boolean array[][], boolean x) {
        for (boolean a[] : array) {
            Arrays.fill(a, x);
        }
    }

    void fill(int array[][][], int x) {
        for (int a[][] : array) {
            fill(a, x);
        }
    }

    void fill(long array[][][], long x) {
        for (long a[][] : array) {
            fill(a, x);
        }
    }

    void fill(double array[][][], double x) {
        for (double a[][] : array) {
            fill(a, x);
        }
    }

    void fill(boolean array[][][], boolean x) {
        for (boolean a[][] : array) {
            fill(a, x);
        }
    }

    long L_INF = (long) 1e18 + 7;

    boolean isINF(long a) {
        return abs(a) > L_INF / 1000;
    }

    boolean isPlusINF(long a) {
        return a > 0 && isINF(a);
    }

    boolean isMinusINF(long a) {
        return isPlusINF(-a);
    }

    int I_INF = (int) 1e9 + 7;

    boolean isINF(int a) {
        return abs(a) > I_INF / 1000;
    }

    boolean isPlusINF(int a) {
        return a > 0 && isINF(a);
    }

    boolean isMinusINF(int a) {
        return isPlusINF(-a);
    }

    /**
     * 指定したx以下の素数をリストアップする
     */
    public long[] getPrimesUnderX(long x) {
        return LongStream.rangeClosed(2, x)
                .filter(i -> LongStream.rangeClosed(2, (long) Math.sqrt(i)).allMatch(j -> i % j != 0)).toArray();
    }


    public long mod(long i) {
        return i % MOD + ((i % MOD) < 0 ? MOD : 0);
    }

    long powMod(long x, long y) {
        if (y == 0) {
            return 1;
        } else {
            long tmp = powMod(x, y / 2);
            return mod(mod(tmp * tmp) * (y % 2 == 0 ? 1 : x));
        }
    }

    long inv(long x) {
        return powMod(x, MOD - 2);
    }

    int MAX_FACT = 5_000_100;
    long fact[];
    long invFact[];

    /**
     * Combination簡易版
     * 5 C 2
     * 異なる n個のものから r個を選ぶ組み合わせの総数 nCr を求めます。
     * 5!(5*4*3*2*1)
     * /
     * 2!(2*1) *  (5-2)!(3*2*1)
     *
     * @param n
     * @param r
     * @return
     */
    private long getComb(int n, int r) {
        long tmp = 1;
        for (int i = 1; i <= r; i++) {
            tmp *= n - i + 1;
            tmp = mod(tmp);
            tmp *= inv(i);
            tmp = mod(tmp);
        }
        return tmp;
    }

    /**
     * 階乗計算の事前累積和
     * [1, 1, 2, 3, 4, 5, … FACTORIAL_NUM]
     * mod済
     */
    void prepareFact() {
        fact = new long[MAX_FACT];
        Arrays.fill(fact, 0);
        invFact = new long[MAX_FACT];
        Arrays.fill(invFact, 0);
        fact[0] = 1;
        int maxIndex = (int) min(MAX_FACT, (int) MOD);
        for (int i = 1; i < maxIndex; i++) {
            fact[i] = mod(fact[i - 1] * i);
        }
        invFact[maxIndex - 1] = inv(fact[maxIndex - 1]);
        for (int i = maxIndex - 1; i > 0; i--) {
            invFact[i - 1] = mod(invFact[i] * i);
        }
    }

    /**
     * 順列
     * nPk -> n! / (n-k)!
     *
     * @param n
     * @param r
     * @return
     */
    long permutation(int n, int r) {
        if (n < 0 || r < 0 || n < r) {
            return 0;
        }
        return mod(fact[n] * invFact[n - r]);
    }

    /**
     * 組み合わせ
     * nCk -> n! / k!・(n-k)!
     *
     * @param n
     * @param r
     * @return
     */
    long combination(int n, int r) {
        if (n < 0 || r < 0 || n < r) {
            return 0;
        }
        return mod(permutation(n, r) * invFact[r]);
    }

    /**
     * 重複組合せ nHr （同次積）
     * nHr = (n+r-1)Cr
     * 異なるn個のものから重複を許してr個取る組合せの総数
     * 例：
     * リンゴ，ミカン，牛肉の3種類の果物があります．これらの中から6個の食材を買って帰ります．
     * このとき，何通りの買い方がありますか？ただし，含まれない食材があってもよいものとします
     *
     * @param n
     * @param r
     * @return
     */
    long homogeneousProduct(int n, int r) {
        return combination((n - 1) + r, r);
    }

    /**
     * 多項係数
     * 文字aをp個,bをq個,cをr個, dをs個 あわせてn個を1列に並べるときの並べ方
     * n! / p!・q!・r!・s!
     *
     * @param n
     * @param strNum
     * @param mod
     * @return
     */

    /**
     * フェルマーの小定理を用いて逆元を求める。
     * ある数xのmod p（pは素数）の逆数x'はx' = x^(p-2)
     * 繰り返し二乗法を用いて計算する。
     * http://satanic0258.hatenablog.com/entry/2016/04/29/004730
     * {@link BigInteger#modInverse(BigInteger)}とどちらが速いか？
     *
     * @param x
     * @return
     */
    private long modInverse(long x, long mod) {
        long res = 1L;
        long k = mod - 2L;
        long y = x;
        while (k != 0) {
            if (k % 2 != 0) {
                res = (res * y) % mod;
            }
            y = (y * y) % mod;
            k /= 2;
        }
        return res;
    }

    private boolean hasNextByte() {
        if (ptr < buflen) {
            return true;
        } else {
            ptr = 0;
            try {
                buflen = in.read(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (buflen <= 0) {
                return false;
            }
        }
        return true;
    }

    private int readByte() {
        if (hasNextByte())
            return buffer[ptr++];
        else
            return -1;
    }

    private static boolean isPrintableChar(int c) {
        return 33 <= c && c <= 126;
    }

    private void skipUnprintable() {
        while (hasNextByte() && !isPrintableChar(buffer[ptr]))
            ptr++;
    }

    public boolean hasNext() {
        skipUnprintable();
        return hasNextByte();
    }

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

    public double nextDouble() {
        return Double.parseDouble(next());
    }

    public String next() {
        if (!hasNext())
            throw new NoSuchElementException();
        StringBuilder sb = new StringBuilder();
        int b = readByte();
        while (isPrintableChar(b)) {
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }

    public long nextLong() {
        if (!hasNext())
            throw new NoSuchElementException();
        long n = 0;
        boolean minus = false;
        int b = readByte();
        if (b == '-') {
            minus = true;
            b = readByte();
        }
        if (b < '0' || '9' < b) {
            throw new NumberFormatException();
        }
        while (true) {
            if ('0' <= b && b <= '9') {
                n *= 10;
                n += b - '0';
            } else if (b == -1 || !isPrintableChar(b)) {
                return minus ? -n : n;
            } else {
                throw new NumberFormatException();
            }
            b = readByte();
        }
    }

    public long min(long... v) {
        long min = Long.MAX_VALUE;
        for (long i : v) min = Math.min(min, i);
        return min;
    }

    public long max(long... v) {
        long max = Long.MIN_VALUE;
        for (long i : v) max = Math.max(max, i);
        return max;
    }
}