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/8b029028-97c3-438c-9705-00a15ecfbe15
 */
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/m-solutions2019/tasks/m_solutions2019_a
     * A - Sum of Interior Angl
     */
    private void solveA() {
        out.println((nextInt() - 2) * 180);
    }

    /**
     * https://atcoder.jp/contests/abc093/tasks/arc094_a
     */
    private void solveB() {
        int[] abc = IntStream.range(0, 3).map(i -> nextInt()).sorted().toArray();
        boolean isBcEve = (abc[2] - abc[1]) % 2 == 0;
        boolean isAcEve = (abc[2] - abc[0]) % 2 == 0;
        int res = 0;
        if (isAcEve && isBcEve) {
            res = (abc[2] - abc[1]) / 2 + (abc[2] - abc[0]) / 2;
        } else if (!isAcEve && !isBcEve) {
            res = (abc[2] - abc[1]) / 2 + (abc[2] - abc[0]) / 2 + 1;
        } else {
            res = (abc[2] - abc[1]) / 2 + (abc[2] - abc[0]) / 2 + 2;
        }
        out.println(res);
    }

    /**
     * https://atcoder.jp/contests/abc118/tasks/abc118_c
     * C - Monsters Battle Royale
     */
    private void solveC() {
        int n = nextInt();
        int[] a = IntStream.range(0, n).map(i -> nextInt()).toArray();
        long res = a[0];
        for (int item : a) {
            res = gcd(res, item);
        }
        out.println(res);
    }

    /**
     * https://atcoder.jp/contests/agc018/tasks/agc018_a
     * A - Getting Difference
     * <p>
     * 操作がユークリッドの互除法と同じ？
     * なら、KをGCDで割り切れてかつ、aの最大値より小さければkを作れるはず
     */
    private void solveD() {
        int n = nextInt();
        int k = nextInt();
        int[] a = IntStream.range(0, n).map(i -> nextInt()).sorted().toArray();
        long gcd = a[0];
        for (int item : a) {
            gcd = gcd(gcd, item);
        }
        if (k % gcd == 0 && k <= a[n - 1])
            out.println("POSSIBLE");
        else
            out.println("IMPOSSIBLE");
    }

    /**
     * https://atcoder.jp/contests/arc097/tasks/arc097_b
     * D - Equals
     */
    private void solveE() {
        int n = nextInt();
        int m = nextInt();
        int[] p = IntStream.range(0, n).map(i -> nextInt() - 1).toArray();
        int[][] xy = IntStream.range(0, m).mapToObj(i -> new int[]{nextInt() - 1, nextInt() - 1}).toArray(int[][]::new);

        UnionFind unionFind = new UnionFind(n);
        for (int[] item : xy) {
            unionFind.unite(item[0], item[1]);
        }
        int res = 0;
        for (int i = 0; i < n; i++) {
            if (unionFind.isSame(i, p[i]))
                res++;
        }
        out.println(res);

    }

    /**
     * https://atcoder.jp/contests/abc137/tasks/abc137_e
     * E - Coins Respawn
     */
    private void solveF() {
        int n = nextInt();
        int m = nextInt();
        int p = nextInt();

        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) {
            int from = item[0];
            int to = item[1];
            int cost = item[2];
            bellmanFord.addEdge(from, to, cost);
            edges.put(from, edges.getOrDefault(from, new ArrayList<Integer>()));
            edges.get(from).add(to);
            reverseEdges.put(to, reverseEdges.getOrDefault(to, new ArrayList<Integer>()));
            reverseEdges.get(to).add(from);
        }
        boolean[] sToE = new boolean[n];
        dfs(sToE, edges, 0);
        boolean[] eToS = new boolean[n];
        dfs(eToS, reverseEdges, n - 1);
        boolean[] root = new boolean[n];
        for (int i = 0; i < n; i++) {
            root[i] = sToE[i] && eToS[i];
        }
        try {
            bellmanFord.shortestPath(0, root);
            out.println(Long.max(-bellmanFord.distance[n - 1], 0));
        } catch (Exception e) {
//            e.printStackTrace();
            out.println(-1);
        }
    }

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

    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) {
                    /*
                    canUseEdges[e.to] 行ってはいけないところは計算しない
                     */
                    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++;
            }
        }
    }

    public static class UnionFind {
        int[] pars;

        public UnionFind(int n) {
            pars = new int[n];
            Arrays.fill(pars, -1);
        }

        public int getChilds(int n) {
            int wk = getRoot(n);
            return pars[wk];
        }

        public int getRoot(int n) {
            if (pars[n] < 0)
                return n;
            return pars[n] = getRoot(pars[n]);
        }

        public boolean isSame(int a, int b) {
            return getRoot(a) == getRoot(b);
        }

        private int getSize(int a) {
            return -pars[getRoot(a)];
        }

        public void unite(int a, int b) {
            int wkA = getRoot(a);
            int wkB = getRoot(b);
            if (wkA == wkB)
                return;

            if (getSize(wkA) < getSize(wkB)) {
                int tmp = wkA;
                wkA = wkB;
                wkB = tmp;
            }
            pars[wkA] = pars[wkA] + pars[wkB];
            pars[wkB] = wkA;
        }
    }

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

Score : 500 points

Problem Statement

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.

Sample Input 1

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

Sample Output 1

35

There are two ways to travel from Vertex 1 to Vertex 3:

Vertex 1 \rightarrow 2 \rightarrow 3: You collect 20 + 30 = 50 coins on the way. After two minutes from the start of the game, you press the button, pay 2 \times 10 = 20 coins, and you have 50 - 20 = 30 coins left.

Vertex 1 \rightarrow 2: You collect 45 coins on the way. After one minute from the start of the game, you press the button, pay 1 \times 10 = 10 coins, and you have 45 - 10 = 35 coins left.

Thus, the maximum score that can be obtained is 35.

Sample Input 2

2 2 10
1 2 100
2 2 100

Sample Output 2

-1

The edge extending from Vertex 1 takes you to Vertex 2. If you then traverse the edge extending from Vertex 2 to itself t times and press the button, your score will be 90 + 90t. Thus, you can infinitely increase your score, which means there is no maximum value of the score that can be obtained.

Sample Input 3

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

Sample Output 3

0

There is no way to travel from Vertex 1 to Vertex 4 other than traversing the edge leading from Vertex 1 to Vertex 4 directly. You will pick up one coin along this edge, but after being asked to paying 10 coins, your score will be 0.

Note that you can collect an infinite number of coins if you traverse the edge leading from Vertex 1 to Vertex 2, but this is pointless since you can no longer reach Vertex 4 and end the game.


import java.util.*;
import java.io.*;
import java.nio.charset.StandardCharsets;

public class Main {
	static class Node {
		int id;
		List<Edge> edges = new ArrayList<>();
		/*
		 * Queue<Edge> edges = new PriorityQueue<>(new Comparator<Edge>() {
		 *
		 * @Override public int compare(Edge o1, Edge o2) { return -1 *
		 * Integer.compare(o1.length, o2.length); } });
		 */
		Set<Edge> passedEdges = new HashSet<>();
		int dist = Integer.MIN_VALUE / 2;

		Node(int id) {
			this.id = id;
		}
	}

	static class Edge {
		int src, dst, length;

		Edge(int src, int dst, int length) {
			this.src = src;
			this.dst = dst;
			this.length = length;
		}
	}

	public static void main(String[] args) throws IOException {
		InputStreamReader reader = new InputStreamReader(System.in, StandardCharsets.UTF_8);
		BufferedReader in = new BufferedReader(reader);
		String[] tokens = in.readLine().split(" ");
		int N = Integer.parseInt(tokens[0]);
		int M = Integer.parseInt(tokens[1]);
		int P = Integer.parseInt(tokens[2]);

		Node[] graph = new Node[N];
		for (int i = 0; i < N; ++i) {
			graph[i] = new Node(i);
		}
		for (int i = 0; i < M; ++i) {
			tokens = in.readLine().split(" ");
			int a = Integer.parseInt(tokens[0]);
			int b = Integer.parseInt(tokens[1]);
			int c = Integer.parseInt(tokens[2]);
			Edge edge = new Edge(a - 1, b - 1, c - P);
			graph[a - 1].edges.add(edge);
		}
		// 開始ノードの距離は0
		graph[0].dist = 0;

		for (int i = 0; i < graph.length; ++i) {
			for (int j = 0; j < graph[i].edges.size(); ++j) {
				Edge edge = graph[i].edges.get(j);
				if (graph[edge.dst].dist < graph[edge.src].dist + edge.length) {
					graph[edge.dst].dist = graph[edge.src].dist + edge.length;
					graph[edge.dst].passedEdges.addAll(graph[edge.src].passedEdges);
					graph[edge.dst].passedEdges.add(edge);
				}
			}
		}

		// 閉路チェック
		boolean hasNegativeLoop = false;
		for (Edge edge : graph[graph.length - 1].passedEdges) {
			if (graph[edge.src].dist + edge.length > graph[edge.dst].dist) {
				hasNegativeLoop = true;
				break;
			}
		}
		if (hasNegativeLoop) {
			System.out.println("-1");
		} else {
			int result = Math.max(0, graph[graph.length - 1].dist);
			System.out.println(result);
		}
	}
}

Global OOD problem IDs are disjoint from train, validation, and in-distribution test problem IDs.

Submitted source-code file size, in bytes.

Execution CPU time reported by official Project CodeNet metadata, in milliseconds.

Peak memory usage reported by official Project CodeNet metadata, in kilobytes.


import java.io.*;
import java.util.*;

class Main {
    static Scanner scanner = new Scanner();
    static long inf = 0x7fffffffffL;

    public static void main(String[]$) throws IOException {
        int n = scanner.nextInt();
        int m = scanner.nextInt();
        int p = scanner.nextInt();
        Edge[] edges = new Edge[m];
        for (int i = 0; i < m; i++) {
            int a = scanner.nextInt() - 1;
            int b = scanner.nextInt() - 1;
            int c = scanner.nextInt();
            edges[i] = new Edge(a, b, p - c);
        }
        long[] d = new long[n];
        Arrays.fill(d, inf);
        d[0] = 0;

        Set<Integer> loop = new HashSet<>();

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (d[edges[j].to] > d[edges[j].from] + edges[j].cost) {
                    d[edges[j].to] = d[edges[j].from] + edges[j].cost;
                    if (i == n - 1) {
                        loop.add(edges[j].to);
                    }
                }
            }
        }

        if (loop.contains(n - 1)) {
            System.out.println(-1);
        } else {
            System.out.println(Math.max(0, -d[n - 1]));
        }
    }

    static class Edge implements Comparable<Edge> {
        int from;
        int to;
        long cost;

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

        @Override
        public int compareTo(Edge o) {
            return Long.compare(this.cost, o.cost);
        }

        @Override
        public String toString() {
            return String.format("[%s, %s, %s]", from, to, cost);
        }
    }

    static class Scanner {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in), 32768);
        StringTokenizer tokenizer;

        String next() throws IOException {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                tokenizer = new StringTokenizer(reader.readLine());
            }
            return tokenizer.nextToken();
        }

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

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

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


import java.io.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.*;

/**
 * @author Utkarsh
 *
 */
public  class Main
{

	   static class FastReader
	    {
	        BufferedReader br;
	        StringTokenizer st;

	        public FastReader()
	        {
	            br = new BufferedReader(new
	                     InputStreamReader(System.in));
	        }

	        String next()
	        {
	            while (st == null || !st.hasMoreTokens())
	            {
	                try
	                {
	                    st = new StringTokenizer(br.readLine());
	                }
	                catch (IOException  e)
	                {
	                    e.printStackTrace();
	                }
	            }
	            return st.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 e)
	            {
	                e.printStackTrace();
	            }
	            return str;
	        }

			public Character charAt(int i) {
				// TODO Auto-generated method stub
				return null;
			}

			public BigInteger nextBigInteger() {
				// TODO Auto-generated method stub
				return null;
			}
	    }

	  // Complete the hurdleRace function below.
//    public static void solve() {
//    	FastReader s=new FastReader();
	    int binarySearch(int arr[], int l, int r, int x)
	    {
	        if (r >= l) {
	            int mid = l + (r - l) / 2;

	            // If the element is present at the
	            // middle itself
	            if (arr[mid] == x)
	                return mid;

	            // If element is smaller than mid, then
	            // it can only be present in left subarray
	            if (arr[mid] > x)
	                return binarySearch(arr, l, mid - 1, x);

	            // Else the element can only be present
	            // in right subarray
	            return binarySearch(arr, mid + 1, r, x);
	        }

	        // We reach here when element is not present
	        // in array
	        return -1;
	    }

	    static // Driver method to test above

	// Java implementation of iterative Binary Search

	    // Returns index of x if it is present in arr[],
	    // else return -1
	    int lowerBound(int[] a,int n,int key){
	        int s =0,e=n-1;
	        int ans = -1;

	        while(s<=e){
	            int mid = (s+e)/2;

	            if(a[mid]==key){
	                ans = mid;
	                e = mid - 1;
	            }
	            else if(a[mid]>key){
	                e = mid - 1;
	            }
	            else{
	                s = mid + 1;
	            }
	        }

	        return ans;
	    }
	    static int count(String se,char c,int l,int r) {
			if(l==r) {
				if(se.charAt(l)==c)return 0;
				else return 1;
			}
			int mid = (l+r)/2;
			int c1=0,c2=0;
			for(int i=l;i<=mid;i++) {
				if(se.charAt(i)!=c)c1++;
			}
			for(int i=r;i>mid;i--) {
				if(se.charAt(i)!=c)c2++;
			}
			int y = count(se,(char)((int)c+1),mid+1,r);
			int x = count(se,(char)((int)c+1),l,mid);
	    	return Math.min(c1+y, c2+x);

	    }
	    public static double log2(long N)
	    {

	        // calculate log2 N indirectly
	        // using log() method
	        double result = (double)(Math.log(N) / Math.log(2));

	        return result;
	    }
	    static boolean sign(long n) {
	    	return n>0;
	    }
	    public static int solve(long[] ar,int n) {
	    	long sum=0;
	    	for(int i=0;i<n;i++) {
	    		sum+=ar[i];
	    		if(sum<=0)return 0;
			}
	    	sum=0;
	    	for(int i=n-1;i>=0;i--) {
	    		sum+=ar[i];
	    		if(sum<=0)return 0;
	    	}
			return 1;
	    }
    public static void main(String[] args) throws IOException {
    	FastReader s=new FastReader();
    	int n = s.nextInt();
    	int[] ar = new int[n];
    	for(int i=0;i<n;i++) {
    		ar[i] = s.nextInt();
    	}
    	for(int i=1;i<n;i++) {
    		if(ar[i-1]>ar[i])ar[i-1]--;
    	}
//    	for(int i=0;i<n;i++) {
//    		System.out.print(ar[i]+" ");
//    	}
    	int flag=0;
    	for(int i=1;i<n && flag==0;i++) {
    		if(ar[i-1]>ar[i])flag=1;
    	}
    	if(flag==1)System.out.println("No");
    	else System.out.println("Yes");
    }
}
//2999999997

Score : 300 points

Problem Statement

There are N squares arranged in a row from left to right. The height of the i-th square from the left is H_i.

For each square, you will perform either of the following operations once:

Decrease the height of the square by 1.

Do nothing.

Determine if it is possible to perform the operations so that the heights of the squares are non-decreasing from left to right.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq H_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
H_1 H_2 ... H_N

Output

If it is possible to perform the operations so that the heights of the squares are non-decreasing from left to right, print Yes; otherwise, print No.

Sample Input 1

5
1 2 1 1 3

Sample Output 1

Yes

You can achieve the objective by decreasing the height of only the second square from the left by 1.

Sample Input 2

4
1 3 2 1

Sample Output 2

No

Sample Input 3

5
1 2 3 4 5

Sample Output 3

Yes

Sample Input 4

1
1000000000

Sample Output 4

Yes


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.StringTokenizer;
/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
	public static void main(String[] args) {
		InputReader in = new InputReader(System.in);
		PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)),true);
		TaskB solver = new TaskB();
		solver.solve(1, in, out);
		out.flush();
		out.close();
	}
}

class TaskB {
    public void solve(int testNumber, InputReader in, PrintWriter pw) {
    	int n=in.nextInt();
    	int arr[]=new int[n];
    	for(int i=0;i<n;i++) {
    		arr[i]=in.nextInt();
    	}
    	boolean flag=true;
    	int temp=arr[0];
    	int max=arr[0];
    	for(int i=1;i<n;i++) {
    		if(arr[i]<temp-1||arr[i]<max) {
    			flag=false;
    			break;
    		}
    		max=temp-1>max?temp-1:max;
    		temp=arr[i];
    	}
    	if(flag) {
    		pw.println("Yes");
    	}else {
    		pw.println("No");
    	}

    	}
}
class Pair<A,B>{
	A first;
	B second;
	Pair(A first,B second){
		this.first=first;
		this.second=second;
	}
}

class InputReader{
    BufferedReader br;
    StringTokenizer st;
    public InputReader(InputStream in){
        br=new BufferedReader(new InputStreamReader(in));
        st=null;
    }
    public String next(){
    while(st==null||!st.hasMoreTokens()){
        try{
            st=new StringTokenizer(br.readLine());
        }catch(IOException e){
            throw new RuntimeException(e);
        }
    }
   return st.nextToken();
    }
    public int nextInt(){
        return Integer.parseInt(next());
    }
    public long nextLong() {
    	return Long.parseLong(next());
    }
}


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.PrintWriter;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) throws Exception {
        try (BufferedInputStream in = new BufferedInputStream(System.in);
             PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out))) {

            Scanner sc = new Scanner(in);

            // 12:44-

            int n = sc.nextInt();
            int last = sc.nextInt() - 1;
            for (int i = 1; i < n; i++) {
                int cur = sc.nextInt();
                if (cur < last) {
                    out.println("NO");
                    return;
                }
                if (cur > last) cur--;
                last = cur;
            }

            out.println("YES");
        }
    }

}


import java.util.Scanner;

public class Main {

	public static void main(String[] args) {

		int a;

		Scanner sc = new Scanner(System.in);

		a = sc.nextInt();

		int[] b = new int[a];

		for (int i = 0; i < b.length; i++) {
			b[i] = sc.nextInt();
		}

		int count = 1;
		boolean flag = true;

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

			if (b[i - 1] <= b[i]) {

				++count;

			} else if ((b[i - 1] -1) <= b[i] && flag) {

				++count;
				flag = false;

			}

		}

		if (b.length == count) {
			System.out.println("Yes");
		} else {
			System.out.println("No");
		}

	}

}


import java.util.*;

public class Main{
  public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    int h ;
    int[] a = new int[n];

    for(int i=0; i<n; i++){
      h = sc.nextInt();
      a[i] = h ;

    }
    if(n==0){
      System.out.println("No");
    }else{
      for(int j=0; j<n-1; j++){
        if(a[j]>a[j+1]){
          a[j] = a[j]-1;
          if(j==0 && a[j]>a[j+1]){
            System.out.println("No");
            break ;
          }
          if(a[j-1]>a[j] || a[j]>a[j+1]){
            System.out.println("No");
            break ;
          }
        }
      }
    System.out.println("Yes");
    }
  }
}


import java.util.Scanner;
public class Main {

	public static void main(String[] args) {
		Scanner stdin=new Scanner(System.in);
		int n=stdin.nextInt();
		int[] h=new int[n+1];
		for(int i=0;i<n;i++)
		 h[i]=stdin.nextInt();
		for(int i=0;i<n-1;i++) {
			if(h[i]>h[i+1]) {
				h[i]=h[i]-1;
			}
		}
		int cnt=0;
		for(int i=0;i<n-1;i++) {
			if(h[i]>h[i+1]) cnt++;
		}

		if(cnt<=0) System.out.println("YES");
		else System.out.println("NO");

	}

}


import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);

		int N = sc.nextInt();
		boolean result = true;

		int left = 0;
		int mid = sc.nextInt();	// 1個目
		int right = 0;

		for (int i = 0; i < N - 1; i++) {
			right = sc.nextInt();

			if (mid - 1 > right) {
				result = false;
				break;
			} else if (mid - 1 == right && left > mid - 1) {
				result = false;
				break;
			}

			if (mid - 1 == right) {
				left = mid - 1;
				mid = right;
			} else {
				left = mid;
				mid = right;
			}
		}

		System.out.println(result ? "Yes" : "No");
	}
}


import java.util.*;

public class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int N = sc.nextInt();
    int[] A = new int[N];
    for (int i = 0; i < N; i++) {
      A[i] = sc.nextInt();
    }

    for (int i = 1; i < N; i++) {
      if (A[i - 1] < A[i]) {
        A[i]--;
      }
      else {
        if (A[i - 1] != A[i]) {
          System.out.println("No");
          break;
        }
      }
    }
    System.out.println("Yes");
  }
}


import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int N = s.nextInt();
        int H[] = new int[N];
        for (int i = 0; i < N; i++) {
            H[i] = s.nextInt();
        }
        boolean bl = false;
        int ch = 0;
        for (int i = 0; i < (N-1); i++) {
            if (H[i] <= H[i + 1]) {
                ch++;
            }
        }
        if (ch ==( N-1)) {
            bl = true;
        }
        if (!bl) {
            for (int i = 0; i <( N-1); i++) {
                if (H[i] > H[i + 1]) {
                    H[i] -= 1;
                }
            }
            ch = 0;
            for (int i = 0; i <( N-1); i++) {
                if (H[i] <= H[i + 1]) {
                    ch++;
                }
            }
            if(ch==(N-1)){
                bl=true;
            }
        }
        if(bl){
            System.out.print("Yes");
        }
        else{
            System.out.print("No");
        }
    }
}


import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int[] h = new int[n];
		for (int i = 0; i < h.length; i++) {
			h[i] = sc.nextInt();
		}
		String ans = "Yes";

		for (int i = n; i > 0; i--) {
			if (h[i] - h[i-1] > 1 ) {
				continue;

			}else if (h[i] - h[i-1] == 1 ) {
				h[i]--;

			} else {
				ans = "No";
				break;
			}
		}

		System.out.println(ans);
		sc.close();
	}
}


import java.util.*;
public class Main {
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);

		// 整数の入力
		int n = sc.nextInt();
        int[] list = new int[n];
        int previous = 0;
        boolean decreased = false;
        boolean isFalse = false;
        for (int i = 0; i < n; i++) {
          int value = sc.nextInt();
          if (value < previous) {
            if (!decreased) {
              list[i - 1] -= 1;
              decreased = true;
            }
          }
          previous = value;
          list[i] = value;
        }
        previous = 0;
        boolean judge = true;
        for (int i = 0; i < n; i++) {
          if (list[i] < previous) {
            judge = false;
            break;
          }
          previous = list[i];
        }
        if (judge) {
          System.out.println("Yes");
        } else {
          System.out.println("No");
        }

	}
}


import java.util.ArrayList;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        boolean flg = true;
        Long[] Hs = new Long[N + 1];
        Long fix = 0L;
        int cnt = 0;
        for (int i = 1; i <= N; i++) {
            long H = sc.nextLong();
            Hs[i] = H;
            if (Hs[i - 1] > H) {
                Hs[i - 1] = Hs[i - 1] - 1;
                if (cnt == 0) {
                    fix = Hs[i - 1];
                }
                cnt++;
                if (Hs[i - 1] > fix) {
                    flg = false;
                    break;
                }
            }
        }

        if (flg) {
            System.out.println("Yes");
        } else {
            System.out.println("No");
        }
    }
}


import java.util.*;
public class Main {
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
	    int buildcnt = sc.nextInt();
        int hights[]= new int[buildcnt];
            boolean reach =false;
      String answer = "YES";
        for(int i=0;i<buildcnt;i++){
         hights[i]=sc.nextInt();
        }
//      List<Integer> numlist = new ArrayList<Integer>();
//      while(sc.hasnext()){
  //      numlist.add(sc.nextInt());
    //  }
      for(int i=0 ; i < buildcnt ;i++){
        for(int j=i; j < buildcnt;j++){
          if(hights[i] - hights[i+j]>j){
          answer = "NO";
          }
        }
      }

//      int now = sc.nextInt();
//      while(sc.hasNext()){
//       int next = sc.nextInt();
       //今-次が2以上ならNG
 //      if(now - next >= 2){
//         answer="NO";
  //       break;
  //     }else if(now - next == 1){

  //       if(reach == true){
  //        answer ="NO";
  //         break;
  //       }else{
  //         reach=true;
  //         now = next;
  //       }
  //     }else{
  //      now = next;
  //      reach=false;
  //     }
   //   }
        // 出力
		System.out.println(answer);
	}
}


import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int[] h = new int[n];
		for (int i = 0; i < h.length; i++) {
			h[i] = sc.nextInt();
		}
		String ans = "Yes";

		for (int i = 0; i < h.length - 1; i++) {
			if (h[i] <= h[i+1]) {
				continue;
			} else {
				if (h[i]-1 != h[i+1] || h[i]-1 < 0) {
					ans = "No";
					break;
				} else if (i != 0 && h[i-1] > h[i]-1) {
					ans = "No";
					break;
				} else {
					h[i]--;
				}
			}
		}

		System.out.println(ans);
		sc.close();
	}
}


import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        int n = Integer.parseInt(sc.nextLine());
        int[] ary = new int[n];
        String line = sc.nextLine();
        String[] line1 = line.split(" ");
        boolean ans = true;
        for(int i = 0; i < n; i++)  ary[i] = Integer.parseInt(line1[i]);
        for(int i = 0; i < n - 1; i++){
            if(ary[i] > ary[i + 1]){
                ary[i] -= 1;
                break;
            }
        }
        for(int i = 0; i < n - 1; i++){
            if(ary[i] > ary[i + 1]) ans = false;
        }
        if(ans) System.out.println("Yes");
        else    System.out.println("No");
    }
}


import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Main {

	public static void main(String[] args) throws Exception {
		// TODO 自動生成されたメソッド・スタブ
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		String W = in.readLine();
		int N = Integer.parseInt(W);

		W = in.readLine();
		String[] ws = W.split(" ");
		long[] H = new long[ws.length];
		String ans = "Yes";
		for(int i=0;i<ws.length;i++){
			H[i]=Long.parseLong(ws[i]);
			if(i==0){

			}else if(i==1){
				if(H[i-1] >= H[i]){
					H[i-1] = H[i-1]-1;
				}
			}else{
				if(H[i-1] >= H[i]){
					if(H[i-2] < H[i-1]){
						H[i-1]=H[i-1]-1;
					}
				}
			}
			if(i!=0 && H[i-1] > H[i]){
				ans="No";
				break;
			}
		}

		System.out.println(ans);

	}

}


import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.util.*;
import java.math.*;
import java.io.*;
import java.text.*;
import java.math.BigInteger;

public class Main
{

    //Life's a bitch
    public static boolean[] sieve(long n)
    {
        boolean[] prime = new boolean[(int)n+1];
        Arrays.fill(prime,true);
        prime[0] = false;
        prime[1] = false;
        long m = (long)Math.sqrt(n);
        for(int i=2;i<=m;i++)
        {
            if(prime[i])
            {
                for(int k=i*i;k<=n;k+=i)
                {
                    prime[k] = false;
                }
            }
        }
        return prime;
    }

    static long GCD(long a,long b)
    {
        if(b==0)
        {
            return a;
        }
        return GCD(b,a%b);
    }

    static long CountCoPrimes(long n)
    {
        long res = n;
        for(int i=2;i*i<=n;i++)
        {
            if(n%i==0)
            {
                while(n%i==0)
                {
                    n/=i;
                }
                res-=res/i;
            }
        }
        if(n>1)
        {
            res-=res/n;
        }
        return res;
    }

    static boolean prime(int n)
    {
        for(int i=2;i*i<=n;i++)
        {
            if(i%2==0 ||i%3==0)
            {
                return false;
            }
        }
        return true;
    }

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

        new Main().run();

    }

    static long findGCD(ArrayList<Long> arr,long start, long n)
    {
        long result = arr.get((int)start);
        for (int i = (int)start+1; i < n; i++)
            result = GCD(arr.get(i), result);

        return result;
    }

    Scanner in = new Scanner(System.in);
    void run() throws IOException
    {

        int n = ni();
        long[] a = new long[n];
        for(int i=0;i<n;i++)
        {
            a[i] = nl();
        }

        if(isSorted(a,n))
        {
            printS("Yes");
            return;
        }

        for(int i=0;i<n-1;i++)
        {
            if(a[i]>a[i+1])
            {
                a[i]-=1;
                if(a[i]>a[i+1])
                {
                    printS("NO");
                    return;
                }
            }

        }

        if(isSorted(a,n))
        {
            printS("Yes");
            return;
        }

        printS("No");

    }

    static boolean isSorted(long[] a,int n)
    {
        for(int i=0;i<n-1;i++)
        {
            if(a[i]>a[i+1])
            {
                return false;
            }
        }
        return true;
    }

    //xor range query
    static long xor(long n)
    {

        if(n%4==0)
        {
            return n;
        }
        if(n%4==1)
        {
            return  1;
        }
        if(n%4==2)
        {
            return n+1;
        }
        return 0;
    }

    static long xor(long a,long b)
    {
        return xor(b)^xor(a-1);
    }

     void printL(long a)
    {
        System.out.println(a);
    }
    void printS(String s)
    {
        System.out.println(s);
    }

     void printD(Double d)
    {
        System.out.println(d);
    }

    static void swap(char c,char p)
    {
        char t = c;
        c = p;
        p = t;
    }

    static long max(long n,long m)
    {
        return Math.max(n,m);
    }
    static long min(long n,long m)
    {
        return Math.min(n,m);
    }

    double nd() throws IOException
    {
        return Double.parseDouble(in.next());
    }
    int ni() throws IOException
    {
        return Integer.parseInt(in.next());
    }

    long nl() throws IOException
    {
        return Long.parseLong(in.next());
    }

    String si() throws IOException
    {
        return in.next();
    }

    static int abs(int n)
    {
        return Math.abs(n);
    }

    static class Scanner
    {
        StringTokenizer st;
        BufferedReader br;

        public Scanner(InputStream s){  br = new BufferedReader(new InputStreamReader(s));}

        public String next() throws IOException
        {
            while (st == null || !st.hasMoreTokens())
            {
                st = new StringTokenizer(br.readLine());
            }
            return st.nextToken();
        }

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

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

        public String nextLine() throws IOException {return br.readLine();}

        public boolean ready() throws IOException {return br.ready();}

    }

}

class Pair implements Comparable<Pair>
{
   int x,y;
    public Pair(int x,int y)
    {
        this.x = x;
        this.y = y;
    }
    public int compareTo(Pair o)
    {
        return this.y-o.y;
    }
}


import java.util.Scanner;

public class Main {
    public static void debug(String str) {
        boolean debug = false;
        if (debug != false) {
            return;
        }
        System.out.println(str);
    }

    public static void main(String[] args) {

        int N;
        long[] H;

        try (Scanner sc = new Scanner(System.in)) {
            N = sc.nextInt();
            H = new long[N];
            for (int i = 0; i < N; i++) {
                H[i] = sc.nextLong();
            }
        }

        if (H.length == 1) {
            System.out.println("Yes");
            return;
        }
        if (H.length == 2 && H[0] - H[1] <= 1) {
            System.out.println("Yes");
            return;
        }

        for (int i = 1; i < N; i++) {
            if (H[i - 1] - H[i] > 1) {
                //1以上減少するケース
                System.out.println("No");
                return;
            } else if (H[i - 1] - H[i] == 1) {

                if (H[i - 2] == H[i - 1]) {
                    //減少させると2つ前のよりも減少するケース
                    System.out.println("No");
                    return;
                }else{
                    //減少させる
                    H[i - 1]--;
                }
            }
        }

        System.out.println("Yes");
        return;

    }
}


import java.io.*;

public class Main{
  public static void main(String[] args) throws Exception{
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    int n = Integer.parseInt(br.readLine());
    String[] line = br.readLine().split(" ");
    int[] nums = new int[n];
    int i;
    boolean flag = false;
    nums[n-1] = Integer.parseInt(line[n-1]);
    for(i=n-2; 0<=i; i--){
      nums[i] = Integer.parseInt(line[i]);
      if( nums[i] > nums[i+1] ){
        if( nums[i]-1 > nums[i+1] || flag ){
          System.out.println("No");
          System.exit(0);
        }else
          flag = true;
      }else
        flag = false;
    }
    System.out.println("Yes");
  }
}


import java.util.Scanner;

public class Main{
	public static void main(String[] args){
		Scanner scanner = new Scanner(System.in);
		String inputN = scanner.nextLine();

		String inputP = scanner.nextLine();
		String[] pStr = inputP.split(" ", 0);

		int n = Integer.parseInt(inputN);
		int pInt[] = new int[n];
		for(int i=0;i<n;i++){
			pInt[i] = Integer.parseInt(pStr[i]);
		}

		for(int i=1;i<n;i++){
			if(pInt[i] > pInt[i-1]){
				pInt[i]--;
			}
		}

		boolean isStair = true;

		for(int i=1;i<n;i++){
			if(pInt[i] < pInt[i-1]){
				isStair = false;
			}
		}

		String show = isStair ? "Yes" : "No";
		System.out.println(show);
	}
}


import java.util.Scanner;

public class Main {
	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);
		long l = sc.nextLong();
		long r = sc.nextLong();
		sc.close();
		if(l - r > 2018) {
			System.out.println(0);
			return;
		}
		long lMod = (l + 2019) % 2019;
		long rMod = (r + 2019) % 2019;
		if(rMod < lMod) {
			System.out.println(0);
		}
		else if(rMod == lMod)
			System.out.print((rMod * (rMod + 1)) % 2019);
		else
			System.out.println((lMod * (lMod + 1)) % 2019);

	}
}

Score : 300 points

Problem Statement

You are given two non-negative integers L and R.
We will choose two integers i and j such that L \leq i < j \leq R.
Find the minimum possible value of (i \times j) \mbox{ mod } 2019.

Constraints

All values in input are integers.

0 \leq L < R \leq 2 \times 10^9

Input

Input is given from Standard Input in the following format:

L R

Output

Print the minimum possible value of (i \times j) \mbox{ mod } 2019 when i and j are chosen under the given condition.

Sample Input 1

2020 2040

Sample Output 1

2

When (i, j) = (2020, 2021), (i \times j) \mbox{ mod } 2019 = 2.

Sample Input 2

4 5

Sample Output 2

20

We have only one choice: (i, j) = (4, 5).


import java.text.DecimalFormat;
import java.util.stream.LongStream;
import java.util.stream.IntStream;
import java.io.*;
import java.util.*;

public class Main {

    public static void main(String[] args) {
        FastScanner sc = new FastScanner();
        PrintWriter out = new PrintWriter(System.out);

        AtCoder problem = new AtCoder(sc);
        problem.solve(out);

        out.flush();
    }

}

class AtCoder {

    int L, R;

    AtCoder(FastScanner sc) {
        L = sc.nextInt();
        R = sc.nextInt();
    }

    void solve(PrintWriter out) {
        long min = Long.MAX_VALUE;
        int cnt = 0;
        outer:
        for (long i = L; i <= R; i++) {
            for (long j = i + 1; j <= R; j++) {
                long rem = i * j % 2019;
                min = Math.min(rem, min);
                cnt++;
                if (cnt > 1e5) break outer;
            }
        }
        out.println(min);
    }

}

class FastScanner {

    private final InputStream in = System.in;
    private final byte[] buffer = new byte[1024];
    private int ptr = 0;
    private int buflen = 0;

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

    public boolean hasNext() {
        while (hasNextByte() && !isPrintableChar(buffer[ptr])) {
            ptr++;
        }
        return hasNextByte();
    }

    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 int nextInt() {
        long nl = nextLong();
        if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) {
            throw new NumberFormatException();
        }
        return (int) nl;
    }

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

    public int[] arrayInt(int N) {
        int[] array = new int[N];
        for (int i = 0; i < N; i++) {
            array[i] = nextInt();
        }
        return array;
    }

    public long[] arrayLong(int N) {
        long[] array = new long[N];
        for (int i = 0; i < N; i++) {
            array[i] = nextLong();
        }
        return array;
    }

    public double[] arrayDouble(int N) {
        double[] array = new double[N];
        for (int i = 0; i < N; i++) {
            array[i] = nextDouble();
        }
        return array;
    }

    public String[] arrayString(int N) {
        String[] array = new String[N];
        for (int i = 0; i < N; i++) {
            array[i] = next();
        }
        return array;
    }
}

class My {

    static void ans(boolean b) {
        System.out.println(b ? "Yes" : "No");
    }

    static void ANS(boolean b) {
        System.out.println(b ? "YES" : "NO");
    }

    static String sort(String s) {
        char[] ch = s.toCharArray();
        Arrays.sort(ch);
        return String.valueOf(ch);
    }

    static String reverse(String s) {
        return new StringBuilder(s).reverse().toString();
    }

    static int[] reverse(int[] array) {
        for (int i = 0; i < array.length / 2; i++) {
            int temp = array[i];
            array[i] = array[array.length - 1 - i];
            array[array.length - 1 - i] = temp;
        }
        return array;
    }

    static long[] reverse(long[] array) {
        for (int i = 0; i < array.length / 2; i++) {
            long temp = array[i];
            array[i] = array[array.length - 1 - i];
            array[array.length - 1 - i] = temp;
        }
        return array;
    }

    static double[] reverse(double[] array) {
        for (int i = 0; i < array.length / 2; i++) {
            double temp = array[i];
            array[i] = array[array.length - 1 - i];
            array[array.length - 1 - i] = temp;
        }
        return array;
    }

    static String[] reverse(String[] array) {
        for (int i = 0; i < array.length / 2; i++) {
            String temp = array[i];
            array[i] = array[array.length - 1 - i];
            array[array.length - 1 - i] = temp;
        }
        return array;
    }

    static char[] reverse(char[] array) {
        for (int i = 0; i < array.length / 2; i++) {
            char temp = array[i];
            array[i] = array[array.length - 1 - i];
            array[array.length - 1 - i] = temp;
        }
        return array;
    }

    static long min(long... numbers) {
        Arrays.sort(numbers);
        return numbers[0];
    }

    static int min(int... numbers) {
        Arrays.sort(numbers);
        return numbers[0];
    }

    static double min(double... numbers) {
        Arrays.sort(numbers);
        return numbers[0];
    }

    static long max(long... numbers) {
        Arrays.sort(numbers);
        return numbers[numbers.length - 1];
    }

    static int max(int... numbers) {
        Arrays.sort(numbers);
        return numbers[numbers.length - 1];
    }

    static double max(double... numbers) {
        Arrays.sort(numbers);
        return numbers[numbers.length - 1];
    }

    static int sum(long number) {
        int sum = 0;
        while (number > 0) {
            sum += number % 10;
            number /= 10;
        }
        return sum;
    }

}


import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		int l=sc.nextInt(),r=sc.nextInt();
		sc.close();
		if(r-l>=2018) System.out.println(0);
		else {
			long min=2018;
			for(int i=l;i<r;i++) {
				for(int j=i+1;j<=r;j++) {
					long temp =(long)i*j;
					long mod = temp%2019;
					if(mod<min) min=mod;
				}
			}
			System.out.println(min);
		}
	}
}


import java.io.*;
import java.util.*;
import java.math.*;

 public class Main	{
   static class Pair implements Comparable<Pair>{
   int a;
   int b;
   public Pair(int x,int y){a=x;b=y;}
   public Pair(){}
   public int compareTo(Pair p){
     return a  - p.a ;
   }
 }
static class TrieNode{
  TrieNode[]child;
  int w;
  boolean term;
  TrieNode(){
    child = new TrieNode[26];
  }
}
  public static int gcd(int a,int b)
  {
    if(a<b)

      return gcd(b,a);
    if(b==0)
      return a;
    return gcd(b,a%b);

  }
  //static long ans = 0;
  static int mod =(int)(1e9+7); //998244353;//

    public static void main(String[] args) throws Exception {
       new Thread(null, null, "Anshum Gupta", 99999999) {
            public void run() {
                try {
                    solve();
                } catch(Exception e) {
                    e.printStackTrace();
                    System.exit(1);
                }
            }
        }.start();
    }

static long pow(long x,long y){
    if(y == 0)return 1;
    if(y==1)return x;
    long a = pow(x,y/2);
    a = (a*a)%mod;
    if(y%2==0){
        return a;
    }
    return (a*x)%mod;
}

static long mxx;
static int mxN = (int)(1e5+5);
static long[]fact,inv_fact;
static long my_inv(long a) {
	return pow(a,mod-2);
}
static long bin(int a,int b) {
    return ((1L*fact[a]*inv_fact[a-b])%mod * inv_fact[b])%mod;
}

static ArrayList<ArrayList<Integer>>adj ;
static boolean[]vis;
static void dfs(int sv,int d,int[]dis) {
	vis[sv] = true;
	dis[sv] = d;
	for(int i=0;i<adj.get(sv).size();++i) {
		int x = adj.get(sv).get(i);
		if(!vis[x]) {
			dfs(x,d+1,dis);
		}
	}

}

 public static void solve() throws Exception {
   // solve the problem here
   MyScanner s = new MyScanner();
        out = new PrintWriter(new BufferedOutputStream(System.out), true);
        int tc = 1;//s.nextInt();
        mxx = (long)(1e18+5);

        while(tc-->0){
        	int l = s.nextInt();
        	int r = s.nextInt();
        	if(r - l > 2019) {
        		out.println("0");
        	}
        	else {
        		int ans = 2020;
        		for(int i=l;i<=r;i++) {
        			for(int j=i+1;j<=r;j++) {
        				ans = Math.min(ans, (i*j)%2019);
        			}
        		}
        		out.println(ans);
        	}
        }

        out.flush();
}

    //-----------PrintWriter for faster output---------------------------------
    public static PrintWriter out;

    //-----------MyScanner class for faster input----------
    public static class MyScanner {
        BufferedReader br;
        StringTokenizer st;

        public MyScanner() {
            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();
        }

        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 e) {
                e.printStackTrace();
            }
            return str;
        }
    }
    //--------------------------------------------------------
}


import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		long L = sc.nextLong();
		long R = sc.nextLong();
		if (L%2019==0||R%2019==0) {
			System.out.println(0);
			return ;
		}
		if (L/2019!=R/2019) {
			System.out.println(0);
			return ;
		}
		int min = 2019;
		for (long i=L;i<R;i++) {
			for (long j=i+1;j<=R;j++) {
				int temp = (int) (((i%2019)*(j%2019))%2019);
				if (temp<min) {
					min = temp;
				}
			}
		}
		System.out.println(min);
	}
}


import java.util.*;
class Main{
	public static void main(String[] args){
		Scanner sc=new Scanner(System.in);
		int L=sc.nextInt();
		int R=sc.nextInt();
		int min=0;
		if(L%2019==0||R%2019==0||L/2019<R/2019){
			System.out.println(0);
			return;
		}

		for(int i=L;i<R;i++){
			for(int j=i+1;j<=R;j++){
				int a=(i*j)%2019;
				if((i==L&&j==L+1)||min>a){min=a;}
			}
		}
		System.out.println(min);
	}
}


import java.util.*;

public class Main{
    public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);

      int L=sc.nextInt();
      int R=sc.nextInt();

      //0 < L <= i < j <= R

      int mod,ii,jj;
      int ans = 2019;

      for(int i=L;i<R;i++){
        ii = i % 2019;
        for(int j=i+1;j<=R;j++){
          jj = j % 2019;
          mod = (ii*jj) % 2019;
          if(mod<ans)ans=mod;
        }
      }

      System.out.println(ans);

    }
}


import java.util.*;

public class Main {
  public static void main(String[] args ) throws Exception {
    Scanner sc = new Scanner(System.in);
    int L = sc.nextInt();
    int R = sc.nextInt();

    int min = 2019;

    for(int i = L; i < R ; i++){
      for(int m = L + 1;m <= R ; m ++){
        int a = i * m;
        int mod = a % 2019;
        if(mod < min ){
          min = mod;
        }
      }
    }
    System.out.println(min);
  }
}


import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int l = sc.nextInt();
		int r = sc.nextInt();
		int min = Integer.MAX_VALUE;
		for (int i = l; i < r; i++) {
			for (int j = i + 1; j <= r; j++) {
				min = Math.min(min, (i * j) % 2019);
			}
		}
		System.out.println(min);
	}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

    public static void main(String[] args) {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        try {
            String str = br.readLine();
            String input[] = str.split(" ");
            int L = Integer.valueOf(input[0]);
            int R = Integer.valueOf(input[1]);

            int result = 2018;
          if(R-L >2019){
            R = L+2019;
          }
          if(L >= 2019){
            L %= 2019;
            R %= 2019;
          }
            for(int i = L; i<R; i++) {
				if(i%2019 == 0 || result == 0){
                  result = 0;
                  break;
                }
              for(int j = i+1; j<=R; j++) {
                  int N = i* j;
                    if( N % 2019 < result && N % 2019 > 0 ) {
                        result = N % 2019;
                    } else if(N%2019 == 0){
                      result = N % 2019;
                      break;
                    }
                }
            }
            System.out.println(result);

        }catch(IOException e) {

        }
    }

}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

    public static void main(String[] args) {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        try {
            String str = br.readLine();
            String input[] = str.split(" ");
            int L = Integer.valueOf(input[0]);
            int R = Integer.valueOf(input[1]);
          	if(L>R || L < 0 || R>2000000000) {
              System.exit(1);
            }

            int result = 2018;
            for(int i = L; i<R; i++) {
				if(i%2019 == 0){
                  result = 0;
                  break;
                }
              for(int j = i+1; j<=R; j++) {
                  int N = i* j;
                    if( N % 2019 < result ) {
                        result = N % 2019;
                    }
                }
            }
            System.out.println(result);

        }catch(IOException e) {

        }
    }

}


import java.util.Scanner;

public class Main {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);

		int L = Integer.parseInt(sc.next());
		int R = Integer.parseInt(sc.next());
		int ans = 2019;

		if (L + 2019 < R) {
			R = L + 2019;
		}

		int i;
		int j;
		int mod;
		for (i = L; i <= R-1; i++) {
			for (j = i + 1; j <= R; j++) {
				mod = ((i % 2019) * (j % 2019)) % 2019;
				if (mod < ans) {
					ans = mod;
				}
			}

		}

		System.out.println(ans);

	}

}


/*
非負整数L、Rが与えられます。
２つの整数i,jをL<=i<j<=Rを満たすように選びます。
(i*J)mod2019の最小値を求めてください。
 */

import java.util.*;

public class Main{
  public static void main(String[]args){
    Scanner sc=new Scanner(System.in);
    while(sc.hasNext()){
      long L=sc.nextLong();
      long R=sc.nextLong();
      long ans=1000000000;
      if(R-L>=2019){
        System.out.println(0);
      }else{
        for(long i=L;i<R;i++){
          for(long j=i+1;j<=R;j++){
            ans=Math.min(ans,(i*j)%2019);
          }
        }
      }
      System.out.println(ans);
    }
  }
}


import java.util.Scanner;

public class Main{

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);

		long R = sc.nextLong();
		long L = sc.nextLong();

		long min = Long.MAX_VALUE;

		for(long i = R; i < L-1; i++) {
			for(long j = L; j > i; j--) {
				if(min > Math.floorMod(i * j , 2019)) {
					min = Math.floorMod(i * j , 2019);
				}
			}
		}
		System.out.println(min);
		sc.close();
	}

}


import java.io.*;
class Main{
    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String sb1 = br.readLine();
        String[] a = sb1.split(" ");
        long[] c = new long[a.length];
        long[] b = new long[a.length];
        long d  = 2019;
        for(int i = 0;i < a.length;i++){
            c[i] = Long.parseLong(a[i]);
        }
        for(int i = 0;i < a.length;i++){
            b[i] = c[i]/d;
        }

        if(c[1] < 2019){
            System.out.println(c[0] * (c[0] + 1));
            System.out.println(1);
        } else if(b[0] == b[1]){
            System.out.println((c[0] * (c[0] + 1) %2019));
        }  else {
            System.out.println(0);
        }

    }
}


import java.util.*;
public class Main {
	public static void main(String args[] ){
		Scanner sc =new Scanner(System.in);
	long n = sc.nextLong();
	long m =sc.nextLong();
	long min =Integer.MAX_VALUE;

	if(m<2019) {
		long data =(n*(n+1))%2019;
		min =data;
	}else{
		for(long i=n;i<m;i++) {
			for(long j=i+1;j<m;j++) {
				long data =(i*j)%2019;
				if(min > data) {
					//System.out.println(i+" "+j);
					min =data;
				}
				if(min==0) break;

			}
			if(min==0) break;
		}
		}

	System.out.println(min);

	}
}


import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        long L = scan.nextLong();
        long R = scan.nextLong();

        long result = 2018;

        for (long i = L; i < R; i++){
            for (long j = i + 1; j <= R; j++){
                long mod = (i * j) % 2019;
                if(result > mod) result = mod;
                if(result == 0) break;
            }
            if(result == 0) break;
        }

        System.out.println(result);
    }
}


import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        long l = Long.parseLong(sc.next());
        long r = Long.parseLong(sc.next());
        long ans = Long.MAX_VALUE;
        long num = 0;
        for (long i = l; i < r; i++) {
            for (long j = i + 1; j <= r; j++) {
                num = (i * j) % 2019;
                if (num < ans) {
                    ans = num;
                }
                if (num == 0) {
                    System.out.println(0);
                    return;
                }
            }
        }
        System.out.println(ans);
    }
}


import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);

		long L = sc.nextLong();
		long R = sc.nextLong();

		if (R - L >= 2019) {
			System.out.println(0);
			return;
		}

		long ans = Long.MAX_VALUE;
		for (long i = L; i < R; i++) {
			long tmp =0;
			for (long j = i+1; j <= R; j++) {
				tmp=(i*j)%2019;
				ans = Math.min(ans, tmp);
			}
		}
		System.out.println(ans);
	}
}


import java.io.*;
import java.util.*;

public class Main {

    public static void main(String[] args) {
        FastScanner sc = new FastScanner(System.in);
        int l = sc.nextInt() % 2019;
        int r = sc.nextInt() % 2019;
        int mini = 2019;
        for (int i = l + 1; i <= r; i++) {
            for (int j = l; j < i; j++) {
                if ((j * i) % 2019 < mini) {
                    mini = (j * i) % 2019;
                }
            }
        }
        if(mini ==2019){
        	mini = l;
        }
        System.out.println(mini);
    }

    static class FastScanner {
        private BufferedReader reader;
        private StringTokenizer tokenizer;

        public FastScanner(InputStream in) {
            reader = new BufferedReader(new InputStreamReader(in));
            tokenizer = null;
        }

        public String next() {
            if (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public String nextLine() {
            if (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    return reader.readLine();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            return tokenizer.nextToken("\n");
        }

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

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

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

        public long[] nextLongArray(int n) {
            long[] a = new long[n];
            for (int i = 0; i < n; i++)
                a[i] = nextLong();
            return a;
        }
    }
}


import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        int a = scan.nextInt();
        int b = scan.nextInt();
        if((b-a)%2019==0&&(a%2019)!=0&&(b%2019)!=0){
            System.out.println(((a%2019)*((a+1)%2019))%2019);
        }else{
            System.out.println(0);
        }
    }
}


import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int left = Integer.parseInt(in.next());
        int right = Integer.parseInt(in.next());
        in.close();
        int leftdiv = left / 2019;
        int rightdiv = right / 2019;
        int leftMod = left % 2019;
        int ans = 0;
        if (leftdiv == rightdiv) {
            ans = leftMod * (leftMod + 1) % 2019;
        }
        System.out.println(ans);
    }
}


import java.util.*;

public class Main {
	public static void main (String[] args) {
		Scanner in = new Scanner(System.in);

		long L = in.nextLong();
        long R = in.nextLong();
      if(L>4037){L=L/2019;R=R/2019;}

      if(L>2019){System.out.print((L*(L+1))%2019);}
      else if(R<2019){System.out.print((R*(R-1))%2019);}

	}
}


import java.util.*;
public class Main {

  public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    int L = sc.nextInt();
    int R = sc.nextInt();

    if ((R / 2019) > (L / 2019)) {
      System.out.println(0);
      return;
    }

    int a = Math.min(L%2019, R%2019);

    System.out.println(a*(a + 1));
  }
}


import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        long L = scanner.nextLong();
        long R = scanner.nextLong();

        long modL = mod2019(mod2019(L));
        long modR = mod2019(mod2019(R));

        long nextMod0Number = (L + 2019 - modL);

        if (nextMod0Number < R) {
            System.out.println(mod2019((nextMod0Number * (nextMod0Number + 1))));
        } else if (nextMod0Number == R) {
            System.out.println(mod2019(R + nextMod0Number));
        } else {
            System.out.println(mod2019(L * (L + 1)));
        }
    }

    private static long mod2019(long hoge) {
        return hoge % 2019;
    }
}


import java.io.IOException;
import java.io.InputStream;
import java.util.NoSuchElementException;

public class Main {

	public static void main(String[] args) {
		FScanner sc = new FScanner();
		long L = sc.nextLong();
		long R = sc.nextLong();
		if (R < 2019) {
			long min = (L * R) % 2019;
			for (long i = L; i < R; i++) {
				for (long j = i + 1; j <= R; j++) {
					long cal = (i * j) % 2019;
					min = Math.min(min, cal);
				}
			}
			System.out.println(min);
			return;
		} else {
			int q = 1;
			boolean contain = false;
			while (q * 2019 <= R) {
				if (L <= q * 2019 && R >= 2019 * q) {
					contain = true;
					break;
				}
				q++;
			}
			if (contain) {
				System.out.println(0);
				return;
			} else {
				long min = (L * R) % 2019;
				for (long i = L; i < R; i++) {
					for (long j = i + 1; j <= R; j++) {
						long cal = (i * j) % 2019;
						min = Math.min(min, cal);
					}
				}
				System.out.println(min);
				return;
			}
		}
	}

}

class FScanner {
	private final InputStream in = System.in;
	private final byte[] buffer = new byte[1024];
	private int ptr = 0;
	private int buflen = 0;

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

	public boolean hasNext() {
		while (hasNextByte() && !isPrintableChar(buffer[ptr]))
			ptr++;
		return hasNextByte();
	}

	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 int nextInt() {
		long nl = nextLong();
		if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE)
			throw new NumberFormatException();
		return (int) nl;
	}

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


import java.util.Scanner;

class Main{

	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		int L = sc.nextInt();
		int R = sc.nextInt();
		int min = 2019;
		int mod = 0;
		for(int i = L; i < R; i++) {
			for(int j = i + 1;j <= R; j++) {
				mod = (i % 2019) * (j % 2019) % 2019;
				if(mod < min) min = mod;
			}
		}
		System.out.println(min);
		sc.close();
	}
}


import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int l = sc.nextInt();
        int r = sc.nextInt();

        int min = Integer.MAX_VALUE;
        int tmp = Math.min(r, l + 2019);
        for (int i = l+1; i <= tmp; i++) {
            for (int j = l; j < i; j++) {
                min = Math.min(min, (i * j) % 2019);
            }
        }

        System.out.println(min);
    }
}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

class MyScanner {
    BufferedReader br;

    MyScanner() {
        br = new BufferedReader(new InputStreamReader(System.in));
    }

    public int intLine() throws IOException {
        return Integer.parseInt(br.readLine());
    }

    public String line() throws IOException {
        return br.readLine();
    }

    public int[] intArray() throws IOException {
        String[] in = br.readLine().split(" ");
        int n = in.length;
        int[] res = new int[n];
        for(int i = 0; i < n; i++) {
            res[i] = Integer.parseInt(in[i]);
        }
        return res;
    }
}

public class Main {
    public static void main(String[] args) throws IOException {
        MyScanner sc = new MyScanner();

        int[] in = sc.intArray();
        int l = in[0];
        int r = in[1];

        /*
        int min = 2019;
        boolean minIsR = true;
        int max = 0;
        boolean maxIsL = true;
        for(int i = l; i <= r; i++) {
            int remainder = i % 2019;
            if(min >= remainder) {
                min = remainder;
                minIsR &= (i == r);
            }
            if(max <= remainder) {
                max = remainder;
                maxIsL &= (i == l);
            }
        }
        if(min == 0) {
            System.out.println(0);
        }else {
            int ans = 2019;
            if(!minIsR) {
                ans = Math.min(ans, (min * (min + 1)) % 2019);
            }
            if(!maxIsL) {
                ans = Math.min(ans, (max * (max - 1)) % 2019);
            }
            System.out.println(ans);
        }
        */

        int ans = 2019;
        for(int i = l; i < r; i++) {
            ans = Math.min(ans, ((i % 2019) * ((i + 1) % 2019)) % 2019);
        }
        System.out.println(ans);

        sc.br.close();
    }
}


import java.util.*;

public class Main {
	Scanner sc = new Scanner(System.in);
	final int MOD = 1000000007;
	final int MAX = Integer.MAX_VALUE;
	final long LMAX = Long.MAX_VALUE;
	final int LEN = 100000;

	void doIt() {
		int l = sc.nextInt();
		int r = sc.nextInt();
		if(r - l < 2019) {
			int min = MAX;
			for(int i = l; i <= r; i++) {
				min = Math.min(min, i % 2019);
			}
			System.out.println(min * (min + 1));
		}
		else {
			System.out.println(1);
		}
	}

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


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		char str[] = br.readLine().toCharArray();

		long tmp = 0;
		long ans = 0;

		for (int i = 0; i < str.length - 1; ++i) {
			if (str[i] == 'A') {
				tmp++;
			} else if (str[i] == 'B' && str[i + 1] == 'C') {
				ans += tmp;
				i++;
			} else {
				tmp = 0;
			}
		}

		System.out.println(ans);
	}

}

Score : 600 points

Problem Statement

You are given a string s consisting of A, B and C.

Snuke wants to perform the following operation on s as many times as possible:

Choose a contiguous substring of s that reads ABC and replace it with BCA.

Find the maximum possible number of operations.

Constraints

1 \leq |s| \leq 200000

Each character of s is A, B and C.

Input

Input is given from Standard Input in the following format:

s

Output

Find the maximum possible number of operations.

Sample Input 1

ABCABC

Sample Output 1

3

You can perform the operations three times as follows: ABCABC → BCAABC → BCABCA → BCBCAA. This is the maximum result.

Sample Input 2

C

Sample Output 2

0

Sample Input 3

ABCACCBABCBCAABCB

Sample Output 3

6


import java.util.Scanner;

public class Main {
    public static void main(final String[] args) {
        final Scanner scanner = new Scanner(System.in);
        final String s = scanner.next();

        long count = 0;
        long constraintA = 0;

        int i = 0;
        while (i < s.length()) {
            final char c = s.charAt(i);
            if (c == 'A') {
                long tmp = i;
                while (i < s.length() && s.charAt(i) == 'A') {
                    i++;
                }
                final long aCount = i - tmp + constraintA;

                tmp = i;
                while (i < s.length() - 1 && s.charAt(i) == 'B' && s.charAt(i + 1) == 'C') {
                    i += 2;
                }
                final long bcCount = (i - tmp) / 2;
                count += aCount * bcCount;
                constraintA += aCount;
            } else {
                constraintA = 0;
                i++;
            }
        }
        System.out.println(count);
    }
}