exec_outcome
stringclasses
1 value
code_uid
stringlengths
32
32
file_name
stringclasses
111 values
prob_desc_created_at
stringlengths
10
10
prob_desc_description
stringlengths
63
3.8k
prob_desc_memory_limit
stringclasses
18 values
source_code
stringlengths
117
65.5k
lang_cluster
stringclasses
1 value
prob_desc_sample_inputs
stringlengths
2
802
prob_desc_time_limit
stringclasses
27 values
prob_desc_sample_outputs
stringlengths
2
796
prob_desc_notes
stringlengths
4
3k
lang
stringclasses
5 values
prob_desc_input_from
stringclasses
3 values
tags
sequencelengths
0
11
src_uid
stringlengths
32
32
prob_desc_input_spec
stringlengths
28
2.37k
difficulty
int64
-1
3.5k
prob_desc_output_spec
stringlengths
17
1.47k
prob_desc_output_to
stringclasses
3 values
hidden_unit_tests
stringclasses
1 value
PASSED
85a0e9fd46377736d7cc4c4d1e45a999
train_000.jsonl
1537171500
Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r < t$$$.
256 megabytes
import java.io.OutputStream;import java.io.IOException;import java.io.InputStream;import java.io.PrintWriter;import java.util.Arrays; import java.util.SplittableRandom;import java.util.InputMismatchException;import java.io.IOException;import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, FastReader in, PrintWriter out) { int n = in.nextInt(); long ans = 0; long t = in.nextLong(); long[] a = new long[n]; for (int i = 0; i < a.length; i++) { a[i] = in.nextLong(); } long[] sum = new long[n + 1]; for (int i = 1; i < sum.length; i++) { sum[i] = sum[i - 1] + a[i - 1]; } long[] s = sum.clone(); ArrayUtils.sort(s); FenwickTreeL fenwickTreeL = new FenwickTreeL(n + 1); for (int i = 0; i < s.length; i++) { if (i > 0) { int l = -1; int r = n + 1; while (l + 1 < r) { int m = (l + r) / 2; if (s[m] <= sum[i] - t) { l = m; } else { r = m; } } ans += i - fenwickTreeL.getSum(l); } int l = -1; int r = n + 1; while (l + 1 < r) { int m = (l + r) / 2; if (s[m] <= sum[i]) { l = m; } else { r = m; } } fenwickTreeL.add(l, 1); } out.println(ans); } } static class FastReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar; private int pnumChars; public FastReader(InputStream stream) { this.stream = stream; } private int pread() { if (pnumChars == -1) { throw new InputMismatchException(); } if (curChar >= pnumChars) { curChar = 0; try { pnumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (pnumChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = pread(); while (isSpaceChar(c)) c = pread(); int sgn = 1; if (c == '-') { sgn = -1; c = pread(); } int res = 0; do { if (c == ',') { c = pread(); } if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = pread(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = pread(); while (isSpaceChar(c)) c = pread(); int sgn = 1; if (c == '-') { sgn = -1; c = pread(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = pread(); } while (!isSpaceChar(c)); return res * sgn; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } static class ArrayUtils { public static long[] sort(long[] a) { a = shuffle(a, new SplittableRandom()); Arrays.sort(a); return a; } public static long[] shuffle(long[] a, SplittableRandom gen) { for (int i = 0, n = a.length; i < n; i++) { int ind = gen.nextInt(n - i) + i; long d = a[i]; a[i] = a[ind]; a[ind] = d; } return a; } } static class FenwickTreeL { public long[] fen; public int N; public FenwickTreeL(long[] a) { N = a.length; fen = new long[N + 1]; for (int i = 0; i < N; i++) { for (int x = i + 1; x <= N; x += x & (-x)) { fen[x] += a[i]; } } } public FenwickTreeL(int n) { N = n; fen = new long[N + 1]; } public void add(int ind, long val) { if (val == 0) return; for (int x = ind + 1; x <= N; x += x & (-x)) { fen[x] += val; } } public long getSum(int ind) { long sum = 0; for (int x = ind + 1; x > 0; x -= x & (-x)) { sum += fen[x]; } return sum; } }}
Java
["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"]
2 seconds
["5", "4", "3"]
NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$
Java 8
standard input
[ "data structures", "two pointers", "divide and conquer" ]
42c4adc1c4a10cc619c05a842e186e60
The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements.
1,800
Print the number of segments in Petya's array with the sum of elements less than $$$t$$$.
standard output
PASSED
80282c187e013f68f8cc9fddf7e46acc
train_000.jsonl
1537171500
Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r &lt; t$$$.
256 megabytes
import java.io.OutputStream;import java.io.IOException;import java.io.InputStream;import java.io.PrintWriter;import java.util.Arrays;import java.util.SplittableRandom;import java.util.InputMismatchException;import java.io.IOException;import java.io.InputStream;/** * Built using CHelper plug-in * Actual solution is at the top */public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, FastReader in, PrintWriter out) { int n = in.nextInt(); long ans = 0; long t = in.nextLong(); long[] a = new long[n]; for (int i = 0; i < a.length; i++) { a[i] = in.nextLong(); } long[] sum = new long[n + 1]; for (int i = 1; i < sum.length; i++) { sum[i] = sum[i - 1] + a[i - 1]; } long[] s = sum.clone(); ArrayUtils.sort(s); FenwickTreeL fenwickTreeL = new FenwickTreeL(n + 1); for (int i = 0; i < s.length; i++) { if (i > 0) { int l = -1; int r = n + 1; while (l + 1 < r) { int m = (l + r) / 2; if (s[m] <= sum[i] - t) { l = m; } else { r = m; } } ans += i - fenwickTreeL.getSum(l); } int l = -1; int r = n + 1; while (l + 1 < r) { int m = (l + r) / 2; if (s[m] <= sum[i]) { l = m; } else { r = m; } } fenwickTreeL.add(l, 1); } out.println(ans); } } static class FastReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar; private int pnumChars; public FastReader(InputStream stream) { this.stream = stream; } private int pread() { if (pnumChars == -1) { throw new InputMismatchException(); } if (curChar >= pnumChars) { curChar = 0; try { pnumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (pnumChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = pread(); while (isSpaceChar(c)) c = pread(); int sgn = 1; if (c == '-') { sgn = -1; c = pread(); } int res = 0; do { if (c == ',') { c = pread(); } if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = pread(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = pread(); while (isSpaceChar(c)) c = pread(); int sgn = 1; if (c == '-') { sgn = -1; c = pread(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = pread(); } while (!isSpaceChar(c)); return res * sgn; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } static class ArrayUtils { public static long[] sort(long[] a) { a = shuffle(a, new SplittableRandom()); Arrays.sort(a); return a; } public static long[] shuffle(long[] a, SplittableRandom gen) { for (int i = 0, n = a.length; i < n; i++) { int ind = gen.nextInt(n - i) + i; long d = a[i]; a[i] = a[ind]; a[ind] = d; } return a; } } static class FenwickTreeL { public long[] fen; public int N; public FenwickTreeL(long[] a) { N = a.length; fen = new long[N + 1]; for (int i = 0; i < N; i++) { for (int x = i + 1; x <= N; x += x & (-x)) { fen[x] += a[i]; } } } public FenwickTreeL(int n) { N = n; fen = new long[N + 1]; } public void add(int ind, long val) { if (val == 0) return; for (int x = ind + 1; x <= N; x += x & (-x)) { fen[x] += val; } } public long getSum(int ind) { long sum = 0; for (int x = ind + 1; x > 0; x -= x & (-x)) { sum += fen[x]; } return sum; } }}
Java
["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"]
2 seconds
["5", "4", "3"]
NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$
Java 8
standard input
[ "data structures", "two pointers", "divide and conquer" ]
42c4adc1c4a10cc619c05a842e186e60
The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements.
1,800
Print the number of segments in Petya's array with the sum of elements less than $$$t$$$.
standard output
PASSED
804e8fff422c3653cc459f3cc051fb1f
train_000.jsonl
1537171500
Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r &lt; t$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.SplittableRandom; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, FastReader in, PrintWriter out) { int n = in.nextInt(); long ans = 0; long t = in.nextLong(); long[] a = new long[n]; for (int i = 0; i < a.length; i++) { a[i] = in.nextLong(); } long[] sum = new long[n + 1]; for (int i = 1; i < sum.length; i++) { sum[i] = sum[i - 1] + a[i - 1]; } long[] s = sum.clone(); ArrayUtils.sort(s); FenwickTreeL fenwickTreeL = new FenwickTreeL(n + 1); for (int i = 0; i < s.length; i++) { if (i > 0) { int l = -1; int r = n + 1; while (l + 1 < r) { int m = (l + r) / 2; if (s[m] <= sum[i] - t) { l = m; } else { r = m; } } ans += i - fenwickTreeL.getSum(l); } int l = -1; int r = n + 1; while (l + 1 < r) { int m = (l + r) / 2; if (s[m] <= sum[i]) { l = m; } else { r = m; } } fenwickTreeL.add(l, 1); } out.println(ans); } } static class FenwickTreeL { public long[] fen; public int N; public FenwickTreeL(long[] a) { N = a.length; fen = new long[N + 1]; for (int i = 0; i < N; i++) { for (int x = i + 1; x <= N; x += x & (-x)) { fen[x] += a[i]; } } } public FenwickTreeL(int n) { N = n; fen = new long[N + 1]; } public void add(int ind, long val) { if (val == 0) return; for (int x = ind + 1; x <= N; x += x & (-x)) { fen[x] += val; } } public long getSum(int ind) { long sum = 0; for (int x = ind + 1; x > 0; x -= x & (-x)) { sum += fen[x]; } return sum; } } static class FastReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar; private int pnumChars; public FastReader(InputStream stream) { this.stream = stream; } private int pread() { if (pnumChars == -1) { throw new InputMismatchException(); } if (curChar >= pnumChars) { curChar = 0; try { pnumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (pnumChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = pread(); while (isSpaceChar(c)) c = pread(); int sgn = 1; if (c == '-') { sgn = -1; c = pread(); } int res = 0; do { if (c == ',') { c = pread(); } if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = pread(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = pread(); while (isSpaceChar(c)) c = pread(); int sgn = 1; if (c == '-') { sgn = -1; c = pread(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = pread(); } while (!isSpaceChar(c)); return res * sgn; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } static class ArrayUtils { public static long[] sort(long[] a) { a = shuffle(a, new SplittableRandom()); Arrays.sort(a); return a; } public static long[] shuffle(long[] a, SplittableRandom gen) { for (int i = 0, n = a.length; i < n; i++) { int ind = gen.nextInt(n - i) + i; long d = a[i]; a[i] = a[ind]; a[ind] = d; } return a; } } }
Java
["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"]
2 seconds
["5", "4", "3"]
NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$
Java 8
standard input
[ "data structures", "two pointers", "divide and conquer" ]
42c4adc1c4a10cc619c05a842e186e60
The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements.
1,800
Print the number of segments in Petya's array with the sum of elements less than $$$t$$$.
standard output
PASSED
27800f14115dc1e6719a000ed69c4146
train_000.jsonl
1537171500
Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r &lt; t$$$.
256 megabytes
import java.io.*; import java.util.*; public class D { FastReader scn; PrintWriter out; String INPUT = ""; void solve() { int n = scn.nextInt(); long k = scn.nextLong(); long[][] pref = new long[n + 1][2]; for (int i = 1; i <= n; i++) { pref[i][0] = pref[i - 1][0] + scn.nextLong(); pref[i][1] = i; } Arrays.sort(pref, (o1, o2) -> o2[0] > o1[0] ? 1 : o2[0] < o1[0] ? -1 : 0); int[] bit = new int[n + 1]; long ans = 0; for (int i = 0, j = 0; i <= n; i++) { while (j <= n && pref[j][0] > pref[i][0] - k) { update(bit, 1, (int) pref[j][1] + 1); j++; } ans += query(bit, (int) pref[i][1]); } out.println(ans); } void update(int[] bit, int val, int ind) { while (ind < bit.length) { bit[ind] += val; ind += ind & (-ind); } } int query(int[] bit, int ind) { int rv = 0; while (ind > 0) { rv += bit[ind]; ind -= ind & (-ind); } return rv; } void run() throws Exception { long time = System.currentTimeMillis(); boolean oj = System.getProperty("ONLINE_JUDGE") != null; out = new PrintWriter(System.out); scn = new FastReader(oj); solve(); out.flush(); if (!oj) { System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" })); } } public static void main(String[] args) throws Exception { new D().run(); } class FastReader { InputStream is; public FastReader(boolean onlineJudge) { is = onlineJudge ? System.in : new ByteArrayInputStream(INPUT.getBytes()); } byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } double nextDouble() { return Double.parseDouble(next()); } char nextChar() { return (char) skip(); } String next() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } String nextLine() { int b = skip(); StringBuilder sb = new StringBuilder(); while ((!isSpaceChar(b) || b == ' ')) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } char[] next(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } int nextInt() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } long nextLong() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } char[][] nextMatrix(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = next(m); return map; } int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } int[][] next2DInt(int n, int m) { int[][] arr = new int[n][]; for (int i = 0; i < n; i++) { arr[i] = nextIntArray(m); } return arr; } long[][] next2DLong(int n, int m) { long[][] arr = new long[n][]; for (int i = 0; i < n; i++) { arr[i] = nextLongArray(m); } return arr; } int[] shuffle(int[] arr) { Random r = new Random(); for (int i = 1, j; i < arr.length; i++) { j = r.nextInt(i); arr[i] = arr[i] ^ arr[j]; arr[j] = arr[i] ^ arr[j]; arr[i] = arr[i] ^ arr[j]; } return arr; } } }
Java
["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"]
2 seconds
["5", "4", "3"]
NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$
Java 8
standard input
[ "data structures", "two pointers", "divide and conquer" ]
42c4adc1c4a10cc619c05a842e186e60
The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements.
1,800
Print the number of segments in Petya's array with the sum of elements less than $$$t$$$.
standard output
PASSED
5aaa90bfd12b585cfbd01bd341d9d2a7
train_000.jsonl
1537171500
Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r &lt; t$$$.
256 megabytes
import java.io.*; import java.util.*; public class D { FastReader scn; PrintWriter out; String INPUT = ""; void solve() { int n = scn.nextInt(); long k = scn.nextLong(); long[] arr = new long[n + 1]; long[][] pref = new long[n + 1][2]; for (int i = 1; i <= n; i++) { arr[i] = scn.nextLong(); pref[i][0] = pref[i - 1][0] + arr[i]; pref[i][1] = i; } Arrays.sort(pref, (o1, o2) -> o2[0] > o1[0] ? 1 : o2[0] < o1[0] ? -1 : 0); int[] bit = new int[n + 1]; long ans = 0; for (int i = 0, j = 0; i <= n; i++) { while (j <= n && pref[j][0] > pref[i][0] - k) { update(bit, 1, (int) pref[j][1] + 1); j++; } ans += query(bit, (int) pref[i][1]); } out.println(ans); } void update(int[] bit, int val, int ind) { while (ind < bit.length) { bit[ind] += val; ind += ind & (-ind); } } int query(int[] bit, int ind) { int rv = 0; while (ind > 0) { rv += bit[ind]; ind -= ind & (-ind); } return rv; } void run() throws Exception { long time = System.currentTimeMillis(); boolean oj = System.getProperty("ONLINE_JUDGE") != null; out = new PrintWriter(System.out); scn = new FastReader(oj); solve(); out.flush(); if (!oj) { System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" })); } } public static void main(String[] args) throws Exception { new D().run(); } class FastReader { InputStream is; public FastReader(boolean onlineJudge) { is = onlineJudge ? System.in : new ByteArrayInputStream(INPUT.getBytes()); } byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } double nextDouble() { return Double.parseDouble(next()); } char nextChar() { return (char) skip(); } String next() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } String nextLine() { int b = skip(); StringBuilder sb = new StringBuilder(); while ((!isSpaceChar(b) || b == ' ')) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } char[] next(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } int nextInt() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } long nextLong() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } char[][] nextMatrix(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = next(m); return map; } int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } int[][] next2DInt(int n, int m) { int[][] arr = new int[n][]; for (int i = 0; i < n; i++) { arr[i] = nextIntArray(m); } return arr; } long[][] next2DLong(int n, int m) { long[][] arr = new long[n][]; for (int i = 0; i < n; i++) { arr[i] = nextLongArray(m); } return arr; } int[] shuffle(int[] arr) { Random r = new Random(); for (int i = 1, j; i < arr.length; i++) { j = r.nextInt(i); arr[i] = arr[i] ^ arr[j]; arr[j] = arr[i] ^ arr[j]; arr[i] = arr[i] ^ arr[j]; } return arr; } } }
Java
["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"]
2 seconds
["5", "4", "3"]
NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$
Java 8
standard input
[ "data structures", "two pointers", "divide and conquer" ]
42c4adc1c4a10cc619c05a842e186e60
The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements.
1,800
Print the number of segments in Petya's array with the sum of elements less than $$$t$$$.
standard output
PASSED
579ffe404b07f02d772ffc9e43f5a34c
train_000.jsonl
1537171500
Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r &lt; t$$$.
256 megabytes
import java.io.*; import java.util.*; public class D { FastReader scn; PrintWriter out; String INPUT = ""; void solve() { int n = scn.nextInt(); long k = scn.nextLong(); long[] arr = new long[n + 1]; long[][] pref = new long[n + 1][2]; for (int i = 1; i <= n; i++) { arr[i] = scn.nextLong(); pref[i][0] = pref[i - 1][0] + arr[i]; pref[i][1] = i; } Arrays.sort(pref, (o1, o2) -> o2[0] > o1[0] ? 1 : o2[0] < o1[0] ? -1 : 0); int[] bit = new int[n + 1]; long ans = 0; for (int i = 0, j = 0; i <= n; i++) { while (j <= n && pref[j][0] > pref[i][0] - k) { update(bit, 1, (int) pref[j][1]); j++; } if (pref[i][1] != 0) { ans += query(bit, (int) pref[i][1] - 1); } } out.println(ans); } void update(int[] bit, int val, int ind) { if (ind == 0) { bit[ind] += val; return; } while (ind < bit.length) { bit[ind] += val; ind += ind & (-ind); } } int query(int[] bit, int ind) { int rv = 0; while (ind > 0) { rv += bit[ind]; ind -= ind & (-ind); } return rv + bit[0]; } void run() throws Exception { long time = System.currentTimeMillis(); boolean oj = System.getProperty("ONLINE_JUDGE") != null; out = new PrintWriter(System.out); scn = new FastReader(oj); solve(); out.flush(); if (!oj) { System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" })); } } public static void main(String[] args) throws Exception { new D().run(); } class FastReader { InputStream is; public FastReader(boolean onlineJudge) { is = onlineJudge ? System.in : new ByteArrayInputStream(INPUT.getBytes()); } byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } double nextDouble() { return Double.parseDouble(next()); } char nextChar() { return (char) skip(); } String next() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } String nextLine() { int b = skip(); StringBuilder sb = new StringBuilder(); while ((!isSpaceChar(b) || b == ' ')) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } char[] next(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } int nextInt() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } long nextLong() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } char[][] nextMatrix(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = next(m); return map; } int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } int[][] next2DInt(int n, int m) { int[][] arr = new int[n][]; for (int i = 0; i < n; i++) { arr[i] = nextIntArray(m); } return arr; } long[][] next2DLong(int n, int m) { long[][] arr = new long[n][]; for (int i = 0; i < n; i++) { arr[i] = nextLongArray(m); } return arr; } int[] shuffle(int[] arr) { Random r = new Random(); for (int i = 1, j; i < arr.length; i++) { j = r.nextInt(i); arr[i] = arr[i] ^ arr[j]; arr[j] = arr[i] ^ arr[j]; arr[i] = arr[i] ^ arr[j]; } return arr; } } }
Java
["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"]
2 seconds
["5", "4", "3"]
NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$
Java 8
standard input
[ "data structures", "two pointers", "divide and conquer" ]
42c4adc1c4a10cc619c05a842e186e60
The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements.
1,800
Print the number of segments in Petya's array with the sum of elements less than $$$t$$$.
standard output
PASSED
b5c6c505a6f668eca9f1eb2c3c378cbd
train_000.jsonl
1537171500
Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r &lt; t$$$.
256 megabytes
import java.util.*; import java.lang.*; import java.math.*; import java.io.*; import static java.lang.Math.*; public class Solution{ static long[] tree; static long[] arr,pre,post; static ArrayList<Long>[] al; static long build(int i,int l,int r,long t,int n){ int j; //System.out.println(l+" "+r); if(l==r){ if(arr[l]<t){ tree[i]=1; } al[i].add(arr[l]); //System.out.println(i+" "+tree[i]); return tree[i]; } int mid=(l+r)/2,lq,rq,rr; tree[i]=build(2*i+1,l,mid,t,n)+build(2*i+2,mid+1,r,t,n); long ad; for(j=l;j<=r;j++){ if(j>n-1) continue; if(l==0){ ad=pre[j]; } else ad=pre[j]-pre[l-1]; al[i].add(ad); } Collections.sort(al[i]); for(j=l;j<=mid;j++){ if(j>n-1) continue; if(mid==n-1) ad=post[j]; else ad=post[j]-post[mid+1]; lq=0; rq=al[2*i+2].size()-1; rr=-1; while(lq<=rq){ int m=(lq+rq)/2; if(ad+al[2*i+2].get(m)>=t){ rq=m-1; } else{ rr=m; lq=m+1; } } lq=0; rq=al[2*i+2].size()-1; tree[i]+=rr+1; } //System.out.println(i+" "+tree[i]); //System.out.println(i+" "+al[i]); return tree[i]; } public static void main(String[] args) { InputReader s = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int n=s.nextInt(),i; int len=(int)Math.ceil(Math.log(n)/Math.log(2)); int l=(int)Math.pow(2,len); arr=new long[n]; pre=new long[n]; post=new long[n]; int lent=(int)Math.pow(2,len+1)-1; tree=new long[lent]; al=new ArrayList[lent]; long t=s.nextLong(); for(i=0;i<n;i++){ arr[i]=s.nextLong(); if(i==0) pre[i]=arr[i]; else pre[i]=pre[i-1]+arr[i]; } for(i=0;i<lent;i++){ al[i]=new ArrayList<Long>(); } post[n-1]=arr[n-1]; for(i=n-2;i>=0;i--){ post[i]=post[i+1]+arr[i]; } build(0,0,n-1,t,n); System.out.println(tree[0]); } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"]
2 seconds
["5", "4", "3"]
NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$
Java 8
standard input
[ "data structures", "two pointers", "divide and conquer" ]
42c4adc1c4a10cc619c05a842e186e60
The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements.
1,800
Print the number of segments in Petya's array with the sum of elements less than $$$t$$$.
standard output
PASSED
070b1e5953ef4304f1b91055ed9a31d3
train_000.jsonl
1537171500
Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r &lt; t$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.StreamTokenizer; public class Main { static class Node { public int height; public long value; public Node parent; public Node leftSon; public Node rightSon; public int valueCount; public int count; public Node(long v) { value = v; height = 1; parent = null; leftSon = null; rightSon = null; count = 1; valueCount = 1; } public void calculateCount() { int count = 0; if (null != leftSon) count += leftSon.count; if (null != rightSon) count += rightSon.count; this.count = count + valueCount; } public void calculatorHeight() { int leftHeight = 0; int rightHeight = 0; if (null != leftSon) leftHeight = leftSon.height; if (null != rightSon) rightHeight = rightSon.height; this.height = Math.max(leftHeight, rightHeight) + 1; } } static Node root; public static void main(String[] args) throws IOException { StreamTokenizer streamTokenizer = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); streamTokenizer.nextToken(); int n = (int) streamTokenizer.nval; streamTokenizer.nextToken(); long t = (long) streamTokenizer.nval; long x; long count = 0; root = new Node(0); Node temp; long ans = 0; for (int i = 0; i < n; i++) { streamTokenizer.nextToken(); x = (long) streamTokenizer.nval; count += x; temp = new Node(count); ans += find(count - t); addNode(root, temp); } System.out.println(ans); } public static void addNode(Node cur, Node node) { if (cur.value < node.value) { if (null == cur.rightSon) { node.parent = cur; cur.rightSon = node; } else addNode(cur.rightSon, node); } else if (cur.value > node.value) { if (null == cur.leftSon) { node.parent = cur; cur.leftSon = node; } else addNode(cur.leftSon, node); } else { cur.valueCount++; cur.count++; } int leftHeight = 0; int rightHeight = 0; int leftHeight2 = 0; int rightHeight2 = 0; if (null != cur.leftSon) leftHeight = cur.leftSon.height; if (null != cur.rightSon) rightHeight = cur.rightSon.height; if (leftHeight > rightHeight + 1) { //左边高 if (null != cur.leftSon.leftSon) leftHeight2 = cur.leftSon.leftSon.height; if (null != cur.leftSon.rightSon) rightHeight2 = cur.leftSon.rightSon.height; if (leftHeight2 > rightHeight2) //左左 rightTranslate(cur); else { //左右 leftTranslate(cur.leftSon); rightTranslate(cur); } } else if (rightHeight > leftHeight + 1) {//右边高 if (null != cur.rightSon.leftSon) leftHeight2 = cur.rightSon.leftSon.height; if (null != cur.rightSon.rightSon) rightHeight2 = cur.rightSon.rightSon.height; if (leftHeight2 > rightHeight2) { //右左 rightTranslate(cur.rightSon); leftTranslate(cur); } else //右右 leftTranslate(cur); } else { cur.height = Math.max(leftHeight, rightHeight) + 1; cur.calculateCount(); } } public static void leftTranslate(Node node) { Node rightSon = node.rightSon; node.rightSon = rightSon.leftSon; if (null != node.rightSon) node.rightSon.parent = node; rightSon.leftSon = node; if (null == node.parent) root = rightSon; else if (node.parent.leftSon == node) node.parent.leftSon = rightSon; else node.parent.rightSon = rightSon; rightSon.parent = node.parent; node.parent = rightSon; node.calculateCount(); rightSon.calculateCount(); node.calculatorHeight(); rightSon.calculatorHeight(); } public static void rightTranslate(Node node) { Node leftSon = node.leftSon; node.leftSon = leftSon.rightSon; if (null != node.leftSon) node.leftSon.parent = node; leftSon.rightSon = node; if (null == node.parent) root = leftSon; else if (node.parent.leftSon == node) node.parent.leftSon = leftSon; else node.parent.rightSon = leftSon; leftSon.parent = node.parent; node.parent = leftSon; node.calculateCount(); leftSon.calculateCount(); node.calculatorHeight(); leftSon.calculatorHeight(); } public static int find(long v) { Node node = root; int result = 0; while (null != node) { if (node.value > v) { if (null != node.rightSon) result += node.rightSon.count; result += node.valueCount; node = node.leftSon; } else node = node.rightSon; } return result; } }
Java
["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"]
2 seconds
["5", "4", "3"]
NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$
Java 8
standard input
[ "data structures", "two pointers", "divide and conquer" ]
42c4adc1c4a10cc619c05a842e186e60
The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements.
1,800
Print the number of segments in Petya's array with the sum of elements less than $$$t$$$.
standard output
PASSED
57577df0956dd89d5f4c12573f1ae106
train_000.jsonl
1537171500
Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r &lt; t$$$.
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.*; import java.util.Random; import java.util.StringTokenizer; public class Main { String fileName = ""; ////////////////////// SOLUTION SOLUTION SOLUTION ////////////////////////////// Long INF = Long.MAX_VALUE; int MODULO = 1000_000_000 + 7; int MAX_VALUE = 1000_1000; int[][] steps = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}}; private final static Random rnd = new Random(); double eps = 1e-1; ArrayList<Integer>[] graph; int[] distFromRoot; int[] distFromX; int[] maxDistFromRoot; boolean[] used; int ans = -1; void solve() throws IOException { int n = readInt(); long t = readLong(); int[] arr = readIntArray(n); long[] prefSum = new long[n+2]; for (int i=2; i<=n+1; ++i) prefSum[i] = prefSum[i-1] + arr[i-2]; SegmentTree sgt = new SegmentTree(prefSum, n+1); long ans = 0; for (int i=2; i<=n+1; ++i){ ans += sgt.get(1, 1, n+1, 1, i-1, prefSum[i] - t); } out.println(ans); } class SegmentTree { long[][] t; SegmentTree(long[] b, int n) { t = new long[n * 4][]; build(b, 1, 1, n); } void build(long[] b, int v, int tl, int tr) { if (tl > tr) return; if (tl == tr) { t[v] = new long[1]; t[v][0] = b[tl]; return; } int tm = (tl + tr) / 2; build(b, 2 * v, tl, tm); build(b, 2 * v + 1, tm + 1, tr); t[v] = new long[tr - tl + 1]; for (int i = tl; i <= tr; ++i) t[v][i - tl] = i <= tm ? t[2 * v][i - tl] : t[2 * v + 1][i - tm - 1]; Arrays.sort(t[v]); } long get(int v, int tl, int tr, int l, int r, long minLeft) { if (l > r) return 0; if (tl == l && tr == r) { int left = -1; int right = t[v].length; while (right - left > 1) { int mid = (right + left) / 2; if (t[v][mid] <= minLeft) left = mid; else right = mid; } return t[v].length - left - 1; } int tm = (tl + tr) / 2; return get(2 * v, tl, tm, l, Math.min(tm, r), minLeft) + get(2 * v + 1, tm + 1, tr, Math.max(l, tm + 1), r, minLeft); } } long binPow(long a, long b, long m) { if (b == 0) { return 1; } if (b % 2 == 1) { return ((a % m) * (binPow(a, b - 1, m) % m)) % m; } else { long c = binPow(a, b / 2, m); return (c * c) % m; } } class Fenwik { int[] t; int n; Fenwik(int n){ t = new int[n]; this.n = n; } void inc(int r, int delta){ for (; r < n; r = r | (r + 1)) t[r] += delta; } int getSum(int r){ int res = 0; for (; r >=0; r = (r & (r + 1) ) - 1) res += t[r]; return res; } } boolean isPrime(int n){ for (int i=2; i*i<=n; ++i){ if (n%i==0) return false; } return true; } class Edge{ int from, to; long dist; public Edge(int to, long dist) { this.to = to; this.dist = dist; } } class Number implements Comparable<Number>{ int x, cost; Number(int x, int cost){ this.x = x; this.cost = cost; } @Override public int compareTo(Number o) { return Integer.compare(this.cost, o.cost); } } /////////////////////////////////////////////////////////////////////////////////////////// class Dsu{ int[] parent; int countSets; Dsu(int n){ parent = new int[n]; countSets = n; for (int i=0; i<n; ++i){ parent[i] = i; } } int findSet(int a){ if (a == parent[a]) return a; parent[a] = findSet(parent[a]); return parent[a]; } void unionSets(int a, int b){ a = findSet(a); b = findSet(b); if (a != b){ parent[a] = b; countSets--; } } } class SparseTable{ int[][] rmq; int[] logTable; int n; SparseTable(int[] a){ n = a.length; logTable = new int[n+1]; for(int i = 2; i <= n; ++i){ logTable[i] = logTable[i >> 1] + 1; } rmq = new int[logTable[n] + 1][n]; for(int i=0; i<n; ++i){ rmq[0][i] = a[i]; } for(int k=1; (1 << k) < n; ++k){ for(int i=0; i + (1 << k) <= n; ++i){ int max1 = rmq[k - 1][i]; int max2 = rmq[k-1][i + (1 << (k-1))]; rmq[k][i] = Math.max(max1, max2); } } } int max(int l, int r){ int k = logTable[r - l]; int max1 = rmq[k][l]; int max2 = rmq[k][r - (1 << k) + 1]; return Math.max(max1, max2); } } long checkBit(long mask, int bit){ return (mask >> bit) & 1; } static int checkBit(int mask, int bit) { return (mask >> bit) & 1; } boolean isLower(char c){ return c >= 'a' && c <= 'z'; } //////////////////////////////////////////////////////////// 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); } double binPow(double a, int pow){ if (pow == 0) return 1; if (pow % 2 == 1) { return a * binPow(a, pow - 1); } else { double c = binPow(a, pow / 2); return c * c; } } int minInt(int... values) { int min = Integer.MAX_VALUE; for (int value : values) min = Math.min(min, value); return min; } int maxInt(int... values) { int max = Integer.MIN_VALUE; for (int value : values) max = Math.max(max, value); return max; } public static void main(String[] args) throws NumberFormatException, IOException { // TODO Auto-generated method stub new Main().run(); } void run() throws NumberFormatException, IOException { solve(); out.close(); }; BufferedReader in; PrintWriter out; StringTokenizer tok; String delim = " "; Main() throws FileNotFoundException { try { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } catch (Exception e) { if (fileName.isEmpty()) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader(fileName + ".in")); out = new PrintWriter(fileName + ".out"); } } tok = new StringTokenizer(""); } String readLine() throws IOException { return in.readLine(); } String readString() throws IOException { while (!tok.hasMoreTokens()) { String nextLine = readLine(); if (null == nextLine) { return null; } tok = new StringTokenizer(nextLine); } return tok.nextToken(); } int readInt() throws NumberFormatException, IOException { return Integer.parseInt(readString()); } byte readByte() throws NumberFormatException, IOException { return Byte.parseByte(readString()); } int[] readIntArray (int n) throws NumberFormatException, IOException { int[] a = new int[n]; for(int i=0; i<n; ++i){ a[i] = readInt(); } return a; } Integer[] readIntegerArray (int n) throws NumberFormatException, IOException { Integer[] a = new Integer[n]; for(int i=0; i<n; ++i){ a[i] = readInt(); } return a; } long readLong() throws NumberFormatException, IOException { return Long.parseLong(readString()); } double readDouble() throws NumberFormatException, IOException { return Double.parseDouble(readString()); } }
Java
["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"]
2 seconds
["5", "4", "3"]
NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$
Java 8
standard input
[ "data structures", "two pointers", "divide and conquer" ]
42c4adc1c4a10cc619c05a842e186e60
The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements.
1,800
Print the number of segments in Petya's array with the sum of elements less than $$$t$$$.
standard output
PASSED
d68b93a50c3d36a8735e7ff7e2a80f85
train_000.jsonl
1537171500
Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r &lt; t$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.TreeMap; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { long[] fenwick; public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); long t = in.nextLong(); long[] pref = new long[n + 1]; TreeMap<Long, Integer> getId = new TreeMap<>(); getId.put(0L, 1); for (int i = 1; i <= n; i++) { pref[i] = pref[i - 1] + in.nextInt(); getId.put(pref[i], i); } int id = 2; for (long i : getId.keySet()) { getId.put(i, id); id++; } fenwick = new long[n + 3]; long ans = 0; for (int i = n; i >= 0; i--) { Long nextPref = getId.lowerKey(pref[i] + t); if (nextPref != null) { int nextPrefId = getId.get(nextPref); ans += get(nextPrefId); } set(getId.get(pref[i])); } out.println(ans); } long get(int val) { long res = 0; for (int i = val; i > 0; i -= Integer.lowestOneBit(i)) { res += fenwick[i]; } return res; } void set(int val) { for (int i = val; i < fenwick.length; i += Integer.lowestOneBit(i)) { fenwick[i]++; } } } static class InputReader { private BufferedReader reader; private StringTokenizer stt; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { return null; } } public String next() { while (stt == null || !stt.hasMoreTokens()) { stt = new StringTokenizer(nextLine()); } return stt.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"]
2 seconds
["5", "4", "3"]
NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$
Java 8
standard input
[ "data structures", "two pointers", "divide and conquer" ]
42c4adc1c4a10cc619c05a842e186e60
The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements.
1,800
Print the number of segments in Petya's array with the sum of elements less than $$$t$$$.
standard output
PASSED
187a847edb146007703156e65ef9f949
train_000.jsonl
1537171500
Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r &lt; t$$$.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class d1042 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int N = in.nextInt(); long T = in.nextLong(); long[] arr = new long[N]; for(int n=0;n<N;n++) arr[n] = in.nextLong(); long[] sum = new long[N+1]; for(int n=0;n<N;n++){ sum[n+1] = sum[n] + arr[n]; } // System.out.println(Arrays.toString(sum)); WLT wlt = new WLT(sum); long ret = 0; for(int n=0;n<N;n++){ long add = wlt.numValsBtwn(sum[n+1] + 1 - T, Long.MAX_VALUE, 0, n+1); // System.out.println(add); ret += add; } System.out.println(ret); } static class WLT{ WLT left = null, right = null; long arr[], min = Long.MAX_VALUE, max = Long.MIN_VALUE; int sPtr[] = null, N; WLT(long[] arr){ this.arr = arr; N = arr.length; for(long l : arr){ min = Math.min(min, l); max = Math.max(max, l); } if(min == max) return; long half = min + (max - min) / 2; sPtr = new int[N+1]; for(int n=0;n<N;n++){ sPtr[n+1] = sPtr[n]; if(arr[n] <= half) sPtr[n+1]++; } // System.out.println(Arrays.toString(sPtr)); long[] l = new long[sPtr[N]]; long[] r = new long[N - sPtr[N]]; for(int n=0;n<N;n++){ if(arr[n] <= half){ l[sPtr[n]] = arr[n]; } else{ r[n - sPtr[n]] = arr[n]; } } left = new WLT(l); right = new WLT(r); } long numValsBtwn(long sm, long bi, int le, int ri){ if(bi < min || max < sm) return 0; if(sm <= min && max <= bi){ // System.out.println(Arrays.toString(arr)+" "+le+" "+ri); return ri - le; } long llll = left.numValsBtwn(sm, bi, sPtr[le], sPtr[ri]); long rrrr = right.numValsBtwn(sm, bi, le - sPtr[le], ri - sPtr[ri]); return llll + rrrr; } } }
Java
["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"]
2 seconds
["5", "4", "3"]
NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$
Java 8
standard input
[ "data structures", "two pointers", "divide and conquer" ]
42c4adc1c4a10cc619c05a842e186e60
The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements.
1,800
Print the number of segments in Petya's array with the sum of elements less than $$$t$$$.
standard output
PASSED
136804384442054447d7a4ac0db857d9
train_000.jsonl
1537171500
Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r &lt; t$$$.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.stream.Stream; /** * @author madi.sagimbekov */ public class C1042D { private static BufferedReader in; private static BufferedWriter out; private static long[] tree; public static void main(String[] args) throws IOException { open(); long[] x = readLongs(); int n = (int)x[0]; long t = x[1]; long[] a = readLongs(); long[] sum = new long[n + 1]; long[] sumt = new long[n + 1]; long[] all = new long[2 * n + 2]; sum[0] = 0; sumt[0] = t; all[0] = sum[0]; all[1] = sumt[0]; for (int i = 0; i < n; i++) { sum[i + 1] = sum[i] + a[i]; sumt[i + 1] = sum[i + 1] + t; all[2 * i + 2] = sum[i + 1]; all[2 * i + 3] = sumt[i + 1]; } Arrays.sort(all); Map<Long, Integer> map = new HashMap<>(); int index = 0; long last = all[0]; map.put(last, index); for (int i = 1; i < 2 *n + 2; i++) { if (all[i] != last) { index++; map.put(all[i], index); last = all[i]; } } int len = index + 1; tree = new long[4 * len]; long cnt = 0; for (int i = 0; i < n; i++) { int ind = map.get(sumt[i]); addToRange(1, 0, len - 1, 0, ind - 1, 1); int ind2 = map.get(sum[i + 1]); cnt += getAfterAddingToRange(1, 0, len - 1, ind2); } out.write(cnt + "\n"); close(); } private static void addToRange(int v, int start, int end, int left, int right, int val) { if (left > right) { return; } if (left == start && right == end) { tree[v] += val; } else { int mid = start + ((end - start) >> 1); int ch = (v << 1); addToRange(ch, start, mid, left, Math.min(mid, right), val); addToRange(ch + 1, mid + 1, end, Math.max(mid + 1, left), right, val); } } private static long getAfterAddingToRange(int v, int start, int end, int pos) { if (start == end) { return tree[v]; } int mid = start + ((end - start) >> 1); int ch = (v << 1); if (pos <= mid) { return tree[v] + getAfterAddingToRange(ch, start, mid, pos); } else { return tree[v] + getAfterAddingToRange(ch + 1, mid + 1, end, pos); } } private static int[] readInts() throws IOException { return Stream.of(in.readLine().split(" ")).mapToInt(Integer::parseInt).toArray(); } private static int readInt() throws IOException { return Integer.parseInt(in.readLine()); } private static long[] readLongs() throws IOException { return Stream.of(in.readLine().split(" ")).mapToLong(Long::parseLong).toArray(); } private static long readLong() throws IOException { return Long.parseLong(in.readLine()); } private static double[] readDoubles() throws IOException { return Stream.of(in.readLine().split(" ")).mapToDouble(Double::parseDouble).toArray(); } private static double readDouble() throws IOException { return Double.parseDouble(in.readLine()); } private static String readString() throws IOException { return in.readLine(); } private static void open() { in = new BufferedReader(new InputStreamReader(System.in)); out = new BufferedWriter(new OutputStreamWriter((System.out))); } private static void close() throws IOException { out.flush(); out.close(); in.close(); } }
Java
["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"]
2 seconds
["5", "4", "3"]
NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$
Java 8
standard input
[ "data structures", "two pointers", "divide and conquer" ]
42c4adc1c4a10cc619c05a842e186e60
The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements.
1,800
Print the number of segments in Petya's array with the sum of elements less than $$$t$$$.
standard output
PASSED
203d8742f540f1e5babad68a3763a159
train_000.jsonl
1537171500
Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r &lt; t$$$.
256 megabytes
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ import java.io.*; import java.util.*; public class D1042 { static int tree[]; public static void main(String args[])throws IOException { Reader sc=new Reader(); int n=sc.nextInt(); long limit=sc.nextLong(); int a[]=new int[n+1]; for(int i=1;i<=n;i++) { a[i]=sc.nextInt(); } TreeSet<Long> set=new TreeSet<>(); HashMap<Long,Integer> map=new HashMap<>(); long sum=0; for(int i=0;i<=n;i++) { sum+=a[i]; set.add(sum); } int c=1; for(long x:set) { map.put(x,c); c++; } int size=c-1; set=new TreeSet<>();sum=0; tree=new int[size<<2]; update(1,size,1,map.get(0L)); long res=0;set.add(0L); for(int i=1;i<=n;i++) { sum+=a[i]; long req=sum-limit; if(set.higher(req)!=null) { long xx=set.higher(req); int pos=map.get(xx); res+=query(1,size,1,pos,size); } set.add(sum); update(1,size,1,map.get(sum)); } System.out.println(res); } static int query(int st,int end,int node,int l,int r) { if(st>end || r<st || l>end) return 0; if(st>=l && end<=r) return tree[node]; int mid=(st+end)/2; return query(st,mid,node*2,l,r)+query(mid+1,end,node*2 +1,l,r); } static void update(int st,int end,int node,int ind) { if(st==end) { tree[node]++; return; } int mid=(st+end)/2; if(ind>=st && ind<=mid) update(st,mid,node*2,ind); else update(mid+1,end,node*2 +1,ind); tree[node]=tree[node*2]+tree[node*2 +1]; } } class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte [] buffer; private int bufferPointer, bytesRead; public Reader () { din = new DataInputStream (System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader (String file_name) throws IOException { din = new DataInputStream (new FileInputStream (file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine () throws IOException { byte [] buf = new byte[1024]; int cnt = 0, c; while ((c = read ()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String (buf, 0, cnt); } public int nextInt () throws IOException { int ret = 0; byte c = read (); while (c <= ' ') c = read (); boolean neg = (c == '-'); if (neg) c = read (); do { ret = ret * 10 + c - '0'; } while ((c = read ()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong () throws IOException { long ret = 0; byte c = read (); while (c <= ' ') c = read (); boolean neg = (c == '-'); if (neg) c = read (); do { ret = ret * 10 + c - '0'; } while ((c = read ()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble () throws IOException { double ret = 0, div = 1; byte c = read (); while (c <= ' ') c = read (); boolean neg = (c == '-'); if (neg) c = read (); do { ret = ret * 10 + c - '0'; } while ((c = read ()) >= '0' && c <= '9'); if (c == '.') while ((c = read ()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10); if (neg) return -ret; return ret; } private void fillBuffer () throws IOException { bytesRead = din.read (buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read () throws IOException { if (bufferPointer == bytesRead) fillBuffer (); return buffer[bufferPointer++]; } public void close () throws IOException { if (din == null) return; din.close (); } }
Java
["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"]
2 seconds
["5", "4", "3"]
NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$
Java 8
standard input
[ "data structures", "two pointers", "divide and conquer" ]
42c4adc1c4a10cc619c05a842e186e60
The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements.
1,800
Print the number of segments in Petya's array with the sum of elements less than $$$t$$$.
standard output
PASSED
26687a005c638e6fb902c75c46b98d1b
train_000.jsonl
1537171500
Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r &lt; t$$$.
256 megabytes
import java.io.*; import java.util.*; import java.util.stream.*; public class Main { public static void main(String[] args) { IO io = new IO(System.in, System.out); int n = io.nextInt(); long t = io.nextLong(); long ans = 0; long sum = 0; SplayTree st = new SplayTree(); st.insert(0); while (n-- > 0) { sum += io.nextInt(); ans += st.query(sum - t); st.insert(sum); } io.out.println(ans); io.out.flush(); System.exit(0); } public static class SplayTree { Node root; Node L, R; public SplayTree() { L = R = root = null; } Node rot(Node c) { Node p = c.p; Node g = p.p; if (g != null) { if (g.l == p) g.l = c; else g.r = c; } if (p.l == c) { p.l = c.r; if (null != p.l) p.l.p = p; c.r = p; } else { p.r = c.l; if (null != p.r) p.r.p = p; c.l = p; } p.p = c; c.p = g; p.update(); return c.update(); } Node splay(Node c) { while (null != c.p) { Node p = c.p; Node g = p.p; if (null != g && (g.l == p) == (p.l == c)) rot(p); rot(c); } return c.update(); } // count > x int query(long x) { Node p = root; int cnt = 0; Node last = p; Node lastValid = null; while (null != p) { last = p; if (x < p.x) { cnt += p.s - (null != p.l ? p.l.s : 0); p = p.l; } else { lastValid = p; p = p.r; } } if (null != lastValid) last = lastValid; if (null != last) splay(last); root = last; return cnt; } void split(Node p, long x) { Node last = p; Node lastValid = null; while (null != p) { last = p; if (x < p.x) { p = p.l; } else { lastValid = p; p = p.r; } } ; if (null != lastValid) { splay(lastValid); L = lastValid; R = L.r; if (null != R) R.p = null; L.r = null; L.update(); } else if (null != last) { splay(last); L = null; R = last; } else { L = R = null; } } Node join(Node l, Node r) { if (null == l) return r; if (null == r) return l; while (null != l.r) l = l.r; splay(l); l.r = r; r.p = l; return l.update(); } void insert(long x) { split(root, x); root = join(L, join(new Node(x), R)); } class Node { long x; int s; Node l; Node r; Node p; Node() { s = 1; l = r = p = null; } Node(long v) { this(); x = v; } Node update() { s = 1; if (null != l) s += l.s; if (null != r) s += r.s; return this; } } } public static class IO { PrintWriter out; BufferedReader in; StringTokenizer tokens; public IO(InputStream is, OutputStream os) { in = new BufferedReader(new InputStreamReader(is)); out = new PrintWriter(os); tokens = new StringTokenizer(""); } public String next() { try { if (!tokens.hasMoreTokens()) tokens = new StringTokenizer(in.readLine()); } catch (IOException ioe) { ioe.printStackTrace(); } return tokens.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"]
2 seconds
["5", "4", "3"]
NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$
Java 8
standard input
[ "data structures", "two pointers", "divide and conquer" ]
42c4adc1c4a10cc619c05a842e186e60
The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements.
1,800
Print the number of segments in Petya's array with the sum of elements less than $$$t$$$.
standard output
PASSED
a70e534dc0dde1dc5b74e8918f61acaf
train_000.jsonl
1537171500
Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r &lt; t$$$.
256 megabytes
import java.io.*; import java.util.*; import java.util.stream.*; public class Main { static long ans = 0; public static void main(String[] args) { IO io = new IO(System.in, System.out); int n = io.nextInt(); long t = io.nextLong(); SplayTree st = new SplayTree(); st.insert(0); LongStream.range(0, n) .map(x -> io.nextInt()) .reduce(0, (x, y) -> { long z = x + y; ans += st.query(z - t); st.insert(z); return z; }); io.out.println(ans); io.out.flush(); } public static class SplayTree { Node root; Node L, R; public SplayTree() { L = R = root = null; } Node rot(Node c) { Node p = c.p; Node g = p.p; if (g != null) { if (g.l == p) g.l = c; else g.r = c; } if (p.l == c) { p.l = c.r; if (null != p.l) p.l.p = p; c.r = p; } else { p.r = c.l; if (null != p.r) p.r.p = p; c.l = p; } p.p = c; c.p = g; p.update(); return c.update(); } Node splay(Node c) { while (null != c.p) { Node p = c.p; Node g = p.p; if (null != g && (g.l == p) == (p.l == c)) rot(p); rot(c); } return c.update(); } // count > x int query(long x) { Node p = root; int cnt = 0; Node last = p; Node lastValid = null; while (null != p) { last = p; if (x < p.x) { cnt += p.s - (null != p.l ? p.l.s : 0); p = p.l; } else { lastValid = p; p = p.r; } } if (null != lastValid) last = lastValid; if (null != last) splay(last); root = last; return cnt; } void split(Node p, long x) { Node last = p; Node lastValid = null; while (null != p) { last = p; if (x < p.x) { p = p.l; } else { lastValid = p; p = p.r; } } ; if (null != lastValid) { splay(lastValid); L = lastValid; R = L.r; if (null != R) R.p = null; L.r = null; L.update(); } else if (null != last) { splay(last); L = null; R = last; } else { L = R = null; } } Node join(Node l, Node r) { if (null == l) return r; if (null == r) return l; while (null != l.r) l = l.r; splay(l); l.r = r; r.p = l; return l.update(); } void insert(long x) { split(root, x); root = join(L, join(new Node(x), R)); } class Node { long x; int s; Node l; Node r; Node p; Node() { s = 1; l = r = p = null; } Node(long v) { this(); x = v; } Node update() { s = 1; if (null != l) s += l.s; if (null != r) s += r.s; return this; } } } public static class IO { PrintWriter out; BufferedReader in; StringTokenizer tokens; public IO(InputStream is, OutputStream os) { in = new BufferedReader(new InputStreamReader(is)); out = new PrintWriter(os); tokens = new StringTokenizer(""); } public String next() { try { if (!tokens.hasMoreTokens()) tokens = new StringTokenizer(in.readLine()); } catch (IOException ioe) { ioe.printStackTrace(); } return tokens.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"]
2 seconds
["5", "4", "3"]
NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$
Java 8
standard input
[ "data structures", "two pointers", "divide and conquer" ]
42c4adc1c4a10cc619c05a842e186e60
The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements.
1,800
Print the number of segments in Petya's array with the sum of elements less than $$$t$$$.
standard output
PASSED
1a2d41a6741d4de66bd065284f3c85b8
train_000.jsonl
1537171500
Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r &lt; t$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.TreeMap; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { void incr(long key, FenwickTree ft, TreeMap<Long, Integer> tm) { ft.add(tm.get(key), 1); } public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); long t = in.readLong(); int[] a = IOUtils.readIntArray(in, n); TreeMap<Long, Integer> tm = new TreeMap<>(); tm.put(0L, -1); { long prefix = 0; for (int val : a) { prefix += val; tm.put(prefix, -1); } int counter = 0; for (long key : tm.keySet()) { tm.put(key, counter++); } } FenwickTree ft = new FenwickTree(tm.size()); incr(0, ft, tm); long prefix = 0; long res = 0; for (int val : a) { prefix += val; long minValid = prefix - t + 1; Long actualKey = tm.ceilingKey(minValid); if (actualKey != null) { int translated = tm.get(actualKey); res += ft.get(translated, tm.size() - 1); } incr(prefix, ft, tm); } out.printLine(res); } } static class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = in.readInt(); } return array; } } static class FenwickTree { private final long[] value; public FenwickTree(int size) { value = new long[size]; } public long get(int from, int to) { return get(to) - get(from - 1); } private long get(int to) { to = Math.min(to, value.length - 1); long result = 0; while (to >= 0) { result += value[to]; to = (to & (to + 1)) - 1; } return result; } public void add(int at, long value) { while (at < this.value.length) { this.value[at] += value; at = at | (at + 1); } } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void printLine(long i) { writer.println(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long readLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"]
2 seconds
["5", "4", "3"]
NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$
Java 8
standard input
[ "data structures", "two pointers", "divide and conquer" ]
42c4adc1c4a10cc619c05a842e186e60
The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements.
1,800
Print the number of segments in Petya's array with the sum of elements less than $$$t$$$.
standard output
PASSED
9a35d4d2520096901de8839eea694b3d
train_000.jsonl
1537171500
Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r &lt; t$$$.
256 megabytes
import java.util.*; public class PetyaAndArray { public static void main(String[] args) { Scanner scan=new Scanner(System.in);//damn im bad int n=scan.nextInt(); long t=scan.nextLong(); long[] a=new long[n]; Long[] sorted=new Long[n]; for(int i=0;i<n;i++) { a[i]=scan.nextLong(); if(i!=0) a[i]+=a[i-1]; sorted[i]=a[i]; } long res=0; TreeMap<Long,Integer> comp=new TreeMap<>(); Arrays.sort(sorted); //brute force r //and for every r: how many l such that 0<=l<=r and s[l]>s[r]-t for(int i=0;i<n;i++) { if(!comp.containsKey(sorted[i])) comp.put(sorted[i],comp.size()); } BIT b=new BIT(n+1); // System.out.println(comp); for(int r=0;r<n;r++) { long greater=a[r]-t; if(a[r]<t) res++; Long start=comp.higherKey(greater); if(start==null) { b.update(comp.get(a[r])+1,1); continue; } res+=b.sum(comp.get(start)+1,n); b.update(comp.get(a[r])+1,1); } System.out.println(res); } static class BIT { int n; int[] a; BIT(int n) { this.n=n; this.a=new int[n]; } void update(int i, int val) { while(i<n) { a[i]+=val; i+=i&-i; } } int sum(int i) { int res=0; while(i>0) { res+=a[i]; i-=i&-i; } return res; } int sum(int i, int j) { return sum(j)-sum(i-1); } } } /* 3 7 6 4 -4 */
Java
["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"]
2 seconds
["5", "4", "3"]
NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$
Java 8
standard input
[ "data structures", "two pointers", "divide and conquer" ]
42c4adc1c4a10cc619c05a842e186e60
The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements.
1,800
Print the number of segments in Petya's array with the sum of elements less than $$$t$$$.
standard output
PASSED
123ee985887a0616beeea4af4a0ca02f
train_000.jsonl
1537171500
Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r &lt; t$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.StringTokenizer; public class D { static final boolean debug=false; public static void main(String[] args) { FastScanner fs=new FastScanner(); int n=fs.nextInt(); long querySum=fs.nextLong(); int[] a=fs.readArray(n); long total=0; AVLTree tree=new AVLTree(); for (int nextNode=0; nextNode<n; nextNode++) { tree.addOffset(a[nextNode]); tree.add(a[nextNode]); int sumsInRange=tree.firstIndexOf(querySum); total+=sumsInRange; } System.out.println(total); } static class AVLTree { //added: 0, -5, -4, -7, -11 // AVLNode root; long offset; public void addOffset(long offset) { this.offset+=offset; } public void add(long l) { l-=offset; if (root==null) root=new AVLNode(l); else root=root.add(l); } public int firstIndexOf(long l) { l-=offset; if (root==null) return 0; return root.firstIndexOf(l); } } static class AVLNode { AVLNode lChild, rChild; long value; int height; int size; public AVLNode(long value) { height=1; this.value=value; size=1; } public AVLNode add(long v) { AVLNode toReturn=this; if (v<=value) { if (lChild==null) { lChild=new AVLNode(v); size++; } else { lChild=lChild.add(v); toReturn=balance(); } } else { if (rChild==null) { rChild=new AVLNode(v); size++; } else { rChild=rChild.add(v); toReturn=balance(); } } height=Math.max(lHeight(), rHeight())+1; size=lSize()+rSize()+1; return toReturn; } public AVLNode balance() { if (lChild==null&&rChild==null) { height=1; return this; } if (Math.abs(lHeight()-rHeight())>1) { if (lHeight()>rHeight()) { if (lChild.rHeight()>lChild.lHeight()) lChild=lChild.leftRot(); return rightRot(); } else { if (rChild.lHeight()>rChild.rHeight()) rChild=rChild.rightRot(); return leftRot(); } } return this; } public AVLNode leftRot() { // A -> C // B C A E // D E B D F // F AVLNode oldRight=rChild; rChild=rChild.lChild; oldRight.lChild=this; height=Math.max(lHeight(), rHeight())+1; oldRight.height=Math.max(oldRight.lHeight(), oldRight.rHeight())+1; size=lSize()+rSize()+1; oldRight.size=oldRight.lSize()+oldRight.rSize()+1; return oldRight; } public AVLNode rightRot() { AVLNode oldLeft=lChild; lChild=lChild.rChild; oldLeft.rChild=this; height=Math.max(lHeight(), rHeight())+1; oldLeft.height=Math.max(oldLeft.lHeight(), oldLeft.rHeight())+1; size=lSize()+rSize()+1; oldLeft.size=oldLeft.lSize()+oldLeft.rSize()+1; return oldLeft; } int lHeight() { return lChild==null?0:lChild.height; } int rHeight() { return rChild==null?0:rChild.height; } int lSize() { return lChild==null?0:lChild.size; } int rSize() { return rChild==null?0:rChild.size; } //returns the index in this subtree where val would be placed if inserted //in a left-biased way public int firstIndexOf(long val) { if (val>value) { return (rChild==null?0:rChild.firstIndexOf(val))+lSize()+1; } else { return lChild==null?0:lChild.firstIndexOf(val); } } public String toString() { return "("+(lChild==null?"":lChild.toString())+") "+value+" ("+(rChild==null?"":rChild.toString())+")"; } } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); public String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } } }
Java
["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"]
2 seconds
["5", "4", "3"]
NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$
Java 8
standard input
[ "data structures", "two pointers", "divide and conquer" ]
42c4adc1c4a10cc619c05a842e186e60
The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements.
1,800
Print the number of segments in Petya's array with the sum of elements less than $$$t$$$.
standard output
PASSED
3f5a9b631583aee9e057920f5e52ebdb
train_000.jsonl
1537171500
Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r &lt; t$$$.
256 megabytes
/** * Date: 27 Sep, 2019 * Link: * * @author Prasad Chaudhari * @linkedIn: https://www.linkedin.com/in/prasad-chaudhari-841655a6/ * @git: https://github.com/Prasad-Chaudhari */ import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.Random; public class newProgram0 { public static void main(String[] args) throws IOException { // TODO code application logic here FastIO in = new FastIO(); int n = in.ni(); long t = in.nl(); long a[] = in.gla(n); long sum[] = new long[n + 1]; sum[1] = a[0]; for (int i = 2; i <= n; i++) { sum[i] = sum[i - 1] + a[i - 1]; } long ans = 0; Treap<Long> bst = new Treap<>(); for (int i = n; i >= 1; i--) { bst.add(sum[i]); ans += bst.getLessThan(t + sum[i - 1]); } System.out.println(ans); in.bw.flush(); } static class Treap<T extends Comparable<T>> { private class Node { Node left; Node right; int priority; T value; int size; public Node() { left = null; right = null; } } private Node root; private Random r; public Treap() { root = null; r = new Random(); } public void add(T d) { root = traverse(root, d); } public int getLessThan(T d) { Node curr = root; int less_than_number = 0; while (curr != null) { if (d.compareTo(curr.value) == 0) { if (curr.left != null) { less_than_number += curr.left.size; } return less_than_number; } else if (d.compareTo(curr.value) > 0) { if (curr.left != null) { less_than_number += curr.left.size + 1; } else { less_than_number++; } curr = curr.right; } else { curr = curr.left; } } return less_than_number; } public void inorder() { inorder_T(root); System.out.println(""); } private Node traverse(Node n, T d) { if (n == null) { n = new Node(); n.value = d; n.priority = r.nextInt(1000000000); n.size = 1; return n; } n.size = getSize(n.left) + getSize(n.right) + 1; if (d.compareTo(n.value) <= 0) { n.left = traverse(n.left, d); if (n.left.priority > n.priority) { n = rightRotate(n); } } else { n.right = traverse(n.right, d); if (n.right.priority > n.priority) { n = leftRotate(n); } } n.size = getSize(n.left) + getSize(n.right) + 1; return n; } private Node rightRotate(Node y) { Node x = y.left; Node t2 = x.right; x.right = y; y.left = t2; y.size = getSize(y.left) + getSize(y.right) + 1; x.size = getSize(x.left) + getSize(x.right) + 1; return x; } private Node leftRotate(Node x) { Node y = x.right; Node t2 = y.left; y.left = x; x.right = t2; y.size = getSize(y.left) + getSize(y.right) + 1; x.size = getSize(x.left) + getSize(x.right) + 1; return y; } private int getSize(Node n) { return n == null ? 0 : n.size; } private void inorder_T(Node root) { if (root != null) { inorder_T(root.left); System.out.print(root.value + " "); inorder_T(root.right); } } } static class FastIO { private final BufferedReader br; private final BufferedWriter bw; private String s[]; private int index; public FastIO() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); bw = new BufferedWriter(new OutputStreamWriter(System.out, "UTF-8")); s = br.readLine().split(" "); index = 0; } public int ni() throws IOException { return Integer.parseInt(nextToken()); } public double nd() throws IOException { return Double.parseDouble(nextToken()); } public long nl() throws IOException { return Long.parseLong(nextToken()); } public String next() throws IOException { return nextToken(); } public String nli() throws IOException { try { return br.readLine(); } catch (IOException ex) { } return null; } public int[] gia(int n) throws IOException { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = ni(); } return a; } public int[] gia(int n, int start, int end) throws IOException { validate(n, start, end); int a[] = new int[n]; for (int i = start; i < end; i++) { a[i] = ni(); } return a; } public double[] gda(int n) throws IOException { double a[] = new double[n]; for (int i = 0; i < n; i++) { a[i] = nd(); } return a; } public double[] gda(int n, int start, int end) throws IOException { validate(n, start, end); double a[] = new double[n]; for (int i = start; i < end; i++) { a[i] = nd(); } return a; } public long[] gla(int n) throws IOException { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = nl(); } return a; } public long[] gla(int n, int start, int end) throws IOException { validate(n, start, end); long a[] = new long[n]; for (int i = start; i < end; i++) { a[i] = nl(); } return a; } public int[][][] gwtree(int n) throws IOException { int m = n - 1; int adja[][] = new int[n + 1][]; int weight[][] = new int[n + 1][]; int from[] = new int[m]; int to[] = new int[m]; int count[] = new int[n + 1]; int cost[] = new int[n + 1]; for (int i = 0; i < m; i++) { from[i] = i + 1; to[i] = ni(); cost[i] = ni(); count[from[i]]++; count[to[i]]++; } for (int i = 0; i <= n; i++) { adja[i] = new int[count[i]]; weight[i] = new int[count[i]]; } for (int i = 0; i < m; i++) { adja[from[i]][count[from[i]] - 1] = to[i]; adja[to[i]][count[to[i]] - 1] = from[i]; weight[from[i]][count[from[i]] - 1] = cost[i]; weight[to[i]][count[to[i]] - 1] = cost[i]; count[from[i]]--; count[to[i]]--; } return new int[][][] { adja, weight }; } public int[][][] gwg(int n, int m) throws IOException { int adja[][] = new int[n + 1][]; int weight[][] = new int[n + 1][]; int from[] = new int[m]; int to[] = new int[m]; int count[] = new int[n + 1]; int cost[] = new int[n + 1]; for (int i = 0; i < m; i++) { from[i] = ni(); to[i] = ni(); cost[i] = ni(); count[from[i]]++; count[to[i]]++; } for (int i = 0; i <= n; i++) { adja[i] = new int[count[i]]; weight[i] = new int[count[i]]; } for (int i = 0; i < m; i++) { adja[from[i]][count[from[i]] - 1] = to[i]; adja[to[i]][count[to[i]] - 1] = from[i]; weight[from[i]][count[from[i]] - 1] = cost[i]; weight[to[i]][count[to[i]] - 1] = cost[i]; count[from[i]]--; count[to[i]]--; } return new int[][][] { adja, weight }; } public int[][] gtree(int n) throws IOException { int adja[][] = new int[n + 1][]; int from[] = new int[n - 1]; int to[] = new int[n - 1]; int count[] = new int[n + 1]; for (int i = 0; i < n - 1; i++) { from[i] = i + 1; to[i] = ni(); count[from[i]]++; count[to[i]]++; } for (int i = 0; i <= n; i++) { adja[i] = new int[count[i]]; } for (int i = 0; i < n - 1; i++) { adja[from[i]][--count[from[i]]] = to[i]; adja[to[i]][--count[to[i]]] = from[i]; } return adja; } public int[][] gg(int n, int m) throws IOException { int adja[][] = new int[n + 1][]; int from[] = new int[m]; int to[] = new int[m]; int count[] = new int[n + 1]; for (int i = 0; i < m; i++) { from[i] = ni(); to[i] = ni(); count[from[i]]++; count[to[i]]++; } for (int i = 0; i <= n; i++) { adja[i] = new int[count[i]]; } for (int i = 0; i < m; i++) { adja[from[i]][--count[from[i]]] = to[i]; adja[to[i]][--count[to[i]]] = from[i]; } return adja; } public void print(String s) throws IOException { bw.write(s); } public void println(String s) throws IOException { bw.write(s); bw.newLine(); } public void print(int s) throws IOException { bw.write(s + ""); } public void println(int s) throws IOException { bw.write(s + ""); bw.newLine(); } public void print(long s) throws IOException { bw.write(s + ""); } public void println(long s) throws IOException { bw.write(s + ""); bw.newLine(); } public void print(double s) throws IOException { bw.write(s + ""); } public void println(double s) throws IOException { bw.write(s + ""); bw.newLine(); } private String nextToken() throws IndexOutOfBoundsException, IOException { if (index == s.length) { s = br.readLine().split(" "); index = 0; } return s[index++]; } private void validate(int n, int start, int end) { if (start < 0 || end >= n) { throw new IllegalArgumentException(); } } } }
Java
["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"]
2 seconds
["5", "4", "3"]
NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$
Java 8
standard input
[ "data structures", "two pointers", "divide and conquer" ]
42c4adc1c4a10cc619c05a842e186e60
The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements.
1,800
Print the number of segments in Petya's array with the sum of elements less than $$$t$$$.
standard output
PASSED
3244faceb82cded44bdb8a6b558f3f22
train_000.jsonl
1537171500
Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r &lt; t$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Random; import java.util.StringTokenizer; public class Main implements Runnable { int sz[]; int id[]; List<Integer> edges[]; long tree[]; private void solve() throws IOException { int n = nextInt(); long t = nextLong(); long a[] = new long[n + 1]; List<long[]> l = new ArrayList<>(); l.add(new long[] { 0, 0, 0 }); int c[][] = new int[n + 1][2]; for (int i = 1; i <= n; ++i) { a[i] = nextLong(); if (i > 0) a[i] += a[i - 1]; l.add(new long[] { a[i], i, 0 }); l.add(new long[] { a[i] - t, i, 1 }); } Collections.sort(l, new Comparator<long[]>() { public int compare(long a[], long b[]) { return Long.compare(a[0], b[0]); } }); int j = 1; for (int i = 0; i < l.size(); ++i) { if (i > 0 && l.get(i)[0] != l.get(i - 1)[0]) { ++j; } c[(int) l.get(i)[1]][(int) l.get(i)[2]] = j; } tree = new long[j + 1]; long ans = 0; for (int i = 1; i <= n; ++i) { upd(c[i - 1][0], 1); ans += (i - get(c[i][1])); } pw.println(ans); } long get(int x) { long sum = 0; for (int i = x; i > 0; i -= i & -i) { sum += tree[i]; } return sum; } void upd(int p, long x) { for (int i = p; i < tree.length; i += i & -i) { tree[i] += x; } } void test() throws IOException { Random rnd = new Random(); for (int i = 0; i < 2; ++i) { int n = rnd.nextInt(30) + 1; int a[] = new int[n]; System.err.println(n); for (int j = 0; j < n; ++j) { a[j] = rnd.nextInt(2) + 1; System.err.print(a[j] + " "); } // solve(n, a); System.err.println(); } } BufferedReader br; StringTokenizer st; PrintWriter pw; public static void main(String args[]) { new Main().run(); } public void run() { try { br = new BufferedReader(new InputStreamReader(System.in), 32768); pw = new PrintWriter(System.out); st = null; solve(); pw.flush(); pw.close(); br.close(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } }
Java
["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"]
2 seconds
["5", "4", "3"]
NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$
Java 8
standard input
[ "data structures", "two pointers", "divide and conquer" ]
42c4adc1c4a10cc619c05a842e186e60
The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements.
1,800
Print the number of segments in Petya's array with the sum of elements less than $$$t$$$.
standard output
PASSED
19da331aec02d980c08f65ac49275755
train_000.jsonl
1537171500
Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r &lt; t$$$.
256 megabytes
import java.util.*; import java.io.*; public class Main { static long[] sorted; static Fenwick tree; public static void main(String[] args) { FastReader reader = new FastReader(); PrintWriter writer = new PrintWriter(System.out); int n = reader.nextInt()+1; long t = reader.nextLong(); long[] a = new long[n]; long[] sum = new long[n]; sorted = new long[n]; for (int i=1; i<n; i++) { a[i] = reader.nextLong(); sum[i] = sum[i-1] + a[i]; sorted[i] = sum[i]; } Arrays.sort(sorted); tree = new Fenwick(n); tree.update(binary(0)); long ans = 0; for (int i=1; i<n; i++) { int pos = binary(sum[i]-t); long temp = tree.getSum(n) - tree.getSum(pos); ans += temp; pos = binary(sum[i]); tree.update(pos); } writer.print(ans); writer.close(); } static int binary(long x) { int ans=-1; int start = 0; int end = sorted.length-1; while (start <= end) { int mid = (start+end)/2; if (sorted[mid] <= x) { ans = mid; start = mid+1; } else end = mid-1; } return ans+1; } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } 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; } } } class Fenwick { int n; long[] array; Fenwick(int n) { this.n = n+1; array = new long[this.n]; } void update(int x) { if (x==0) return; for (int i=x; i<n; i += (i & -i)) array[i]++; } long getSum(int x) { long sum=0; for (int i=x; i>0; i -= (i & -i)) sum += array[i]; return sum; } }
Java
["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"]
2 seconds
["5", "4", "3"]
NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$
Java 8
standard input
[ "data structures", "two pointers", "divide and conquer" ]
42c4adc1c4a10cc619c05a842e186e60
The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements.
1,800
Print the number of segments in Petya's array with the sum of elements less than $$$t$$$.
standard output
PASSED
faa72ad5eb15839245616ecd2d37d4f6
train_000.jsonl
1537171500
Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r &lt; t$$$.
256 megabytes
import java.io.*; import java.util.*; /** * Copyright © 2018 Chris. All rights reserved. * * @author Chris * 2018/7/9 15:33 * @see format */ public class D { private static BufferedReader br; private static StreamTokenizer st; private static PrintWriter pw; static int[] BT; static int lowbit(int x) { return x & (-x); } static void add(int x) { while (x < BT.length) { BT[x]++; x += lowbit(x); } } static int get(int x) { int s = 0; while (x > 0) { s += BT[x]; x -= lowbit(x); } return s; } private static void solve() throws IOException { String ss[] = nextSS(" "); int n = Integer.parseInt(ss[0]); long t = Long.parseLong(ss[1]); long sum[] = new long[n + 1]; long ans = 0; Map<Long, Integer> idx = new HashMap<>(); List<Long> data = new ArrayList<>(); data.add(-1L); for (int i = 1; i <= n; i++) { sum[i] = nextInt(); sum[i] += sum[i - 1]; data.add(sum[i] - 1); data.add(sum[i] - t); } data.sort(Comparator.naturalOrder()); int cur = 1; List<Long> avail = new ArrayList<>(); for (int i = 0; i < data.size(); i++) { if (!idx.containsKey(data.get(i))) { idx.put(data.get(i), cur++); avail.add(data.get(i)); } } BT = new int[cur + 1]; for (int i = n; i >= 1; i--) { add(idx.get(sum[i] - t)); ans += get(idx.get(sum[i - 1] - 1)); } pw.print(ans); } public static void main(String args[]) throws IOException { boolean oj = System.getProperty("ONLINE_JUDGE") != null; if (!oj) { System.setIn(new FileInputStream("in.txt")); // System.setOut(new PrintStream("out.txt")); } br = new BufferedReader(new InputStreamReader(System.in)); st = new StreamTokenizer(br); pw = new PrintWriter(new OutputStreamWriter(System.out)); st.ordinaryChar('\''); //指定单引号、双引号和注释符号是普通字符 st.ordinaryChar('\"'); st.ordinaryChar('/'); long t = System.currentTimeMillis(); solve(); if (!oj) { pw.println("[" + (System.currentTimeMillis() - t) + "ms]"); } pw.flush(); } private static int nextInt() throws IOException { st.nextToken(); return (int) st.nval; } private static long nextLong() throws IOException { st.nextToken(); return (long) st.nval; } private static double nextDouble() throws IOException { st.nextToken(); return st.nval; } private static String[] nextSS(String reg) throws IOException { return br.readLine().split(reg); } private static String nextLine() throws IOException { return br.readLine(); } }
Java
["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"]
2 seconds
["5", "4", "3"]
NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$
Java 8
standard input
[ "data structures", "two pointers", "divide and conquer" ]
42c4adc1c4a10cc619c05a842e186e60
The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements.
1,800
Print the number of segments in Petya's array with the sum of elements less than $$$t$$$.
standard output
PASSED
60ae14dbf85ffd95e967d5a17fd7a471
train_000.jsonl
1537171500
Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r &lt; t$$$.
256 megabytes
import java.io.InputStreamReader; import java.util.Arrays; import java.io.BufferedReader; import java.io.IOException; public class Main { final static int MAXN = 200010; static int n; static long K; final static long ranl = -200000000000000L, ranr = 200000000000000L; public static class node { node ls, rs; int v; node() { ls = rs = null; v = 0; } } public static node modify(node u, long l, long r, long tar) { if (u == null) u = new node(); if (l == r) { ++u.v; return u; } long mid = l + r >> 1; if (tar <= mid) u.ls = modify(u.ls, l, mid, tar); else u.rs = modify(u.rs, mid + 1, r, tar); u.v = 0; if (u.ls != null) u.v += u.ls.v; if (u.rs != null) u.v += u.rs.v; return u; } public static int query(node u, long l, long r, long L, long R) { if (u == null) return 0; if (L <= l && r <= R) return u.v; long mid = l + r >> 1; int res = 0; if (L <= mid) res += query(u.ls, l, mid, L, R); if (mid < R) res += query(u.rs, mid + 1, r, L, R); return res; } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String [] pt = br.readLine().split(" "); n = Integer.parseInt(pt[0]); K = Long.parseLong(pt[1]); pt = br.readLine().split(" "); long pre = 0, ans = 0; node rt = new node(); modify(rt, ranl, ranr, 0); for (int i = 0; i < n; ++i) { pre = pre + Integer.parseInt(pt[i]); long vt = pre - K + 1; if (vt < ranl) vt = ranl; ans += query(rt, ranl, ranr, vt, ranr); modify(rt, ranl, ranr, pre); // System.out.println(pre + " " + vt); } System.out.println(ans); } }
Java
["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"]
2 seconds
["5", "4", "3"]
NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$
Java 8
standard input
[ "data structures", "two pointers", "divide and conquer" ]
42c4adc1c4a10cc619c05a842e186e60
The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements.
1,800
Print the number of segments in Petya's array with the sum of elements less than $$$t$$$.
standard output
PASSED
8cd05d5b36180826d501c7871d70bf2c
train_000.jsonl
1537171500
Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r &lt; t$$$.
256 megabytes
/* * * @Author Ajudiya_13(Bhargav Girdharbhai Ajudiya) * Dhirubhai Ambani Institute of Information And Communication Technology * */ import java.util.*; import java.io.*; import java.lang.*; public class Code336 { static class SegmentTree { long st[][]; SegmentTree(long[] a,int n) { int x = (int)Math.ceil(Math.log(n)/Math.log(2)); int Max_Size = 2*(int)(Math.pow(2, x))-1; st= new long[Max_Size][]; constructSegTreeUtil(a,0,n-1,0); } int getMid(int start,int end) { return (start+end)/2; } void constructSegTreeUtil(long[] a,int ss,int se,int si) { st[si] = new long[se-ss+1]; if(ss==se) { st[si][0] = a[ss]; return; } int mid = getMid(ss, se); constructSegTreeUtil(a, ss, mid, 2*si+1); constructSegTreeUtil(a, mid+1, se, 2*si+2); merge(si,2*si+1,2*si+2); } void merge(int si,int left,int right) { int n = st[left].length; int m = st[right].length; int i = 0; int j = 0; int k = 0; while(i<n && j<m) { if(st[left][i]<=st[right][j]) { st[si][k] = st[left][i]; i++; } else { st[si][k] = st[right][j]; j++; } k++; } while(i<n) { st[si][k] = st[left][i]; i++; k++; } while(j<m) { st[si][k] = st[right][j]; j++; k++; } } long getSum(int n, int qs, int qe, long key) { if(qs<0 || qe>n-1 || qs>qe) return -1; return getSumUtil(0,n-1,qs,qe,0,key); } long getSumUtil(int ss, int se,int qs, int qe, int si,long key) { if(qs<=ss && qe>=se) return binarysearch(si,key); if(qs>se || qe<ss) return 0; int mid = getMid(ss, se); return getSumUtil(ss, mid, qs, qe, 2*si+1, key)+ getSumUtil(mid+1, se, qs, qe, 2*si+2, key); } long binarysearch(int si,long key) { int start = 0; int end = st[si].length-1; int ans = -1; while(start<=end) { int mid = (start+end)/2; if(st[si][mid]<key) { ans = mid; start = mid+1; } else end = mid -1; } return (ans+1); } } public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter pw = new PrintWriter(System.out); int n = in.nextInt(); long t = in.nextLong(); long[] a = new long[n]; for(int i=0;i<n;i++) a[i] = in.nextLong(); for(int i=1;i<n;i++) a[i] += a[i-1]; long ans = 0; SegmentTree st = new SegmentTree(a, n); for(int i=0;i<n;i++) { if(i==0) ans += st.getSum(n, i, n-1, t); else ans += st.getSum(n, i, n-1, t+a[i-1]); } pw.println(ans); pw.flush(); pw.close(); } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"]
2 seconds
["5", "4", "3"]
NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$
Java 8
standard input
[ "data structures", "two pointers", "divide and conquer" ]
42c4adc1c4a10cc619c05a842e186e60
The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements.
1,800
Print the number of segments in Petya's array with the sum of elements less than $$$t$$$.
standard output
PASSED
c5b964cebc15724d14a09453211474b3
train_000.jsonl
1537171500
Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r &lt; t$$$.
256 megabytes
//package baobab; import java.io.*; import java.util.*; public class D { public static void main(String[] args) { Solver solver = new Solver(); } static class Solver { IO io; public Solver() { this.io = new IO(); try { solve(); } finally { io.close(); } } /****************************** START READING HERE ********************************/ List<Long> sum; HashMap<Long, Integer> reverse; SegmentTree deletions; void solve() { int n = io.nextInt(); long t = io.nextLong(); long[] a = new long[n]; for (int i=0; i<n; i++) { a[i] = io.nextLong(); } sum = new ArrayList<>(n); sum.add(a[0]); for (int i=1; i<n; i++) { sum.add(sum.get(i-1) + a[i]); } Collections.sort(sum); reverse = new HashMap<>(); for (int i=n-1; i>=0; i--) { reverse.put(sum.get(i), i); } long ans = 0; long sumUpToPrev = 0; deletions = new SegmentTree(n, true, false, false); for (int start=0; start<n; start++) { long count = getCount(t+sumUpToPrev); ans += count; sumUpToPrev += a[start]; delete(sumUpToPrev); } io.println(ans); } long getCount(long threshold) { int min = 0; int max = sum.size()-1; while (min < max) { int guess = min + (max-min+1)/2; if (sum.get(guess) < threshold) { min = guess; } else { max = guess-1; } } if (min == 0 && sum.get(0) >= threshold) return 0; return (1 + min) - deletions.getSum(0, min); } void delete(long sumUpToPrev) { int indexForSum = reverse.get(sumUpToPrev); reverse.put(sumUpToPrev, indexForSum+1); // always correct when this key is queried in the future. incorrect when it's not queried. deletions.modifyRange(1, indexForSum, indexForSum); } /************************** UTILITY CODE BELOW THIS LINE **************************/ long MOD = (long)1e9 + 7; boolean closeToZero(double v) { // Check if double is close to zero, considering precision issues. return Math.abs(v) <= 0.0000000000001; } class DrawGrid { void draw(boolean[][] d) { System.out.print(" "); for (int x=0; x<d[0].length; x++) { System.out.print(" " + x + " "); } System.out.println(""); for (int y=0; y<d.length; y++) { System.out.print(y + " "); for (int x=0; x<d[0].length; x++) { System.out.print((d[y][x] ? "[x]" : "[ ]")); } System.out.println(""); } } void draw(int[][] d) { int max = 1; for (int y=0; y<d.length; y++) { for (int x=0; x<d[0].length; x++) { max = Math.max(max, ("" + d[y][x]).length()); } } System.out.print(" "); String format = "%" + (max+2) + "s"; for (int x=0; x<d[0].length; x++) { System.out.print(String.format(format, x) + " "); } format = "%" + (max) + "s"; System.out.println(""); for (int y=0; y<d.length; y++) { System.out.print(y + " "); for (int x=0; x<d[0].length; x++) { System.out.print(" [" + String.format(format, (d[y][x])) + "]"); } System.out.println(""); } } } class IDval implements Comparable<IDval> { int id; long val; public IDval(int id, long val) { this.val = val; this.id = id; } @Override public int compareTo(IDval o) { if (this.val < o.val) return -1; if (this.val > o.val) return 1; return this.id - o.id; } } private class ElementCounter { private HashMap<Long, Integer> elements; public ElementCounter() { elements = new HashMap<>(); } public void add(long element) { int count = 1; Integer prev = elements.get(element); if (prev != null) count += prev; elements.put(element, count); } public void remove(long element) { int count = elements.remove(element); count--; if (count > 0) elements.put(element, count); } public int get(long element) { Integer val = elements.get(element); if (val == null) return 0; return val; } public int size() { return elements.size(); } } class StringCounter { HashMap<String, Integer> elements; public StringCounter() { elements = new HashMap<>(); } public void add(String identifier) { int count = 1; Integer prev = elements.get(identifier); if (prev != null) count += prev; elements.put(identifier, count); } public void remove(String identifier) { int count = elements.remove(identifier); count--; if (count > 0) elements.put(identifier, count); } public long get(String identifier) { Integer val = elements.get(identifier); if (val == null) return 0; return val; } public int size() { return elements.size(); } } class DisjointSet { /** Union Find / Disjoint Set data structure. */ int[] size; int[] parent; int componentCount; public DisjointSet(int n) { componentCount = n; size = new int[n]; parent = new int[n]; for (int i=0; i<n; i++) parent[i] = i; for (int i=0; i<n; i++) size[i] = 1; } public void join(int a, int b) { /* Find roots */ int rootA = parent[a]; int rootB = parent[b]; while (rootA != parent[rootA]) rootA = parent[rootA]; while (rootB != parent[rootB]) rootB = parent[rootB]; if (rootA == rootB) { /* Already in the same set */ return; } /* Merge smaller set into larger set. */ if (size[rootA] > size[rootB]) { size[rootA] += size[rootB]; parent[rootB] = rootA; } else { size[rootB] += size[rootA]; parent[rootA] = rootB; } componentCount--; } } class Trie { int N; int Z; int nextFreeId; int[][] pointers; boolean[] end; /** maxLenSum = maximum possible sum of length of words */ public Trie(int maxLenSum, int alphabetSize) { this.N = maxLenSum; this.Z = alphabetSize; this.nextFreeId = 1; pointers = new int[N+1][alphabetSize]; end = new boolean[N+1]; } public void addWord(String word) { int curr = 0; for (int j=0; j<word.length(); j++) { int c = word.charAt(j) - 'a'; int next = pointers[curr][c]; if (next == 0) { next = nextFreeId++; pointers[curr][c] = next; } curr = next; } end[curr] = true; } public boolean hasWord(String word) { int curr = 0; for (int j=0; j<word.length(); j++) { int c = word.charAt(j) - 'a'; int next = pointers[curr][c]; if (next == 0) return false; curr = next; } return end[curr]; } } private static class Prob { /** For heavy calculations on probabilities, this class * provides more accuracy & efficiency than doubles. * Math explained: https://en.wikipedia.org/wiki/Log_probability * Quick start: * - Instantiate probabilities, eg. Prob a = new Prob(0.75) * - add(), multiply() return new objects, can perform on nulls & NaNs. * - get() returns probability as a readable double */ /** Logarithmized probability. Note: 0% represented by logP NaN. */ private double logP; /** Construct instance with real probability. */ public Prob(double real) { if (real > 0) this.logP = Math.log(real); else this.logP = Double.NaN; } /** Construct instance with already logarithmized value. */ static boolean dontLogAgain = true; public Prob(double logP, boolean anyBooleanHereToChooseThisConstructor) { this.logP = logP; } /** Returns real probability as a double. */ public double get() { return Math.exp(logP); } @Override public String toString() { return ""+get(); } /***************** STATIC METHODS BELOW ********************/ /** Note: returns NaN only when a && b are both NaN/null. */ public static Prob add(Prob a, Prob b) { if (nullOrNaN(a) && nullOrNaN(b)) return new Prob(Double.NaN, dontLogAgain); if (nullOrNaN(a)) return copy(b); if (nullOrNaN(b)) return copy(a); double x = Math.max(a.logP, b.logP); double y = Math.min(a.logP, b.logP); double sum = x + Math.log(1 + Math.exp(y - x)); return new Prob(sum, dontLogAgain); } /** Note: multiplying by null or NaN produces NaN (repping 0% real prob). */ public static Prob multiply(Prob a, Prob b) { if (nullOrNaN(a) || nullOrNaN(b)) return new Prob(Double.NaN, dontLogAgain); return new Prob(a.logP + b.logP, dontLogAgain); } /** Returns true if p is null or NaN. */ private static boolean nullOrNaN(Prob p) { return (p == null || Double.isNaN(p.logP)); } /** Returns a new instance with the same value as original. */ private static Prob copy(Prob original) { return new Prob(original.logP, dontLogAgain); } } class Binary implements Comparable<Binary> { /** * Use example: Binary b = new Binary(Long.toBinaryString(53249834L)); * * When manipulating small binary strings, instantiate new Binary(string) * When just reading large binary strings, instantiate new Binary(string,true) * get(int i) returns a character '1' or '0', not an int. */ private boolean[] d; private int first; // Starting from left, the first (most remarkable) '1' public int length; public Binary(String binaryString) { this(binaryString, false); } public Binary(String binaryString, boolean initWithMinArraySize) { length = binaryString.length(); int size = Math.max(2*length, 1); first = length/4; if (initWithMinArraySize) { first = 0; size = Math.max(length, 1); } d = new boolean[size]; for (int i=0; i<length; i++) { if (binaryString.charAt(i) == '1') d[i+first] = true; } } public void addFirst(char c) { if (first-1 < 0) doubleArraySize(); first--; d[first] = (c == '1' ? true : false); length++; } public void addLast(char c) { if (first+length >= d.length) doubleArraySize(); d[first+length] = (c == '1' ? true : false); length++; } private void doubleArraySize() { boolean[] bigArray = new boolean[(d.length+1) * 2]; int newFirst = bigArray.length / 4; for (int i=0; i<length; i++) { bigArray[i + newFirst] = d[i + first]; } first = newFirst; d = bigArray; } public boolean flip(int i) { boolean value = (this.d[first+i] ? false : true); this.d[first+i] = value; return value; } public void set(int i, char c) { boolean value = (c == '1' ? true : false); this.d[first+i] = value; } public char get(int i) { return (this.d[first+i] ? '1' : '0'); } @Override public int compareTo(Binary o) { if (this.length != o.length) return this.length - o.length; int len = this.length; for (int i=0; i<len; i++) { int diff = this.get(i) - o.get(i); if (diff != 0) return diff; } return 0; } @Override public String toString() { StringBuilder sb = new StringBuilder(); for (int i=0; i<length; i++) { sb.append(d[i+first] ? '1' : '0'); } return sb.toString(); } } /************************** Range queries **************************/ class FenwickMin { long n; long[] original; long[] bottomUp; long[] topDown; public FenwickMin(int n) { this.n = n; original = new long[n+2]; bottomUp = new long[n+2]; topDown = new long[n+2]; } public void set(int modifiedNode, long value) { long replaced = original[modifiedNode]; original[modifiedNode] = value; // Update left tree int i = modifiedNode; long v = value; while (i <= n) { if (v > bottomUp[i]) { if (replaced == bottomUp[i]) { v = Math.min(v, original[i]); for (int r=1 ;; r++) { int x = (i&-i)>>>r; if (x == 0) break; int child = i-x; v = Math.min(v, bottomUp[child]); } } else break; } if (v == bottomUp[i]) break; bottomUp[i] = v; i += (i&-i); } // Update right tree i = modifiedNode; v = value; while (i > 0) { if (v > topDown[i]) { if (replaced == topDown[i]) { v = Math.min(v, original[i]); for (int r=1 ;; r++) { int x = (i&-i)>>>r; if (x == 0) break; int child = i+x; if (child > n+1) break; v = Math.min(v, topDown[child]); } } else break; } if (v == topDown[i]) break; topDown[i] = v; i -= (i&-i); } } public long getMin(int a, int b) { long min = original[a]; int prev = a; int curr = prev + (prev&-prev); // parent right hand side while (curr <= b) { min = Math.min(min, topDown[prev]); // value from the other tree prev = curr; curr = prev + (prev&-prev);; } min = Math.min(min, original[prev]); prev = b; curr = prev - (prev&-prev); // parent left hand side while (curr >= a) { min = Math.min(min,bottomUp[prev]); // value from the other tree prev = curr; curr = prev - (prev&-prev); } return min; } } class FenwickSum { public long[] d; public FenwickSum(int n) { d=new long[n+1]; } /** a[0] must be unused. */ public FenwickSum(long[] a) { d=new long[a.length]; for (int i=1; i<a.length; i++) { modify(i, a[i]); } } /** Do not modify i=0. */ void modify(int i, long v) { while (i<d.length) { d[i] += v; // Move to next uplink on the RIGHT side of i i += (i&-i); } } /** Returns sum from a to b, *BOTH* inclusive. */ long getSum(int a, int b) { return getSum(b) - getSum(a-1); } private long getSum(int i) { long sum = 0; while (i>0) { sum += d[i]; // Move to next uplink on the LEFT side of i i -= (i&-i); } return sum; } } class SegmentTree { /* Provides log(n) operations for: * - Range query (sum, min or max) * - Range update ("+8 to all values between indexes 4 and 94") */ int N; long[] lazy; long[] sum; long[] min; long[] max; boolean supportSum; boolean supportMin; boolean supportMax; public SegmentTree(int n) { this(n, true, true, true); } public SegmentTree(int n, boolean supportSum, boolean supportMin, boolean supportMax) { for (N=2; N<n;) N*=2; this.lazy = new long[2*N]; this.supportSum = supportSum; this.supportMin = supportMin; this.supportMax = supportMax; if (this.supportSum) this.sum = new long[2*N]; if (this.supportMin) this.min = new long[2*N]; if (this.supportMax) this.max = new long[2*N]; } void modifyRange(long x, int a, int b) { modifyRec(a, b, 1, 0, N-1, x); } void setRange() { //TODO } long getSum(int a, int b) { return querySum(a, b, 1, 0, N-1); } long getMin(int a, int b) { return queryMin(a, b, 1, 0, N-1); } long getMax(int a, int b) { return queryMax(a, b, 1, 0, N-1); } private long querySum(int wantedLeft, int wantedRight, int i, int actualLeft, int actualRight) { if (wantedLeft > actualRight || wantedRight < actualLeft) { return 0; } if (wantedLeft == actualLeft && wantedRight == actualRight) { int count = wantedRight - wantedLeft + 1; return sum[i] + count * lazy[i]; } if (lazy[i] != 0) propagate(i, actualLeft, actualRight); int d = (actualRight - actualLeft + 1) / 2; long left = querySum(wantedLeft, min(actualLeft+d-1, wantedRight), 2*i, actualLeft, actualLeft+d-1); long right = querySum(max(actualLeft+d, wantedLeft), wantedRight, 2*i+1, actualLeft+d, actualRight); return left + right; } private long queryMin(int wantedLeft, int wantedRight, int i, int actualLeft, int actualRight) { if (wantedLeft > actualRight || wantedRight < actualLeft) { return 0; } if (wantedLeft == actualLeft && wantedRight == actualRight) { return min[i] + lazy[i]; } if (lazy[i] != 0) propagate(i, actualLeft, actualRight); int d = (actualRight - actualLeft + 1) / 2; long left = queryMin(wantedLeft, min(actualLeft+d-1, wantedRight), 2*i, actualLeft, actualLeft+d-1); long right = queryMin(max(actualLeft+d, wantedLeft), wantedRight, 2*i+1, actualLeft+d, actualRight); return min(left, right); } private long queryMax(int wantedLeft, int wantedRight, int i, int actualLeft, int actualRight) { if (wantedLeft > actualRight || wantedRight < actualLeft) { return 0; } if (wantedLeft == actualLeft && wantedRight == actualRight) { return max[i] + lazy[i]; } if (lazy[i] != 0) propagate(i, actualLeft, actualRight); int d = (actualRight - actualLeft + 1) / 2; long left = queryMax(wantedLeft, min(actualLeft+d-1, wantedRight), 2*i, actualLeft, actualLeft+d-1); long right = queryMax(max(actualLeft+d, wantedLeft), wantedRight, 2*i+1, actualLeft+d, actualRight); return max(left, right); } private void modifyRec(int wantedLeft, int wantedRight, int i, int actualLeft, int actualRight, long value) { if (wantedLeft > actualRight || wantedRight < actualLeft) { return; } if (wantedLeft == actualLeft && wantedRight == actualRight) { lazy[i] += value; return; } if (lazy[i] != 0) propagate(i, actualLeft, actualRight); int d = (actualRight - actualLeft + 1) / 2; modifyRec(wantedLeft, min(actualLeft+d-1, wantedRight), 2*i, actualLeft, actualLeft+d-1, value); modifyRec(max(actualLeft+d, wantedLeft), wantedRight, 2*i+1, actualLeft+d, actualRight, value); if (supportSum) sum[i] += value * (min(actualRight, wantedRight) - max(actualLeft, wantedLeft) + 1); if (supportMin) min[i] = min(min[2*i] + lazy[2*i], min[2*i+1] + lazy[2*i+1]); if (supportMax) max[i] = max(max[2*i] + lazy[2*i], max[2*i+1] + lazy[2*i+1]); } private void propagate(int i, int actualLeft, int actualRight) { lazy[2*i] += lazy[i]; lazy[2*i+1] += lazy[i]; if (supportSum) sum[i] += lazy[i] * (actualRight - actualLeft + 1); if (supportMin) min[i] += lazy[i]; if (supportMax) max[i] += lazy[i]; lazy[i] = 0; } } /***************************** Graphs *****************************/ List<Integer>[] toGraph(IO io, int n) { List<Integer>[] g = new ArrayList[n+1]; for (int i=1; i<=n; i++) g[i] = new ArrayList<>(); for (int i=1; i<=n-1; i++) { int a = io.nextInt(); int b = io.nextInt(); g[a].add(b); g[b].add(a); } return g; } class Graph { HashMap<Long, List<Long>> edges; public Graph() { edges = new HashMap<>(); } List<Long> getSetNeighbors(Long node) { List<Long> neighbors = edges.get(node); if (neighbors == null) { neighbors = new ArrayList<>(); edges.put(node, neighbors); } return neighbors; } void addBiEdge(Long a, Long b) { addEdge(a, b); addEdge(b, a); } void addEdge(Long from, Long to) { getSetNeighbors(to); // make sure all have initialized lists List<Long> neighbors = getSetNeighbors(from); neighbors.add(to); } // topoSort variables int UNTOUCHED = 0; int FINISHED = 2; int INPROGRESS = 1; HashMap<Long, Integer> vis; List<Long> topoAns; List<Long> failDueToCycle = new ArrayList<Long>() {{ add(-1L); }}; List<Long> topoSort() { topoAns = new ArrayList<>(); vis = new HashMap<>(); for (Long a : edges.keySet()) { if (!topoDFS(a)) return failDueToCycle; } Collections.reverse(topoAns); return topoAns; } boolean topoDFS(long curr) { Integer status = vis.get(curr); if (status == null) status = UNTOUCHED; if (status == FINISHED) return true; if (status == INPROGRESS) { return false; } vis.put(curr, INPROGRESS); for (long next : edges.get(curr)) { if (!topoDFS(next)) return false; } vis.put(curr, FINISHED); topoAns.add(curr); return true; } } public class StronglyConnectedComponents { /** Kosaraju's algorithm */ ArrayList<Integer>[] forw; ArrayList<Integer>[] bacw; /** Use: getCount(2, new int[] {1,2}, new int[] {2,1}) */ public int getCount(int n, int[] mista, int[] minne) { forw = new ArrayList[n+1]; bacw = new ArrayList[n+1]; for (int i=1; i<=n; i++) { forw[i] = new ArrayList<Integer>(); bacw[i] = new ArrayList<Integer>(); } for (int i=0; i<mista.length; i++) { int a = mista[i]; int b = minne[i]; forw[a].add(b); bacw[b].add(a); } int count = 0; List<Integer> list = new ArrayList<Integer>(); boolean[] visited = new boolean[n+1]; for (int i=1; i<=n; i++) { dfsForward(i, visited, list); } visited = new boolean[n+1]; for (int i=n-1; i>=0; i--) { int node = list.get(i); if (visited[node]) continue; count++; dfsBackward(node, visited); } return count; } public void dfsForward(int i, boolean[] visited, List<Integer> list) { if (visited[i]) return; visited[i] = true; for (int neighbor : forw[i]) { dfsForward(neighbor, visited, list); } list.add(i); } public void dfsBackward(int i, boolean[] visited) { if (visited[i]) return; visited[i] = true; for (int neighbor : bacw[i]) { dfsBackward(neighbor, visited); } } } class LCAFinder { /* O(n log n) Initialize: new LCAFinder(graph) * O(log n) Queries: find(a,b) returns lowest common ancestor for nodes a and b */ int[] nodes; int[] depths; int[] entries; int pointer; FenwickMin fenwick; public LCAFinder(List<Integer>[] graph) { this.nodes = new int[(int)10e6]; this.depths = new int[(int)10e6]; this.entries = new int[graph.length]; this.pointer = 1; boolean[] visited = new boolean[graph.length+1]; dfs(1, 0, graph, visited); fenwick = new FenwickMin(pointer-1); for (int i=1; i<pointer; i++) { fenwick.set(i, depths[i] * 1000000L + i); } } private void dfs(int node, int depth, List<Integer>[] graph, boolean[] visited) { visited[node] = true; entries[node] = pointer; nodes[pointer] = node; depths[pointer] = depth; pointer++; for (int neighbor : graph[node]) { if (visited[neighbor]) continue; dfs(neighbor, depth+1, graph, visited); nodes[pointer] = node; depths[pointer] = depth; pointer++; } } public int find(int a, int b) { int left = entries[a]; int right = entries[b]; if (left > right) { int temp = left; left = right; right = temp; } long mixedBag = fenwick.getMin(left, right); int index = (int) (mixedBag % 1000000L); return nodes[index]; } } /**************************** Geometry ****************************/ class Point { int y; int x; public Point(int y, int x) { this.y = y; this.x = x; } } boolean segmentsIntersect(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4) { // Returns true if segment 1-2 intersects segment 3-4 if (x1 == x2 && x3 == x4) { // Both segments are vertical if (x1 != x3) return false; if (min(y1,y2) < min(y3,y4)) { return max(y1,y2) >= min(y3,y4); } else { return max(y3,y4) >= min(y1,y2); } } if (x1 == x2) { // Only segment 1-2 is vertical. Does segment 3-4 cross it? y = a*x + b double a34 = (y4-y3)/(x4-x3); double b34 = y3 - a34*x3; double y = a34 * x1 + b34; return y >= min(y1,y2) && y <= max(y1,y2) && x1 >= min(x3,x4) && x1 <= max(x3,x4); } if (x3 == x4) { // Only segment 3-4 is vertical. Does segment 1-2 cross it? y = a*x + b double a12 = (y2-y1)/(x2-x1); double b12 = y1 - a12*x1; double y = a12 * x3 + b12; return y >= min(y3,y4) && y <= max(y3,y4) && x3 >= min(x1,x2) && x3 <= max(x1,x2); } double a12 = (y2-y1)/(x2-x1); double b12 = y1 - a12*x1; double a34 = (y4-y3)/(x4-x3); double b34 = y3 - a34*x3; if (closeToZero(a12 - a34)) { // Parallel lines return closeToZero(b12 - b34); } // Non parallel non vertical lines intersect at x. Is x part of both segments? double x = -(b12-b34)/(a12-a34); return x >= min(x1,x2) && x <= max(x1,x2) && x >= min(x3,x4) && x <= max(x3,x4); } boolean pointInsideRectangle(Point p, List<Point> r) { Point a = r.get(0); Point b = r.get(1); Point c = r.get(2); Point d = r.get(3); double apd = areaOfTriangle(a, p, d); double dpc = areaOfTriangle(d, p, c); double cpb = areaOfTriangle(c, p, b); double pba = areaOfTriangle(p, b, a); double sumOfAreas = apd + dpc + cpb + pba; if (closeToZero(sumOfAreas - areaOfRectangle(r))) { if (closeToZero(apd) || closeToZero(dpc) || closeToZero(cpb) || closeToZero(pba)) { return false; } return true; } return false; } double areaOfTriangle(Point a, Point b, Point c) { return 0.5 * Math.abs((a.x-c.x)*(b.y-a.y)-(a.x-b.x)*(c.y-a.y)); } double areaOfRectangle(List<Point> r) { double side1xDiff = r.get(0).x - r.get(1).x; double side1yDiff = r.get(0).y - r.get(1).y; double side2xDiff = r.get(1).x - r.get(2).x; double side2yDiff = r.get(1).y - r.get(2).y; double side1 = Math.sqrt(side1xDiff * side1xDiff + side1yDiff * side1yDiff); double side2 = Math.sqrt(side2xDiff * side2xDiff + side2yDiff * side2yDiff); return side1 * side2; } boolean pointsOnSameLine(double x1, double y1, double x2, double y2, double x3, double y3) { double areaTimes2 = x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2); return (closeToZero(areaTimes2)); } class PointToLineSegmentDistanceCalculator { // Just call this double minDistFromPointToLineSegment(double point_x, double point_y, double x1, double y1, double x2, double y2) { return Math.sqrt(distToSegmentSquared(point_x, point_y, x1, y1, x2, y2)); } private double distToSegmentSquared(double point_x, double point_y, double x1, double y1, double x2, double y2) { double l2 = dist2(x1,y1,x2,y2); if (l2 == 0) return dist2(point_x, point_y, x1, y1); double t = ((point_x - x1) * (x2 - x1) + (point_y - y1) * (y2 - y1)) / l2; if (t < 0) return dist2(point_x, point_y, x1, y1); if (t > 1) return dist2(point_x, point_y, x2, y2); double com_x = x1 + t * (x2 - x1); double com_y = y1 + t * (y2 - y1); return dist2(point_x, point_y, com_x, com_y); } private double dist2(double x1, double y1, double x2, double y2) { return Math.pow((x1 - x2), 2) + Math.pow((y1 - y2), 2); } } /****************************** Math ******************************/ long pow(long base, int exp) { if (exp == 0) return 1L; long x = pow(base, exp/2); long ans = x * x; if (exp % 2 != 0) ans *= base; return ans; } long gcd(long... v) { /** Chained calls to Euclidean algorithm. */ if (v.length == 1) return v[0]; long ans = gcd(v[1], v[0]); for (int i=2; i<v.length; i++) { ans = gcd(ans, v[i]); } return ans; } long gcd(long a, long b) { /** Euclidean algorithm. */ if (b == 0) return a; return gcd(b, a%b); } int[] generatePrimesUpTo(int last) { /* Sieve of Eratosthenes. Practically O(n). Values of 0 indicate primes. */ int[] div = new int[last+1]; for (int x=2; x<=last; x++) { if (div[x] > 0) continue; for (int u=2*x; u<=last; u+=x) { div[u] = x; } } return div; } long lcm(long a, long b) { /** Least common multiple */ return a * b / gcd(a,b); } class BaseConverter { /* Palauttaa luvun esityksen kannassa base */ public String convert(Long number, int base) { return Long.toString(number, base); } /* Palauttaa luvun esityksen kannassa baseTo, kun annetaan luku Stringinä kannassa baseFrom */ public String convert(String number, int baseFrom, int baseTo) { return Long.toString(Long.parseLong(number, baseFrom), baseTo); } /* Tulkitsee kannassa base esitetyn luvun longiksi (kannassa 10) */ public long longify(String number, int baseFrom) { return Long.parseLong(number, baseFrom); } } class BinomialCoefficients { /** Total number of K sized unique combinations from pool of size N (unordered) N! / ( K! (N - K)! ) */ /** For simple queries where output fits in long. */ public long biCo(long n, long k) { long r = 1; if (k > n) return 0; for (long d = 1; d <= k; d++) { r *= n--; r /= d; } return r; } /** For multiple queries with same n, different k. */ public long[] precalcBinomialCoefficientsK(int n, int maxK) { long v[] = new long[maxK+1]; v[0] = 1; // nC0 == 1 for (int i=1; i<=n; i++) { for (int j=Math.min(i,maxK); j>0; j--) { v[j] = v[j] + v[j-1]; // Pascal's triangle } } return v; } /** When output needs % MOD. */ public long[] precalcBinomialCoefficientsK(int n, int k, long M) { long v[] = new long[k+1]; v[0] = 1; // nC0 == 1 for (int i=1; i<=n; i++) { for (int j=Math.min(i,k); j>0; j--) { v[j] = v[j] + v[j-1]; // Pascal's triangle v[j] %= M; } } return v; } } /**************************** Strings ****************************/ class Zalgo { public int pisinEsiintyma(String haku, String kohde) { char[] s = new char[haku.length() + 1 + kohde.length()]; for (int i=0; i<haku.length(); i++) { s[i] = haku.charAt(i); } int j = haku.length(); s[j++] = '#'; for (int i=0; i<kohde.length(); i++) { s[j++] = kohde.charAt(i); } int[] z = toZarray(s); int max = 0; for (int i=haku.length(); i<z.length; i++) { max = Math.max(max, z[i]); } return max; } public int[] toZarray(char[] s) { int n = s.length; int[] z = new int[n]; int a = 0, b = 0; for (int i = 1; i < n; i++) { if (i > b) { for (int j = i; j < n && s[j - i] == s[j]; j++) z[i]++; } else { z[i] = z[i - a]; if (i + z[i - a] > b) { for (int j = b + 1; j < n && s[j - i] == s[j]; j++) z[i]++; a = i; b = i + z[i] - 1; } } } return z; } public List<Integer> getStartIndexesWhereWordIsFound(String haku, String kohde) { // this is alternative use case char[] s = new char[haku.length() + 1 + kohde.length()]; for (int i=0; i<haku.length(); i++) { s[i] = haku.charAt(i); } int j = haku.length(); s[j++] = '#'; for (int i=0; i<kohde.length(); i++) { s[j++] = kohde.charAt(i); } int[] z = toZarray(s); List<Integer> indexes = new ArrayList<>(); for (int i=haku.length(); i<z.length; i++) { if (z[i] < haku.length()) continue; indexes.add(i); } return indexes; } } class StringHasher { class HashedString { long[] hashes; long[] modifiers; public HashedString(long[] hashes, long[] modifiers) { this.hashes = hashes; this.modifiers = modifiers; } } long P; long M; public StringHasher() { initializePandM(); } HashedString hashString(String s) { int n = s.length(); long[] hashes = new long[n]; long[] modifiers = new long[n]; hashes[0] = s.charAt(0); modifiers[0] = 1; for (int i=1; i<n; i++) { hashes[i] = (hashes[i-1] * P + s.charAt(i)) % M; modifiers[i] = (modifiers[i-1] * P) % M; } return new HashedString(hashes, modifiers); } /** * Indices are inclusive. */ long getHash(HashedString hashedString, int startIndex, int endIndex) { long[] hashes = hashedString.hashes; long[] modifiers = hashedString.modifiers; long result = hashes[endIndex]; if (startIndex > 0) result -= (hashes[startIndex-1] * modifiers[endIndex-startIndex+1]) % M; if (result < 0) result += M; return result; } // Less interesting methods below /** * Efficient for 2 input parameter strings in particular. */ HashedString[] hashString(String first, String second) { HashedString[] array = new HashedString[2]; int n = first.length(); long[] modifiers = new long[n]; modifiers[0] = 1; long[] firstHashes = new long[n]; firstHashes[0] = first.charAt(0); array[0] = new HashedString(firstHashes, modifiers); long[] secondHashes = new long[n]; secondHashes[0] = second.charAt(0); array[1] = new HashedString(secondHashes, modifiers); for (int i=1; i<n; i++) { modifiers[i] = (modifiers[i-1] * P) % M; firstHashes[i] = (firstHashes[i-1] * P + first.charAt(i)) % M; secondHashes[i] = (secondHashes[i-1] * P + second.charAt(i)) % M; } return array; } /** * Efficient for 3+ strings * More efficient than multiple hashString calls IF strings are same length. */ HashedString[] hashString(String... strings) { HashedString[] array = new HashedString[strings.length]; int n = strings[0].length(); long[] modifiers = new long[n]; modifiers[0] = 1; for (int j=0; j<strings.length; j++) { // if all strings are not same length, defer work to another method if (strings[j].length() != n) { for (int i=0; i<n; i++) { array[i] = hashString(strings[i]); } return array; } // otherwise initialize stuff long[] hashes = new long[n]; hashes[0] = strings[j].charAt(0); array[j] = new HashedString(hashes, modifiers); } for (int i=1; i<n; i++) { modifiers[i] = (modifiers[i-1] * P) % M; for (int j=0; j<strings.length; j++) { String s = strings[j]; long[] hashes = array[j].hashes; hashes[i] = (hashes[i-1] * P + s.charAt(i)) % M; } } return array; } void initializePandM() { ArrayList<Long> modOptions = new ArrayList<>(20); modOptions.add(353873237L); modOptions.add(353875897L); modOptions.add(353878703L); modOptions.add(353882671L); modOptions.add(353885303L); modOptions.add(353888377L); modOptions.add(353893457L); P = modOptions.get(new Random().nextInt(modOptions.size())); modOptions.clear(); modOptions.add(452940277L); modOptions.add(452947687L); modOptions.add(464478431L); modOptions.add(468098221L); modOptions.add(470374601L); modOptions.add(472879717L); modOptions.add(472881973L); M = modOptions.get(new Random().nextInt(modOptions.size())); } } /*************************** Technical ***************************/ private class IO extends PrintWriter { private InputStreamReader r; private static final int BUFSIZE = 1 << 15; private char[] buf; private int bufc; private int bufi; private StringBuilder sb; public IO() { super(new BufferedOutputStream(System.out)); r = new InputStreamReader(System.in); buf = new char[BUFSIZE]; bufc = 0; bufi = 0; sb = new StringBuilder(); } /** Print, flush, return nextInt. */ private int queryInt(String s) { io.println(s); io.flush(); return nextInt(); } /** Print, flush, return nextLong. */ private long queryLong(String s) { io.println(s); io.flush(); return nextLong(); } /** Print, flush, return next word. */ private String queryNext(String s) { io.println(s); io.flush(); return next(); } private void fillBuf() throws IOException { bufi = 0; bufc = 0; while(bufc == 0) { bufc = r.read(buf, 0, BUFSIZE); if(bufc == -1) { bufc = 0; return; } } } private boolean pumpBuf() throws IOException { if(bufi == bufc) { fillBuf(); } return bufc != 0; } private boolean isDelimiter(char c) { return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f'; } private void eatDelimiters() throws IOException { while(true) { if(bufi == bufc) { fillBuf(); if(bufc == 0) throw new RuntimeException("IO: Out of input."); } if(!isDelimiter(buf[bufi])) break; ++bufi; } } public String next() { try { sb.setLength(0); eatDelimiters(); int start = bufi; while(true) { if(bufi == bufc) { sb.append(buf, start, bufi - start); fillBuf(); start = 0; if(bufc == 0) break; } if(isDelimiter(buf[bufi])) break; ++bufi; } sb.append(buf, start, bufi - start); return sb.toString(); } catch(IOException e) { throw new RuntimeException("IO.next: Caught IOException."); } } public int nextInt() { try { int ret = 0; eatDelimiters(); boolean positive = true; if(buf[bufi] == '-') { ++bufi; if(!pumpBuf()) throw new RuntimeException("IO.nextInt: Invalid int."); positive = false; } boolean first = true; while(true) { if(!pumpBuf()) break; if(isDelimiter(buf[bufi])) { if(first) throw new RuntimeException("IO.nextInt: Invalid int."); break; } first = false; if(buf[bufi] >= '0' && buf[bufi] <= '9') { if(ret < -214748364) throw new RuntimeException("IO.nextInt: Invalid int."); ret *= 10; ret -= (int)(buf[bufi] - '0'); if(ret > 0) throw new RuntimeException("IO.nextInt: Invalid int."); } else { throw new RuntimeException("IO.nextInt: Invalid int."); } ++bufi; } if(positive) { if(ret == -2147483648) throw new RuntimeException("IO.nextInt: Invalid int."); ret = -ret; } return ret; } catch(IOException e) { throw new RuntimeException("IO.nextInt: Caught IOException."); } } public long nextLong() { try { long ret = 0; eatDelimiters(); boolean positive = true; if(buf[bufi] == '-') { ++bufi; if(!pumpBuf()) throw new RuntimeException("IO.nextLong: Invalid long."); positive = false; } boolean first = true; while(true) { if(!pumpBuf()) break; if(isDelimiter(buf[bufi])) { if(first) throw new RuntimeException("IO.nextLong: Invalid long."); break; } first = false; if(buf[bufi] >= '0' && buf[bufi] <= '9') { if(ret < -922337203685477580L) throw new RuntimeException("IO.nextLong: Invalid long."); ret *= 10; ret -= (long)(buf[bufi] - '0'); if(ret > 0) throw new RuntimeException("IO.nextLong: Invalid long."); } else { throw new RuntimeException("IO.nextLong: Invalid long."); } ++bufi; } if(positive) { if(ret == -9223372036854775808L) throw new RuntimeException("IO.nextLong: Invalid long."); ret = -ret; } return ret; } catch(IOException e) { throw new RuntimeException("IO.nextLong: Caught IOException."); } } public double nextDouble() { return Double.parseDouble(next()); } } void print(Object output) { io.println(output); } void done(Object output) { print(output); done(); } void done() { io.close(); throw new RuntimeException("Clean exit"); } long min(long... v) { long ans = v[0]; for (int i=1; i<v.length; i++) { ans = Math.min(ans, v[i]); } return ans; } double min(double... v) { double ans = v[0]; for (int i=1; i<v.length; i++) { ans = Math.min(ans, v[i]); } return ans; } int min(int... v) { int ans = v[0]; for (int i=1; i<v.length; i++) { ans = Math.min(ans, v[i]); } return ans; } long max(long... v) { long ans = v[0]; for (int i=1; i<v.length; i++) { ans = Math.max(ans, v[i]); } return ans; } double max(double... v) { double ans = v[0]; for (int i=1; i<v.length; i++) { ans = Math.max(ans, v[i]); } return ans; } int max(int... v) { int ans = v[0]; for (int i=1; i<v.length; i++) { ans = Math.max(ans, v[i]); } return ans; } } }
Java
["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"]
2 seconds
["5", "4", "3"]
NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$
Java 8
standard input
[ "data structures", "two pointers", "divide and conquer" ]
42c4adc1c4a10cc619c05a842e186e60
The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements.
1,800
Print the number of segments in Petya's array with the sum of elements less than $$$t$$$.
standard output
PASSED
2780da9517b3c156147f1967ae040557
train_000.jsonl
1523370900
There are $$$n$$$ consecutive seat places in a railway carriage. Each place is either empty or occupied by a passenger.The university team for the Olympiad consists of $$$a$$$ student-programmers and $$$b$$$ student-athletes. Determine the largest number of students from all $$$a+b$$$ students, which you can put in the railway carriage so that: no student-programmer is sitting next to the student-programmer; and no student-athlete is sitting next to the student-athlete. In the other words, there should not be two consecutive (adjacent) places where two student-athletes or two student-programmers are sitting.Consider that initially occupied seat places are occupied by jury members (who obviously are not students at all).
256 megabytes
import java.util.*; import java.math.*; import java.text.*; import java.io.*; public class Main{ public static void main(String[] args){ Scanner cin=new Scanner(System.in); int n,a,b; String s; int ans=0; n=cin.nextInt(); a=cin.nextInt(); b=cin.nextInt(); s=cin.next(); //System.out.println(s); int sum=a+b; String[] array=s.split("\\*"); int cnt=array.length; for(int i=0;i<cnt;i++){ if(a<=0&&b<=0) break; if(array[i].length()==0) continue; int temp=array[i].length(); int t=Math.min(a,b); if(temp%2==0){ a-=temp/2; b-=temp/2; } else{ if(a>b){ a-=temp/2+1; b-=temp/2; } else{ b-=temp/2+1; a-=temp/2; } } } if(a<=0) a=0; if(b<=0) b=0; //System.out.println(a+" "+b); if(a==0&&b==0) System.out.println(sum); else System.out.println(sum-a-b); } }
Java
["5 1 1\n*...*", "6 2 3\n*...*.", "11 3 10\n.*....**.*.", "3 2 3\n***"]
2 seconds
["2", "4", "7", "0"]
NoteIn the first example you can put all student, for example, in the following way: *.AB*In the second example you can put four students, for example, in the following way: *BAB*BIn the third example you can put seven students, for example, in the following way: B*ABAB**A*BThe letter A means a student-programmer, and the letter B — student-athlete.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy" ]
6208dbdf9567b759b0026db4af4545a9
The first line contain three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$1 \le n \le 2\cdot10^{5}$$$, $$$0 \le a, b \le 2\cdot10^{5}$$$, $$$a + b &gt; 0$$$) — total number of seat places in the railway carriage, the number of student-programmers and the number of student-athletes. The second line contains a string with length $$$n$$$, consisting of characters "." and "*". The dot means that the corresponding place is empty. The asterisk means that the corresponding place is occupied by the jury member.
1,300
Print the largest number of students, which you can put in the railway carriage so that no student-programmer is sitting next to a student-programmer and no student-athlete is sitting next to a student-athlete.
standard output
PASSED
613dfaa91c6d2b0054704d25e309f200
train_000.jsonl
1523370900
There are $$$n$$$ consecutive seat places in a railway carriage. Each place is either empty or occupied by a passenger.The university team for the Olympiad consists of $$$a$$$ student-programmers and $$$b$$$ student-athletes. Determine the largest number of students from all $$$a+b$$$ students, which you can put in the railway carriage so that: no student-programmer is sitting next to the student-programmer; and no student-athlete is sitting next to the student-athlete. In the other words, there should not be two consecutive (adjacent) places where two student-athletes or two student-programmers are sitting.Consider that initially occupied seat places are occupied by jury members (who obviously are not students at all).
256 megabytes
import java.util.*; public class Solution{ static int solve(char[] arr, int A, int B) { int abCount = 0; if (A <= 0 && B <= 0) return 0; if (arr[0] != '*') { arr[0] = A > B ? 'a' : 'b'; if (A > B) A--; else B--; abCount++; } for (int i = 1; i < arr.length; i++) { if (B <= 0 && A <= 0) return abCount; if (arr[i] == '*') continue; // arr[i] == '.' if (arr[i-1] == 'a') { if (B > 0) { arr[i] = 'b'; B--; abCount++; } continue; } if (arr[i-1] == 'b') { if (A > 0) { arr[i] = 'a'; A--; abCount++; } continue; } if (arr[i-1] == '*' || arr[i-1] == '.') { // put most common if (A >= B) { arr[i] = 'a'; A--; } else { arr[i] = 'b'; B--; } abCount++; continue; } } return abCount; } static void check(int a, int b) { if (a != b) { throw new AssertionError(a + " != " + b); } } static char[] convert(String s) { char[] res = new char[s.length()]; for (int i = 0; i < s.length(); i++) { res[i] = s.charAt(i); } return res; } static void runTests () { char[] t1 = convert("*...*"); check(solve(t1, 1, 1), 2); System.out.println("test 1 passed"); char[] t2 = convert("*...*."); check(solve(t2, 2, 3), 4); System.out.println("test 2 passed"); char[] t3 = convert(".*....**.*."); check(solve(t3, 3, 10), 7); System.out.println("test 3 passed"); char[] t4 = convert("***"); check(solve(t4, 2, 3), 0); System.out.println("test 4 passed"); System.out.println("all tests passed"); } static void takeInput () { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); int A = sc.nextInt(); int B = sc.nextInt(); char[] arr = new char[N]; String line = sc.next(); for (int i = 0; i < N; i++) { arr[i] = line.charAt(i); } int ans = solve(arr, A, B); System.out.println(ans); } public static void main(String[] args) { //runTests(); takeInput(); } }
Java
["5 1 1\n*...*", "6 2 3\n*...*.", "11 3 10\n.*....**.*.", "3 2 3\n***"]
2 seconds
["2", "4", "7", "0"]
NoteIn the first example you can put all student, for example, in the following way: *.AB*In the second example you can put four students, for example, in the following way: *BAB*BIn the third example you can put seven students, for example, in the following way: B*ABAB**A*BThe letter A means a student-programmer, and the letter B — student-athlete.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy" ]
6208dbdf9567b759b0026db4af4545a9
The first line contain three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$1 \le n \le 2\cdot10^{5}$$$, $$$0 \le a, b \le 2\cdot10^{5}$$$, $$$a + b &gt; 0$$$) — total number of seat places in the railway carriage, the number of student-programmers and the number of student-athletes. The second line contains a string with length $$$n$$$, consisting of characters "." and "*". The dot means that the corresponding place is empty. The asterisk means that the corresponding place is occupied by the jury member.
1,300
Print the largest number of students, which you can put in the railway carriage so that no student-programmer is sitting next to a student-programmer and no student-athlete is sitting next to a student-athlete.
standard output
PASSED
6662c60954ac9756f226b278b953a3ed
train_000.jsonl
1523370900
There are $$$n$$$ consecutive seat places in a railway carriage. Each place is either empty or occupied by a passenger.The university team for the Olympiad consists of $$$a$$$ student-programmers and $$$b$$$ student-athletes. Determine the largest number of students from all $$$a+b$$$ students, which you can put in the railway carriage so that: no student-programmer is sitting next to the student-programmer; and no student-athlete is sitting next to the student-athlete. In the other words, there should not be two consecutive (adjacent) places where two student-athletes or two student-programmers are sitting.Consider that initially occupied seat places are occupied by jury members (who obviously are not students at all).
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.StreamTokenizer; import java.util.ArrayList; import java.util.List; public class Problem2 { private static final char EMPTY = '.'; private static final char NOT_EMPTY = '*'; public static void main(String[] args) { try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { String[] numbers = reader.readLine().split(" "); int n = Integer.parseInt(numbers[0]); int a = Integer.parseInt(numbers[1]); int b = Integer.parseInt(numbers[2]); String places = reader.readLine(); int total = 0; boolean previousA = false; boolean previousB = false; for (int i = 0; i < n && (a > 0 || b > 0); i++) { if (places.charAt(i) == EMPTY) { if (a > b) { if (!previousA) { a--; total++; previousA = true; previousB=false; continue; } else { if (b > 0) { total++; b--; previousB=true; previousA=false; continue; } } } else { if (!previousB) { b--; total++; previousB = true; previousA=false; continue; } else { if (a > 0) { total++; a--; previousA=true; previousB=false; continue; } } } } previousA=false; previousB=false; } System.out.println(total); } catch (IOException e) { e.printStackTrace(); } } }
Java
["5 1 1\n*...*", "6 2 3\n*...*.", "11 3 10\n.*....**.*.", "3 2 3\n***"]
2 seconds
["2", "4", "7", "0"]
NoteIn the first example you can put all student, for example, in the following way: *.AB*In the second example you can put four students, for example, in the following way: *BAB*BIn the third example you can put seven students, for example, in the following way: B*ABAB**A*BThe letter A means a student-programmer, and the letter B — student-athlete.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy" ]
6208dbdf9567b759b0026db4af4545a9
The first line contain three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$1 \le n \le 2\cdot10^{5}$$$, $$$0 \le a, b \le 2\cdot10^{5}$$$, $$$a + b &gt; 0$$$) — total number of seat places in the railway carriage, the number of student-programmers and the number of student-athletes. The second line contains a string with length $$$n$$$, consisting of characters "." and "*". The dot means that the corresponding place is empty. The asterisk means that the corresponding place is occupied by the jury member.
1,300
Print the largest number of students, which you can put in the railway carriage so that no student-programmer is sitting next to a student-programmer and no student-athlete is sitting next to a student-athlete.
standard output
PASSED
c4463e876d33e32f0a8a7f755df3978b
train_000.jsonl
1523370900
There are $$$n$$$ consecutive seat places in a railway carriage. Each place is either empty or occupied by a passenger.The university team for the Olympiad consists of $$$a$$$ student-programmers and $$$b$$$ student-athletes. Determine the largest number of students from all $$$a+b$$$ students, which you can put in the railway carriage so that: no student-programmer is sitting next to the student-programmer; and no student-athlete is sitting next to the student-athlete. In the other words, there should not be two consecutive (adjacent) places where two student-athletes or two student-programmers are sitting.Consider that initially occupied seat places are occupied by jury members (who obviously are not students at all).
256 megabytes
import java.io.PrintWriter; import java.util.Scanner; public class cf962b2 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int seats = sc.nextInt(); int a = sc.nextInt(); int b =sc.nextInt(); sc.nextLine(); char[] arr = sc.nextLine().toCharArray(); int cnt = 0; for (int i =0 ; i < arr.length; i++) { if (arr[i] == '*') { continue; } if (a == 0 && b == 0) { break; } if (cnt == 0) { if (a >= b) { arr[i] = 'A'; a--; cnt++; }else { arr[i] = 'B'; b--; cnt++; } } else { if (a >= b && arr[i-1] != 'A') { arr[i] = 'A'; a--; cnt++; }else if (b > a && arr[i-1] != 'B') { arr[i] = 'B'; b--; cnt++; }else if (a > 0 && arr[i-1] != 'A') { arr[i] = 'A'; a--; cnt++; }else if (b > 0 && arr[i-1] != 'B') { arr[i] = 'B'; b--; cnt++; } } } System.out.println(cnt); } }
Java
["5 1 1\n*...*", "6 2 3\n*...*.", "11 3 10\n.*....**.*.", "3 2 3\n***"]
2 seconds
["2", "4", "7", "0"]
NoteIn the first example you can put all student, for example, in the following way: *.AB*In the second example you can put four students, for example, in the following way: *BAB*BIn the third example you can put seven students, for example, in the following way: B*ABAB**A*BThe letter A means a student-programmer, and the letter B — student-athlete.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy" ]
6208dbdf9567b759b0026db4af4545a9
The first line contain three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$1 \le n \le 2\cdot10^{5}$$$, $$$0 \le a, b \le 2\cdot10^{5}$$$, $$$a + b &gt; 0$$$) — total number of seat places in the railway carriage, the number of student-programmers and the number of student-athletes. The second line contains a string with length $$$n$$$, consisting of characters "." and "*". The dot means that the corresponding place is empty. The asterisk means that the corresponding place is occupied by the jury member.
1,300
Print the largest number of students, which you can put in the railway carriage so that no student-programmer is sitting next to a student-programmer and no student-athlete is sitting next to a student-athlete.
standard output
PASSED
f8bcbaab11833a24324c6ea01174a62e
train_000.jsonl
1523370900
There are $$$n$$$ consecutive seat places in a railway carriage. Each place is either empty or occupied by a passenger.The university team for the Olympiad consists of $$$a$$$ student-programmers and $$$b$$$ student-athletes. Determine the largest number of students from all $$$a+b$$$ students, which you can put in the railway carriage so that: no student-programmer is sitting next to the student-programmer; and no student-athlete is sitting next to the student-athlete. In the other words, there should not be two consecutive (adjacent) places where two student-athletes or two student-programmers are sitting.Consider that initially occupied seat places are occupied by jury members (who obviously are not students at all).
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Puneet //FastRead class is taken from different online Sources */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastRead in = new FastRead(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { public void solve(int testNumber, FastRead in, PrintWriter out) { int n = in.nextInt(), b = in.nextInt(), c = in.nextInt(); char[] sc = (in.nextString()).toCharArray(); int a1 = b, a2 = c; int chek = 2; for (int i = n - 1; i >= 0; i--) { if (sc[i] == '*') { chek = 2; continue; } if (chek == 1) { a1--; chek = 0; continue; } if (chek == 0) { a2--; chek = 1; continue; } if (chek == 2) { if (a1 > a2) { a1--; chek = 0; } else { a2--; chek = 1; } } } // out.println(a1+" "+a2); int ans = b + c; if (a1 > 0) ans -= a1; if (a2 > 0) ans -= a2; out.print(ans); } } static class FastRead { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private FastRead.SpaceCharFilter filter; public FastRead(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String nextString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["5 1 1\n*...*", "6 2 3\n*...*.", "11 3 10\n.*....**.*.", "3 2 3\n***"]
2 seconds
["2", "4", "7", "0"]
NoteIn the first example you can put all student, for example, in the following way: *.AB*In the second example you can put four students, for example, in the following way: *BAB*BIn the third example you can put seven students, for example, in the following way: B*ABAB**A*BThe letter A means a student-programmer, and the letter B — student-athlete.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy" ]
6208dbdf9567b759b0026db4af4545a9
The first line contain three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$1 \le n \le 2\cdot10^{5}$$$, $$$0 \le a, b \le 2\cdot10^{5}$$$, $$$a + b &gt; 0$$$) — total number of seat places in the railway carriage, the number of student-programmers and the number of student-athletes. The second line contains a string with length $$$n$$$, consisting of characters "." and "*". The dot means that the corresponding place is empty. The asterisk means that the corresponding place is occupied by the jury member.
1,300
Print the largest number of students, which you can put in the railway carriage so that no student-programmer is sitting next to a student-programmer and no student-athlete is sitting next to a student-athlete.
standard output
PASSED
83c784c1278c6abf3aa4a4cfa0cfb102
train_000.jsonl
1523370900
There are $$$n$$$ consecutive seat places in a railway carriage. Each place is either empty or occupied by a passenger.The university team for the Olympiad consists of $$$a$$$ student-programmers and $$$b$$$ student-athletes. Determine the largest number of students from all $$$a+b$$$ students, which you can put in the railway carriage so that: no student-programmer is sitting next to the student-programmer; and no student-athlete is sitting next to the student-athlete. In the other words, there should not be two consecutive (adjacent) places where two student-athletes or two student-programmers are sitting.Consider that initially occupied seat places are occupied by jury members (who obviously are not students at all).
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Solution { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); _962b solver = new _962b(); solver.solve(1, in, out); out.close(); } static class _962b { static int a; static int b; public void solve(int testNumber, InputReader in, OutputWriter out) { //pass can be jury member, no weight, but fills a sea int n = in.readInt(); a = in.readInt(); b = in.readInt(); char[] s = in.readCharArray(n); int res = 0; for (int i = 0; i < n; ++i) { if (s[i] == '.') { if (i == 0 || (i > 0 && s[i - 1] == '*')) { if (a < b) swap(); if (a > 0) { --a; ++res; } } else { swap(); if (a > 0) { ++res; --a; } } } } out.printLine(res); } static void swap() { int tmp = a; a = b; b = tmp; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void printLine(int i) { writer.println(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public char[] readCharArray(int size) { char[] array = new char[size]; for (int i = 0; i < size; i++) { array[i] = readCharacter(); } return array; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public char readCharacter() { int c = read(); while (isSpaceChar(c)) { c = read(); } return (char) c; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["5 1 1\n*...*", "6 2 3\n*...*.", "11 3 10\n.*....**.*.", "3 2 3\n***"]
2 seconds
["2", "4", "7", "0"]
NoteIn the first example you can put all student, for example, in the following way: *.AB*In the second example you can put four students, for example, in the following way: *BAB*BIn the third example you can put seven students, for example, in the following way: B*ABAB**A*BThe letter A means a student-programmer, and the letter B — student-athlete.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy" ]
6208dbdf9567b759b0026db4af4545a9
The first line contain three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$1 \le n \le 2\cdot10^{5}$$$, $$$0 \le a, b \le 2\cdot10^{5}$$$, $$$a + b &gt; 0$$$) — total number of seat places in the railway carriage, the number of student-programmers and the number of student-athletes. The second line contains a string with length $$$n$$$, consisting of characters "." and "*". The dot means that the corresponding place is empty. The asterisk means that the corresponding place is occupied by the jury member.
1,300
Print the largest number of students, which you can put in the railway carriage so that no student-programmer is sitting next to a student-programmer and no student-athlete is sitting next to a student-athlete.
standard output
PASSED
34f73a2bbc7be9b7bddc2a932904c256
train_000.jsonl
1523370900
There are $$$n$$$ consecutive seat places in a railway carriage. Each place is either empty or occupied by a passenger.The university team for the Olympiad consists of $$$a$$$ student-programmers and $$$b$$$ student-athletes. Determine the largest number of students from all $$$a+b$$$ students, which you can put in the railway carriage so that: no student-programmer is sitting next to the student-programmer; and no student-athlete is sitting next to the student-athlete. In the other words, there should not be two consecutive (adjacent) places where two student-athletes or two student-programmers are sitting.Consider that initially occupied seat places are occupied by jury members (who obviously are not students at all).
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; public class Main { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String[] temp = in.readLine().split(" "); int n = Integer.parseInt(temp[0]); int a = Integer.parseInt(temp[1]); int b = Integer.parseInt(temp[2]); char[] seats = in.readLine().toCharArray(); int id = 0; int s = 0; while (id < n) { if (seats[id] == '.') { if (id == 0 || seats[id - 1] == '*' || seats[id - 1] == '.') { if (a > b && a > 0) { seats[id] = 'A'; a--; s++; } else if (b >= a && b > 0) { seats[id] = 'B'; b--; s++; } } else if (seats[id - 1] == 'B' && a > 0) { seats[id] = 'A'; a--; s++; } else if (seats[id - 1] == 'A' && b > 0) { seats[id] = 'B'; b--; s++; } } id++; } System.out.println(s); } }
Java
["5 1 1\n*...*", "6 2 3\n*...*.", "11 3 10\n.*....**.*.", "3 2 3\n***"]
2 seconds
["2", "4", "7", "0"]
NoteIn the first example you can put all student, for example, in the following way: *.AB*In the second example you can put four students, for example, in the following way: *BAB*BIn the third example you can put seven students, for example, in the following way: B*ABAB**A*BThe letter A means a student-programmer, and the letter B — student-athlete.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy" ]
6208dbdf9567b759b0026db4af4545a9
The first line contain three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$1 \le n \le 2\cdot10^{5}$$$, $$$0 \le a, b \le 2\cdot10^{5}$$$, $$$a + b &gt; 0$$$) — total number of seat places in the railway carriage, the number of student-programmers and the number of student-athletes. The second line contains a string with length $$$n$$$, consisting of characters "." and "*". The dot means that the corresponding place is empty. The asterisk means that the corresponding place is occupied by the jury member.
1,300
Print the largest number of students, which you can put in the railway carriage so that no student-programmer is sitting next to a student-programmer and no student-athlete is sitting next to a student-athlete.
standard output
PASSED
144403c903e6930e7db96af672d5dca2
train_000.jsonl
1523370900
There are $$$n$$$ consecutive seat places in a railway carriage. Each place is either empty or occupied by a passenger.The university team for the Olympiad consists of $$$a$$$ student-programmers and $$$b$$$ student-athletes. Determine the largest number of students from all $$$a+b$$$ students, which you can put in the railway carriage so that: no student-programmer is sitting next to the student-programmer; and no student-athlete is sitting next to the student-athlete. In the other words, there should not be two consecutive (adjacent) places where two student-athletes or two student-programmers are sitting.Consider that initially occupied seat places are occupied by jury members (who obviously are not students at all).
256 megabytes
import java.util.Scanner; public class bProblem { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int a = scan.nextInt(); int b = scan.nextInt(); char[] arr = scan.next().toCharArray(); for(int i = 0;i<n;i++){ if(arr[i] == '*'){ continue; } if(i==0){ if(a>=b && a>0){ arr[0] = 'a'; a--; }else if(b>0){ arr[0] = 'b'; b--; } continue; } if(arr[i-1] == ' '|| arr[i-1] == '*'){ if(a>=b && a>0){ arr[i] = 'a'; a--; }else if(b>0){ arr[i] = 'b'; b--; } } if(arr[i-1] == 'a'){ if(b>0){ arr[i] = 'b'; b--; }else{ arr[i] = ' '; } } if(arr[i-1] == 'b'){ if(a>0){ arr[i] = 'a'; a--; }else{ arr[i] = ' '; } } } int count = 0; for(int i = 0;i<n;i++){ if(arr[i] =='a'||arr[i] =='b'){ count++; } } System.out.println(count); } }
Java
["5 1 1\n*...*", "6 2 3\n*...*.", "11 3 10\n.*....**.*.", "3 2 3\n***"]
2 seconds
["2", "4", "7", "0"]
NoteIn the first example you can put all student, for example, in the following way: *.AB*In the second example you can put four students, for example, in the following way: *BAB*BIn the third example you can put seven students, for example, in the following way: B*ABAB**A*BThe letter A means a student-programmer, and the letter B — student-athlete.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy" ]
6208dbdf9567b759b0026db4af4545a9
The first line contain three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$1 \le n \le 2\cdot10^{5}$$$, $$$0 \le a, b \le 2\cdot10^{5}$$$, $$$a + b &gt; 0$$$) — total number of seat places in the railway carriage, the number of student-programmers and the number of student-athletes. The second line contains a string with length $$$n$$$, consisting of characters "." and "*". The dot means that the corresponding place is empty. The asterisk means that the corresponding place is occupied by the jury member.
1,300
Print the largest number of students, which you can put in the railway carriage so that no student-programmer is sitting next to a student-programmer and no student-athlete is sitting next to a student-athlete.
standard output
PASSED
3bec0de828931453406c7558f30eaa0f
train_000.jsonl
1523370900
There are $$$n$$$ consecutive seat places in a railway carriage. Each place is either empty or occupied by a passenger.The university team for the Olympiad consists of $$$a$$$ student-programmers and $$$b$$$ student-athletes. Determine the largest number of students from all $$$a+b$$$ students, which you can put in the railway carriage so that: no student-programmer is sitting next to the student-programmer; and no student-athlete is sitting next to the student-athlete. In the other words, there should not be two consecutive (adjacent) places where two student-athletes or two student-programmers are sitting.Consider that initially occupied seat places are occupied by jury members (who obviously are not students at all).
256 megabytes
import java.util.Scanner; public class Test { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int a = in.nextInt(); int b = in.nextInt(); String s = in.next(); int count = 0; for (int i = 0; i < s.length(); i++) { if (a > 0 || b > 0) { if (s.charAt(i) == '.') { if (i + 1 < s.length()) { if (s.charAt(i + 1) == '*') { count++; if (a > b) { a--; } else b--; i++; } else { if (a > 0 && b > 0) { a--; b--; count += 2; i++; } else { a = (a > 0) ? --a : a; b = (b > 0) ? --b : b; count++; i++; } } } else count++; } } } System.out.println(count); } }
Java
["5 1 1\n*...*", "6 2 3\n*...*.", "11 3 10\n.*....**.*.", "3 2 3\n***"]
2 seconds
["2", "4", "7", "0"]
NoteIn the first example you can put all student, for example, in the following way: *.AB*In the second example you can put four students, for example, in the following way: *BAB*BIn the third example you can put seven students, for example, in the following way: B*ABAB**A*BThe letter A means a student-programmer, and the letter B — student-athlete.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy" ]
6208dbdf9567b759b0026db4af4545a9
The first line contain three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$1 \le n \le 2\cdot10^{5}$$$, $$$0 \le a, b \le 2\cdot10^{5}$$$, $$$a + b &gt; 0$$$) — total number of seat places in the railway carriage, the number of student-programmers and the number of student-athletes. The second line contains a string with length $$$n$$$, consisting of characters "." and "*". The dot means that the corresponding place is empty. The asterisk means that the corresponding place is occupied by the jury member.
1,300
Print the largest number of students, which you can put in the railway carriage so that no student-programmer is sitting next to a student-programmer and no student-athlete is sitting next to a student-athlete.
standard output
PASSED
5bad53688dd7e2c51ca0c34bb4d2d6f7
train_000.jsonl
1523370900
There are $$$n$$$ consecutive seat places in a railway carriage. Each place is either empty or occupied by a passenger.The university team for the Olympiad consists of $$$a$$$ student-programmers and $$$b$$$ student-athletes. Determine the largest number of students from all $$$a+b$$$ students, which you can put in the railway carriage so that: no student-programmer is sitting next to the student-programmer; and no student-athlete is sitting next to the student-athlete. In the other words, there should not be two consecutive (adjacent) places where two student-athletes or two student-programmers are sitting.Consider that initially occupied seat places are occupied by jury members (who obviously are not students at all).
256 megabytes
import java.io.*; import java.util.stream.Stream; /** * @author madi.sagimbekov */ public class C962B { private static BufferedReader in; private static BufferedWriter out; public static void main(String[] args) throws IOException { open(); int[] x = readInts(); int n = x[0]; int a = x[1]; int b = x[2]; char[] c = readString().toCharArray(); int res = 0; boolean lasta = false; boolean star = true; for (int i = 0; i < c.length; i++) { if (c[i] == '.') { if (star) { if (a > b && a > 0) { res++; a--; lasta = true; star = false; } else if (b > 0) { res++; b--; lasta = false; star = false; } else { break; } } else { if (lasta) { if (b > 0) { b--; res++; lasta = false; star = false; } else { star = true; lasta = false; } } else { if (a > 0) { a--; res++; lasta = true; star = false; } else { star = true; lasta = false; } } } } else { star = true; lasta = false; } } out.write(res + "\n"); close(); } private static int[] readInts() throws IOException { return Stream.of(in.readLine().split(" ")).mapToInt(Integer::parseInt).toArray(); } private static int readInt() throws IOException { return Integer.parseInt(in.readLine()); } private static long[] readLongs() throws IOException { return Stream.of(in.readLine().split(" ")).mapToLong(Long::parseLong).toArray(); } private static long readLong() throws IOException { return Long.parseLong(in.readLine()); } private static double[] readDoubles() throws IOException { return Stream.of(in.readLine().split(" ")).mapToDouble(Double::parseDouble).toArray(); } private static double readDouble() throws IOException { return Double.parseDouble(in.readLine()); } private static String readString() throws IOException { return in.readLine(); } private static void open() { in = new BufferedReader(new InputStreamReader(System.in)); out = new BufferedWriter(new OutputStreamWriter((System.out))); } private static void close() throws IOException { out.flush(); out.close(); in.close(); } }
Java
["5 1 1\n*...*", "6 2 3\n*...*.", "11 3 10\n.*....**.*.", "3 2 3\n***"]
2 seconds
["2", "4", "7", "0"]
NoteIn the first example you can put all student, for example, in the following way: *.AB*In the second example you can put four students, for example, in the following way: *BAB*BIn the third example you can put seven students, for example, in the following way: B*ABAB**A*BThe letter A means a student-programmer, and the letter B — student-athlete.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy" ]
6208dbdf9567b759b0026db4af4545a9
The first line contain three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$1 \le n \le 2\cdot10^{5}$$$, $$$0 \le a, b \le 2\cdot10^{5}$$$, $$$a + b &gt; 0$$$) — total number of seat places in the railway carriage, the number of student-programmers and the number of student-athletes. The second line contains a string with length $$$n$$$, consisting of characters "." and "*". The dot means that the corresponding place is empty. The asterisk means that the corresponding place is occupied by the jury member.
1,300
Print the largest number of students, which you can put in the railway carriage so that no student-programmer is sitting next to a student-programmer and no student-athlete is sitting next to a student-athlete.
standard output
PASSED
de082a846383dc243207203fbece59f4
train_000.jsonl
1523370900
There are $$$n$$$ consecutive seat places in a railway carriage. Each place is either empty or occupied by a passenger.The university team for the Olympiad consists of $$$a$$$ student-programmers and $$$b$$$ student-athletes. Determine the largest number of students from all $$$a+b$$$ students, which you can put in the railway carriage so that: no student-programmer is sitting next to the student-programmer; and no student-athlete is sitting next to the student-athlete. In the other words, there should not be two consecutive (adjacent) places where two student-athletes or two student-programmers are sitting.Consider that initially occupied seat places are occupied by jury members (who obviously are not students at all).
256 megabytes
import java.util.*; public class HelloWorld{ public static void main(String []args){ Scanner in = new Scanner(System.in); in.nextInt(); int na = in.nextInt(); int nb = in.nextInt(); String line = in.next(); int ans = 0; int count = 0; int last = 0; for(char temp : line.toCharArray()) { if(temp == '*') { last = 0; } else if(na == 0 && nb == 0) break; else if(last == 0) { if(na > nb) { na--; ans++; last = 1; } else { nb--; ans++; last = 2; } } else if(last == 1 && nb > 0) { last = 2; nb--; ans++; } else if(last == 2 && na > 0) { last = 1; na--; ans++; } else { last = 0; } } System.out.println(ans); } }
Java
["5 1 1\n*...*", "6 2 3\n*...*.", "11 3 10\n.*....**.*.", "3 2 3\n***"]
2 seconds
["2", "4", "7", "0"]
NoteIn the first example you can put all student, for example, in the following way: *.AB*In the second example you can put four students, for example, in the following way: *BAB*BIn the third example you can put seven students, for example, in the following way: B*ABAB**A*BThe letter A means a student-programmer, and the letter B — student-athlete.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy" ]
6208dbdf9567b759b0026db4af4545a9
The first line contain three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$1 \le n \le 2\cdot10^{5}$$$, $$$0 \le a, b \le 2\cdot10^{5}$$$, $$$a + b &gt; 0$$$) — total number of seat places in the railway carriage, the number of student-programmers and the number of student-athletes. The second line contains a string with length $$$n$$$, consisting of characters "." and "*". The dot means that the corresponding place is empty. The asterisk means that the corresponding place is occupied by the jury member.
1,300
Print the largest number of students, which you can put in the railway carriage so that no student-programmer is sitting next to a student-programmer and no student-athlete is sitting next to a student-athlete.
standard output
PASSED
6dbb195f056a86a3d657a09af3bc69b3
train_000.jsonl
1523370900
There are $$$n$$$ consecutive seat places in a railway carriage. Each place is either empty or occupied by a passenger.The university team for the Olympiad consists of $$$a$$$ student-programmers and $$$b$$$ student-athletes. Determine the largest number of students from all $$$a+b$$$ students, which you can put in the railway carriage so that: no student-programmer is sitting next to the student-programmer; and no student-athlete is sitting next to the student-athlete. In the other words, there should not be two consecutive (adjacent) places where two student-athletes or two student-programmers are sitting.Consider that initially occupied seat places are occupied by jury members (who obviously are not students at all).
256 megabytes
//codeforces_962B import java.io.*; import java.util.*; import static java.lang.Math.*; public class acm{ public static void main(String args[]) throws IOException{ BufferedReader gi = new BufferedReader(new InputStreamReader(System.in)); PrintWriter go = new PrintWriter(System.out); String line[] = gi.readLine().split(" "); int n = Integer.parseInt(line[0]); int a = Integer.parseInt(line[1]); int b = Integer.parseInt(line[2]); line = gi.readLine().split("[*]"); int len; int students[] = new int[2]; int ma,mi; students[0] = a; students[1] = b; for (String e : line){ len = e.length(); ma = max(students[0],students[1]); mi = min(students[0],students[1]); students[0] = ma; students[1] = mi; for (int k = 0; k<len; k++){ if (students[k%2]!=0){ students[k%2]--; } } } go.println(a+b-students[0]-students[1]); go.close(); } }
Java
["5 1 1\n*...*", "6 2 3\n*...*.", "11 3 10\n.*....**.*.", "3 2 3\n***"]
2 seconds
["2", "4", "7", "0"]
NoteIn the first example you can put all student, for example, in the following way: *.AB*In the second example you can put four students, for example, in the following way: *BAB*BIn the third example you can put seven students, for example, in the following way: B*ABAB**A*BThe letter A means a student-programmer, and the letter B — student-athlete.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy" ]
6208dbdf9567b759b0026db4af4545a9
The first line contain three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$1 \le n \le 2\cdot10^{5}$$$, $$$0 \le a, b \le 2\cdot10^{5}$$$, $$$a + b &gt; 0$$$) — total number of seat places in the railway carriage, the number of student-programmers and the number of student-athletes. The second line contains a string with length $$$n$$$, consisting of characters "." and "*". The dot means that the corresponding place is empty. The asterisk means that the corresponding place is occupied by the jury member.
1,300
Print the largest number of students, which you can put in the railway carriage so that no student-programmer is sitting next to a student-programmer and no student-athlete is sitting next to a student-athlete.
standard output
PASSED
4ec26c66c0faa05a85dd558033eb3e20
train_000.jsonl
1523370900
There are $$$n$$$ consecutive seat places in a railway carriage. Each place is either empty or occupied by a passenger.The university team for the Olympiad consists of $$$a$$$ student-programmers and $$$b$$$ student-athletes. Determine the largest number of students from all $$$a+b$$$ students, which you can put in the railway carriage so that: no student-programmer is sitting next to the student-programmer; and no student-athlete is sitting next to the student-athlete. In the other words, there should not be two consecutive (adjacent) places where two student-athletes or two student-programmers are sitting.Consider that initially occupied seat places are occupied by jury members (who obviously are not students at all).
256 megabytes
import java.util.*; public class RailWay{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int pro = sc.nextInt(); int ath = sc.nextInt(); String pos = sc.next(); char[] seat = pos.toCharArray(); int cnt = 0; if(seat[0] == '.' && pro >= ath){ seat[0] = 'p'; pro--; cnt++; } else if(seat[0] == '.' && ath > pro){ seat[0] = 'a'; ath--; cnt++; } for(int i = 1; i < seat.length; i++){ if(ath + pro == 0){ break; } if(seat[i] == '.' && pro > 0 && pro >= ath){ if(seat[i-1] != 'p'){ pro--; cnt ++; seat[i] = 'p'; } else if(ath > 0){ ath--; cnt++; seat[i] = 'a'; } } else if(seat[i] == '.' && ath > 0 && ath >= pro){ if(seat[i-1] != 'a'){ ath--; cnt ++; seat[i] = 'a'; } else if(pro > 0){ pro--; cnt++; seat[i] = 'p'; } } else { continue; } } System.out.println(cnt); } }
Java
["5 1 1\n*...*", "6 2 3\n*...*.", "11 3 10\n.*....**.*.", "3 2 3\n***"]
2 seconds
["2", "4", "7", "0"]
NoteIn the first example you can put all student, for example, in the following way: *.AB*In the second example you can put four students, for example, in the following way: *BAB*BIn the third example you can put seven students, for example, in the following way: B*ABAB**A*BThe letter A means a student-programmer, and the letter B — student-athlete.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy" ]
6208dbdf9567b759b0026db4af4545a9
The first line contain three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$1 \le n \le 2\cdot10^{5}$$$, $$$0 \le a, b \le 2\cdot10^{5}$$$, $$$a + b &gt; 0$$$) — total number of seat places in the railway carriage, the number of student-programmers and the number of student-athletes. The second line contains a string with length $$$n$$$, consisting of characters "." and "*". The dot means that the corresponding place is empty. The asterisk means that the corresponding place is occupied by the jury member.
1,300
Print the largest number of students, which you can put in the railway carriage so that no student-programmer is sitting next to a student-programmer and no student-athlete is sitting next to a student-athlete.
standard output
PASSED
91615cc4ebaf350162e24db6c5d44705
train_000.jsonl
1523370900
There are $$$n$$$ consecutive seat places in a railway carriage. Each place is either empty or occupied by a passenger.The university team for the Olympiad consists of $$$a$$$ student-programmers and $$$b$$$ student-athletes. Determine the largest number of students from all $$$a+b$$$ students, which you can put in the railway carriage so that: no student-programmer is sitting next to the student-programmer; and no student-athlete is sitting next to the student-athlete. In the other words, there should not be two consecutive (adjacent) places where two student-athletes or two student-programmers are sitting.Consider that initially occupied seat places are occupied by jury members (who obviously are not students at all).
256 megabytes
/** * Date: 10 Apr, 2018 * Link: 962 B * * @author Prasad-Chaudhari * @email [email protected] */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class newProgram2 { public static void main(String[] args) throws IOException { // TODO code application logic here FastIO2 in = new FastIO2(); int n = in.ni(); int a = in.ni(); int b = in.ni(); char c[] = in.next().toCharArray(); if (a > b) { a ^= b; b ^= a; a ^= b; } int count = 0; for (int i = 0; i < n; i++) { if (c[i] == '.') { if (a > b) { a ^= b; b ^= a; a ^= b; } int p = 0; char d='a'; for(int j=i;j<n;j++,i++){ if(c[j]=='*'){ break; } if(p%2==0){ if(b==0){ break; } c[i] ='b'; count++; b--; } else{ if(a==0){ d='.'; } if(d=='a'){ c[i]='a'; count++; a--; } } p++; } } } System.out.println(count); } static class FastIO2 { private final BufferedReader br; private String s[]; private int index; public FastIO2() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); s = br.readLine().split(" "); index = 0; } public int ni() throws IOException { return Integer.parseInt(nextToken()); } public double nd() throws IOException { return Double.parseDouble(nextToken()); } public long nl() throws IOException { return Long.parseLong(nextToken()); } public String next() throws IOException { return nextToken(); } public String nli() throws IOException { try { return br.readLine(); } catch (IOException ex) { } return null; } public int[] gia(int n) throws IOException { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = ni(); } return a; } public int[] gia(int n, int start, int end) throws IOException { validate(n, start, end); int a[] = new int[n]; for (int i = start; i < end; i++) { a[i] = ni(); } return a; } public double[] gda(int n) throws IOException { double a[] = new double[n]; for (int i = 0; i < n; i++) { a[i] = nd(); } return a; } public double[] gda(int n, int start, int end) throws IOException { validate(n, start, end); double a[] = new double[n]; for (int i = start; i < end; i++) { a[i] = nd(); } return a; } public long[] gla(int n) throws IOException { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = ni(); } return a; } public long[] gla(int n, int start, int end) throws IOException { validate(n, start, end); long a[] = new long[n]; for (int i = start; i < end; i++) { a[i] = ni(); } return a; } private String nextToken() throws IndexOutOfBoundsException, IOException { if (index == s.length) { s = br.readLine().split(" "); index = 0; } return s[index++]; } private void validate(int n, int start, int end) { if (start < 0 || end >= n) { throw new IllegalArgumentException(); } } } }
Java
["5 1 1\n*...*", "6 2 3\n*...*.", "11 3 10\n.*....**.*.", "3 2 3\n***"]
2 seconds
["2", "4", "7", "0"]
NoteIn the first example you can put all student, for example, in the following way: *.AB*In the second example you can put four students, for example, in the following way: *BAB*BIn the third example you can put seven students, for example, in the following way: B*ABAB**A*BThe letter A means a student-programmer, and the letter B — student-athlete.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy" ]
6208dbdf9567b759b0026db4af4545a9
The first line contain three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$1 \le n \le 2\cdot10^{5}$$$, $$$0 \le a, b \le 2\cdot10^{5}$$$, $$$a + b &gt; 0$$$) — total number of seat places in the railway carriage, the number of student-programmers and the number of student-athletes. The second line contains a string with length $$$n$$$, consisting of characters "." and "*". The dot means that the corresponding place is empty. The asterisk means that the corresponding place is occupied by the jury member.
1,300
Print the largest number of students, which you can put in the railway carriage so that no student-programmer is sitting next to a student-programmer and no student-athlete is sitting next to a student-athlete.
standard output
PASSED
78609adf1da6c5a3fe1eedf289b36f6d
train_000.jsonl
1523370900
There are $$$n$$$ consecutive seat places in a railway carriage. Each place is either empty or occupied by a passenger.The university team for the Olympiad consists of $$$a$$$ student-programmers and $$$b$$$ student-athletes. Determine the largest number of students from all $$$a+b$$$ students, which you can put in the railway carriage so that: no student-programmer is sitting next to the student-programmer; and no student-athlete is sitting next to the student-athlete. In the other words, there should not be two consecutive (adjacent) places where two student-athletes or two student-programmers are sitting.Consider that initially occupied seat places are occupied by jury members (who obviously are not students at all).
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.Scanner; public class B { static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); public static int nextInt() throws IOException { in.nextToken(); return (int) in.nval; } public static String next() throws IOException { in.nextToken(); return (String) in.sval; } public static void main(String[] args) throws IOException { Scanner input = new Scanner(System.in); int n, a, b; n = input.nextInt(); a = input.nextInt(); b = input.nextInt(); String str = input.next(); // 输入字符串 、next() 输入是空串、 long ans = 0; // 记录能坐的学生的个数、、 int empty = 0; // 记录空闲的位置, int max = Math.max(a, b); int min = Math.min(a, b); for(int i = 0; i < str.length(); i++) { int tmp = Math.max(max, min); min = Math.min(max, min); max = tmp; if(str.charAt(i) == '.') { // 可以放学生、 坐下 empty++; }else { // *号 、 结算、 if((empty & 1) == 1) { // 奇数、 大的能多放一个、 ans += Math.min(empty / 2 + 1, max); ans += Math.min(min, empty / 2); max = Math.max(0, max - empty / 2 - 1); min = Math.max(0, min - empty / 2); }else { // 偶数、、 ans += Math.min(empty / 2, max); ans += Math.min(empty / 2, min); max = Math.max(0, max - empty / 2); min = Math.max(0, min - empty / 2); } empty = 0; } } // 补充最后一个的、、 一直没有 * 号用来结算、 if((empty & 1) == 1) { // 奇数、 大的能多放一个、 ans += Math.min(empty / 2 + 1, max); ans += Math.min(min, empty / 2); max = Math.max(0, max - empty / 2 - 1); min = Math.max(0, min - empty / 2); }else { // 偶数、、 ans += Math.min(empty / 2, max); ans += Math.min(empty / 2, min); max = Math.max(0, max - empty / 2); min = Math.max(0, min - empty / 2); } out.println(ans); out.flush(); // input.close(); } }
Java
["5 1 1\n*...*", "6 2 3\n*...*.", "11 3 10\n.*....**.*.", "3 2 3\n***"]
2 seconds
["2", "4", "7", "0"]
NoteIn the first example you can put all student, for example, in the following way: *.AB*In the second example you can put four students, for example, in the following way: *BAB*BIn the third example you can put seven students, for example, in the following way: B*ABAB**A*BThe letter A means a student-programmer, and the letter B — student-athlete.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy" ]
6208dbdf9567b759b0026db4af4545a9
The first line contain three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$1 \le n \le 2\cdot10^{5}$$$, $$$0 \le a, b \le 2\cdot10^{5}$$$, $$$a + b &gt; 0$$$) — total number of seat places in the railway carriage, the number of student-programmers and the number of student-athletes. The second line contains a string with length $$$n$$$, consisting of characters "." and "*". The dot means that the corresponding place is empty. The asterisk means that the corresponding place is occupied by the jury member.
1,300
Print the largest number of students, which you can put in the railway carriage so that no student-programmer is sitting next to a student-programmer and no student-athlete is sitting next to a student-athlete.
standard output
PASSED
a3102dc26c8ed05514ccd7c72664c096
train_000.jsonl
1523370900
There are $$$n$$$ consecutive seat places in a railway carriage. Each place is either empty or occupied by a passenger.The university team for the Olympiad consists of $$$a$$$ student-programmers and $$$b$$$ student-athletes. Determine the largest number of students from all $$$a+b$$$ students, which you can put in the railway carriage so that: no student-programmer is sitting next to the student-programmer; and no student-athlete is sitting next to the student-athlete. In the other words, there should not be two consecutive (adjacent) places where two student-athletes or two student-programmers are sitting.Consider that initially occupied seat places are occupied by jury members (who obviously are not students at all).
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.Scanner; public class B { static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); public static int nextInt() throws IOException { in.nextToken(); return (int) in.nval; } public static String next() throws IOException { in.nextToken(); return (String) in.sval; } public static void main(String[] args) throws IOException { Scanner input = new Scanner(System.in); int n, a, b; n = input.nextInt(); a = input.nextInt(); b = input.nextInt(); String str = input.next(); // 输入字符串 、next() 输入是空串、 long ans = 0; // 记录能坐的学生的个数、、 int empty = 0; // 记录空闲的位置, int max = Math.max(a, b); int min = Math.min(a, b); for(int i = 0; i < str.length(); i++) { int tmp = Math.max(max, min); min = Math.min(max, min); max = tmp; if(str.charAt(i) == '.') { // 可以放学生、 坐下 empty++; }else { // *号 、 结算、 if((empty & 1) == 1) { // 奇数、 大的能多放一个、 ans += Math.min(empty / 2 + 1, max); ans += Math.min(min, empty / 2); max = Math.max(0, max - empty / 2 - 1); min = Math.max(0, min - empty / 2); }else { // 偶数、、 ans += Math.min(empty / 2, max); ans += Math.min(empty / 2, min); max = Math.max(0, max - empty / 2); min = Math.max(0, min - empty / 2); } empty = 0; } } // 补充最后一个的、、 一直没有 * 号用来结算、 if((empty & 1) == 1) { // 奇数、 大的能多放一个、 ans += Math.min(empty / 2 + 1, max); ans += Math.min(min, empty / 2); max = Math.max(0, max - empty / 2 - 1); min = Math.max(0, min - empty / 2); }else { // 偶数、、 ans += Math.min(empty / 2, max); ans += Math.min(empty / 2, min); max = Math.max(0, max - empty / 2); min = Math.max(0, min - empty / 2); } out.println(ans); out.flush(); input.close(); } }
Java
["5 1 1\n*...*", "6 2 3\n*...*.", "11 3 10\n.*....**.*.", "3 2 3\n***"]
2 seconds
["2", "4", "7", "0"]
NoteIn the first example you can put all student, for example, in the following way: *.AB*In the second example you can put four students, for example, in the following way: *BAB*BIn the third example you can put seven students, for example, in the following way: B*ABAB**A*BThe letter A means a student-programmer, and the letter B — student-athlete.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy" ]
6208dbdf9567b759b0026db4af4545a9
The first line contain three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$1 \le n \le 2\cdot10^{5}$$$, $$$0 \le a, b \le 2\cdot10^{5}$$$, $$$a + b &gt; 0$$$) — total number of seat places in the railway carriage, the number of student-programmers and the number of student-athletes. The second line contains a string with length $$$n$$$, consisting of characters "." and "*". The dot means that the corresponding place is empty. The asterisk means that the corresponding place is occupied by the jury member.
1,300
Print the largest number of students, which you can put in the railway carriage so that no student-programmer is sitting next to a student-programmer and no student-athlete is sitting next to a student-athlete.
standard output
PASSED
4853c0f9840fcb724d21abe19427d404
train_000.jsonl
1523370900
There are $$$n$$$ consecutive seat places in a railway carriage. Each place is either empty or occupied by a passenger.The university team for the Olympiad consists of $$$a$$$ student-programmers and $$$b$$$ student-athletes. Determine the largest number of students from all $$$a+b$$$ students, which you can put in the railway carriage so that: no student-programmer is sitting next to the student-programmer; and no student-athlete is sitting next to the student-athlete. In the other words, there should not be two consecutive (adjacent) places where two student-athletes or two student-programmers are sitting.Consider that initially occupied seat places are occupied by jury members (who obviously are not students at all).
256 megabytes
import java.util.Scanner; public class Main { public static void main(String args[]){ Scanner s = new Scanner(System.in); int n = s.nextInt(); int a = s.nextInt(); int b = s.nextInt(); String str = s.next(); char prev = '!'; int c = 0; for(int i=0;i<n;i++) { if(str.charAt(i) == '.') { if(prev == '!') { if(a>0 || b >0) { if(a>b) { a--; prev = 'a'; c++; } else { b--; prev = 'b'; c++; } } } else if(prev == 'a') { if(b>0) { b--; prev = 'b'; c++; } else if(b == 0) prev = '!'; } else if(prev == 'b') { if(a > 0) { a--; prev = 'a'; c++; } else if(a == 0) prev = '!'; } } else { prev = '!'; } } System.out.println(c); } }
Java
["5 1 1\n*...*", "6 2 3\n*...*.", "11 3 10\n.*....**.*.", "3 2 3\n***"]
2 seconds
["2", "4", "7", "0"]
NoteIn the first example you can put all student, for example, in the following way: *.AB*In the second example you can put four students, for example, in the following way: *BAB*BIn the third example you can put seven students, for example, in the following way: B*ABAB**A*BThe letter A means a student-programmer, and the letter B — student-athlete.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy" ]
6208dbdf9567b759b0026db4af4545a9
The first line contain three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$1 \le n \le 2\cdot10^{5}$$$, $$$0 \le a, b \le 2\cdot10^{5}$$$, $$$a + b &gt; 0$$$) — total number of seat places in the railway carriage, the number of student-programmers and the number of student-athletes. The second line contains a string with length $$$n$$$, consisting of characters "." and "*". The dot means that the corresponding place is empty. The asterisk means that the corresponding place is occupied by the jury member.
1,300
Print the largest number of students, which you can put in the railway carriage so that no student-programmer is sitting next to a student-programmer and no student-athlete is sitting next to a student-athlete.
standard output
PASSED
074debb1b12fc3f22c7ed66c0d6ec2df
train_000.jsonl
1523370900
There are $$$n$$$ consecutive seat places in a railway carriage. Each place is either empty or occupied by a passenger.The university team for the Olympiad consists of $$$a$$$ student-programmers and $$$b$$$ student-athletes. Determine the largest number of students from all $$$a+b$$$ students, which you can put in the railway carriage so that: no student-programmer is sitting next to the student-programmer; and no student-athlete is sitting next to the student-athlete. In the other words, there should not be two consecutive (adjacent) places where two student-athletes or two student-programmers are sitting.Consider that initially occupied seat places are occupied by jury members (who obviously are not students at all).
256 megabytes
import java.io.*; import java.util.*; import java.math.BigInteger; public class Main { private static StringBuilder sb = new StringBuilder(); private static void s(String s){ System.out.print(s); } private static void s(Double s){ System.out.print(s); } private static void s(char s){ System.out.print(s); } private static void sn(String s){ System.out.println(s); } private static void sn(Boolean s){ System.out.println(s); } private static void sn(long s){ System.out.println(s); } private static void sn(Double s){ System.out.println(s); } private static void sn(String s, Object o){ sb.append(s+"\n"); } private static void s(String s, Object o){ sb.append(s); } private static void sn(long s, Object o){ sb.append(s+"\n"); } private static void sn(boolean s, Object o){ sb.append(s+"\n"); } private static void pr() throws Exception{ BufferedWriter bw =new BufferedWriter(new OutputStreamWriter(System.out)); bw.write(sb.toString()); bw.flush(); } static class Reader{ final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[51]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } private static boolean isPrime(Integer ii){ return new BigInteger(ii+"").isProbablePrime(1); } private static boolean isDigit(int ii){ return Character.isDigit((char)ii); } private static long fact(int f){ if(f==0){ return 1; } return (long)f * (long)fact(f-1); } private static Reader r = new Reader(); private static int ni() throws Exception{ return r.nextInt(); } private static String ns() throws Exception{ return r.readLine(); } private static long nl() throws Exception{ return r.nextLong(); } private static int[] na(int a) throws Exception{ int arr[] = new int[a]; for(int i=0;i<a;i++){ arr[i] = r.nextInt(); } return arr; } private static long[] nal(int a) throws Exception{ long arr[] = new long[a]; for(int i=0;i<a;i++){ arr[i] = r.nextLong(); } return arr; } static void printSubsets(char set[]) { int n = set.length; // Run a loop for printing all 2^n // subsets one by obe for (int i = 0; i < (1<<n); i++) { System.out.print("{ "); // Print current subset for (int j = 0; j < n; j++) // (1<<j) is a number with jth bit 1 // so when we 'and' them with the // subset number we get which numbers // are present in the subset and which // are not if ((i & (1 << j)) > 0) System.out.print(set[j] + " "); System.out.println("}"); } } static class Query implements Comparable<Query>{ int l,r,blk,idx; long an; Query(int l, int r, int blk, int f){ this.l = l; this.r = r; this.blk = blk; idx= f; } public int compareTo(Query q){ if(blk==q.blk){ if((blk & 1) != 1){ return r - q.r; } else return q.r - r; } else{ return blk-q.blk; } } public String toString(){ return l+" "+r+ " "+blk+" "+idx; } } private static void add(int ind, int arr[]){ ans+=(++cnt[arr[ind]]==1?1:0); } private static void remove(int ind, int arr[]){ ans-=(cnt[arr[ind]]--==1?1:0); } static int ans =0; static int curl = 0; static int curr = 0; static int cnt[] = new int[1000006]; class Sol{ int idx,cnt; char rr; } private static void solve() throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //int n = Integer.valueOf(br.readLine()); String temp = br.readLine(); int cnt=0; int n = Integer.valueOf(temp.split(" ")[0]); int sp=Integer.valueOf(temp.split(" ")[1]),sa = Integer.valueOf(temp.split(" ")[2]); String str = br.readLine(); char []r = str.toCharArray(); int spc = sp, sac = sa; for(int i=0;i<n;i++){ if(i>0 && r[i]=='.'){ if(r[i-1]=='*'){ if(spc>sac && spc>0){ r[i]='A'; spc--; cnt++; } else if(sac>0) { r[i]='B'; sac--; cnt++; } } else if(r[i-1]=='A'){ if(sac>0){ sac--; r[i]='B'; cnt++; } } else if(r[i-1]=='B'){ if(spc>0){ spc--; r[i]='A'; cnt++; } } else if(r[i-1]=='.'){ if(spc>0){ spc--; r[i]='A'; cnt++; } else if(sac>0){ sac--; r[i]='B'; cnt++; } } } else if(r[i]=='.' && i==0){ if(spc>sac && spc>0){ spc--; r[i]='A'; cnt++; } else if(sac>0){ sac--; r[i]='B'; cnt++; } } } sn(cnt); } public static void main (String[] args) throws Exception{ int tc =1; while(tc-->0){ solve(); } } }
Java
["5 1 1\n*...*", "6 2 3\n*...*.", "11 3 10\n.*....**.*.", "3 2 3\n***"]
2 seconds
["2", "4", "7", "0"]
NoteIn the first example you can put all student, for example, in the following way: *.AB*In the second example you can put four students, for example, in the following way: *BAB*BIn the third example you can put seven students, for example, in the following way: B*ABAB**A*BThe letter A means a student-programmer, and the letter B — student-athlete.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy" ]
6208dbdf9567b759b0026db4af4545a9
The first line contain three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$1 \le n \le 2\cdot10^{5}$$$, $$$0 \le a, b \le 2\cdot10^{5}$$$, $$$a + b &gt; 0$$$) — total number of seat places in the railway carriage, the number of student-programmers and the number of student-athletes. The second line contains a string with length $$$n$$$, consisting of characters "." and "*". The dot means that the corresponding place is empty. The asterisk means that the corresponding place is occupied by the jury member.
1,300
Print the largest number of students, which you can put in the railway carriage so that no student-programmer is sitting next to a student-programmer and no student-athlete is sitting next to a student-athlete.
standard output
PASSED
d3f74460d4dd223c17f3e4ae7df04abb
train_000.jsonl
1523370900
There are $$$n$$$ consecutive seat places in a railway carriage. Each place is either empty or occupied by a passenger.The university team for the Olympiad consists of $$$a$$$ student-programmers and $$$b$$$ student-athletes. Determine the largest number of students from all $$$a+b$$$ students, which you can put in the railway carriage so that: no student-programmer is sitting next to the student-programmer; and no student-athlete is sitting next to the student-athlete. In the other words, there should not be two consecutive (adjacent) places where two student-athletes or two student-programmers are sitting.Consider that initially occupied seat places are occupied by jury members (who obviously are not students at all).
256 megabytes
import java.util.Scanner; public class abc { public static void main(String[] args) { Scanner sc = new Scanner(System.in); char c=' '; int n=sc.nextInt(),a=sc.nextInt(),b=sc.nextInt(),t=0;sc.nextLine(); String s=sc.nextLine(); if(s.charAt(0) =='.' && b<=a && a!=0 ) { a--;t++;c='a';} else if(s.charAt(0) =='.' && a<=b && b!=0) { b--;t++;c='b';} for(int i =1;i<n;i++) { if(s.charAt(i)=='.' && s.charAt(i-1)=='.' && a!=0 && c=='b') { a--;t++;c='a';} else if(s.charAt(i)=='.' && s.charAt(i-1)=='.' && a==0 && b!=0 && c=='b') { c='a';} else if(s.charAt(i)=='.' && s.charAt(i-1)=='.' && b!=0 && c=='a') { b--;t++;c='b';} else if(s.charAt(i)=='.' && s.charAt(i-1)=='.' && b==0 && a!=0 && c=='a') { c='b';} else if(s.charAt(i) =='.' && s.charAt(i-1)=='*' && b<=a && a!=0 ) { a--;t++;c='a';} else if(s.charAt(i) =='.' && s.charAt(i-1)=='*' &&b>=a && b!=0) { b--;t++;c='b';} } System.out.print(t); } }
Java
["5 1 1\n*...*", "6 2 3\n*...*.", "11 3 10\n.*....**.*.", "3 2 3\n***"]
2 seconds
["2", "4", "7", "0"]
NoteIn the first example you can put all student, for example, in the following way: *.AB*In the second example you can put four students, for example, in the following way: *BAB*BIn the third example you can put seven students, for example, in the following way: B*ABAB**A*BThe letter A means a student-programmer, and the letter B — student-athlete.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy" ]
6208dbdf9567b759b0026db4af4545a9
The first line contain three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$1 \le n \le 2\cdot10^{5}$$$, $$$0 \le a, b \le 2\cdot10^{5}$$$, $$$a + b &gt; 0$$$) — total number of seat places in the railway carriage, the number of student-programmers and the number of student-athletes. The second line contains a string with length $$$n$$$, consisting of characters "." and "*". The dot means that the corresponding place is empty. The asterisk means that the corresponding place is occupied by the jury member.
1,300
Print the largest number of students, which you can put in the railway carriage so that no student-programmer is sitting next to a student-programmer and no student-athlete is sitting next to a student-athlete.
standard output
PASSED
fb439663f00cd01b7fc2f512773dc247
train_000.jsonl
1550504400
You a captain of a ship. Initially you are standing in a point $$$(x_1, y_1)$$$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $$$(x_2, y_2)$$$. You know the weather forecast — the string $$$s$$$ of length $$$n$$$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $$$s_1$$$, the second day — $$$s_2$$$, the $$$n$$$-th day — $$$s_n$$$ and $$$(n+1)$$$-th day — $$$s_1$$$ again and so on. Ship coordinates change the following way: if wind blows the direction U, then the ship moves from $$$(x, y)$$$ to $$$(x, y + 1)$$$; if wind blows the direction D, then the ship moves from $$$(x, y)$$$ to $$$(x, y - 1)$$$; if wind blows the direction L, then the ship moves from $$$(x, y)$$$ to $$$(x - 1, y)$$$; if wind blows the direction R, then the ship moves from $$$(x, y)$$$ to $$$(x + 1, y)$$$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $$$(x, y)$$$ it will move to the point $$$(x - 1, y + 1)$$$, and if it goes the direction U, then it will move to the point $$$(x, y + 2)$$$.You task is to determine the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$.
256 megabytes
import java.util.*; import java.io.*; import static java.lang.Math.*; public class MainS { static final long MOD = 1_000_000_007, INF = 1_000_000_000_000_000_000L; static final int INf = 1_000_000_000; static FastReader reader; static PrintWriter writer; public static void main(String[] args) { Thread t = new Thread(null, new O(), "Integer.MAX_VALUE", 100000000); t.start(); } static class O implements Runnable { public void run() { try { magic(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } } public static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } 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; } } static long x1,y1,x2,y2,cumU[], cumD[], cumL[], cumR[]; static int n; static String s; static void magic() throws IOException { reader = new FastReader(); writer = new PrintWriter(System.out, true); x1 = reader.nextInt(); y1 = reader.nextInt(); x2 = reader.nextInt(); y2 = reader.nextInt(); n = reader.nextInt(); s = reader.next(); cumL = new long[n]; cumR = new long[n]; cumD = new long[n]; cumU = new long[n]; for(int i=0;i<n;++i) { if(s.charAt(i)=='U') { cumU[i]++; } else if(s.charAt(i)=='D') { cumD[i]++; } else if(s.charAt(i)=='L') { cumL[i]++; } else { cumR[i]++; } if(i>0) { cumD[i]+=cumD[i-1]; cumL[i]+=cumL[i-1]; cumU[i]+=cumU[i-1]; cumR[i]+=cumR[i-1]; } } // for(int i=0;i<100;++i) { // if(check(i)) { // writer.println("true"); // } // else { // writer.println("false"); // } // } long low = 0, high = 1000000000000000L, mid; if(!check(high)) { writer.println(-1); System.exit(0); } while(low<high) { mid = (low+high)>>1; if(check(mid)) { if(mid==0 || !check(mid-1)) { low = mid; break; } else high = --mid; } else low = ++mid; } writer.println(low); } static boolean check(long T) { long L = 1L * (T/n) * cumL[n-1]; long R = 1L * (T/n) * cumR[n-1]; long D = 1L * (T/n) * cumD[n-1]; long U = 1L * (T/n) * cumU[n-1]; if(T%n!=0) { L+=cumL[(int)(T%n)-1]; R+=cumR[(int)(T%n)-1]; D+=cumD[(int)(T%n)-1]; U+=cumU[(int)(T%n)-1]; } long net_hor_movement_towards_right = R - L; long net_ver_movement_towards_up = U - D; long need_hor_movement = x2 - x1; long need_ver_movement = y2 - y1; long time_need = 0; time_need+=abs(need_hor_movement - net_hor_movement_towards_right); time_need+=abs(need_ver_movement - net_ver_movement_towards_up); // if(need_hor_movement>=0) { // if(net_hor_movement_towards_right<need_hor_movement) { // time_need+=(need_hor_movement - net_hor_movement_towards_right); // } // } // else { // if(net_hor_movement_towards_right>need_hor_movement) { // time_need+=(net_hor_movement_towards_right - need_hor_movement); // } // } // if(need_ver_movement>=0) { // if(net_ver_movement_towards_up<need_ver_movement) { // time_need+=(need_ver_movement - net_ver_movement_towards_up); // } // } // else { // if(net_ver_movement_towards_up>need_ver_movement) { // time_need+=(net_ver_movement_towards_up - need_ver_movement); // } // } return time_need<=T; } }
Java
["0 0\n4 6\n3\nUUU", "0 3\n0 0\n3\nUDD", "0 0\n0 1\n1\nL"]
2 seconds
["5", "3", "-1"]
NoteIn the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: $$$(0, 0)$$$ $$$\rightarrow$$$ $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ $$$\rightarrow$$$ $$$(3, 3)$$$ $$$\rightarrow$$$ $$$(4, 4)$$$ $$$\rightarrow$$$ $$$(4, 6)$$$.In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 1)$$$ $$$\rightarrow$$$ $$$(0, 0)$$$.In the third example the ship can never reach the point $$$(0, 1)$$$.
Java 8
standard input
[ "binary search" ]
3967727db1225c4b6072d9f18e0dce00
The first line contains two integers $$$x_1, y_1$$$ ($$$0 \le x_1, y_1 \le 10^9$$$) — the initial coordinates of the ship. The second line contains two integers $$$x_2, y_2$$$ ($$$0 \le x_2, y_2 \le 10^9$$$) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The fourth line contains the string $$$s$$$ itself, consisting only of letters U, D, L and R.
1,900
The only line should contain the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$. If it's impossible then print "-1".
standard output
PASSED
02c9932aed2841a3176e0752e546757a
train_000.jsonl
1550504400
You a captain of a ship. Initially you are standing in a point $$$(x_1, y_1)$$$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $$$(x_2, y_2)$$$. You know the weather forecast — the string $$$s$$$ of length $$$n$$$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $$$s_1$$$, the second day — $$$s_2$$$, the $$$n$$$-th day — $$$s_n$$$ and $$$(n+1)$$$-th day — $$$s_1$$$ again and so on. Ship coordinates change the following way: if wind blows the direction U, then the ship moves from $$$(x, y)$$$ to $$$(x, y + 1)$$$; if wind blows the direction D, then the ship moves from $$$(x, y)$$$ to $$$(x, y - 1)$$$; if wind blows the direction L, then the ship moves from $$$(x, y)$$$ to $$$(x - 1, y)$$$; if wind blows the direction R, then the ship moves from $$$(x, y)$$$ to $$$(x + 1, y)$$$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $$$(x, y)$$$ it will move to the point $$$(x - 1, y + 1)$$$, and if it goes the direction U, then it will move to the point $$$(x, y + 2)$$$.You task is to determine the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author revanth */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); CMagicShip solver = new CMagicShip(); solver.solve(1, in, out); out.close(); } static class CMagicShip { long x; long y; long x1; long y1; long x2; long y2; int n; int[][] a; boolean check(long m) { x = (m / n) * a[n][0] + a[(int) (m % n)][0]; y = m / n * a[n][1] + a[(int) (m % n)][1]; return Math.abs(x2 - x1 - x) + Math.abs(y2 - y1 - y) <= m; } public void solve(int testNumber, InputReader in, OutputWriter out) { x1 = in.nextInt(); y1 = in.nextInt(); x2 = in.nextInt(); y2 = in.nextInt(); n = in.nextInt(); a = new int[n + 1][2]; String s = in.nextString(); char ch; for (int i = 1; i <= n; i++) { ch = s.charAt(i - 1); a[i][0] += a[i - 1][0]; a[i][1] += a[i - 1][1]; if (ch == 'L') --a[i][0]; if (ch == 'R') ++a[i][0]; if (ch == 'U') ++a[i][1]; if (ch == 'D') --a[i][1]; } long l = 1, r = (long) 1e18, m; while (l < r) { m = (l + r) / 2; if (check(m)) r = m; else l = m + 1; } if (l == (long) 1e18 && !check(l)) out.print("-1"); else out.print(l); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar; private int snumChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public String nextString() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void close() { writer.close(); } } }
Java
["0 0\n4 6\n3\nUUU", "0 3\n0 0\n3\nUDD", "0 0\n0 1\n1\nL"]
2 seconds
["5", "3", "-1"]
NoteIn the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: $$$(0, 0)$$$ $$$\rightarrow$$$ $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ $$$\rightarrow$$$ $$$(3, 3)$$$ $$$\rightarrow$$$ $$$(4, 4)$$$ $$$\rightarrow$$$ $$$(4, 6)$$$.In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 1)$$$ $$$\rightarrow$$$ $$$(0, 0)$$$.In the third example the ship can never reach the point $$$(0, 1)$$$.
Java 8
standard input
[ "binary search" ]
3967727db1225c4b6072d9f18e0dce00
The first line contains two integers $$$x_1, y_1$$$ ($$$0 \le x_1, y_1 \le 10^9$$$) — the initial coordinates of the ship. The second line contains two integers $$$x_2, y_2$$$ ($$$0 \le x_2, y_2 \le 10^9$$$) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The fourth line contains the string $$$s$$$ itself, consisting only of letters U, D, L and R.
1,900
The only line should contain the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$. If it's impossible then print "-1".
standard output
PASSED
9700ef76152ad4addd96a7de29c66665
train_000.jsonl
1550504400
You a captain of a ship. Initially you are standing in a point $$$(x_1, y_1)$$$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $$$(x_2, y_2)$$$. You know the weather forecast — the string $$$s$$$ of length $$$n$$$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $$$s_1$$$, the second day — $$$s_2$$$, the $$$n$$$-th day — $$$s_n$$$ and $$$(n+1)$$$-th day — $$$s_1$$$ again and so on. Ship coordinates change the following way: if wind blows the direction U, then the ship moves from $$$(x, y)$$$ to $$$(x, y + 1)$$$; if wind blows the direction D, then the ship moves from $$$(x, y)$$$ to $$$(x, y - 1)$$$; if wind blows the direction L, then the ship moves from $$$(x, y)$$$ to $$$(x - 1, y)$$$; if wind blows the direction R, then the ship moves from $$$(x, y)$$$ to $$$(x + 1, y)$$$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $$$(x, y)$$$ it will move to the point $$$(x - 1, y + 1)$$$, and if it goes the direction U, then it will move to the point $$$(x, y + 2)$$$.You task is to determine the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.PriorityQueue; import java.util.StringTokenizer; public class Main { public static boolean check(long numdays, long d1, long d2, char[] Arr) { long n=numdays; long D1 = 0; long Acc1 = 0; long Acc2 = 0; long D2 = 0; long rem = numdays % Arr.length; long div = numdays / Arr.length; for (int i = 0; i < Arr.length; i++) { if (Arr[i] == 'L') { D1--; } else if (Arr[i] == 'R') { D1++; } else if (Arr[i] == 'U') { D2++; } else if (Arr[i] == 'D') { D2--; } if (i == rem - 1) { Acc1 = D1; Acc2 = D2; } } D1=D1*div+Acc1; D2=D2*div+Acc2; n-=Math.abs(d1-D1); n-=Math.abs(d2-D2); return n>=0; } public static long binSearch(long d1, long d2, char[] Arr) { long l = 0; long r = (long) 1e18; long mid; long result = -1; while (l <= r) { mid = (l + r) / 2; if (check(mid, d1, d2, Arr)) { result = mid; r = mid - 1; } else { l = mid + 1; } } return result; } public static void main(String[] args) throws IOException, InterruptedException { PrintWriter pw = new PrintWriter(System.out); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // String str = br.readLine(); // PriorityQueue<Long> q = new PriorityQueue<Long>(); // HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>(); StringTokenizer st = new StringTokenizer(br.readLine()); int x1 = Integer.parseInt(st.nextToken()); int y1 = Integer.parseInt(st.nextToken()); st = new StringTokenizer(br.readLine()); int x2 = Integer.parseInt(st.nextToken()); int y2 = Integer.parseInt(st.nextToken()); long d1 = x2 - x1; long d2 = y2 - y1; int n = Integer.parseInt(br.readLine()); String str = br.readLine(); char[] Arr = str.toCharArray(); System.out.println(binSearch(d1, d2, Arr)); } }
Java
["0 0\n4 6\n3\nUUU", "0 3\n0 0\n3\nUDD", "0 0\n0 1\n1\nL"]
2 seconds
["5", "3", "-1"]
NoteIn the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: $$$(0, 0)$$$ $$$\rightarrow$$$ $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ $$$\rightarrow$$$ $$$(3, 3)$$$ $$$\rightarrow$$$ $$$(4, 4)$$$ $$$\rightarrow$$$ $$$(4, 6)$$$.In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 1)$$$ $$$\rightarrow$$$ $$$(0, 0)$$$.In the third example the ship can never reach the point $$$(0, 1)$$$.
Java 8
standard input
[ "binary search" ]
3967727db1225c4b6072d9f18e0dce00
The first line contains two integers $$$x_1, y_1$$$ ($$$0 \le x_1, y_1 \le 10^9$$$) — the initial coordinates of the ship. The second line contains two integers $$$x_2, y_2$$$ ($$$0 \le x_2, y_2 \le 10^9$$$) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The fourth line contains the string $$$s$$$ itself, consisting only of letters U, D, L and R.
1,900
The only line should contain the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$. If it's impossible then print "-1".
standard output
PASSED
1662aa6aeeb5c1e2ff914254c6e960dc
train_000.jsonl
1550504400
You a captain of a ship. Initially you are standing in a point $$$(x_1, y_1)$$$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $$$(x_2, y_2)$$$. You know the weather forecast — the string $$$s$$$ of length $$$n$$$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $$$s_1$$$, the second day — $$$s_2$$$, the $$$n$$$-th day — $$$s_n$$$ and $$$(n+1)$$$-th day — $$$s_1$$$ again and so on. Ship coordinates change the following way: if wind blows the direction U, then the ship moves from $$$(x, y)$$$ to $$$(x, y + 1)$$$; if wind blows the direction D, then the ship moves from $$$(x, y)$$$ to $$$(x, y - 1)$$$; if wind blows the direction L, then the ship moves from $$$(x, y)$$$ to $$$(x - 1, y)$$$; if wind blows the direction R, then the ship moves from $$$(x, y)$$$ to $$$(x + 1, y)$$$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $$$(x, y)$$$ it will move to the point $$$(x - 1, y + 1)$$$, and if it goes the direction U, then it will move to the point $$$(x, y + 2)$$$.You task is to determine the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.PriorityQueue; import java.util.StringTokenizer; public class Main { static class pair { long acc1; long acc2; public pair(long d1, long d2) { this.acc1 = d1; this.acc2 = d2; } } public static boolean check(long numdays, long d1, long d2, pair[] Arr) { long n = numdays; long rem = numdays % Arr.length; long div = numdays / Arr.length; long D1 = Arr[Arr.length - 1].acc1; long D2 = Arr[Arr.length - 1].acc2; long Acc1 = (rem==0)?0:Arr[(int) (rem - 1)].acc1; long Acc2 =(rem==0)?0: Arr[(int) (rem - 1)].acc2; D1 = D1 * div + Acc1; D2 = D2 * div + Acc2; n -= Math.abs(d1 - D1); n -= Math.abs(d2 - D2); return n >= 0; } public static long binSearch(long d1, long d2, pair[] Arr) { long l = 0; long r = (long) 1e18; long mid; long result = -1; while (l <= r) { mid = (l + r) / 2; if (check(mid, d1, d2, Arr)) { result = mid; r = mid - 1; } else { l = mid + 1; } } return result; } public static void main(String[] args) throws IOException, InterruptedException { PrintWriter pw = new PrintWriter(System.out); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // String str = br.readLine(); // PriorityQueue<Long> q = new PriorityQueue<Long>(); // HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>(); StringTokenizer st = new StringTokenizer(br.readLine()); int x1 = Integer.parseInt(st.nextToken()); int y1 = Integer.parseInt(st.nextToken()); st = new StringTokenizer(br.readLine()); int x2 = Integer.parseInt(st.nextToken()); int y2 = Integer.parseInt(st.nextToken()); long d1 = x2 - x1; long d2 = y2 - y1; int n = Integer.parseInt(br.readLine()); String str = br.readLine(); char[] Arr = str.toCharArray(); pair[] arr = new pair[n]; long D1 = 0; long Acc1 = 0; long Acc2 = 0; long D2 = 0; for (int i = 0; i < Arr.length; i++) { if (Arr[i] == 'L') { D1--; } else if (Arr[i] == 'R') { D1++; } else if (Arr[i] == 'U') { D2++; } else if (Arr[i] == 'D') { D2--; } arr[i] = new pair(D1, D2); } System.out.println(binSearch(d1, d2, arr)); } }
Java
["0 0\n4 6\n3\nUUU", "0 3\n0 0\n3\nUDD", "0 0\n0 1\n1\nL"]
2 seconds
["5", "3", "-1"]
NoteIn the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: $$$(0, 0)$$$ $$$\rightarrow$$$ $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ $$$\rightarrow$$$ $$$(3, 3)$$$ $$$\rightarrow$$$ $$$(4, 4)$$$ $$$\rightarrow$$$ $$$(4, 6)$$$.In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 1)$$$ $$$\rightarrow$$$ $$$(0, 0)$$$.In the third example the ship can never reach the point $$$(0, 1)$$$.
Java 8
standard input
[ "binary search" ]
3967727db1225c4b6072d9f18e0dce00
The first line contains two integers $$$x_1, y_1$$$ ($$$0 \le x_1, y_1 \le 10^9$$$) — the initial coordinates of the ship. The second line contains two integers $$$x_2, y_2$$$ ($$$0 \le x_2, y_2 \le 10^9$$$) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The fourth line contains the string $$$s$$$ itself, consisting only of letters U, D, L and R.
1,900
The only line should contain the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$. If it's impossible then print "-1".
standard output
PASSED
e7f9e0d227cdcee198655a2c48b952b1
train_000.jsonl
1550504400
You a captain of a ship. Initially you are standing in a point $$$(x_1, y_1)$$$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $$$(x_2, y_2)$$$. You know the weather forecast — the string $$$s$$$ of length $$$n$$$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $$$s_1$$$, the second day — $$$s_2$$$, the $$$n$$$-th day — $$$s_n$$$ and $$$(n+1)$$$-th day — $$$s_1$$$ again and so on. Ship coordinates change the following way: if wind blows the direction U, then the ship moves from $$$(x, y)$$$ to $$$(x, y + 1)$$$; if wind blows the direction D, then the ship moves from $$$(x, y)$$$ to $$$(x, y - 1)$$$; if wind blows the direction L, then the ship moves from $$$(x, y)$$$ to $$$(x - 1, y)$$$; if wind blows the direction R, then the ship moves from $$$(x, y)$$$ to $$$(x + 1, y)$$$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $$$(x, y)$$$ it will move to the point $$$(x - 1, y + 1)$$$, and if it goes the direction U, then it will move to the point $$$(x, y + 2)$$$.You task is to determine the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$.
256 megabytes
import java.util.*; public class C1117 { public static void main(String[] args) { Scanner in = new Scanner(System.in); long xo = in.nextInt(); long yo = in.nextInt(); long xf = in.nextInt(); long yf = in.nextInt(); int l = in.nextInt(); int[] dx = new int[l]; int[] dy = new int[l]; int sx = 0; int sy = 0; int count = 0; char[] s = in.next().toCharArray(); for(char c : s) { if(c=='U') { sy += 1; } else if(c=='D') { sy -= 1; } else if(c=='L') { sx -= 1; } else { sx += 1; } dx[count] = sx; dy[count] = sy; count++; } //System.out.println(Arrays.toString(dy)); if(xo == xf && yo == yf) { System.out.println(0); return; } for(int i = 0; i < l; i++) { if(Math.abs(dx[i]+xo-xf) + Math.abs(dy[i]+yo-yf) < i+2) { System.out.println(i+1); return; } } long lo = 0; long hi = 2*(long)(10e14) * 2 + 50; while(lo < hi) { long mid = (lo+hi)/2; long x = sx * (mid/l) + ((mid % l) != 0 ? dx[(int)(mid % l) -1] : 0); long y = sy * (mid/l) + ((mid % l) != 0 ? dy[(int)(mid % l) -1] : 0); long dist = Math.abs(x+xo-xf) + Math.abs(y+yo-yf); //System.out.println(mid + " " + x + " " + y + " " + dist); if(dist > mid) { lo = mid +1; } else { hi = mid; } } System.out.println(lo != 4000000000000050l ? lo : -1); } }
Java
["0 0\n4 6\n3\nUUU", "0 3\n0 0\n3\nUDD", "0 0\n0 1\n1\nL"]
2 seconds
["5", "3", "-1"]
NoteIn the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: $$$(0, 0)$$$ $$$\rightarrow$$$ $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ $$$\rightarrow$$$ $$$(3, 3)$$$ $$$\rightarrow$$$ $$$(4, 4)$$$ $$$\rightarrow$$$ $$$(4, 6)$$$.In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 1)$$$ $$$\rightarrow$$$ $$$(0, 0)$$$.In the third example the ship can never reach the point $$$(0, 1)$$$.
Java 8
standard input
[ "binary search" ]
3967727db1225c4b6072d9f18e0dce00
The first line contains two integers $$$x_1, y_1$$$ ($$$0 \le x_1, y_1 \le 10^9$$$) — the initial coordinates of the ship. The second line contains two integers $$$x_2, y_2$$$ ($$$0 \le x_2, y_2 \le 10^9$$$) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The fourth line contains the string $$$s$$$ itself, consisting only of letters U, D, L and R.
1,900
The only line should contain the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$. If it's impossible then print "-1".
standard output
PASSED
d19cfb1c3fc4fa53403b431c30b56fbe
train_000.jsonl
1550504400
You a captain of a ship. Initially you are standing in a point $$$(x_1, y_1)$$$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $$$(x_2, y_2)$$$. You know the weather forecast — the string $$$s$$$ of length $$$n$$$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $$$s_1$$$, the second day — $$$s_2$$$, the $$$n$$$-th day — $$$s_n$$$ and $$$(n+1)$$$-th day — $$$s_1$$$ again and so on. Ship coordinates change the following way: if wind blows the direction U, then the ship moves from $$$(x, y)$$$ to $$$(x, y + 1)$$$; if wind blows the direction D, then the ship moves from $$$(x, y)$$$ to $$$(x, y - 1)$$$; if wind blows the direction L, then the ship moves from $$$(x, y)$$$ to $$$(x - 1, y)$$$; if wind blows the direction R, then the ship moves from $$$(x, y)$$$ to $$$(x + 1, y)$$$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $$$(x, y)$$$ it will move to the point $$$(x - 1, y + 1)$$$, and if it goes the direction U, then it will move to the point $$$(x, y + 2)$$$.You task is to determine the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author real */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { long x1; long y1; long x2; long y2; long[] prex; long[] prey; long deltax; long deltay; int n; public void solve(int testNumber, InputReader in, PrintWriter out) { x1 = in.nextLong(); y1 = in.nextLong(); x2 = in.nextLong(); y2 = in.nextLong(); deltax = x2 - x1; deltay = y2 - y1; n = in.nextInt(); String str = in.readString(); prex = new long[n + 1]; prey = new long[n + 1]; for (int i = 0; i < n; i++) { if (str.charAt(i) == 'L') { prex[i + 1]--; } if (str.charAt(i) == 'R') { prex[i + 1]++; } if (str.charAt(i) == 'U') { prey[i + 1]++; } if (str.charAt(i) == 'D') { prey[i + 1]--; } } for (int i = 1; i <= n; i++) { prey[i] += prey[i - 1]; prex[i] += prex[i - 1]; } long ans = bs(1, (long) 1e16); out.print(ans); } long bs(long l, long r) { if (l == r) { if (check(l)) return l; return -1; } if (l - r == -1) { if (check(l)) return l; if (check(r)) return r; return -1; } long mid = l + r; mid = mid / 2; if (check(mid)) return bs(l, mid); return bs(mid + 1, r); } boolean check(long val) { long cycles = val / n; long xcovered = cycles * prex[n]; long ycovered = cycles * prey[n]; long incomplete = val % n; xcovered += prex[(int) incomplete]; ycovered += prey[(int) incomplete]; long xneeded = x1 + xcovered - x2; long yneeded = y1 + ycovered - y2; if (Math.abs(xneeded) + Math.abs(yneeded) <= val) return true; return false; } } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar; private int snumChars; public InputReader(InputStream st) { this.stream = st; } public int read() { //*-*------clare------ //remeber while comparing 2 non primitive data type not to use == //remember Arrays.sort for primitive data has worst time case complexity of 0(n^2) bcoz it uses quick sort //again silly mistakes ,yr kb tk krta rhega ye mistakes //try to write simple codes ,break it into simple things // for test cases make sure println(); ;) //knowledge>rating /* public class Main implements Runnable{ public static void main(String[] args) { new Thread(null,new Main(),"Main",1<<26).start(); } public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC();//chenge the name of task solver.solve(1, in, out); out.close(); } */ if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["0 0\n4 6\n3\nUUU", "0 3\n0 0\n3\nUDD", "0 0\n0 1\n1\nL"]
2 seconds
["5", "3", "-1"]
NoteIn the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: $$$(0, 0)$$$ $$$\rightarrow$$$ $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ $$$\rightarrow$$$ $$$(3, 3)$$$ $$$\rightarrow$$$ $$$(4, 4)$$$ $$$\rightarrow$$$ $$$(4, 6)$$$.In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 1)$$$ $$$\rightarrow$$$ $$$(0, 0)$$$.In the third example the ship can never reach the point $$$(0, 1)$$$.
Java 8
standard input
[ "binary search" ]
3967727db1225c4b6072d9f18e0dce00
The first line contains two integers $$$x_1, y_1$$$ ($$$0 \le x_1, y_1 \le 10^9$$$) — the initial coordinates of the ship. The second line contains two integers $$$x_2, y_2$$$ ($$$0 \le x_2, y_2 \le 10^9$$$) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The fourth line contains the string $$$s$$$ itself, consisting only of letters U, D, L and R.
1,900
The only line should contain the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$. If it's impossible then print "-1".
standard output
PASSED
637168252539c6e22b0f80e3db9be920
train_000.jsonl
1550504400
You a captain of a ship. Initially you are standing in a point $$$(x_1, y_1)$$$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $$$(x_2, y_2)$$$. You know the weather forecast — the string $$$s$$$ of length $$$n$$$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $$$s_1$$$, the second day — $$$s_2$$$, the $$$n$$$-th day — $$$s_n$$$ and $$$(n+1)$$$-th day — $$$s_1$$$ again and so on. Ship coordinates change the following way: if wind blows the direction U, then the ship moves from $$$(x, y)$$$ to $$$(x, y + 1)$$$; if wind blows the direction D, then the ship moves from $$$(x, y)$$$ to $$$(x, y - 1)$$$; if wind blows the direction L, then the ship moves from $$$(x, y)$$$ to $$$(x - 1, y)$$$; if wind blows the direction R, then the ship moves from $$$(x, y)$$$ to $$$(x + 1, y)$$$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $$$(x, y)$$$ it will move to the point $$$(x - 1, y + 1)$$$, and if it goes the direction U, then it will move to the point $$$(x, y + 2)$$$.You task is to determine the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.io.UncheckedIOException; import java.io.Closeable; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27); thread.start(); thread.join(); } static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastInput in = new FastInput(inputStream); FastOutput out = new FastOutput(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } static class TaskC { public void solve(int testNumber, FastInput in, FastOutput out) { long[] src = new long[]{in.readInt(), in.readInt()}; long[] dst = new long[]{in.readInt(), in.readInt()}; int n = in.readInt(); int[][] dxy = new int[n][2]; for (int i = 0; i < n; i++) { switch (in.readChar()) { case 'U': dxy[i][1] = 1; break; case 'D': dxy[i][1] = -1; break; case 'L': dxy[i][0] = -1; break; case 'R': dxy[i][0] = 1; break; } } long l = 0; long r = (long) 1e18; while (l < r) { long mid = (l + r) >>> 1; if (check(src, dst, dxy, mid)) { r = mid; } else { l = mid + 1; } } if (check(src, dst, dxy, l)) { out.println(l); } else { out.println(-1); } } public boolean check(long[] src, long[] dst, int[][] dxy, long time) { int n = dxy.length; long[] sum = new long[2]; for (int i = 0; i < n; i++) { sum[0] += dxy[i][0]; sum[1] += dxy[i][1]; } long[] trace = src.clone(); trace[0] += sum[0] * (time / n); trace[1] += sum[1] * (time / n); for (int i = 0; i < time % n; i++) { trace[0] += dxy[i][0]; trace[1] += dxy[i][1]; } return dist(trace, dst) <= time; } public long dist(long[] a, long[] b) { return Math.abs(a[0] - b[0]) + Math.abs(a[1] - b[1]); } } static class FastInput { private final InputStream is; private byte[] buf = new byte[1 << 13]; private int bufLen; private int bufOffset; private int next; public FastInput(InputStream is) { this.is = is; } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { bufLen = -1; } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public int readInt() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } int val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } public char readChar() { skipBlank(); char c = (char) next; next = read(); return c; } } static class FastOutput implements AutoCloseable, Closeable { private StringBuilder cache = new StringBuilder(10 << 20); private final Writer os; public FastOutput(Writer os) { this.os = os; } public FastOutput(OutputStream os) { this(new OutputStreamWriter(os)); } public FastOutput println(int c) { cache.append(c).append('\n'); return this; } public FastOutput println(long c) { cache.append(c).append('\n'); return this; } public FastOutput flush() { try { os.append(cache); os.flush(); cache.setLength(0); } catch (IOException e) { throw new UncheckedIOException(e); } return this; } public void close() { flush(); try { os.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } public String toString() { return cache.toString(); } } }
Java
["0 0\n4 6\n3\nUUU", "0 3\n0 0\n3\nUDD", "0 0\n0 1\n1\nL"]
2 seconds
["5", "3", "-1"]
NoteIn the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: $$$(0, 0)$$$ $$$\rightarrow$$$ $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ $$$\rightarrow$$$ $$$(3, 3)$$$ $$$\rightarrow$$$ $$$(4, 4)$$$ $$$\rightarrow$$$ $$$(4, 6)$$$.In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 1)$$$ $$$\rightarrow$$$ $$$(0, 0)$$$.In the third example the ship can never reach the point $$$(0, 1)$$$.
Java 8
standard input
[ "binary search" ]
3967727db1225c4b6072d9f18e0dce00
The first line contains two integers $$$x_1, y_1$$$ ($$$0 \le x_1, y_1 \le 10^9$$$) — the initial coordinates of the ship. The second line contains two integers $$$x_2, y_2$$$ ($$$0 \le x_2, y_2 \le 10^9$$$) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The fourth line contains the string $$$s$$$ itself, consisting only of letters U, D, L and R.
1,900
The only line should contain the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$. If it's impossible then print "-1".
standard output
PASSED
fb427fa56d88b44293c813f22d131c12
train_000.jsonl
1550504400
You a captain of a ship. Initially you are standing in a point $$$(x_1, y_1)$$$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $$$(x_2, y_2)$$$. You know the weather forecast — the string $$$s$$$ of length $$$n$$$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $$$s_1$$$, the second day — $$$s_2$$$, the $$$n$$$-th day — $$$s_n$$$ and $$$(n+1)$$$-th day — $$$s_1$$$ again and so on. Ship coordinates change the following way: if wind blows the direction U, then the ship moves from $$$(x, y)$$$ to $$$(x, y + 1)$$$; if wind blows the direction D, then the ship moves from $$$(x, y)$$$ to $$$(x, y - 1)$$$; if wind blows the direction L, then the ship moves from $$$(x, y)$$$ to $$$(x - 1, y)$$$; if wind blows the direction R, then the ship moves from $$$(x, y)$$$ to $$$(x + 1, y)$$$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $$$(x, y)$$$ it will move to the point $$$(x - 1, y + 1)$$$, and if it goes the direction U, then it will move to the point $$$(x, y + 2)$$$.You task is to determine the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$.
256 megabytes
import java.util.*; import java.io.*; import java.util.regex.*; public class Codeforces{ static class MyScanner{ BufferedReader br; StringTokenizer st; MyScanner(FileReader fileReader){ br = new BufferedReader(fileReader); } MyScanner(){ br = new BufferedReader(new InputStreamReader(System.in)); } String nn(){ while(st == null || !st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); }catch(IOException e){ e.printStackTrace(); } } return st.nextToken(); } char nc(){ return nn().charAt(0); } int ni(){ return Integer.parseInt(nn()); } long nl(){ return Long.parseLong(nn()); } double nd(){ return Double.parseDouble(nn()); } int[] niArr0(int n){ int[] ar = new int[n]; for(int i = 0; i < n; i++) ar[i] = ni(); return ar; } int[] niArr1(int n){ int[] ar = new int[n + 1]; for(int i = 1; i <= n; i++) ar[i] = ni(); return ar; } long[] nlArr0(int n){ long[] ar = new long[n]; for(int i = 0; i < n; i++) ar[i] = nl(); return ar; } } public static <T> void mprintln(T ... ar){ for(T i: ar) out.print(i + " "); out.println(); } private static PrintWriter out; public static void main(String[] args) throws FileNotFoundException{ // Input from file // File inputFile = new File("JavaFile.txt"); // File outputFile = new File("JavaOutputFile.txt"); // FileReader fileReader = new FileReader(inputFile); // Here it ends MyScanner sc = new MyScanner(); // MyScanner sc = new MyScanner(fileReader); out = new PrintWriter(new BufferedOutputStream(System.out)); // Output to console // out = new PrintWriter(new PrintStream(outputFile)); // Output to file getAns(sc); out.close(); } private static void getAns(MyScanner sc){ long x1 = sc.nl(), y1 = sc.nl(); long x2 = sc.nl(), y2 = sc.nl(); int n = sc.ni(); char[] ar = sc.nn().toCharArray(); int[][] pSum = new int[2][n + 1]; for(int i = 1; i <= n; i++){ int x = pSum[0][i - 1], y = pSum[1][i - 1]; if(ar[i - 1] == 'U') y++; else if(ar[i - 1] == 'D') y--; else if(ar[i - 1] == 'L') x--; else x++; pSum[0][i] = x; pSum[1][i] = y; } // System.out.println(Arrays.deepToString(pSum)); long start = 1, end = (long)1e14 * 2, ans = -1; while(start <= end){ long mid = start + end >> 1; if(!OK(mid, pSum, x1, y1, x2, y2, n)){ start = mid + 1; }else{ ans = mid; end = mid - 1; } } out.println(ans); } private static boolean OK(long mid, int[][] pSum, long x1, long y1, long x2, long y2, int n){ long full = mid / n, partial = mid % n; long x3 = full * pSum[0][n] + pSum[0][(int)partial] + x1; long y3 = full * pSum[1][n] + pSum[1][(int)partial] + y1; return Math.abs(x3 - x2) + Math.abs(y3 - y2) <= mid; } }
Java
["0 0\n4 6\n3\nUUU", "0 3\n0 0\n3\nUDD", "0 0\n0 1\n1\nL"]
2 seconds
["5", "3", "-1"]
NoteIn the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: $$$(0, 0)$$$ $$$\rightarrow$$$ $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ $$$\rightarrow$$$ $$$(3, 3)$$$ $$$\rightarrow$$$ $$$(4, 4)$$$ $$$\rightarrow$$$ $$$(4, 6)$$$.In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 1)$$$ $$$\rightarrow$$$ $$$(0, 0)$$$.In the third example the ship can never reach the point $$$(0, 1)$$$.
Java 8
standard input
[ "binary search" ]
3967727db1225c4b6072d9f18e0dce00
The first line contains two integers $$$x_1, y_1$$$ ($$$0 \le x_1, y_1 \le 10^9$$$) — the initial coordinates of the ship. The second line contains two integers $$$x_2, y_2$$$ ($$$0 \le x_2, y_2 \le 10^9$$$) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The fourth line contains the string $$$s$$$ itself, consisting only of letters U, D, L and R.
1,900
The only line should contain the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$. If it's impossible then print "-1".
standard output
PASSED
f3b754d9c49e1498668095d012dda24d
train_000.jsonl
1550504400
You a captain of a ship. Initially you are standing in a point $$$(x_1, y_1)$$$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $$$(x_2, y_2)$$$. You know the weather forecast — the string $$$s$$$ of length $$$n$$$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $$$s_1$$$, the second day — $$$s_2$$$, the $$$n$$$-th day — $$$s_n$$$ and $$$(n+1)$$$-th day — $$$s_1$$$ again and so on. Ship coordinates change the following way: if wind blows the direction U, then the ship moves from $$$(x, y)$$$ to $$$(x, y + 1)$$$; if wind blows the direction D, then the ship moves from $$$(x, y)$$$ to $$$(x, y - 1)$$$; if wind blows the direction L, then the ship moves from $$$(x, y)$$$ to $$$(x - 1, y)$$$; if wind blows the direction R, then the ship moves from $$$(x, y)$$$ to $$$(x + 1, y)$$$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $$$(x, y)$$$ it will move to the point $$$(x - 1, y + 1)$$$, and if it goes the direction U, then it will move to the point $$$(x, y + 2)$$$.You task is to determine the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.UncheckedIOException; import java.util.Objects; import java.nio.charset.Charset; import java.util.StringTokenizer; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author mikit */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; LightScanner in = new LightScanner(inputStream); LightWriter out = new LightWriter(outputStream); CMagicShip solver = new CMagicShip(); solver.solve(1, in, out); out.close(); } static class CMagicShip { public void solve(int testNumber, LightScanner in, LightWriter out) { Vec2l start = new Vec2l(in.longs(), in.longs()); Vec2l goal = new Vec2l(in.longs(), in.longs()); int n = in.ints(); String s = in.string(); if (start.x > goal.x) { long t = start.x; start.x = goal.x; goal.x = t; s = s.replace('L', 'X').replace('R', 'L').replace('X', 'R'); } if (start.y > goal.y) { long t = start.y; start.y = goal.y; goal.y = t; s = s.replace('U', 'X').replace('D', 'U').replace('X', 'D'); } Vec2l total = new Vec2l(0, 0); for (int i = 0; i < n; i++) { switch (s.charAt(i)) { case 'L': total.x--; break; case 'R': total.x++; break; case 'D': total.y--; break; case 'U': total.y++; break; } } long ans = Long.MAX_VALUE; for (int i = 0; i < n; i++) { switch (s.charAt(i)) { case 'L': goal.x++; break; case 'R': goal.x--; break; case 'D': goal.y++; break; case 'U': goal.y--; break; } long min = -1, max = 1_000_000_000_000L; boolean succ = false; while (max - min > 0) { long mid = (min + max + 1) / 2; long count = n * mid + i + 1; long gx = goal.x - mid * total.x; long gy = goal.y - mid * total.y; if (Math.abs(gx - start.x) + Math.abs(gy - start.y) <= count) { max = mid - 1; succ = true; } else { min = mid; } } min++; //System.out.println("i=" + i); //System.out.println("start=>" + start + " goal=>" + goal + " total=>" + total); //System.out.println("min=" + min); if (succ) { ans = Math.min(ans, n * min + i + 1); } } if (ans == Long.MAX_VALUE) { out.ansln(-1); } else { out.ansln(ans); } } } static class Vec2l implements Comparable<Vec2l> { public long x; public long y; public Vec2l(long x, long y) { this.x = x; this.y = y; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Vec2l vec2i = (Vec2l) o; return x == vec2i.x && y == vec2i.y; } public int hashCode() { return Objects.hash(x, y); } public String toString() { return "(" + x + ", " + y + ")"; } public int compareTo(Vec2l o) { if (x == o.x) { return Long.compare(y, o.y); } return Long.compare(x, o.x); } } static class LightWriter implements AutoCloseable { private final Writer out; private boolean autoflush = false; private boolean breaked = true; public LightWriter(Writer out) { this.out = out; } public LightWriter(OutputStream out) { this(new BufferedWriter(new OutputStreamWriter(out, Charset.defaultCharset()))); } public LightWriter print(char c) { try { out.write(c); breaked = false; } catch (IOException ex) { throw new UncheckedIOException(ex); } return this; } public LightWriter print(String s) { try { out.write(s, 0, s.length()); breaked = false; } catch (IOException ex) { throw new UncheckedIOException(ex); } return this; } public LightWriter ans(String s) { if (!breaked) { print(' '); } return print(s); } public LightWriter ans(long l) { return ans(Long.toString(l)); } public LightWriter ans(int i) { return ans(Integer.toString(i)); } public LightWriter ansln(int... n) { for (int n1 : n) { ans(n1).ln(); } return this; } public LightWriter ansln(long... n) { for (long n1 : n) { ans(n1).ln(); } return this; } public LightWriter ln() { print(System.lineSeparator()); breaked = true; if (autoflush) { try { out.flush(); } catch (IOException ex) { throw new UncheckedIOException(ex); } } return this; } public void close() { try { out.close(); } catch (IOException ex) { throw new UncheckedIOException(ex); } } } static class LightScanner { private BufferedReader reader = null; private StringTokenizer tokenizer = null; public LightScanner(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); } public String string() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new UncheckedIOException(e); } } return tokenizer.nextToken(); } public int ints() { return Integer.parseInt(string()); } public long longs() { return Long.parseLong(string()); } } }
Java
["0 0\n4 6\n3\nUUU", "0 3\n0 0\n3\nUDD", "0 0\n0 1\n1\nL"]
2 seconds
["5", "3", "-1"]
NoteIn the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: $$$(0, 0)$$$ $$$\rightarrow$$$ $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ $$$\rightarrow$$$ $$$(3, 3)$$$ $$$\rightarrow$$$ $$$(4, 4)$$$ $$$\rightarrow$$$ $$$(4, 6)$$$.In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 1)$$$ $$$\rightarrow$$$ $$$(0, 0)$$$.In the third example the ship can never reach the point $$$(0, 1)$$$.
Java 8
standard input
[ "binary search" ]
3967727db1225c4b6072d9f18e0dce00
The first line contains two integers $$$x_1, y_1$$$ ($$$0 \le x_1, y_1 \le 10^9$$$) — the initial coordinates of the ship. The second line contains two integers $$$x_2, y_2$$$ ($$$0 \le x_2, y_2 \le 10^9$$$) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The fourth line contains the string $$$s$$$ itself, consisting only of letters U, D, L and R.
1,900
The only line should contain the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$. If it's impossible then print "-1".
standard output
PASSED
da56cf96208ae1e342b8ce8cff3279a4
train_000.jsonl
1550504400
You a captain of a ship. Initially you are standing in a point $$$(x_1, y_1)$$$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $$$(x_2, y_2)$$$. You know the weather forecast — the string $$$s$$$ of length $$$n$$$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $$$s_1$$$, the second day — $$$s_2$$$, the $$$n$$$-th day — $$$s_n$$$ and $$$(n+1)$$$-th day — $$$s_1$$$ again and so on. Ship coordinates change the following way: if wind blows the direction U, then the ship moves from $$$(x, y)$$$ to $$$(x, y + 1)$$$; if wind blows the direction D, then the ship moves from $$$(x, y)$$$ to $$$(x, y - 1)$$$; if wind blows the direction L, then the ship moves from $$$(x, y)$$$ to $$$(x - 1, y)$$$; if wind blows the direction R, then the ship moves from $$$(x, y)$$$ to $$$(x + 1, y)$$$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $$$(x, y)$$$ it will move to the point $$$(x - 1, y + 1)$$$, and if it goes the direction U, then it will move to the point $$$(x, y + 2)$$$.You task is to determine the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$.
256 megabytes
import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.Scanner; import java.util.TreeSet; public class E60C { public static void main(String[] args) { JS scan = new JS(); TreeSet<Long> worked = new TreeSet<>(); long x1 = scan.nextLong(), y1 = scan.nextLong(), x2 = scan.nextLong(), y2 = scan.nextLong(); int n= scan.nextInt(); char[] arr = scan.next().toCharArray(); int U = 0, D = 0, L = 0, R = 0; for(int i = 0;i<arr.length;i++){ if(arr[i]=='U')U++; if(arr[i]=='D')D++; if(arr[i]=='L')L++; if(arr[i]=='R')R++; } long tempx = x1, tempy = y1, tempx2 = x2, tempy2 = y2; long l = 0; long r = n*1000000000l+5; while(l!=r){ long mid = (l+r)/2; //System.out.println(mid); long multiple = mid/n; long remaining = mid%n; x1=tempx; y1 = tempy; x2 = tempx2; y2 = tempy2; x1+=R*multiple; x1-=L*multiple; y1+=U*multiple; y1-=D*multiple; for(int i = 0;i<remaining;i++){ if(arr[i]=='U')y1++; if(arr[i]=='D')y1--; if(arr[i]=='L')x1--; if(arr[i]=='R')x1++; } //System.out.println(Math.abs(y2-y1)+Math.abs(x2-x1)); //System.out.println(mid); if(Math.abs(y2-y1)+Math.abs(x2-x1)<=mid){ worked.add(mid); r = mid; } else{ l = mid+1; } } System.out.println(l == (n*1000000000l+5) ? -1 : l); // if(worked.size()==0){ // System.out.println(-1); // }else{ // for(Long curr:worked){ // System.out.println(curr); // break; // } // } } static class JS{ public int BS = 1<<16; public char NC = (char)0; byte[] buf = new byte[BS]; int bId = 0, size = 0; char c = NC; double num = 1; BufferedInputStream in; public JS() { in = new BufferedInputStream(System.in, BS); } public JS(String s) throws FileNotFoundException { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } public char nextChar(){ while(bId==size) { try { size = in.read(buf); }catch(Exception e) { return NC; } if(size==-1)return NC; bId=0; } return (char)buf[bId++]; } public int nextInt() { return (int)nextLong(); } public long nextLong() { num=1; boolean neg = false; if(c==NC)c=nextChar(); for(;(c<'0' || c>'9'); c = nextChar()) { if(c=='-')neg=true; } long res = 0; for(; c>='0' && c <='9'; c=nextChar()) { res = (res<<3)+(res<<1)+c-'0'; num*=10; } return neg?-res:res; } public double nextDouble() { double cur = nextLong(); return c!='.' ? cur:cur+nextLong()/num; } public String next() { StringBuilder res = new StringBuilder(); while(c<=32)c=nextChar(); while(c>32) { res.append(c); c=nextChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while(c<=32)c=nextChar(); while(c!='\n') { res.append(c); c=nextChar(); } return res.toString(); } public boolean hasNext() { if(c>32)return true; while(true) { c=nextChar(); if(c==NC)return false; else if(c>32)return true; } } } }
Java
["0 0\n4 6\n3\nUUU", "0 3\n0 0\n3\nUDD", "0 0\n0 1\n1\nL"]
2 seconds
["5", "3", "-1"]
NoteIn the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: $$$(0, 0)$$$ $$$\rightarrow$$$ $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ $$$\rightarrow$$$ $$$(3, 3)$$$ $$$\rightarrow$$$ $$$(4, 4)$$$ $$$\rightarrow$$$ $$$(4, 6)$$$.In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 1)$$$ $$$\rightarrow$$$ $$$(0, 0)$$$.In the third example the ship can never reach the point $$$(0, 1)$$$.
Java 8
standard input
[ "binary search" ]
3967727db1225c4b6072d9f18e0dce00
The first line contains two integers $$$x_1, y_1$$$ ($$$0 \le x_1, y_1 \le 10^9$$$) — the initial coordinates of the ship. The second line contains two integers $$$x_2, y_2$$$ ($$$0 \le x_2, y_2 \le 10^9$$$) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The fourth line contains the string $$$s$$$ itself, consisting only of letters U, D, L and R.
1,900
The only line should contain the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$. If it's impossible then print "-1".
standard output
PASSED
ad6d3b8e6c0baa7f4b53e905fefd1b4a
train_000.jsonl
1550504400
You a captain of a ship. Initially you are standing in a point $$$(x_1, y_1)$$$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $$$(x_2, y_2)$$$. You know the weather forecast — the string $$$s$$$ of length $$$n$$$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $$$s_1$$$, the second day — $$$s_2$$$, the $$$n$$$-th day — $$$s_n$$$ and $$$(n+1)$$$-th day — $$$s_1$$$ again and so on. Ship coordinates change the following way: if wind blows the direction U, then the ship moves from $$$(x, y)$$$ to $$$(x, y + 1)$$$; if wind blows the direction D, then the ship moves from $$$(x, y)$$$ to $$$(x, y - 1)$$$; if wind blows the direction L, then the ship moves from $$$(x, y)$$$ to $$$(x - 1, y)$$$; if wind blows the direction R, then the ship moves from $$$(x, y)$$$ to $$$(x + 1, y)$$$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $$$(x, y)$$$ it will move to the point $$$(x - 1, y + 1)$$$, and if it goes the direction U, then it will move to the point $$$(x, y + 2)$$$.You task is to determine the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$.
256 megabytes
import java.util.*; import org.omg.CORBA.Principal; import java.awt.List; import java.io.*; import java.lang.*; public class c1 { public static long mod = (long) Math.pow(10, 9) + 7; public static InputReader in = new InputReader(System.in); public static PrintWriter pw = new PrintWriter(System.out); public static int cnt = 0; public static long x1, x2, y1, y2, wup, wrl ,sup, srl; public static void main(String[] args) { // Code starts.. x1 = in.nextLong(); y1 = in.nextLong(); x2 = in.nextLong(); y2 = in.nextLong(); int n = in.nextInt(); String s = in.nextLine(); int[] w = new int[4]; HashMap<Character, Integer> map = new HashMap<Character, Integer>(); map.put('U', 0); map.put('D', 1); map.put('L', 2); map.put('R', 3); HashMap<Long, Long> up = new HashMap<Long, Long>(); HashMap<Long, Long> rl = new HashMap<Long, Long>(); up.put(0L, 0L); rl.put(0L, 0L); for(int i=0; i<n; i++) { w[map.get(s.charAt(i))]++; up.put((long)(i+1), (long) (w[0] - w[1])); rl.put((long)(i+1), (long) (w[3] - w[2])); } wup = w[0] - w[1]; wrl = w[3] - w[2]; sup = y2 - y1; srl = x2 - x1; //pw.print(wup+" "+wrl+" "+sup+" "+srl); //pw.print(up+" "+rl); pw.print(bs(up, rl, n)); // code ends... pw.flush(); pw.close(); } public static boolean flag = false; public static long solveQuadratic(long a, long b, long c) { long D = b * b - 4 * a * c; if (D < 0) throw new RuntimeException(); // complex solution return (long)(-b + Math.sqrt(D)) / (2 * a); } public static long bs(HashMap<Long, Long> up, HashMap<Long, Long> rl, long n) { long l = 0; long r = (long) Math.pow(10, 18)+1; long mid = 0; long ans = -1; while (r - l > 0) { mid = (r + l) / 2; //pw.println(n+" "+(mid%n)+" "+up.get(n)); long t1 = (mid/n)*up.get((long)n) + up.get(mid%n); long t2 = (mid/n)*rl.get((long)n)+ rl.get(mid%n); long woup = y1 + t1; long worl = x1 + t2; long a1 = Math.abs(y2 - woup); long a2 = Math.abs(x2 - worl); //System.out.println(mid+" "+a1+" "+a2+" "+woup+" "+worl+" "+t1+" "+t2); if(a1+a2<=mid) { ans = mid; r = mid; } else { l = mid+1; } } return ans; } public static Comparator<Integer> cmp = new Comparator<Integer>() { @Override public int compare(Integer t1, Integer t2) { return t2 - t1; } }; public static int lcs(char[] X, char[] Y, int m, int n) { int L[][] = new int[m + 1][n + 1]; for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (X[i - 1] == Y[j - 1]) L[i][j] = L[i - 1][j - 1] + 1; else L[i][j] = Math.max(L[i - 1][j], L[i][j - 1]); if (L[i][j] >= 100) return 100; } } return L[m][n]; } public static void factSieve(int[] fact, long n) { for (int i = 2; i <= n; i += 2) fact[i] = 2; for (int i = 3; i <= n; i += 2) { if (fact[i] == 0) { fact[i] = i; for (int j = i; (long) j * i <= n; j++) { fact[(int) ((long) i * j)] = i; } } } /* * int k = 1000; while(k!=1) { System.out.print(a[k]+" "); k /= a[k]; * * } */ } public static int gcd(int p2, int p22) { if (p2 == 0) return (int) p22; return gcd(p22 % p2, p2); } public static void nextGreater(long[] a, int[] ans) { Stack<Integer> stk = new Stack<>(); stk.push(0); for (int i = 1; i < a.length; i++) { if (!stk.isEmpty()) { int s = stk.pop(); while (a[s] < a[i]) { ans[s] = i; if (!stk.isEmpty()) s = stk.pop(); else break; } if (a[s] >= a[i]) stk.push(s); } stk.push(i); } return; } public static void nextGreaterRev(long[] a, int[] ans) { int n = a.length; int[] pans = new int[n]; Arrays.fill(pans, -1); long[] arev = new long[n]; for (int i = 0; i < n; i++) arev[i] = a[n - 1 - i]; Stack<Integer> stk = new Stack<>(); stk.push(0); for (int i = 1; i < n; i++) { if (!stk.isEmpty()) { int s = stk.pop(); while (arev[s] < arev[i]) { pans[s] = n - i - 1; if (!stk.isEmpty()) s = stk.pop(); else break; } if (arev[s] >= arev[i]) stk.push(s); } stk.push(i); } // for(int i=0; i<n; i++) // System.out.print(pans[i]+" "); for (int i = 0; i < n; i++) ans[i] = pans[n - i - 1]; return; } public static void nextSmaller(long[] a, int[] ans) { Stack<Integer> stk = new Stack<>(); stk.push(0); for (int i = 1; i < a.length; i++) { if (!stk.isEmpty()) { int s = stk.pop(); while (a[s] > a[i]) { ans[s] = i; if (!stk.isEmpty()) s = stk.pop(); else break; } if (a[s] <= a[i]) stk.push(s); } stk.push(i); } return; } public static long lcm(int[] numbers) { long lcm = 1; int divisor = 2; while (true) { int cnt = 0; boolean divisible = false; for (int i = 0; i < numbers.length; i++) { if (numbers[i] == 0) { return 0; } else if (numbers[i] < 0) { numbers[i] = numbers[i] * (-1); } if (numbers[i] == 1) { cnt++; } if (numbers[i] % divisor == 0) { divisible = true; numbers[i] = numbers[i] / divisor; } } if (divisible) { lcm = lcm * divisor; } else { divisor++; } if (cnt == numbers.length) { return lcm; } } } public static long fact(long n) { long factorial = 1; for (int i = 1; i <= n; i++) { factorial *= i; } return factorial; } public static long choose(long total, long choose) { if (total < choose) return 0; if (choose == 0 || choose == total) return 1; return (choose(total - 1, choose - 1) + choose(total - 1, choose)) % mod; } public static int[] suffle(int[] a, Random gen) { int n = a.length; for (int i = 0; i < n; i++) { int ind = gen.nextInt(n - i) + i; int temp = a[ind]; a[ind] = a[i]; a[i] = temp; } return a; } public static int[] sufflesort(int[] a) { int n = a.length; Random gen = new Random(); for (int i = 0; i < n; i++) { int ind = gen.nextInt(n - i) + i; int temp = a[ind]; a[ind] = a[i]; a[i] = temp; } Arrays.sort(a); return a; } public static int floorSearch(int arr[], int low, int high, int x) { if (low > high) return -1; if (x > arr[high]) return high; int mid = (low + high) / 2; if (mid > 0 && arr[mid - 1] < x && x < arr[mid]) return mid - 1; if (x < arr[mid]) return floorSearch(arr, low, mid - 1, x); return floorSearch(arr, mid + 1, high, x); } public static void swap(int a, int b) { int temp = a; a = b; b = temp; } public static ArrayList<Integer> primeFactorization(int n) { ArrayList<Integer> a = new ArrayList<Integer>(); for (int i = 2; i * i <= n; i++) { while (n % i == 0) { a.add(i); n /= i; } } if (n != 1) a.add(n); return a; } public static void sieve(boolean[] isPrime, int n) { for (int i = 1; i < n; i++) isPrime[i] = true; isPrime[0] = false; isPrime[1] = false; for (int i = 2; i * i < n; i++) { if (isPrime[i] == true) { for (int j = (2 * i); j < n; j += i) isPrime[j] = false; } } } public static int lowerbound(ArrayList<Long> net, long c2) { int i = Collections.binarySearch(net, c2); if (i < 0) i = -(i + 2); return i; } public static int lowerboundArray(int[] dis, int c2) { int i = Arrays.binarySearch(dis, c2); if (i < 0) i = -(i + 2); return i; } public static int uperbound(ArrayList<Integer> list, int c2) { int i = Collections.binarySearch(list, c2); if (i < 0) i = -(i + 1); return i; } public static int uperboundArray(int[] dis, int c2) { int i = Arrays.binarySearch(dis, c2); if (i < 0) i = -(i + 1); return i; } public static int GCD(int a, int b) { if (b == 0) return a; else return GCD(b, a % b); } public static long GCD(long a, long b) { if (b == 0) return a; else return GCD(b, a % b); } public static int d1; public static int p1; public static int q1; public static void extendedEuclid(int A, int B) { if (B == 0) { d1 = A; p1 = 1; q1 = 0; } else { extendedEuclid(B, A % B); int temp = p1; p1 = q1; q1 = temp - (A / B) * q1; } } public static long LCM(long a, long b) { return (a * b) / GCD(a, b); } public static int LCM(int a, int b) { return (a * b) / GCD(a, b); } public static int binaryExponentiation(int x, int n) { int result = 1; while (n > 0) { if (n % 2 == 1) result = result * x; x = x * x; n = n / 2; } return result; } public static int[] countDer(int n) { int der[] = new int[n + 1]; der[0] = 1; der[1] = 0; der[2] = 1; for (int i = 3; i <= n; ++i) der[i] = (i - 1) * (der[i - 1] + der[i - 2]); // Return result for n return der; } static long binomialCoeff(int n, int k) { long C[][] = new long[n + 1][k + 1]; int i, j; // Calculate value of Binomial Coefficient in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= Math.min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using previosly stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } return C[n][k]; } public static long binaryExponentiation(long x, long n) { long result = 1; while (n > 0) { if (n % 2 == 1) result = result * x; x = (x % mod * x % mod) % mod; n = n / 2; } return result; } public static int modularExponentiation(int x, int n, int M) { int result = 1; while (n > 0) { if (n % 2 == 1) result = (result * x) % M; x = (x * x) % M; n = n / 2; } return result; } public static long modularExponentiation(long x, long n, long M) { long result = 1; while (n > 0) { if (n % 2 == 1) result = (result * x) % M; x = (x * x) % M; n = n / 2; } return result; } public static long pow(long x, long n, long M) { long result = 1; while (n > 0) { if (n % 2 == 1) result = (result * x) % M; x = (x * x) % M; n = n / 2; } return result; } public static long modInverse(long q, long mod2) { return modularExponentiation(q, mod2 - 2, mod2); } public static long sie(long A, long M) { return modularExponentiation(A, M - 2, M); } public static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) { if (n % i == 0 || n % (i + 2) == 0) return false; } return true; } static class pair implements Comparable<pair> { Long x, y; pair(long bi, long wi) { this.x = bi; this.y = wi; } public int compareTo(pair o) { int result = x.compareTo(o.x); if (result == 0) result = y.compareTo(o.y); return result; } public String toString() { return x + " " + y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair) o; return (p.x -x == 0) && (p.y - y == 0); } return false; } public int hashCode() { return new Long(x).hashCode() * 31 + new Long(y).hashCode(); } } static class tripletD implements Comparable<tripletD> { Double x, y, z; tripletD(double x, double y, double z) { this.x = x; this.y = y; this.z = z; } public int compareTo(tripletD o) { int result = x.compareTo(o.x); if (result == 0) { double x1 = o.x + o.y; result = ((Double) x1).compareTo((double) (x + y)); } return result; } public String toString() { return x + " " + y + " " + z; } public boolean equals(Object o) { if (o instanceof tripletD) { tripletD p = (tripletD) o; return (p.x - x == 0) && (p.y - y==0) && (p.z - z==0); } return false; } public int hashCode() { return new Double(x).hashCode() * 31 + new Double(y).hashCode(); } } static class tripletL implements Comparable<tripletL> { Long x, y, z; tripletL(long x, long y, long z) { this.x = x; this.y = y; this.z = z; } public int compareTo(tripletL o) { int result = x.compareTo(o.x); if (result == 0) result = y.compareTo(o.y); if (result == 0) result = z.compareTo(o.z); return result; } public boolean equlas(Object o) { if (o instanceof tripletL) { tripletL p = (tripletL) o; return (x - p.x == 0) && (y - p.y ==0 ) && (z - p.z == 0); } return false; } public String toString() { return x + " " + y + " " + z; } public int hashCode() { return new Long(x).hashCode() * 31 + new Long(y).hashCode() + new Long(z).hashCode(); } } static class triplet implements Comparable<triplet> { Integer x, y, z; triplet(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } public int compareTo(triplet o) { int result = x.compareTo(o.x); if (result == 0) result = y.compareTo(o.y); if (result == 0) result = z.compareTo(o.z); return result; } public boolean equlas(Object o) { if (o instanceof triplet) { triplet p = (triplet) o; return (x - p.x == 0) && (y - p.y ==0 ) && (z - p.z == 0); } return false; } public String toString() { return x + " " + y + " " + z; } public int hashCode() { return new Long(x).hashCode() * 31 + new Long(y).hashCode() + new Long(z).hashCode(); } } /* * static class node implements Comparable<node> * * { Integer x, y, z; node(int x,int y, int z) { this.x=x; this.y=y; this.z=z; } * * public int compareTo(pair o) { int result = x.compareTo(o.x); if(result==0) * result = y.compareTo(o.y); if(result==0) result = z.compareTo(z); return * result; } * * @Override public int compareTo(node o) { // TODO Auto-generated method stub * return 0; } } */ static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["0 0\n4 6\n3\nUUU", "0 3\n0 0\n3\nUDD", "0 0\n0 1\n1\nL"]
2 seconds
["5", "3", "-1"]
NoteIn the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: $$$(0, 0)$$$ $$$\rightarrow$$$ $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ $$$\rightarrow$$$ $$$(3, 3)$$$ $$$\rightarrow$$$ $$$(4, 4)$$$ $$$\rightarrow$$$ $$$(4, 6)$$$.In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 1)$$$ $$$\rightarrow$$$ $$$(0, 0)$$$.In the third example the ship can never reach the point $$$(0, 1)$$$.
Java 8
standard input
[ "binary search" ]
3967727db1225c4b6072d9f18e0dce00
The first line contains two integers $$$x_1, y_1$$$ ($$$0 \le x_1, y_1 \le 10^9$$$) — the initial coordinates of the ship. The second line contains two integers $$$x_2, y_2$$$ ($$$0 \le x_2, y_2 \le 10^9$$$) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The fourth line contains the string $$$s$$$ itself, consisting only of letters U, D, L and R.
1,900
The only line should contain the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$. If it's impossible then print "-1".
standard output
PASSED
c7d02b6b9755f7a5b29a539aa015de74
train_000.jsonl
1550504400
You a captain of a ship. Initially you are standing in a point $$$(x_1, y_1)$$$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $$$(x_2, y_2)$$$. You know the weather forecast — the string $$$s$$$ of length $$$n$$$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $$$s_1$$$, the second day — $$$s_2$$$, the $$$n$$$-th day — $$$s_n$$$ and $$$(n+1)$$$-th day — $$$s_1$$$ again and so on. Ship coordinates change the following way: if wind blows the direction U, then the ship moves from $$$(x, y)$$$ to $$$(x, y + 1)$$$; if wind blows the direction D, then the ship moves from $$$(x, y)$$$ to $$$(x, y - 1)$$$; if wind blows the direction L, then the ship moves from $$$(x, y)$$$ to $$$(x - 1, y)$$$; if wind blows the direction R, then the ship moves from $$$(x, y)$$$ to $$$(x + 1, y)$$$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $$$(x, y)$$$ it will move to the point $$$(x - 1, y + 1)$$$, and if it goes the direction U, then it will move to the point $$$(x, y + 2)$$$.You task is to determine the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main { public void solve() { int x1 = ni(), y1 = ni(), x2 = ni(), y2 = ni(), n = ni(); int[] up = new int[n], rp = new int[n]; String wf = n(); for (int i = 0; i < n; i++) { switch (wf.charAt(i)) { case 'U': up[i]++; break; case 'D': up[i]--; break; case 'L': rp[i]--; break; case 'R': rp[i]++; break; } if (i > 0) { up[i] += up[i - 1]; rp[i] += rp[i - 1]; } } long l = 0; long r = 1_000_000_000_000_001L; while (l < r) { long mid = (l + r) / 2; long xo = rp[n - 1] * (mid / n) + (mid % n > 0 ? rp[(int)(mid % n - 1)] : 0) + x1; long yo = up[n - 1] * (mid / n) + (mid % n > 0 ? up[(int)(mid % n - 1)] : 0) + y1; if (Math.abs(xo - x2) + Math.abs(yo - y2) > mid) { l = mid + 1; } else { r = mid; } } if (l < 1_000_000_000_000_001L) { write(l + "\n"); } else { write("-1\n"); } } public static void main(String[] args) { Main m = new Main(); m.solve(); try { m.out.close(); } catch (IOException e) {} } BufferedReader in; BufferedWriter out; StringTokenizer tokenizer; public Main() { in = new BufferedReader(new InputStreamReader(System.in)); out = new BufferedWriter(new OutputStreamWriter(System.out)); } public String n() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(in.readLine()); } catch (IOException e) {} } return tokenizer.nextToken(); } public int ni() { return Integer.parseInt(n()); } public long nl() { return Long.parseLong(n()); } public void write(String s) { try { out.write(s); } catch (IOException e) {} } }
Java
["0 0\n4 6\n3\nUUU", "0 3\n0 0\n3\nUDD", "0 0\n0 1\n1\nL"]
2 seconds
["5", "3", "-1"]
NoteIn the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: $$$(0, 0)$$$ $$$\rightarrow$$$ $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ $$$\rightarrow$$$ $$$(3, 3)$$$ $$$\rightarrow$$$ $$$(4, 4)$$$ $$$\rightarrow$$$ $$$(4, 6)$$$.In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 1)$$$ $$$\rightarrow$$$ $$$(0, 0)$$$.In the third example the ship can never reach the point $$$(0, 1)$$$.
Java 8
standard input
[ "binary search" ]
3967727db1225c4b6072d9f18e0dce00
The first line contains two integers $$$x_1, y_1$$$ ($$$0 \le x_1, y_1 \le 10^9$$$) — the initial coordinates of the ship. The second line contains two integers $$$x_2, y_2$$$ ($$$0 \le x_2, y_2 \le 10^9$$$) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The fourth line contains the string $$$s$$$ itself, consisting only of letters U, D, L and R.
1,900
The only line should contain the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$. If it's impossible then print "-1".
standard output
PASSED
675d7cf0c15c6e04d453c520ecc5eab8
train_000.jsonl
1550504400
You a captain of a ship. Initially you are standing in a point $$$(x_1, y_1)$$$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $$$(x_2, y_2)$$$. You know the weather forecast — the string $$$s$$$ of length $$$n$$$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $$$s_1$$$, the second day — $$$s_2$$$, the $$$n$$$-th day — $$$s_n$$$ and $$$(n+1)$$$-th day — $$$s_1$$$ again and so on. Ship coordinates change the following way: if wind blows the direction U, then the ship moves from $$$(x, y)$$$ to $$$(x, y + 1)$$$; if wind blows the direction D, then the ship moves from $$$(x, y)$$$ to $$$(x, y - 1)$$$; if wind blows the direction L, then the ship moves from $$$(x, y)$$$ to $$$(x - 1, y)$$$; if wind blows the direction R, then the ship moves from $$$(x, y)$$$ to $$$(x + 1, y)$$$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $$$(x, y)$$$ it will move to the point $$$(x - 1, y + 1)$$$, and if it goes the direction U, then it will move to the point $$$(x, y + 2)$$$.You task is to determine the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$.
256 megabytes
import java.util.*; import java.io.*; public class Main { static int n; static long x1, y1, x2, y2; static char[] arr; static long[] dxs, dys; public static void main (String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] line = br.readLine().split(" "); x1 = p(line[0]); y1 = p(line[1]); line = br.readLine().split(" "); x2 = p(line[0]) - x1; y2 = p(line[1]) - y1; x1 = 0; y1 = 0; n = p(br.readLine()); arr = br.readLine().toCharArray(); dxs = new long[n]; dys = new long[n]; for(int i = 0; i < n; ++i){ int dx = 0, dy = 0; if(arr[i] == 'R') ++dx; else if(arr[i] == 'U') ++dy; else if(arr[i] == 'L') --dx; else --dy; if(i != 0){ dxs[i] = dxs[i - 1]; dys[i] = dys[i - 1]; } dxs[i] += dx; dys[i] += dy; } long l = 0, h = (long)(1e18); while(l != h){ long g = (l + h) / 2; if(g + 2 >= 1e18){ l = -1; break; } if(go(g)) h = g; else l = g + 1; } long out = l; System.out.println(out); } static boolean go(long in){ long numFulls = in / n; long cx = dxs[n - 1] * numFulls; long cy = dys[n - 1] * numFulls; int rem = (int)(in - numFulls * n); if(rem > 0){ cx += dxs[rem - 1]; cy += dys[rem - 1]; } return in >= Math.abs(cx - x2) + Math.abs(cy - y2); } static int p(String in){ return Integer.parseInt(in); } }
Java
["0 0\n4 6\n3\nUUU", "0 3\n0 0\n3\nUDD", "0 0\n0 1\n1\nL"]
2 seconds
["5", "3", "-1"]
NoteIn the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: $$$(0, 0)$$$ $$$\rightarrow$$$ $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ $$$\rightarrow$$$ $$$(3, 3)$$$ $$$\rightarrow$$$ $$$(4, 4)$$$ $$$\rightarrow$$$ $$$(4, 6)$$$.In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 1)$$$ $$$\rightarrow$$$ $$$(0, 0)$$$.In the third example the ship can never reach the point $$$(0, 1)$$$.
Java 8
standard input
[ "binary search" ]
3967727db1225c4b6072d9f18e0dce00
The first line contains two integers $$$x_1, y_1$$$ ($$$0 \le x_1, y_1 \le 10^9$$$) — the initial coordinates of the ship. The second line contains two integers $$$x_2, y_2$$$ ($$$0 \le x_2, y_2 \le 10^9$$$) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The fourth line contains the string $$$s$$$ itself, consisting only of letters U, D, L and R.
1,900
The only line should contain the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$. If it's impossible then print "-1".
standard output
PASSED
d7750b69d5a66046113ec308b5ab90b5
train_000.jsonl
1550504400
You a captain of a ship. Initially you are standing in a point $$$(x_1, y_1)$$$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $$$(x_2, y_2)$$$. You know the weather forecast — the string $$$s$$$ of length $$$n$$$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $$$s_1$$$, the second day — $$$s_2$$$, the $$$n$$$-th day — $$$s_n$$$ and $$$(n+1)$$$-th day — $$$s_1$$$ again and so on. Ship coordinates change the following way: if wind blows the direction U, then the ship moves from $$$(x, y)$$$ to $$$(x, y + 1)$$$; if wind blows the direction D, then the ship moves from $$$(x, y)$$$ to $$$(x, y - 1)$$$; if wind blows the direction L, then the ship moves from $$$(x, y)$$$ to $$$(x - 1, y)$$$; if wind blows the direction R, then the ship moves from $$$(x, y)$$$ to $$$(x + 1, y)$$$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $$$(x, y)$$$ it will move to the point $$$(x - 1, y + 1)$$$, and if it goes the direction U, then it will move to the point $$$(x, y + 2)$$$.You task is to determine the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; /* BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); Integer.parseInt(st.nextToken()); Long.parseLong(st.nextToken()); Scanner sc = new Scanner(System.in); */ public class issam3{ public static long nn; public static class Monster{ long x,y; long dx,dy; long x2,y2; long d; long iter = 0; public Monster(long x,long y,long dx,long dy,long x2,long y2,long d){ this.x = x; this.y = y; this.x2 = x2; this.y2 = y2; this.dx = dx; this.dy = dy; this.d = d; } public void iterate(long i){ long div = i-iter; x += div*dx; y += div*dy; d += div*nn; iter = i; } public boolean watch(){ long dist = Math.abs(x2-x)+Math.abs(y2-y); dist -= d; if(dist<=0) return true; return false; } //m.binery(a,b,m.iter) public long binery(long a,long b){ if(b-a==0){ return a; } if(b-a==1){ iterate(a); long c = b; if(watch()) c = a; return c; } long c = (a+b)/2; iterate(c); if(watch()) return binery(a,c); else return binery(c,b); } } public static long finalD(long n,long x,long y,long dx,long dy,long x2,long y2,long d){ Monster m = new Monster(x,y,dx,dy,x2,y2,d); if(m.watch()) return m.d; long tx=-1,ty=-1; if(dx!=0) tx = (Math.abs(x2-x))/Math.abs(dx); if(dy!=0) ty = (Math.abs(y2-y))/Math.abs(dy); long a = Math.min(tx,ty); long b = Math.max(tx,ty); long it = 0; long res = -1; if(a!=-1){ m.iterate(a); if(m.watch()) res = m.binery(it,a); else{ m.iterate(a+1); if(m.watch()) res = a+1; else it = a+1; } } if(res!=-1) { m.iterate(res); return m.d; } if(b>=it){ m.iterate(b); if(m.watch()){ res = m.binery(it,b); } else{ m.iterate(b+1); if(m.watch()) res = b+1; else it = b+1; } } if(res!=-1) { m.iterate(res); return m.d; } m.iterate((long)Math.pow(10,18)/(n+1)); if(m.watch()){ res = m.binery(it,m.iter); m.iterate(res); return m.d; } return -1; } public static long test(long x,long y,long x2,long y2,long d){ long dx = x2-x; long dy = y2-y; long dt = Math.abs(dy)+Math.abs(dx); if(d>=dt) return d; return 0; } public static void main(String[] args) throws Exception{ Scanner sc = new Scanner(System.in); long x1 = sc.nextLong(); long y1 = sc.nextLong(); long x2 = sc.nextLong(); long y2 = sc.nextLong(); int n = sc.nextInt(); nn = (long)n; String s = sc.next(); char[] c = s.toCharArray(); boolean ok = false; long x=x1,y=y1; long res = 0; for(int i=0;i<n;i++){ if(c[i]=='U') y++; else if(c[i]=='D') y--; else if(c[i]=='L') x--; else x++; res = test(x,y,x2,y2,(long)i+1); if(res!=0){ ok = true; break; } } if(ok) System.out.println(res); else{ long dx = x-x1; long dy = y-y1; x = x1; y = y1; long min = -1; //System.out.println(min); for(int i=0;i<n;i++){ if(c[i]=='U') y++; else if(c[i]=='D') y--; else if(c[i]=='L') x--; else x++; res = finalD(n,x,y,dx,dy,x2,y2,(long)i+1); if(res>=0){ if(min==-1) min = res; else if(min>res) min = res; } } System.out.println(min); } } }
Java
["0 0\n4 6\n3\nUUU", "0 3\n0 0\n3\nUDD", "0 0\n0 1\n1\nL"]
2 seconds
["5", "3", "-1"]
NoteIn the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: $$$(0, 0)$$$ $$$\rightarrow$$$ $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ $$$\rightarrow$$$ $$$(3, 3)$$$ $$$\rightarrow$$$ $$$(4, 4)$$$ $$$\rightarrow$$$ $$$(4, 6)$$$.In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 1)$$$ $$$\rightarrow$$$ $$$(0, 0)$$$.In the third example the ship can never reach the point $$$(0, 1)$$$.
Java 8
standard input
[ "binary search" ]
3967727db1225c4b6072d9f18e0dce00
The first line contains two integers $$$x_1, y_1$$$ ($$$0 \le x_1, y_1 \le 10^9$$$) — the initial coordinates of the ship. The second line contains two integers $$$x_2, y_2$$$ ($$$0 \le x_2, y_2 \le 10^9$$$) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The fourth line contains the string $$$s$$$ itself, consisting only of letters U, D, L and R.
1,900
The only line should contain the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$. If it's impossible then print "-1".
standard output
PASSED
6175632e2d6ddfa56e3197fbd2a2f87a
train_000.jsonl
1550504400
You a captain of a ship. Initially you are standing in a point $$$(x_1, y_1)$$$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $$$(x_2, y_2)$$$. You know the weather forecast — the string $$$s$$$ of length $$$n$$$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $$$s_1$$$, the second day — $$$s_2$$$, the $$$n$$$-th day — $$$s_n$$$ and $$$(n+1)$$$-th day — $$$s_1$$$ again and so on. Ship coordinates change the following way: if wind blows the direction U, then the ship moves from $$$(x, y)$$$ to $$$(x, y + 1)$$$; if wind blows the direction D, then the ship moves from $$$(x, y)$$$ to $$$(x, y - 1)$$$; if wind blows the direction L, then the ship moves from $$$(x, y)$$$ to $$$(x - 1, y)$$$; if wind blows the direction R, then the ship moves from $$$(x, y)$$$ to $$$(x + 1, y)$$$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $$$(x, y)$$$ it will move to the point $$$(x - 1, y + 1)$$$, and if it goes the direction U, then it will move to the point $$$(x, y + 2)$$$.You task is to determine the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$.
256 megabytes
import java.util.*; public class magicship { static long dx,dy; static int x1,y1,x2,y2; public static void main(String[] args) { Scanner scan=new Scanner(System.in); x1=scan.nextInt(); y1=scan.nextInt(); x2=scan.nextInt(); y2=scan.nextInt(); int n=scan.nextInt(); char[] s=scan.next().toCharArray(); dx=0L;dy=0L; for(int i=0;i<n;i++) { if(s[i]=='U') dy++; if(s[i]=='D') dy--; if(s[i]=='R') dx++; if(s[i]=='L') dx--; } long lo=0, hi=(long)1e18; while(hi>=lo) { long mid=(hi+lo)/2; if(!good(mid,s)) lo=mid+1; else hi=mid-1; } if(lo>=1e15) System.out.println(-1); else System.out.println(lo); } public static boolean good(long test, char[] s) { long full=test/s.length; long posx=x1+dx*full, posy=y1+dy*full; for(int id=0;;id++) { if(full*s.length+id==test) break; if(s[id]=='U') posy++; if(s[id]=='D') posy--; if(s[id]=='L') posx--; if(s[id]=='R') posx++; // System.out.println(full*s.length+" "+id+" "+test); } return Math.abs(posx-x2)+Math.abs(posy-y2)<=test; } }
Java
["0 0\n4 6\n3\nUUU", "0 3\n0 0\n3\nUDD", "0 0\n0 1\n1\nL"]
2 seconds
["5", "3", "-1"]
NoteIn the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: $$$(0, 0)$$$ $$$\rightarrow$$$ $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ $$$\rightarrow$$$ $$$(3, 3)$$$ $$$\rightarrow$$$ $$$(4, 4)$$$ $$$\rightarrow$$$ $$$(4, 6)$$$.In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 1)$$$ $$$\rightarrow$$$ $$$(0, 0)$$$.In the third example the ship can never reach the point $$$(0, 1)$$$.
Java 8
standard input
[ "binary search" ]
3967727db1225c4b6072d9f18e0dce00
The first line contains two integers $$$x_1, y_1$$$ ($$$0 \le x_1, y_1 \le 10^9$$$) — the initial coordinates of the ship. The second line contains two integers $$$x_2, y_2$$$ ($$$0 \le x_2, y_2 \le 10^9$$$) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The fourth line contains the string $$$s$$$ itself, consisting only of letters U, D, L and R.
1,900
The only line should contain the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$. If it's impossible then print "-1".
standard output
PASSED
1ae0e3b11069ada4cb69012a89137299
train_000.jsonl
1550504400
You a captain of a ship. Initially you are standing in a point $$$(x_1, y_1)$$$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $$$(x_2, y_2)$$$. You know the weather forecast — the string $$$s$$$ of length $$$n$$$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $$$s_1$$$, the second day — $$$s_2$$$, the $$$n$$$-th day — $$$s_n$$$ and $$$(n+1)$$$-th day — $$$s_1$$$ again and so on. Ship coordinates change the following way: if wind blows the direction U, then the ship moves from $$$(x, y)$$$ to $$$(x, y + 1)$$$; if wind blows the direction D, then the ship moves from $$$(x, y)$$$ to $$$(x, y - 1)$$$; if wind blows the direction L, then the ship moves from $$$(x, y)$$$ to $$$(x - 1, y)$$$; if wind blows the direction R, then the ship moves from $$$(x, y)$$$ to $$$(x + 1, y)$$$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $$$(x, y)$$$ it will move to the point $$$(x - 1, y + 1)$$$, and if it goes the direction U, then it will move to the point $$$(x, y + 2)$$$.You task is to determine the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; import java.util.*; public class Main { static int x1; static int y1; static int x2; static int y2; static int n; static String s; static long[][] ruiseki; public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); x1 = in.nextInt(); y1 = in.nextInt(); x2 = in.nextInt(); y2 = in.nextInt(); n = in.nextInt(); s = in.next(); ruiseki = new long[n+1][2]; for (int i=0;i<n;i++) { ruiseki[i+1][0] = ruiseki[i][0]; ruiseki[i+1][1] = ruiseki[i][1]; if (s.charAt(i)=='U') { ruiseki[i+1][1]++; } else if (s.charAt(i)=='D') { ruiseki[i+1][1]--; } else if (s.charAt(i)=='R') { ruiseki[i+1][0]++; } else if (s.charAt(i)=='L') { ruiseki[i+1][0]--; } } long ans = binary_search(); if (ans==10000000000000000L) { out.println(-1); } else { out.println(ans); } out.close(); } public static boolean isOK(long index) { long quotient = index/n; int remainder = (int)(index%n); if (Math.abs(x2-x1-ruiseki[remainder][0]-ruiseki[n][0]*quotient) + Math.abs(y2-y1-ruiseki[remainder][1]-ruiseki[n][1]*quotient) <= index) return true; else return false; } public static long binary_search() { long left = -1; long right = 10000000000000000L; while (right - left > 1) { long mid = left + (right - left) / 2; if (isOK(mid)) right = mid; else left = mid; } return right; } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["0 0\n4 6\n3\nUUU", "0 3\n0 0\n3\nUDD", "0 0\n0 1\n1\nL"]
2 seconds
["5", "3", "-1"]
NoteIn the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: $$$(0, 0)$$$ $$$\rightarrow$$$ $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ $$$\rightarrow$$$ $$$(3, 3)$$$ $$$\rightarrow$$$ $$$(4, 4)$$$ $$$\rightarrow$$$ $$$(4, 6)$$$.In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 1)$$$ $$$\rightarrow$$$ $$$(0, 0)$$$.In the third example the ship can never reach the point $$$(0, 1)$$$.
Java 8
standard input
[ "binary search" ]
3967727db1225c4b6072d9f18e0dce00
The first line contains two integers $$$x_1, y_1$$$ ($$$0 \le x_1, y_1 \le 10^9$$$) — the initial coordinates of the ship. The second line contains two integers $$$x_2, y_2$$$ ($$$0 \le x_2, y_2 \le 10^9$$$) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The fourth line contains the string $$$s$$$ itself, consisting only of letters U, D, L and R.
1,900
The only line should contain the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$. If it's impossible then print "-1".
standard output
PASSED
35e982c14687bccf13548c5393a78f9f
train_000.jsonl
1550504400
You a captain of a ship. Initially you are standing in a point $$$(x_1, y_1)$$$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $$$(x_2, y_2)$$$. You know the weather forecast — the string $$$s$$$ of length $$$n$$$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $$$s_1$$$, the second day — $$$s_2$$$, the $$$n$$$-th day — $$$s_n$$$ and $$$(n+1)$$$-th day — $$$s_1$$$ again and so on. Ship coordinates change the following way: if wind blows the direction U, then the ship moves from $$$(x, y)$$$ to $$$(x, y + 1)$$$; if wind blows the direction D, then the ship moves from $$$(x, y)$$$ to $$$(x, y - 1)$$$; if wind blows the direction L, then the ship moves from $$$(x, y)$$$ to $$$(x - 1, y)$$$; if wind blows the direction R, then the ship moves from $$$(x, y)$$$ to $$$(x + 1, y)$$$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $$$(x, y)$$$ it will move to the point $$$(x - 1, y + 1)$$$, and if it goes the direction U, then it will move to the point $$$(x, y + 2)$$$.You task is to determine the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; public class C { static long oo = Long.MAX_VALUE/3; static int n; static long[] cx, cy; static int[] dx = new int[256]; static int[] dy = new int[256]; public static void main(String[] args) { dx['L'] = -1; dx['R'] = 1; dy['D'] = -1; dy['U'] = 1; FastScanner scan = new FastScanner(); int x1 = scan.nextInt(), y1 = scan.nextInt(); int x2 = scan.nextInt(), y2 = scan.nextInt(); n = scan.nextInt(); char[] w = scan.next().toCharArray(); n = w.length; cx = new long[n+1]; cy = new long[n+1]; int x = 0, y = 0; for (int i = 0; i < w.length; i++) { x += dx[w[i]]; y += dy[w[i]]; cx[i+1] = x; cy[i+1] = y; } long lo = 0, hi = oo; while (lo < hi) { long mid = (lo+hi)/2; if (can(mid, x1, y1, x2, y2, w)) hi = mid; else lo = mid+1; } System.out.println(lo >= oo ? -1 : lo); } private static boolean can(long days, long x1, long y1, long x2, long y2, char[] w) { long rep = days/n; int rem = (int)(days%n); long x = x1 + cx[n]*rep + cx[rem]; long y = y1 + cy[n]*rep + cy[rem]; long xx = Math.abs(x2-x); long yy = Math.abs(y2-y); return days >= xx+yy; } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { try { br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } } public String next() { if (st.hasMoreTokens()) return st.nextToken(); try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public String nextLine() { String line = ""; try { line = br.readLine(); } catch (Exception e) { e.printStackTrace(); } return line; } } }
Java
["0 0\n4 6\n3\nUUU", "0 3\n0 0\n3\nUDD", "0 0\n0 1\n1\nL"]
2 seconds
["5", "3", "-1"]
NoteIn the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: $$$(0, 0)$$$ $$$\rightarrow$$$ $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ $$$\rightarrow$$$ $$$(3, 3)$$$ $$$\rightarrow$$$ $$$(4, 4)$$$ $$$\rightarrow$$$ $$$(4, 6)$$$.In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 1)$$$ $$$\rightarrow$$$ $$$(0, 0)$$$.In the third example the ship can never reach the point $$$(0, 1)$$$.
Java 8
standard input
[ "binary search" ]
3967727db1225c4b6072d9f18e0dce00
The first line contains two integers $$$x_1, y_1$$$ ($$$0 \le x_1, y_1 \le 10^9$$$) — the initial coordinates of the ship. The second line contains two integers $$$x_2, y_2$$$ ($$$0 \le x_2, y_2 \le 10^9$$$) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The fourth line contains the string $$$s$$$ itself, consisting only of letters U, D, L and R.
1,900
The only line should contain the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$. If it's impossible then print "-1".
standard output
PASSED
9cd85559ea903a6940e495cd9578b84c
train_000.jsonl
1550504400
You a captain of a ship. Initially you are standing in a point $$$(x_1, y_1)$$$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $$$(x_2, y_2)$$$. You know the weather forecast — the string $$$s$$$ of length $$$n$$$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $$$s_1$$$, the second day — $$$s_2$$$, the $$$n$$$-th day — $$$s_n$$$ and $$$(n+1)$$$-th day — $$$s_1$$$ again and so on. Ship coordinates change the following way: if wind blows the direction U, then the ship moves from $$$(x, y)$$$ to $$$(x, y + 1)$$$; if wind blows the direction D, then the ship moves from $$$(x, y)$$$ to $$$(x, y - 1)$$$; if wind blows the direction L, then the ship moves from $$$(x, y)$$$ to $$$(x - 1, y)$$$; if wind blows the direction R, then the ship moves from $$$(x, y)$$$ to $$$(x + 1, y)$$$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $$$(x, y)$$$ it will move to the point $$$(x - 1, y + 1)$$$, and if it goes the direction U, then it will move to the point $$$(x, y + 2)$$$.You task is to determine the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { InputReader in = new InputReader(); PrintWriter out = new PrintWriter(System.out); int t = 1; Solver s = new Solver(); for (int i = 1; i <= t; i++) { s.solve(i, in, out); } out.close(); } } class Solver { private static final long MAX = (long) 1e18; int[] posx, posy; int sx, sy, ex, ey; void solve(int test, InputReader in, PrintWriter out) { sx = in.nextInt(); sy = in.nextInt(); ex = in.nextInt(); ey = in.nextInt(); int n = in.nextInt(); String s = in.next(); posx = new int[n]; posy = new int[n]; for (int i = 0; i < n; i++) { if (s.charAt(i) == 'U') posy[i]++; else if (s.charAt(i) == 'D') posy[i]--; else if (s.charAt(i) == 'L') posx[i]--; else posx[i]++; if (i > 0) { posx[i] += posx[i - 1]; posy[i] += posy[i - 1]; } } long low = 0, high = MAX, ans = -1; while (low <= high) { long mid = (low + high) >> 1; if (can(mid)) { ans = mid; high = mid - 1; } else low = mid + 1; } out.println(ans); } private boolean can(long steps) { int n = posx.length; long times = steps / n; long x = sx, y = sy; x += posx[n - 1] * times; y += posy[n - 1] * times; if (steps % n != 0) { int e = (int) (steps % n); e--; x += posx[e]; y += posy[e]; } return (Math.abs(x - ex) + Math.abs(y - ey)) <= steps; } } class InputReader { BufferedReader br; StringTokenizer st; public InputReader() { br = new BufferedReader(new InputStreamReader(System.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()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() { return Double.parseDouble(next()); } }
Java
["0 0\n4 6\n3\nUUU", "0 3\n0 0\n3\nUDD", "0 0\n0 1\n1\nL"]
2 seconds
["5", "3", "-1"]
NoteIn the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: $$$(0, 0)$$$ $$$\rightarrow$$$ $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ $$$\rightarrow$$$ $$$(3, 3)$$$ $$$\rightarrow$$$ $$$(4, 4)$$$ $$$\rightarrow$$$ $$$(4, 6)$$$.In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 1)$$$ $$$\rightarrow$$$ $$$(0, 0)$$$.In the third example the ship can never reach the point $$$(0, 1)$$$.
Java 8
standard input
[ "binary search" ]
3967727db1225c4b6072d9f18e0dce00
The first line contains two integers $$$x_1, y_1$$$ ($$$0 \le x_1, y_1 \le 10^9$$$) — the initial coordinates of the ship. The second line contains two integers $$$x_2, y_2$$$ ($$$0 \le x_2, y_2 \le 10^9$$$) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The fourth line contains the string $$$s$$$ itself, consisting only of letters U, D, L and R.
1,900
The only line should contain the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$. If it's impossible then print "-1".
standard output
PASSED
e60e374c7cfaccaa9f2ae636718d75ad
train_000.jsonl
1550504400
You a captain of a ship. Initially you are standing in a point $$$(x_1, y_1)$$$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $$$(x_2, y_2)$$$. You know the weather forecast — the string $$$s$$$ of length $$$n$$$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $$$s_1$$$, the second day — $$$s_2$$$, the $$$n$$$-th day — $$$s_n$$$ and $$$(n+1)$$$-th day — $$$s_1$$$ again and so on. Ship coordinates change the following way: if wind blows the direction U, then the ship moves from $$$(x, y)$$$ to $$$(x, y + 1)$$$; if wind blows the direction D, then the ship moves from $$$(x, y)$$$ to $$$(x, y - 1)$$$; if wind blows the direction L, then the ship moves from $$$(x, y)$$$ to $$$(x - 1, y)$$$; if wind blows the direction R, then the ship moves from $$$(x, y)$$$ to $$$(x + 1, y)$$$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $$$(x, y)$$$ it will move to the point $$$(x - 1, y + 1)$$$, and if it goes the direction U, then it will move to the point $$$(x, y + 2)$$$.You task is to determine the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$.
256 megabytes
import java.io.*; import java.util.InputMismatchException; public class C { public static void main(String args[]) throws Exception { int x1 = scn.nextInt(); int y1 = scn.nextInt(); int x2 = scn.nextInt(); int y2 = scn.nextInt(); int n = scn.nextInt(); String s = scn.next(); int x = x2-x1; int y = y2-y1; int[] dx = new int[s.length()], dy = new int[s.length()]; for (int i = 0; i < s.length(); i++) { if (i > 0){ dx[i] = dx[i - 1]; dy[i] = dy[i - 1]; } if (s.charAt(i) == 'U') dy[i]++; else if (s.charAt(i) == 'D') dy[i]--; else if (s.charAt(i) == 'L') dx[i]--; else if (s.charAt(i) == 'R') dx[i]++; } long l = 0, r = (long) 2e18; while(l<r){ long mid = (l+r) >> 1; if(done(mid, n, dx, dy, x, y)) r = mid; else l = mid+1; } if(r == 2e18){ out.println(-1); }else{ out.println(r); } out.close(); } private static boolean done(long k, int n, int[] dx, int[] dy, int x, int y){ long steps = k/n; int d = (int) (k%n); long xx = steps*dx[n-1]; long yy = steps*dy[n-1]; if(d>0){ xx += dx[d-1]; yy += dy[d-1]; } long dist = Math.abs(xx-x)+Math.abs(yy-y); return k>=dist; } static class Pair implements Comparable<Pair> { int x, y; Pair(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return this.x + " [" + this.y + "]"; } @Override public int compareTo(Pair o) { return Integer.compare(this.x, o.x); } @Override public boolean equals(Object obj) { if (obj instanceof Pair) { Pair o = (Pair) obj; return this.y == o.y; } return false; } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static InputReader scn = new InputReader(System.in); public static PrintWriter out = new PrintWriter(System.out); }
Java
["0 0\n4 6\n3\nUUU", "0 3\n0 0\n3\nUDD", "0 0\n0 1\n1\nL"]
2 seconds
["5", "3", "-1"]
NoteIn the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: $$$(0, 0)$$$ $$$\rightarrow$$$ $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ $$$\rightarrow$$$ $$$(3, 3)$$$ $$$\rightarrow$$$ $$$(4, 4)$$$ $$$\rightarrow$$$ $$$(4, 6)$$$.In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 1)$$$ $$$\rightarrow$$$ $$$(0, 0)$$$.In the third example the ship can never reach the point $$$(0, 1)$$$.
Java 8
standard input
[ "binary search" ]
3967727db1225c4b6072d9f18e0dce00
The first line contains two integers $$$x_1, y_1$$$ ($$$0 \le x_1, y_1 \le 10^9$$$) — the initial coordinates of the ship. The second line contains two integers $$$x_2, y_2$$$ ($$$0 \le x_2, y_2 \le 10^9$$$) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The fourth line contains the string $$$s$$$ itself, consisting only of letters U, D, L and R.
1,900
The only line should contain the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$. If it's impossible then print "-1".
standard output
PASSED
f21b831cfebbbeb8575563f9a0836ddc
train_000.jsonl
1550504400
You a captain of a ship. Initially you are standing in a point $$$(x_1, y_1)$$$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $$$(x_2, y_2)$$$. You know the weather forecast — the string $$$s$$$ of length $$$n$$$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $$$s_1$$$, the second day — $$$s_2$$$, the $$$n$$$-th day — $$$s_n$$$ and $$$(n+1)$$$-th day — $$$s_1$$$ again and so on. Ship coordinates change the following way: if wind blows the direction U, then the ship moves from $$$(x, y)$$$ to $$$(x, y + 1)$$$; if wind blows the direction D, then the ship moves from $$$(x, y)$$$ to $$$(x, y - 1)$$$; if wind blows the direction L, then the ship moves from $$$(x, y)$$$ to $$$(x - 1, y)$$$; if wind blows the direction R, then the ship moves from $$$(x, y)$$$ to $$$(x + 1, y)$$$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $$$(x, y)$$$ it will move to the point $$$(x - 1, y + 1)$$$, and if it goes the direction U, then it will move to the point $$$(x, y + 2)$$$.You task is to determine the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.FilterInputStream; import java.io.BufferedInputStream; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Jenish */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; ScanReader in = new ScanReader(inputStream); PrintWriter out = new PrintWriter(outputStream); CMagicShip solver = new CMagicShip(); solver.solve(1, in, out); out.close(); } static class CMagicShip { int n; int x1; int y1; int x2; int y2; int xdiff; int ydiff; int[] curx; int[] cury; boolean check(long k) { long x = curx[n] * (k / n); long y = cury[n] * (k / n); x += curx[(int) (k % n)]; y += cury[(int) (k % n)]; return Math.abs(xdiff - x) + Math.abs(ydiff - y) <= k; } public void solve(int testNumber, ScanReader in, PrintWriter out) { x1 = in.scanInt(); y1 = in.scanInt(); x2 = in.scanInt(); y2 = in.scanInt(); xdiff = x2 - x1; ydiff = y2 - y1; n = in.scanInt(); curx = new int[n + 1]; cury = new int[n + 1]; String str = in.scanString(); for (int i = 1; i <= n; i++) { char a = str.charAt(i - 1); curx[i] = curx[i - 1]; cury[i] = cury[i - 1]; if (a == 'U') cury[i]++; else if (a == 'D') cury[i]--; else if (a == 'R') curx[i]++; else curx[i]--; } long lo = 0; long hi = (long) 2e14; long ans = -1; while (lo <= hi) { long mid = (lo + hi) / 2; if (check(mid)) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } out.println(ans); } } static class ScanReader { private byte[] buf = new byte[4 * 1024]; private int INDEX; private BufferedInputStream in; private int TOTAL; public ScanReader(InputStream inputStream) { in = new BufferedInputStream(inputStream); } private int scan() { if (INDEX >= TOTAL) { INDEX = 0; try { TOTAL = in.read(buf); } catch (Exception e) { e.printStackTrace(); } if (TOTAL <= 0) return -1; } return buf[INDEX++]; } public int scanInt() { int I = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { I *= 10; I += n - '0'; n = scan(); } } return neg * I; } public String scanString() { int c = scan(); while (isWhiteSpace(c)) c = scan(); StringBuilder RESULT = new StringBuilder(); do { RESULT.appendCodePoint(c); c = scan(); } while (!isWhiteSpace(c)); return RESULT.toString(); } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; else return false; } } }
Java
["0 0\n4 6\n3\nUUU", "0 3\n0 0\n3\nUDD", "0 0\n0 1\n1\nL"]
2 seconds
["5", "3", "-1"]
NoteIn the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: $$$(0, 0)$$$ $$$\rightarrow$$$ $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ $$$\rightarrow$$$ $$$(3, 3)$$$ $$$\rightarrow$$$ $$$(4, 4)$$$ $$$\rightarrow$$$ $$$(4, 6)$$$.In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 1)$$$ $$$\rightarrow$$$ $$$(0, 0)$$$.In the third example the ship can never reach the point $$$(0, 1)$$$.
Java 8
standard input
[ "binary search" ]
3967727db1225c4b6072d9f18e0dce00
The first line contains two integers $$$x_1, y_1$$$ ($$$0 \le x_1, y_1 \le 10^9$$$) — the initial coordinates of the ship. The second line contains two integers $$$x_2, y_2$$$ ($$$0 \le x_2, y_2 \le 10^9$$$) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The fourth line contains the string $$$s$$$ itself, consisting only of letters U, D, L and R.
1,900
The only line should contain the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$. If it's impossible then print "-1".
standard output
PASSED
204036f064abed4a68f22e7b5ce1d930
train_000.jsonl
1550504400
You a captain of a ship. Initially you are standing in a point $$$(x_1, y_1)$$$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $$$(x_2, y_2)$$$. You know the weather forecast — the string $$$s$$$ of length $$$n$$$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $$$s_1$$$, the second day — $$$s_2$$$, the $$$n$$$-th day — $$$s_n$$$ and $$$(n+1)$$$-th day — $$$s_1$$$ again and so on. Ship coordinates change the following way: if wind blows the direction U, then the ship moves from $$$(x, y)$$$ to $$$(x, y + 1)$$$; if wind blows the direction D, then the ship moves from $$$(x, y)$$$ to $$$(x, y - 1)$$$; if wind blows the direction L, then the ship moves from $$$(x, y)$$$ to $$$(x - 1, y)$$$; if wind blows the direction R, then the ship moves from $$$(x, y)$$$ to $$$(x + 1, y)$$$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $$$(x, y)$$$ it will move to the point $$$(x - 1, y + 1)$$$, and if it goes the direction U, then it will move to the point $$$(x, y + 2)$$$.You task is to determine the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$.
256 megabytes
import java.io.*; import java.util.*; import java.util.concurrent.ThreadLocalRandom; public class Main { public static void main(String[] args) throws FileNotFoundException { ConsoleIO io = new ConsoleIO(new InputStreamReader(System.in), new PrintWriter(System.out)); // String fileName = "C-large-practice"; // ConsoleIO io = new ConsoleIO(new FileReader("D:\\Dropbox\\code\\practice\\jb\\src\\" + fileName + ".in"), new PrintWriter(new File("D:\\Dropbox\\code\\practice\\jb\\src\\" + fileName + ".out"))); new Main(io).solve(); // new Main(io).solveLocal(); io.close(); } ConsoleIO io; Main(ConsoleIO io) { this.io = io; } ConsoleIO opt; Main(ConsoleIO io, ConsoleIO opt) { this.io = io; this.opt = opt; } List<List<Integer>> gr = new ArrayList<>(); long MOD = 1_000_000_007; public void solve() { int[] l = io.readIntArray(); long x1 = l[0]; long y1 = l[1]; l = io.readIntArray(); long x2 = l[0], y2 = l[1]; int n = Integer.parseInt(io.readLine()); char[] map = io.readLine().toCharArray(); long x = 0, y = 0; x2-=x1; y2-=y1; for(int i = 0;i<map.length;i++) { char c = map[i]; if (c == 'U') { y++; } else if (c == 'D') { y--; } else if (c == 'L') { x--; } else if (c == 'R') { x++; } } long left = 0, right = 5_000_000_000L; boolean can = false; while(left < right){ long m = (left + right + 1) / 2; long vx = Math.abs(x*m-x2); long vy = Math.abs(y*m-y2); if(vx+vy <= m*n){ right = m - 1; can = true; }else{ left = m; } } if(!can){ io.writeLine("-1"); return; } x *= left; y *= left; for(int i = 0;i<map.length;i++) { char c = map[i]; if (c == 'U') { y++; } else if (c == 'D') { y--; } else if (c == 'L') { x--; } else if (c == 'R') { x++; } long vx = Math.abs(x-x2); long vy = Math.abs(y-y2); if(vx+vy <= n*left + i + 1){ io.writeLine((n*left + i + 1) + ""); return; } } io.writeLine("-2"); } } class ConsoleIO { BufferedReader br; PrintWriter out; public ConsoleIO(Reader reader, PrintWriter writer){br = new BufferedReader(reader);out = writer;} public void flush(){this.out.flush();} public void close(){this.out.close();} public void writeLine(String s) {this.out.println(s);} public void writeInt(int a) {this.out.print(a);this.out.print(' ');} public void writeWord(String s){ this.out.print(s); } public void writeIntArray(int[] a, int k, String separator) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < k; i++) { if (i > 0) sb.append(separator); sb.append(a[i]); } this.writeLine(sb.toString()); } public void writeLongArray(long[] a, int k, String separator) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < k; i++) { if (i > 0) sb.append(separator); sb.append(a[i]); } this.writeLine(sb.toString()); } public int read(char[] buf, int len){try {return br.read(buf,0,len);}catch (Exception ex){ return -1; }} public String readLine() {try {return br.readLine();}catch (Exception ex){ return "";}} public long[] readLongArray() { String[]n=this.readLine().trim().split("\\s+");long[]r=new long[n.length]; for(int i=0;i<n.length;i++)r[i]=Long.parseLong(n[i]); return r; } public int[] readIntArray() { String[]n=this.readLine().trim().split("\\s+");int[]r=new int[n.length]; for(int i=0;i<n.length;i++)r[i]=Integer.parseInt(n[i]); return r; } public int[] readIntArray(int n) { int[] res = new int[n]; char[] all = this.readLine().toCharArray(); int cur = 0;boolean have = false; int k = 0; boolean neg = false; for(int i = 0;i<all.length;i++){ if(all[i]>='0' && all[i]<='9'){ cur = cur*10+all[i]-'0'; have = true; }else if(all[i]=='-') { neg = true; } else if(have){ res[k++] = neg?-cur:cur; cur = 0; have = false; neg = false; } } if(have)res[k++] = neg?-cur:cur; return res; } public int ri() { try { int r = 0; boolean start = false; boolean neg = false; while (true) { int c = br.read(); if (c >= '0' && c <= '9') { r = r * 10 + c - '0'; start = true; } else if (!start && c == '-') { start = true; neg = true; } else if (start || c == -1) return neg ? -r : r; } } catch (Exception ex) { return -1; } } public long readLong() { try { long r = 0; boolean start = false; boolean neg = false; while (true) { int c = br.read(); if (c >= '0' && c <= '9') { r = r * 10 + c - '0'; start = true; } else if (!start && c == '-') { start = true; neg = true; } else if (start || c == -1) return neg ? -r : r; } } catch (Exception ex) { return -1; } } public String readWord() { try { boolean start = false; StringBuilder sb = new StringBuilder(); while (true) { int c = br.read(); if (c!= ' ' && c!= '\r' && c!='\n' && c!='\t') { sb.append((char)c); start = true; } else if (start || c == -1) return sb.toString(); } } catch (Exception ex) { return ""; } } public char readSymbol() { try { while (true) { int c = br.read(); if (c != ' ' && c != '\r' && c != '\n' && c != '\t') { return (char) c; } } } catch (Exception ex) { return 0; } } //public char readChar(){try {return (char)br.read();}catch (Exception ex){ return 0; }} } class Pair { public Pair(int a, int b) {this.a = a;this.b = b;} public int a; public int b; } class PairLL { public PairLL(long a, long b) {this.a = a;this.b = b;} public long a; public long b; } class Triple { public Triple(int a, int b, int c) {this.a = a;this.b = b;this.c = c;} public int a; public int b; public int c; }
Java
["0 0\n4 6\n3\nUUU", "0 3\n0 0\n3\nUDD", "0 0\n0 1\n1\nL"]
2 seconds
["5", "3", "-1"]
NoteIn the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: $$$(0, 0)$$$ $$$\rightarrow$$$ $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ $$$\rightarrow$$$ $$$(3, 3)$$$ $$$\rightarrow$$$ $$$(4, 4)$$$ $$$\rightarrow$$$ $$$(4, 6)$$$.In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 1)$$$ $$$\rightarrow$$$ $$$(0, 0)$$$.In the third example the ship can never reach the point $$$(0, 1)$$$.
Java 8
standard input
[ "binary search" ]
3967727db1225c4b6072d9f18e0dce00
The first line contains two integers $$$x_1, y_1$$$ ($$$0 \le x_1, y_1 \le 10^9$$$) — the initial coordinates of the ship. The second line contains two integers $$$x_2, y_2$$$ ($$$0 \le x_2, y_2 \le 10^9$$$) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The fourth line contains the string $$$s$$$ itself, consisting only of letters U, D, L and R.
1,900
The only line should contain the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$. If it's impossible then print "-1".
standard output
PASSED
cef03aa2a80ec7b6f4ea99a7f6b62426
train_000.jsonl
1550504400
You a captain of a ship. Initially you are standing in a point $$$(x_1, y_1)$$$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $$$(x_2, y_2)$$$. You know the weather forecast — the string $$$s$$$ of length $$$n$$$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $$$s_1$$$, the second day — $$$s_2$$$, the $$$n$$$-th day — $$$s_n$$$ and $$$(n+1)$$$-th day — $$$s_1$$$ again and so on. Ship coordinates change the following way: if wind blows the direction U, then the ship moves from $$$(x, y)$$$ to $$$(x, y + 1)$$$; if wind blows the direction D, then the ship moves from $$$(x, y)$$$ to $$$(x, y - 1)$$$; if wind blows the direction L, then the ship moves from $$$(x, y)$$$ to $$$(x - 1, y)$$$; if wind blows the direction R, then the ship moves from $$$(x, y)$$$ to $$$(x + 1, y)$$$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $$$(x, y)$$$ it will move to the point $$$(x - 1, y + 1)$$$, and if it goes the direction U, then it will move to the point $$$(x, y + 2)$$$.You task is to determine the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$.
256 megabytes
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.IOException; import java.io.PrintWriter; import java.util.StringTokenizer; import static java.lang.Math.*; import static java.util.Arrays.fill; public class Main { FastScanner in; PrintWriter out; private long dist(long x1, long y1, long x2, long y2) { return abs(x1 - x2) + abs(y1 - y2); } private void solve() throws IOException { long x1 = in.nextLong(), y1 = in.nextLong(); long x2 = in.nextLong(), y2 = in.nextLong(); long n = in.nextLong(); char[] s = in.next().toCharArray(); long dx = 0, dy = 0; for (char c : s) if (c == 'U') dy++; else if (c == 'D') dy--; else if (c == 'L') dx--; else if (c == 'R') dx++; long ans = Long.MAX_VALUE; long cur = 0; if (dist(x1, y1, x2, y2) > dist(x1 + dx, y1 + dy, x2, y2) - n) { for (char c : s) { long l = -1, r = Integer.MAX_VALUE; while (l + 1 < r) { long mid = (l + r) / 2; if (dist(x1 + dx * mid, y1 + dy * mid, x2, y2) <= n * mid + cur) r = mid; else l = mid; } if (r < Integer.MAX_VALUE) ans = min(ans, n * r + cur); if (c == 'U') y1++; else if (c == 'D') y1--; else if (c == 'L') x1--; else // if (c == 'R') x1++; cur++; } out.println(ans == Long.MAX_VALUE ? -1 : ans); } else out.println(-1); } class FastScanner { StringTokenizer st; BufferedReader br; FastScanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } boolean hasNext() throws IOException { return br.ready() || (st != null && st.hasMoreTokens()); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException { return br.readLine(); } boolean hasNextLine() throws IOException { return br.ready(); } } private void run() throws IOException { in = new FastScanner(System.in); // new FastScanner(new FileInputStream(".in")); out = new PrintWriter(System.out); // new PrintWriter(new FileOutputStream(".out")); solve(); out.flush(); out.close(); } public static void main(String[] args) throws IOException { new Main().run(); } }
Java
["0 0\n4 6\n3\nUUU", "0 3\n0 0\n3\nUDD", "0 0\n0 1\n1\nL"]
2 seconds
["5", "3", "-1"]
NoteIn the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: $$$(0, 0)$$$ $$$\rightarrow$$$ $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ $$$\rightarrow$$$ $$$(3, 3)$$$ $$$\rightarrow$$$ $$$(4, 4)$$$ $$$\rightarrow$$$ $$$(4, 6)$$$.In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 1)$$$ $$$\rightarrow$$$ $$$(0, 0)$$$.In the third example the ship can never reach the point $$$(0, 1)$$$.
Java 8
standard input
[ "binary search" ]
3967727db1225c4b6072d9f18e0dce00
The first line contains two integers $$$x_1, y_1$$$ ($$$0 \le x_1, y_1 \le 10^9$$$) — the initial coordinates of the ship. The second line contains two integers $$$x_2, y_2$$$ ($$$0 \le x_2, y_2 \le 10^9$$$) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The fourth line contains the string $$$s$$$ itself, consisting only of letters U, D, L and R.
1,900
The only line should contain the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$. If it's impossible then print "-1".
standard output
PASSED
e99a9b7fee992703ab5d5c3a13d52450
train_000.jsonl
1550504400
You a captain of a ship. Initially you are standing in a point $$$(x_1, y_1)$$$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $$$(x_2, y_2)$$$. You know the weather forecast — the string $$$s$$$ of length $$$n$$$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $$$s_1$$$, the second day — $$$s_2$$$, the $$$n$$$-th day — $$$s_n$$$ and $$$(n+1)$$$-th day — $$$s_1$$$ again and so on. Ship coordinates change the following way: if wind blows the direction U, then the ship moves from $$$(x, y)$$$ to $$$(x, y + 1)$$$; if wind blows the direction D, then the ship moves from $$$(x, y)$$$ to $$$(x, y - 1)$$$; if wind blows the direction L, then the ship moves from $$$(x, y)$$$ to $$$(x - 1, y)$$$; if wind blows the direction R, then the ship moves from $$$(x, y)$$$ to $$$(x + 1, y)$$$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $$$(x, y)$$$ it will move to the point $$$(x - 1, y + 1)$$$, and if it goes the direction U, then it will move to the point $$$(x, y + 2)$$$.You task is to determine the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$.
256 megabytes
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.IOException; import java.io.PrintWriter; import java.util.StringTokenizer; import static java.lang.Math.*; import static java.util.Arrays.fill; public class Main { FastScanner in; PrintWriter out; private long dist(long x1, long y1, long x2, long y2) { return abs(x1 - x2) + abs(y1 - y2); } private void solve() throws IOException { long x1 = in.nextLong(), y1 = in.nextLong(); long x2 = in.nextLong(), y2 = in.nextLong(); long n = in.nextLong(); char[] s = in.next().toCharArray(); long dx = 0, dy = 0; for (char c : s) if (c == 'U') dy++; else if (c == 'D') dy--; else if (c == 'L') dx--; else if (c == 'R') dx++; long ans = Long.MAX_VALUE, cur = 0; for (char c : s) { long l = -1, r = Integer.MAX_VALUE; while (l + 1 < r) { long mid = (l + r) / 2; if (dist(x1 + dx * mid, y1 + dy * mid, x2, y2) <= n * mid + cur) r = mid; else l = mid; } if (r < Integer.MAX_VALUE) ans = min(ans, n * r + cur); if (c == 'U') y1++; else if (c == 'D') y1--; else if (c == 'L') x1--; else // if (c == 'R') x1++; cur++; } out.println(ans == Long.MAX_VALUE ? -1 : ans); } class FastScanner { StringTokenizer st; BufferedReader br; FastScanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } boolean hasNext() throws IOException { return br.ready() || (st != null && st.hasMoreTokens()); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException { return br.readLine(); } boolean hasNextLine() throws IOException { return br.ready(); } } private void run() throws IOException { in = new FastScanner(System.in); // new FastScanner(new FileInputStream(".in")); out = new PrintWriter(System.out); // new PrintWriter(new FileOutputStream(".out")); solve(); out.flush(); out.close(); } public static void main(String[] args) throws IOException { new Main().run(); } }
Java
["0 0\n4 6\n3\nUUU", "0 3\n0 0\n3\nUDD", "0 0\n0 1\n1\nL"]
2 seconds
["5", "3", "-1"]
NoteIn the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: $$$(0, 0)$$$ $$$\rightarrow$$$ $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ $$$\rightarrow$$$ $$$(3, 3)$$$ $$$\rightarrow$$$ $$$(4, 4)$$$ $$$\rightarrow$$$ $$$(4, 6)$$$.In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 1)$$$ $$$\rightarrow$$$ $$$(0, 0)$$$.In the third example the ship can never reach the point $$$(0, 1)$$$.
Java 8
standard input
[ "binary search" ]
3967727db1225c4b6072d9f18e0dce00
The first line contains two integers $$$x_1, y_1$$$ ($$$0 \le x_1, y_1 \le 10^9$$$) — the initial coordinates of the ship. The second line contains two integers $$$x_2, y_2$$$ ($$$0 \le x_2, y_2 \le 10^9$$$) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The fourth line contains the string $$$s$$$ itself, consisting only of letters U, D, L and R.
1,900
The only line should contain the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$. If it's impossible then print "-1".
standard output
PASSED
df3bad153fb2656b32e0d9bc31318149
train_000.jsonl
1550504400
You a captain of a ship. Initially you are standing in a point $$$(x_1, y_1)$$$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $$$(x_2, y_2)$$$. You know the weather forecast — the string $$$s$$$ of length $$$n$$$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $$$s_1$$$, the second day — $$$s_2$$$, the $$$n$$$-th day — $$$s_n$$$ and $$$(n+1)$$$-th day — $$$s_1$$$ again and so on. Ship coordinates change the following way: if wind blows the direction U, then the ship moves from $$$(x, y)$$$ to $$$(x, y + 1)$$$; if wind blows the direction D, then the ship moves from $$$(x, y)$$$ to $$$(x, y - 1)$$$; if wind blows the direction L, then the ship moves from $$$(x, y)$$$ to $$$(x - 1, y)$$$; if wind blows the direction R, then the ship moves from $$$(x, y)$$$ to $$$(x + 1, y)$$$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $$$(x, y)$$$ it will move to the point $$$(x - 1, y + 1)$$$, and if it goes the direction U, then it will move to the point $$$(x, y + 2)$$$.You task is to determine the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$.
256 megabytes
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.IOException; import java.io.PrintWriter; import java.util.StringTokenizer; import static java.lang.Math.*; import static java.util.Arrays.fill; public class Main { FastScanner in; PrintWriter out; private void solve() throws IOException { long x1 = in.nextLong(), y1 = in.nextLong(); long x2 = in.nextLong(), y2 = in.nextLong(); long n = in.nextLong(); char[] s = in.next().toCharArray(); long dx = 0, dy = 0; for (char c : s) if (c == 'U') dy++; else if (c == 'D') dy--; else if (c == 'L') dx--; else if (c == 'R') dx++; long ans = Long.MAX_VALUE, cur = 0; for (char c : s) { long l = -1, r = Integer.MAX_VALUE; while (l + 1 < r) { long mid = (l + r) / 2; if (abs(x2 - x1 - dx * mid) + abs(y2 - y1 - dy * mid) <= n * mid + cur) r = mid; else l = mid; } if (r < Integer.MAX_VALUE) ans = min(ans, n * r + cur); if (c == 'U') y1++; else if (c == 'D') y1--; else if (c == 'L') x1--; else // if (c == 'R') x1++; cur++; } out.println(ans == Long.MAX_VALUE ? -1 : ans); } class FastScanner { StringTokenizer st; BufferedReader br; FastScanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } boolean hasNext() throws IOException { return br.ready() || (st != null && st.hasMoreTokens()); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException { return br.readLine(); } boolean hasNextLine() throws IOException { return br.ready(); } } private void run() throws IOException { in = new FastScanner(System.in); // new FastScanner(new FileInputStream(".in")); out = new PrintWriter(System.out); // new PrintWriter(new FileOutputStream(".out")); solve(); out.flush(); out.close(); } public static void main(String[] args) throws IOException { new Main().run(); } }
Java
["0 0\n4 6\n3\nUUU", "0 3\n0 0\n3\nUDD", "0 0\n0 1\n1\nL"]
2 seconds
["5", "3", "-1"]
NoteIn the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: $$$(0, 0)$$$ $$$\rightarrow$$$ $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ $$$\rightarrow$$$ $$$(3, 3)$$$ $$$\rightarrow$$$ $$$(4, 4)$$$ $$$\rightarrow$$$ $$$(4, 6)$$$.In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 1)$$$ $$$\rightarrow$$$ $$$(0, 0)$$$.In the third example the ship can never reach the point $$$(0, 1)$$$.
Java 8
standard input
[ "binary search" ]
3967727db1225c4b6072d9f18e0dce00
The first line contains two integers $$$x_1, y_1$$$ ($$$0 \le x_1, y_1 \le 10^9$$$) — the initial coordinates of the ship. The second line contains two integers $$$x_2, y_2$$$ ($$$0 \le x_2, y_2 \le 10^9$$$) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The fourth line contains the string $$$s$$$ itself, consisting only of letters U, D, L and R.
1,900
The only line should contain the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$. If it's impossible then print "-1".
standard output
PASSED
e6bfe966d1fda4917b3b78d6bf483089
train_000.jsonl
1550504400
You a captain of a ship. Initially you are standing in a point $$$(x_1, y_1)$$$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $$$(x_2, y_2)$$$. You know the weather forecast — the string $$$s$$$ of length $$$n$$$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $$$s_1$$$, the second day — $$$s_2$$$, the $$$n$$$-th day — $$$s_n$$$ and $$$(n+1)$$$-th day — $$$s_1$$$ again and so on. Ship coordinates change the following way: if wind blows the direction U, then the ship moves from $$$(x, y)$$$ to $$$(x, y + 1)$$$; if wind blows the direction D, then the ship moves from $$$(x, y)$$$ to $$$(x, y - 1)$$$; if wind blows the direction L, then the ship moves from $$$(x, y)$$$ to $$$(x - 1, y)$$$; if wind blows the direction R, then the ship moves from $$$(x, y)$$$ to $$$(x + 1, y)$$$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $$$(x, y)$$$ it will move to the point $$$(x - 1, y + 1)$$$, and if it goes the direction U, then it will move to the point $$$(x, y + 2)$$$.You task is to determine the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$.
256 megabytes
//created by Whiplash99 import java.io.*; import java.util.*; public class C { private static Pair[] prefix; static class Pair { long x, y; Pair(){} } private static long _lb(long X1, long Y1, long X2, long Y2, int N) { long l=1, r=(long)(2e14), mid, ans=-1; while (l<=r) { mid=(l+r)/2; long cycles=mid/N; int extra=(int)(mid%N); long X3=X1+cycles*prefix[N].x+prefix[extra].x; long Y3=Y1+cycles*prefix[N].y+prefix[extra].y; if(Math.abs(X2-X3)+Math.abs(Y2-Y3)<=mid){ans=mid; r=mid-1;} else l=mid+1; } return ans; } public static void main(String[] args) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int i,N; String s[]=br.readLine().trim().split(" "); int X1=Integer.parseInt(s[0]); int Y1=Integer.parseInt(s[1]); s=br.readLine().trim().split(" "); int X2=Integer.parseInt(s[0]); int Y2=Integer.parseInt(s[1]); N=Integer.parseInt(br.readLine().trim()); char str[]=br.readLine().trim().toCharArray(); prefix=new Pair[N+5]; for(i=0;i<=N;i++) prefix[i]=new Pair(); for(i=1;i<=N;i++) { prefix[i].x=prefix[i-1].x; prefix[i].y=prefix[i-1].y; switch (str[i-1]) { case 'U': prefix[i].y++; break; case 'D': prefix[i].y--; break; case 'L': prefix[i].x--; break; case 'R': prefix[i].x++; break; } } System.out.println(_lb(X1,Y1,X2,Y2,N)); } }
Java
["0 0\n4 6\n3\nUUU", "0 3\n0 0\n3\nUDD", "0 0\n0 1\n1\nL"]
2 seconds
["5", "3", "-1"]
NoteIn the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: $$$(0, 0)$$$ $$$\rightarrow$$$ $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ $$$\rightarrow$$$ $$$(3, 3)$$$ $$$\rightarrow$$$ $$$(4, 4)$$$ $$$\rightarrow$$$ $$$(4, 6)$$$.In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 1)$$$ $$$\rightarrow$$$ $$$(0, 0)$$$.In the third example the ship can never reach the point $$$(0, 1)$$$.
Java 8
standard input
[ "binary search" ]
3967727db1225c4b6072d9f18e0dce00
The first line contains two integers $$$x_1, y_1$$$ ($$$0 \le x_1, y_1 \le 10^9$$$) — the initial coordinates of the ship. The second line contains two integers $$$x_2, y_2$$$ ($$$0 \le x_2, y_2 \le 10^9$$$) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The fourth line contains the string $$$s$$$ itself, consisting only of letters U, D, L and R.
1,900
The only line should contain the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$. If it's impossible then print "-1".
standard output
PASSED
fbc0dca5d027fb4e7259c84c9c779a01
train_000.jsonl
1550504400
You a captain of a ship. Initially you are standing in a point $$$(x_1, y_1)$$$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $$$(x_2, y_2)$$$. You know the weather forecast — the string $$$s$$$ of length $$$n$$$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $$$s_1$$$, the second day — $$$s_2$$$, the $$$n$$$-th day — $$$s_n$$$ and $$$(n+1)$$$-th day — $$$s_1$$$ again and so on. Ship coordinates change the following way: if wind blows the direction U, then the ship moves from $$$(x, y)$$$ to $$$(x, y + 1)$$$; if wind blows the direction D, then the ship moves from $$$(x, y)$$$ to $$$(x, y - 1)$$$; if wind blows the direction L, then the ship moves from $$$(x, y)$$$ to $$$(x - 1, y)$$$; if wind blows the direction R, then the ship moves from $$$(x, y)$$$ to $$$(x + 1, y)$$$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $$$(x, y)$$$ it will move to the point $$$(x - 1, y + 1)$$$, and if it goes the direction U, then it will move to the point $$$(x, y + 2)$$$.You task is to determine the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$.
256 megabytes
import java.util.*; public class magicship { static long dx,dy; static int x1,y1,x2,y2; public static void main(String[] args) { Scanner scan=new Scanner(System.in); x1=scan.nextInt(); y1=scan.nextInt(); x2=scan.nextInt(); y2=scan.nextInt(); int n=scan.nextInt(); char[] s=scan.next().toCharArray(); dx=0L;dy=0L; for(int i=0;i<n;i++) { if(s[i]=='U') dy++; if(s[i]=='D') dy--; if(s[i]=='R') dx++; if(s[i]=='L') dx--; } long lo=0, hi=(long)1e18; while(hi>=lo) { long mid=(hi+lo)/2; if(!good(mid,s)) lo=mid+1; else hi=mid-1; } if(lo>=1e15) System.out.println(-1); else System.out.println(lo); } public static boolean good(long test, char[] s) { long full=test/s.length; long posx=x1+dx*full, posy=y1+dy*full; for(int id=0;;id++) { if(full*s.length+id==test) break; if(s[id]=='U') posy++; if(s[id]=='D') posy--; if(s[id]=='L') posx--; if(s[id]=='R') posx++; // System.out.println(full*s.length+" "+id+" "+test); } return Math.abs(posx-x2)+Math.abs(posy-y2)<=test; } }
Java
["0 0\n4 6\n3\nUUU", "0 3\n0 0\n3\nUDD", "0 0\n0 1\n1\nL"]
2 seconds
["5", "3", "-1"]
NoteIn the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: $$$(0, 0)$$$ $$$\rightarrow$$$ $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ $$$\rightarrow$$$ $$$(3, 3)$$$ $$$\rightarrow$$$ $$$(4, 4)$$$ $$$\rightarrow$$$ $$$(4, 6)$$$.In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 1)$$$ $$$\rightarrow$$$ $$$(0, 0)$$$.In the third example the ship can never reach the point $$$(0, 1)$$$.
Java 8
standard input
[ "binary search" ]
3967727db1225c4b6072d9f18e0dce00
The first line contains two integers $$$x_1, y_1$$$ ($$$0 \le x_1, y_1 \le 10^9$$$) — the initial coordinates of the ship. The second line contains two integers $$$x_2, y_2$$$ ($$$0 \le x_2, y_2 \le 10^9$$$) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The fourth line contains the string $$$s$$$ itself, consisting only of letters U, D, L and R.
1,900
The only line should contain the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$. If it's impossible then print "-1".
standard output
PASSED
e18036cd85e5783882cc22c6180051ba
train_000.jsonl
1550504400
You a captain of a ship. Initially you are standing in a point $$$(x_1, y_1)$$$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $$$(x_2, y_2)$$$. You know the weather forecast — the string $$$s$$$ of length $$$n$$$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $$$s_1$$$, the second day — $$$s_2$$$, the $$$n$$$-th day — $$$s_n$$$ and $$$(n+1)$$$-th day — $$$s_1$$$ again and so on. Ship coordinates change the following way: if wind blows the direction U, then the ship moves from $$$(x, y)$$$ to $$$(x, y + 1)$$$; if wind blows the direction D, then the ship moves from $$$(x, y)$$$ to $$$(x, y - 1)$$$; if wind blows the direction L, then the ship moves from $$$(x, y)$$$ to $$$(x - 1, y)$$$; if wind blows the direction R, then the ship moves from $$$(x, y)$$$ to $$$(x + 1, y)$$$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $$$(x, y)$$$ it will move to the point $$$(x - 1, y + 1)$$$, and if it goes the direction U, then it will move to the point $$$(x, y + 2)$$$.You task is to determine the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class Main { static long fac[], ifac[], DR[] = new long[101]; static int MOD = (int) (1e9 + 7); static boolean[] isPrime; static int minPrime[]; static long dp[][]; static int n; static int d, x, y; public static void main(String args[]) throws NumberFormatException, IOException { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); long x1=in.nextLong(); long y1=in.nextLong(); long x2=in.nextLong(); long y2=in.nextLong(); int n=in.nextInt(); String st=in.nextToken(); long dx[]=new long[n+1]; long dy[]=new long[n+1]; for(int i=1;i<=n;i++){ dx[i]=dx[i-1]; dy[i]=dy[i-1]; if(st.charAt(i-1)=='D'){ dy[i]--; } if(st.charAt(i-1)=='U'){ dy[i]++; }if(st.charAt(i-1)=='L'){ dx[i]--; }if(st.charAt(i-1)=='R'){ dx[i]++; } } long low=0; long ans=Long.MAX_VALUE/4; long high=(long)(1e18); while(low<=high){ long mid=(low+high)/2; long cntx= x1 + (mid/n)*dx[n] + dx[(int)(mid%n)]; long cnty= y1 + (mid/n)*dy[n] + dy[(int)(mid%n)]; long cx= Math.abs(cntx-x2); long cy= Math.abs(cnty-y2); if(cx+cy<=mid){ ans=mid; high=mid-1; } else{ low=mid+1; } } if(ans==Long.MAX_VALUE/4){ out.println("-1"); out.close(); return; } out.println(ans); out.close(); } static void Dr() { DR[0] = 1; DR[1] = 0; DR[2] = 1; for (int i = 3; i < 101; i++) { DR[i] = ((i - 1) * (DR[i - 1] + DR[i - 2]) % MOD) % MOD; } } static long mp(long a, long b) { long ans = 1; while (b != 0) { if (b % 2 == 1) ans = (ans * a) % MOD; a = (a * a) % MOD; b /= 2; } return ans % MOD; } static void precompute() { int i; int N = 1000005; fac = new long[N]; ifac = new long[N]; fac[0] = 1; for (i = 1; i < N; i++) { fac[i] = (i * fac[i - 1]) % MOD; } ifac[N - 1] = mp(fac[N - 1], MOD - 2); for (i = N - 2; i >= 0; i--) { ifac[i] = ((i + 1) * ifac[i + 1]) % MOD; } } public static long combine(int n, int k) { if (k > n - k) { k = n - k; } long result = 1; for (int i = 0; i < k; i++) { result *= (n - i); result /= (i + 1); } return result; } static long mInv(long A) { return mp(A, MOD - 2); } static long mC(int n, int k) { // calculates C(n,k) mod p (assuming p is prime). // if(k>n-k)k=n-k; long an; // n * (n-1) * ... * (n-k+1) if (k <= 0) return 1; if (n < k) return 0; an = fac[n] % MOD; an *= ifac[n - k]; an %= MOD; an *= ifac[k]; an %= MOD; // numerator / denominator mod p. return an; } static int gcd(int num1, int num2) { if (num1 > num2) { int temp = num1; num1 = num2; num2 = temp; } while (num1 != 0) { int temp = num1; num1 = num2 % num1; num2 = temp; } return num2; } static long gcd(long A, long B) { if (B == 0) return A; else return gcd(B, A % B); } static void extendedEuclid(int A, int B) { if (B == 0) { d = A; x = 1; y = 0; } else { extendedEuclid(B, A % B); int temp = x; x = y; y = temp - (A / B) * y; } } // if(gcd(A,M)==1) static int mInv2(int A, int M) { extendedEuclid(A, M); return (x % M + M) % M; } static void sieve() { int N = 100005; isPrime = new boolean[N + 1]; minPrime = new int[N + 1]; for (int i = 0; i <= N; ++i) { isPrime[i] = true; minPrime[i] = i; } isPrime[0] = false; isPrime[1] = false; for (int i = 2; i * i <= N; ++i) { if (isPrime[i] == true) { for (int j = i * i; j <= N; j += i) { isPrime[j] = false; minPrime[j] = i; } } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String nextToken() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["0 0\n4 6\n3\nUUU", "0 3\n0 0\n3\nUDD", "0 0\n0 1\n1\nL"]
2 seconds
["5", "3", "-1"]
NoteIn the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: $$$(0, 0)$$$ $$$\rightarrow$$$ $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ $$$\rightarrow$$$ $$$(3, 3)$$$ $$$\rightarrow$$$ $$$(4, 4)$$$ $$$\rightarrow$$$ $$$(4, 6)$$$.In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 1)$$$ $$$\rightarrow$$$ $$$(0, 0)$$$.In the third example the ship can never reach the point $$$(0, 1)$$$.
Java 8
standard input
[ "binary search" ]
3967727db1225c4b6072d9f18e0dce00
The first line contains two integers $$$x_1, y_1$$$ ($$$0 \le x_1, y_1 \le 10^9$$$) — the initial coordinates of the ship. The second line contains two integers $$$x_2, y_2$$$ ($$$0 \le x_2, y_2 \le 10^9$$$) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The fourth line contains the string $$$s$$$ itself, consisting only of letters U, D, L and R.
1,900
The only line should contain the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$. If it's impossible then print "-1".
standard output
PASSED
acab7752924335ecd3aa000bb303df46
train_000.jsonl
1550504400
You a captain of a ship. Initially you are standing in a point $$$(x_1, y_1)$$$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $$$(x_2, y_2)$$$. You know the weather forecast — the string $$$s$$$ of length $$$n$$$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $$$s_1$$$, the second day — $$$s_2$$$, the $$$n$$$-th day — $$$s_n$$$ and $$$(n+1)$$$-th day — $$$s_1$$$ again and so on. Ship coordinates change the following way: if wind blows the direction U, then the ship moves from $$$(x, y)$$$ to $$$(x, y + 1)$$$; if wind blows the direction D, then the ship moves from $$$(x, y)$$$ to $$$(x, y - 1)$$$; if wind blows the direction L, then the ship moves from $$$(x, y)$$$ to $$$(x - 1, y)$$$; if wind blows the direction R, then the ship moves from $$$(x, y)$$$ to $$$(x + 1, y)$$$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $$$(x, y)$$$ it will move to the point $$$(x - 1, y + 1)$$$, and if it goes the direction U, then it will move to the point $$$(x, y + 2)$$$.You task is to determine the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$.
256 megabytes
import java.io.*; import java.util.*; public class magicship { public static void main(String[] args) throws IOException{ BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(f.readLine()); int x = Integer.parseInt(st.nextToken()); int y = Integer.parseInt(st.nextToken()); st = new StringTokenizer(f.readLine()); int x2 = Integer.parseInt(st.nextToken()); int y2 = Integer.parseInt(st.nextToken()); int n = Integer.parseInt(f.readLine()); String str = f.readLine(); int[][] wind = new int[n + 1][2]; for(int i = 1; i <= n; i ++) { char ch = str.charAt(i - 1); if(ch == 'U') { wind[i][0] += wind[i-1][0]; wind[i][1] += wind[i-1][1] + 1; } if(ch == 'D') { wind[i][0] += wind[i-1][0]; wind[i][1] += wind[i-1][1] - 1; } if(ch == 'L') { wind[i][0] += wind[i-1][0] - 1; wind[i][1] += wind[i-1][1]; } if(ch == 'R') { wind[i][0] += wind[i-1][0] + 1; wind[i][1] += wind[i-1][1]; } } long left = 0; long right = (long) 1e18; while(right - left > 1) { long mid = (left + right)/2; long count = mid / n; long rem = mid % n; long x3 = x + wind[(int) rem][0] + count * 1L * wind[n][0]; long y3 = y + wind[(int) rem][1] + count * 1L * wind[n][1]; long dist = Math.abs(x3 - x2) + Math.abs(y3 - y2); if(dist <= mid) right = mid; else left = mid; } if(right > (long) 5e17) { right = -1; } System.out.println(right); } }
Java
["0 0\n4 6\n3\nUUU", "0 3\n0 0\n3\nUDD", "0 0\n0 1\n1\nL"]
2 seconds
["5", "3", "-1"]
NoteIn the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: $$$(0, 0)$$$ $$$\rightarrow$$$ $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ $$$\rightarrow$$$ $$$(3, 3)$$$ $$$\rightarrow$$$ $$$(4, 4)$$$ $$$\rightarrow$$$ $$$(4, 6)$$$.In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 1)$$$ $$$\rightarrow$$$ $$$(0, 0)$$$.In the third example the ship can never reach the point $$$(0, 1)$$$.
Java 8
standard input
[ "binary search" ]
3967727db1225c4b6072d9f18e0dce00
The first line contains two integers $$$x_1, y_1$$$ ($$$0 \le x_1, y_1 \le 10^9$$$) — the initial coordinates of the ship. The second line contains two integers $$$x_2, y_2$$$ ($$$0 \le x_2, y_2 \le 10^9$$$) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The fourth line contains the string $$$s$$$ itself, consisting only of letters U, D, L and R.
1,900
The only line should contain the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$. If it's impossible then print "-1".
standard output
PASSED
b45d00e044ae0f3b9e0cdc90b121c930
train_000.jsonl
1550504400
You a captain of a ship. Initially you are standing in a point $$$(x_1, y_1)$$$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $$$(x_2, y_2)$$$. You know the weather forecast — the string $$$s$$$ of length $$$n$$$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $$$s_1$$$, the second day — $$$s_2$$$, the $$$n$$$-th day — $$$s_n$$$ and $$$(n+1)$$$-th day — $$$s_1$$$ again and so on. Ship coordinates change the following way: if wind blows the direction U, then the ship moves from $$$(x, y)$$$ to $$$(x, y + 1)$$$; if wind blows the direction D, then the ship moves from $$$(x, y)$$$ to $$$(x, y - 1)$$$; if wind blows the direction L, then the ship moves from $$$(x, y)$$$ to $$$(x - 1, y)$$$; if wind blows the direction R, then the ship moves from $$$(x, y)$$$ to $$$(x + 1, y)$$$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $$$(x, y)$$$ it will move to the point $$$(x - 1, y + 1)$$$, and if it goes the direction U, then it will move to the point $$$(x, y + 2)$$$.You task is to determine the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$.
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws Throwable { Scanner sc = new Scanner(System.in); int x1 = sc.nextInt() , y1 = sc.nextInt() , x2 = sc.nextInt() , y2 = sc.nextInt(); int n = sc.nextInt(); char[] a = sc.nextLine().toCharArray(); long[] dx = new long[n],dy = new long[n]; for (int i = 0; i < n; i++) { if(i>0) { dx[i] = dx[i-1]; dy[i] = dy[i-1]; } if(a[i]=='U') ++dy[i]; else if(a[i]=='D') --dy[i]; else if(a[i]=='R') ++dx[i]; else if(a[i]=='L') --dx[i]; } long lo = 0 , hi = (long)1e16 , ans = -1; while(lo<=hi) { long steps = lo + ((hi-lo)/2); int idx = (int) ((steps%n)-1); long x = 1l * x1 + dx[n-1]*(steps/n) + (idx>=0?dx[idx]:0); long y = 1l * y1 + dy[n-1]*(steps/n) + (idx>=0?dy[idx]:0); long dist = Math.abs(x2-x) + Math.abs(y2-y); if(dist<=steps) { ans = steps; hi = steps-1; } else lo = steps+1; } System.out.println(ans); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String file) throws FileNotFoundException { br = new BufferedReader(new FileReader(file)); } 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 double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public int[] nexIntArray() throws Throwable { st = new StringTokenizer(br.readLine()); int[] a = new int[st.countTokens()]; for (int i = 0; i < a.length; i++) a[i] = nextInt(); return a; } public boolean ready() throws IOException { return br.ready(); } } }
Java
["0 0\n4 6\n3\nUUU", "0 3\n0 0\n3\nUDD", "0 0\n0 1\n1\nL"]
2 seconds
["5", "3", "-1"]
NoteIn the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: $$$(0, 0)$$$ $$$\rightarrow$$$ $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ $$$\rightarrow$$$ $$$(3, 3)$$$ $$$\rightarrow$$$ $$$(4, 4)$$$ $$$\rightarrow$$$ $$$(4, 6)$$$.In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 1)$$$ $$$\rightarrow$$$ $$$(0, 0)$$$.In the third example the ship can never reach the point $$$(0, 1)$$$.
Java 8
standard input
[ "binary search" ]
3967727db1225c4b6072d9f18e0dce00
The first line contains two integers $$$x_1, y_1$$$ ($$$0 \le x_1, y_1 \le 10^9$$$) — the initial coordinates of the ship. The second line contains two integers $$$x_2, y_2$$$ ($$$0 \le x_2, y_2 \le 10^9$$$) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The fourth line contains the string $$$s$$$ itself, consisting only of letters U, D, L and R.
1,900
The only line should contain the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$. If it's impossible then print "-1".
standard output
PASSED
05d18b90ef517883f820c4d66ac2bf98
train_000.jsonl
1550504400
You a captain of a ship. Initially you are standing in a point $$$(x_1, y_1)$$$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $$$(x_2, y_2)$$$. You know the weather forecast — the string $$$s$$$ of length $$$n$$$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $$$s_1$$$, the second day — $$$s_2$$$, the $$$n$$$-th day — $$$s_n$$$ and $$$(n+1)$$$-th day — $$$s_1$$$ again and so on. Ship coordinates change the following way: if wind blows the direction U, then the ship moves from $$$(x, y)$$$ to $$$(x, y + 1)$$$; if wind blows the direction D, then the ship moves from $$$(x, y)$$$ to $$$(x, y - 1)$$$; if wind blows the direction L, then the ship moves from $$$(x, y)$$$ to $$$(x - 1, y)$$$; if wind blows the direction R, then the ship moves from $$$(x, y)$$$ to $$$(x + 1, y)$$$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $$$(x, y)$$$ it will move to the point $$$(x - 1, y + 1)$$$, and if it goes the direction U, then it will move to the point $$$(x, y + 2)$$$.You task is to determine the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$.
256 megabytes
/*Author: Satyajeet Singh, Delhi Technological University*/ import java.io.*; import java.util.*; import java.text.*; import java.lang.*; public class Main { /*********************************************Constants******************************************/ static PrintWriter out=new PrintWriter(new OutputStreamWriter(System.out)); static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static long mod=(long)1e9+7; static long mod1=998244353; static boolean sieve[]; static ArrayList<Integer> primes; static ArrayList<Long> factorial; static HashSet<Integer> graph[]; /****************************************Solutions Begins*****************************************/ public static void main (String[] args) throws Exception { String st[]=br.readLine().split(" "); int x1=Integer.parseInt(st[0]); int y1=Integer.parseInt(st[1]); st=br.readLine().split(" "); int x2=Integer.parseInt(st[0]); int y2=Integer.parseInt(st[1]); st=br.readLine().split(" "); int n=Integer.parseInt(st[0]); st=br.readLine().split(" "); String str=st[0]; int dx[]=new int[n]; int dy[]=new int[n]; int sx=0; int sy=0; for(int i=0;i<n;i++){ char aa=st[0].charAt(i); if(aa=='U'){ sy++; } else if(aa=='L'){ sx--; } else if(aa=='R'){ sx++; } else{ sy--; } dx[i]=sx; dy[i]=sy; } long start=0; long end=(long)1e18; long ans=-1; while(start<=end){ long mid=(start+end)>>1; long kk=mid/n; long mm=mid%n; long xx=sx*kk+dx[(int)mm]; long yy=sy*kk+dy[(int)mm]; long xr=Math.abs(xx+x1-x2); long yr=Math.abs(yy+y1-y2); if(xr+yr<=mid+1){ //out.println(mid+" "+xr+" "+yr); ans=mid+1; end=mid-1; } else{ start=mid+1; } } out.println(ans); /****************************************Solutions Ends**************************************************/ out.flush(); out.close(); } /****************************************Template Begins************************************************/ /***************************************Precision Printing**********************************************/ static void printPrecision(double d){ DecimalFormat ft = new DecimalFormat("0.000000"); out.println(ft.format(d)); } /******************************************Graph*********************************************************/ static void Makegraph(int n){ graph=new HashSet[n]; for(int i=0;i<n;i++){ graph[i]=new HashSet<>(); } } static void addEdge(int a,int b){ graph[a].add(b); } /*********************************************PAIR********************************************************/ static class PairComp implements Comparator<Pair>{ public int compare(Pair p1,Pair p2){ if(p1.u>p2.u){ return 1; } else if(p1.u<p2.u){ return -1; } else{ return p1.v-p2.v; } } } static class Pair implements Comparable<Pair> { int u; int v; int index=-1; public Pair(int u, int v) { this.u = u; this.v = v; } public int hashCode() { int hu = (int) (u ^ (u >>> 32)); int hv = (int) (v ^ (v >>> 32)); return 31 * hu + hv; } public boolean equals(Object o) { Pair other = (Pair) o; return u == other.u && v == other.v; } public int compareTo(Pair other) { if(index!=other.index) return Long.compare(index, other.index); return Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u); } public String toString() { return "[u=" + u + ", v=" + v + "]"; } } /*******************************************LONG PAIR****************************************************/ static class PairCompL implements Comparator<Pairl>{ public int compare(Pairl p1,Pairl p2){ if(p1.u>p2.u){ return 1; } else if(p1.u<p2.u){ return -1; } else{ return 0; } } } static class Pairl implements Comparable<Pair> { long u; long v; int index=-1; public Pairl(long u, long v) { this.u = u; this.v = v; } public int hashCode() { int hu = (int) (u ^ (u >>> 32)); int hv = (int) (v ^ (v >>> 32)); return 31 * hu + hv; } public boolean equals(Object o) { Pair other = (Pair) o; return u == other.u && v == other.v; } public int compareTo(Pair other) { if(index!=other.index) return Long.compare(index, other.index); return Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u); } public String toString() { return "[u=" + u + ", v=" + v + "]"; } } /*****************************************DEBUG***********************************************************/ public static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } /*****************************************NUMBER THEORY****************************************************/ /************************************MODULAR EXPONENTIATION***********************************************/ static long modulo(long a,long b,long c) { long x=1; long y=a; while(b > 0){ if(b%2 == 1){ x=(x*y)%c; } y = (y*y)%c; // squaring the base b /= 2; } return x%c; } /********************************************GCD**********************************************************/ static long gcd(long x, long y) { if(x==0) return y; if(y==0) return x; long r=0, a, b; a = (x > y) ? x : y; // a is greater number b = (x < y) ? x : y; // b is smaller number r = b; while(a % b != 0) { r = a % b; a = b; b = r; } return r; } /******************************************SIEVE**********************************************************/ static void sieveMake(int n){ sieve=new boolean[n]; Arrays.fill(sieve,true); sieve[0]=false; sieve[1]=false; for(int i=2;i*i<n;i++){ if(sieve[i]){ for(int j=i*i;j<n;j+=i){ sieve[j]=false; } } } primes=new ArrayList<Integer>(); for(int i=0;i<n;i++){ if(sieve[i]){ primes.add(i); } } } /***************************************FACTORIAL*********************************************************/ static void fact(int n){ factorial=new ArrayList<>(); factorial.add((long)1); for(int i=1;i<=n;i++){ factorial.add((factorial.get(i-1)*i)%mod); } } /*******************************************ncr*********************************************************/ static long ncr(int n,int k){ long aa=modulo(factorial.get(n-k),mod-2,mod); long bb=modulo(factorial.get(k),mod-2,mod); long cc=factorial.get(n); long ans=(aa*cc)%mod; ans=(ans*bb)%mod; return ans; } /***************************************STRING REVERSE****************************************************/ static String reverse(String str){ char r[]=new char[str.length()]; int j=0; for(int i=str.length()-1;i>=0;i--){ r[j]=str.charAt(i); j++; } return new String(r); } } /********************************************End***********************************************************/
Java
["0 0\n4 6\n3\nUUU", "0 3\n0 0\n3\nUDD", "0 0\n0 1\n1\nL"]
2 seconds
["5", "3", "-1"]
NoteIn the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: $$$(0, 0)$$$ $$$\rightarrow$$$ $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ $$$\rightarrow$$$ $$$(3, 3)$$$ $$$\rightarrow$$$ $$$(4, 4)$$$ $$$\rightarrow$$$ $$$(4, 6)$$$.In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 1)$$$ $$$\rightarrow$$$ $$$(0, 0)$$$.In the third example the ship can never reach the point $$$(0, 1)$$$.
Java 8
standard input
[ "binary search" ]
3967727db1225c4b6072d9f18e0dce00
The first line contains two integers $$$x_1, y_1$$$ ($$$0 \le x_1, y_1 \le 10^9$$$) — the initial coordinates of the ship. The second line contains two integers $$$x_2, y_2$$$ ($$$0 \le x_2, y_2 \le 10^9$$$) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The fourth line contains the string $$$s$$$ itself, consisting only of letters U, D, L and R.
1,900
The only line should contain the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$. If it's impossible then print "-1".
standard output
PASSED
e61917b112d9c7ca2257009cff586d08
train_000.jsonl
1550504400
You a captain of a ship. Initially you are standing in a point $$$(x_1, y_1)$$$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $$$(x_2, y_2)$$$. You know the weather forecast — the string $$$s$$$ of length $$$n$$$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $$$s_1$$$, the second day — $$$s_2$$$, the $$$n$$$-th day — $$$s_n$$$ and $$$(n+1)$$$-th day — $$$s_1$$$ again and so on. Ship coordinates change the following way: if wind blows the direction U, then the ship moves from $$$(x, y)$$$ to $$$(x, y + 1)$$$; if wind blows the direction D, then the ship moves from $$$(x, y)$$$ to $$$(x, y - 1)$$$; if wind blows the direction L, then the ship moves from $$$(x, y)$$$ to $$$(x - 1, y)$$$; if wind blows the direction R, then the ship moves from $$$(x, y)$$$ to $$$(x + 1, y)$$$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $$$(x, y)$$$ it will move to the point $$$(x - 1, y + 1)$$$, and if it goes the direction U, then it will move to the point $$$(x, y + 2)$$$.You task is to determine the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author prakharjain */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); CMagicShip solver = new CMagicShip(); solver.solve(1, in, out); out.close(); } static class CMagicShip { public void solve(int testNumber, InputReader in, OutputWriter out) { long x1 = in.ni(); long y1 = in.ni(); long x2 = in.ni(); long y2 = in.ni(); if (x1 == x2 && y1 == y2) { out.println(0); return; } int n = in.nextInt(); String s = in.next(); // Set<Character> dr = new HashSet<>(); // // if (x2 > x1) { // dr.add('R'); // } else if (x2 < x1) { // dr.add('L'); // } // // if (y2 > y1) { // dr.add('U'); // } else if (y2 < y1) { // dr.add('D'); // } // boolean poss = false; // for (int i = 0; i < n; i++) { // if (dr.contains(s.charAt(i))) { // poss = true; // break; // } // } // // if (!poss) { // out.println(-1); // return; // } long px = x1; long py = y1; for (int i = 0; i < n; i++) { char ch = s.charAt(i); if (ch == 'U') { py++; } else if (ch == 'D') { py--; } else if (ch == 'L') { px--; } else if (ch == 'R') { px++; } } long dx = px - x1; long dy = py - y1; long cx = x1; long cy = y1; long ans = Long.MAX_VALUE; for (int i = 0; i < n; i++) { char ch = s.charAt(i); if (ch == 'U') { cy++; } else if (ch == 'D') { cy--; } else if (ch == 'L') { cx--; } else if (ch == 'R') { cx++; } long md = Math.abs(x2 - cx) + Math.abs(y2 - cy); if (md <= i + 1) { ans = Math.min(ans, i + 1); continue; } long max = (long) 2e9; long lo = 1; long hi = (long) 2e9; long ca = max + 1; while (lo <= hi) { long mid = lo + (hi - lo) / 2; long nx = cx + mid * dx; long ny = cy + mid * dy; long nmd = Math.abs(x2 - nx) + Math.abs(y2 - ny); long time = i + 1 + n * mid; if (nmd <= time) { ca = Math.min(ca, mid); hi = mid - 1; } else { lo = mid + 1; } } if (ca < max + 1) ans = Math.min(ans, i + 1 + ca * n); } if (ans == Long.MAX_VALUE) { ans = -1; } out.println(ans); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String nextString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public int ni() { return nextInt(); } public String next() { return nextString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void println(long i) { writer.println(i); } public void println(int i) { writer.println(i); } } }
Java
["0 0\n4 6\n3\nUUU", "0 3\n0 0\n3\nUDD", "0 0\n0 1\n1\nL"]
2 seconds
["5", "3", "-1"]
NoteIn the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: $$$(0, 0)$$$ $$$\rightarrow$$$ $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ $$$\rightarrow$$$ $$$(3, 3)$$$ $$$\rightarrow$$$ $$$(4, 4)$$$ $$$\rightarrow$$$ $$$(4, 6)$$$.In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 1)$$$ $$$\rightarrow$$$ $$$(0, 0)$$$.In the third example the ship can never reach the point $$$(0, 1)$$$.
Java 8
standard input
[ "binary search" ]
3967727db1225c4b6072d9f18e0dce00
The first line contains two integers $$$x_1, y_1$$$ ($$$0 \le x_1, y_1 \le 10^9$$$) — the initial coordinates of the ship. The second line contains two integers $$$x_2, y_2$$$ ($$$0 \le x_2, y_2 \le 10^9$$$) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The fourth line contains the string $$$s$$$ itself, consisting only of letters U, D, L and R.
1,900
The only line should contain the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$. If it's impossible then print "-1".
standard output
PASSED
602651f2c20365aad2bc88661f5d0d73
train_000.jsonl
1550504400
You a captain of a ship. Initially you are standing in a point $$$(x_1, y_1)$$$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $$$(x_2, y_2)$$$. You know the weather forecast — the string $$$s$$$ of length $$$n$$$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $$$s_1$$$, the second day — $$$s_2$$$, the $$$n$$$-th day — $$$s_n$$$ and $$$(n+1)$$$-th day — $$$s_1$$$ again and so on. Ship coordinates change the following way: if wind blows the direction U, then the ship moves from $$$(x, y)$$$ to $$$(x, y + 1)$$$; if wind blows the direction D, then the ship moves from $$$(x, y)$$$ to $$$(x, y - 1)$$$; if wind blows the direction L, then the ship moves from $$$(x, y)$$$ to $$$(x - 1, y)$$$; if wind blows the direction R, then the ship moves from $$$(x, y)$$$ to $$$(x + 1, y)$$$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $$$(x, y)$$$ it will move to the point $$$(x - 1, y + 1)$$$, and if it goes the direction U, then it will move to the point $$$(x, y + 2)$$$.You task is to determine the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author prakharjain */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); CMagicShip solver = new CMagicShip(); solver.solve(1, in, out); out.close(); } static class CMagicShip { public void solve(int testNumber, InputReader in, OutputWriter out) { long x1 = in.ni(); long y1 = in.ni(); long x2 = in.ni(); long y2 = in.ni(); if (x1 == x2 && y1 == y2) { out.println(0); return; } int n = in.nextInt(); String s = in.next(); // Set<Character> dr = new HashSet<>(); // // if (x2 > x1) { // dr.add('R'); // } else if (x2 < x1) { // dr.add('L'); // } // // if (y2 > y1) { // dr.add('U'); // } else if (y2 < y1) { // dr.add('D'); // } // boolean poss = false; // for (int i = 0; i < n; i++) { // if (dr.contains(s.charAt(i))) { // poss = true; // break; // } // } // // if (!poss) { // out.println(-1); // return; // } long px = x1; long py = y1; for (int i = 0; i < n; i++) { char ch = s.charAt(i); if (ch == 'U') { py++; } else if (ch == 'D') { py--; } else if (ch == 'L') { px--; } else if (ch == 'R') { px++; } } long dx = px - x1; long dy = py - y1; long cx = x1; long cy = y1; long ans = Long.MAX_VALUE; for (int i = 0; i < n; i++) { char ch = s.charAt(i); if (ch == 'U') { cy++; } else if (ch == 'D') { cy--; } else if (ch == 'L') { cx--; } else if (ch == 'R') { cx++; } long md = Math.abs(x2 - cx) + Math.abs(y2 - cy); if (md <= i + 1) { ans = Math.min(ans, i + 1); continue; } long max = (long) 2e9; long lo = 1; long hi = (long) 2e9; long ca = max + 1; while (lo <= hi) { long mid = lo + (hi - lo) / 2; long nx = cx + mid * dx; long ny = cy + mid * dy; long nmd = Math.abs(x2 - nx) + Math.abs(y2 - ny); long time = i + 1 + n * mid; if (nmd <= time) { ca = Math.min(ca, mid); hi = mid - 1; } else { lo = mid + 1; } } if (ca < max + 1) ans = Math.min(ans, i + 1 + ca * n); } if (ans == Long.MAX_VALUE) { ans = -1; } out.println(ans); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void println(long i) { writer.println(i); } public void println(int i) { writer.println(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String nextString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public int ni() { return nextInt(); } public String next() { return nextString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["0 0\n4 6\n3\nUUU", "0 3\n0 0\n3\nUDD", "0 0\n0 1\n1\nL"]
2 seconds
["5", "3", "-1"]
NoteIn the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: $$$(0, 0)$$$ $$$\rightarrow$$$ $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ $$$\rightarrow$$$ $$$(3, 3)$$$ $$$\rightarrow$$$ $$$(4, 4)$$$ $$$\rightarrow$$$ $$$(4, 6)$$$.In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 1)$$$ $$$\rightarrow$$$ $$$(0, 0)$$$.In the third example the ship can never reach the point $$$(0, 1)$$$.
Java 8
standard input
[ "binary search" ]
3967727db1225c4b6072d9f18e0dce00
The first line contains two integers $$$x_1, y_1$$$ ($$$0 \le x_1, y_1 \le 10^9$$$) — the initial coordinates of the ship. The second line contains two integers $$$x_2, y_2$$$ ($$$0 \le x_2, y_2 \le 10^9$$$) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The fourth line contains the string $$$s$$$ itself, consisting only of letters U, D, L and R.
1,900
The only line should contain the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$. If it's impossible then print "-1".
standard output
PASSED
83e9c7065039be9cee7528235ad30161
train_000.jsonl
1550504400
You a captain of a ship. Initially you are standing in a point $$$(x_1, y_1)$$$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $$$(x_2, y_2)$$$. You know the weather forecast — the string $$$s$$$ of length $$$n$$$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $$$s_1$$$, the second day — $$$s_2$$$, the $$$n$$$-th day — $$$s_n$$$ and $$$(n+1)$$$-th day — $$$s_1$$$ again and so on. Ship coordinates change the following way: if wind blows the direction U, then the ship moves from $$$(x, y)$$$ to $$$(x, y + 1)$$$; if wind blows the direction D, then the ship moves from $$$(x, y)$$$ to $$$(x, y - 1)$$$; if wind blows the direction L, then the ship moves from $$$(x, y)$$$ to $$$(x - 1, y)$$$; if wind blows the direction R, then the ship moves from $$$(x, y)$$$ to $$$(x + 1, y)$$$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $$$(x, y)$$$ it will move to the point $$$(x - 1, y + 1)$$$, and if it goes the direction U, then it will move to the point $$$(x, y + 2)$$$.You task is to determine the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$.
256 megabytes
//package educational.round60; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class C { InputStream is; PrintWriter out; String INPUT = ""; void solve() { long x1 = ni(), y1 = ni(); long x2 = ni(), y2 = ni(); int n = ni(); char[] s = ns(n); x2 -= x1; y2 -= y1; long low = -1, high = (long)(2e16); long q = high; while(high - low > 1){ long h = high+low>>1; if(ok(h, x2, y2, s)){ high = h; }else{ low = h; } } if(high >= q/2){ out.println(-1); }else{ out.println(high); } } boolean ok(long h, long x, long y, char[] s) { int[] dx = { 1, 0, -1, 0 }; int[] dy = { 0, 1, 0, -1 }; String D = "RULD"; long n = s.length; for(int i = 0;i < s.length;i++){ int ind = D.indexOf(s[i]); x -= (h+n-1-i)/n*dx[ind]; y -= (h+n-1-i)/n*dy[ind]; } return Math.abs(x)+Math.abs(y) <= h; } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new C().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["0 0\n4 6\n3\nUUU", "0 3\n0 0\n3\nUDD", "0 0\n0 1\n1\nL"]
2 seconds
["5", "3", "-1"]
NoteIn the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: $$$(0, 0)$$$ $$$\rightarrow$$$ $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ $$$\rightarrow$$$ $$$(3, 3)$$$ $$$\rightarrow$$$ $$$(4, 4)$$$ $$$\rightarrow$$$ $$$(4, 6)$$$.In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 1)$$$ $$$\rightarrow$$$ $$$(0, 0)$$$.In the third example the ship can never reach the point $$$(0, 1)$$$.
Java 8
standard input
[ "binary search" ]
3967727db1225c4b6072d9f18e0dce00
The first line contains two integers $$$x_1, y_1$$$ ($$$0 \le x_1, y_1 \le 10^9$$$) — the initial coordinates of the ship. The second line contains two integers $$$x_2, y_2$$$ ($$$0 \le x_2, y_2 \le 10^9$$$) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The fourth line contains the string $$$s$$$ itself, consisting only of letters U, D, L and R.
1,900
The only line should contain the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$. If it's impossible then print "-1".
standard output
PASSED
aebf2b92a1f96c242ea2b76d6beb6b9b
train_000.jsonl
1550504400
You a captain of a ship. Initially you are standing in a point $$$(x_1, y_1)$$$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $$$(x_2, y_2)$$$. You know the weather forecast — the string $$$s$$$ of length $$$n$$$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $$$s_1$$$, the second day — $$$s_2$$$, the $$$n$$$-th day — $$$s_n$$$ and $$$(n+1)$$$-th day — $$$s_1$$$ again and so on. Ship coordinates change the following way: if wind blows the direction U, then the ship moves from $$$(x, y)$$$ to $$$(x, y + 1)$$$; if wind blows the direction D, then the ship moves from $$$(x, y)$$$ to $$$(x, y - 1)$$$; if wind blows the direction L, then the ship moves from $$$(x, y)$$$ to $$$(x - 1, y)$$$; if wind blows the direction R, then the ship moves from $$$(x, y)$$$ to $$$(x + 1, y)$$$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $$$(x, y)$$$ it will move to the point $$$(x - 1, y + 1)$$$, and if it goes the direction U, then it will move to the point $$$(x, y + 2)$$$.You task is to determine the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$.
256 megabytes
import java.util.*; import java.io.*; import static java.lang.Math.*; /* spar5h */ public class cf3 implements Runnable { public void run() { InputReader s = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int dx = s.nextInt(), dy = s.nextInt(); dx = s.nextInt() - dx; dy = s.nextInt() - dy; int n = s.nextInt(); char[] a = (" " + s.next()).toCharArray(); int[] x = new int[n + 1]; int[] y = new int[n + 1]; for(int i = 1; i <= n; i++) { x[i] = x[i - 1]; y[i] = y[i - 1]; if(a[i] == 'L') x[i]--; else if(a[i] == 'R') x[i]++; else if(a[i] == 'D') y[i]--; else y[i]++; } long l = 0, r = (long)1e15; long res = -1; while(l <= r) { long mid = (l + r) / 2; long cx = mid / n * x[n] + x[(int)(mid % n)]; long cy = mid / n * y[n] + y[(int)(mid % n)]; if(abs(dx - cx) + abs(dy - cy) <= mid) { res = mid; r = mid - 1; } else l = mid + 1; } w.println(res); w.close(); } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static void main(String args[]) throws Exception { new Thread(null, new cf3(),"cf3",1<<26).start(); } }
Java
["0 0\n4 6\n3\nUUU", "0 3\n0 0\n3\nUDD", "0 0\n0 1\n1\nL"]
2 seconds
["5", "3", "-1"]
NoteIn the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: $$$(0, 0)$$$ $$$\rightarrow$$$ $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ $$$\rightarrow$$$ $$$(3, 3)$$$ $$$\rightarrow$$$ $$$(4, 4)$$$ $$$\rightarrow$$$ $$$(4, 6)$$$.In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 1)$$$ $$$\rightarrow$$$ $$$(0, 0)$$$.In the third example the ship can never reach the point $$$(0, 1)$$$.
Java 8
standard input
[ "binary search" ]
3967727db1225c4b6072d9f18e0dce00
The first line contains two integers $$$x_1, y_1$$$ ($$$0 \le x_1, y_1 \le 10^9$$$) — the initial coordinates of the ship. The second line contains two integers $$$x_2, y_2$$$ ($$$0 \le x_2, y_2 \le 10^9$$$) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The fourth line contains the string $$$s$$$ itself, consisting only of letters U, D, L and R.
1,900
The only line should contain the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$. If it's impossible then print "-1".
standard output
PASSED
f61b0f822ccc543c9ea6c5f061fb47a3
train_000.jsonl
1550504400
You a captain of a ship. Initially you are standing in a point $$$(x_1, y_1)$$$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $$$(x_2, y_2)$$$. You know the weather forecast — the string $$$s$$$ of length $$$n$$$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $$$s_1$$$, the second day — $$$s_2$$$, the $$$n$$$-th day — $$$s_n$$$ and $$$(n+1)$$$-th day — $$$s_1$$$ again and so on. Ship coordinates change the following way: if wind blows the direction U, then the ship moves from $$$(x, y)$$$ to $$$(x, y + 1)$$$; if wind blows the direction D, then the ship moves from $$$(x, y)$$$ to $$$(x, y - 1)$$$; if wind blows the direction L, then the ship moves from $$$(x, y)$$$ to $$$(x - 1, y)$$$; if wind blows the direction R, then the ship moves from $$$(x, y)$$$ to $$$(x + 1, y)$$$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $$$(x, y)$$$ it will move to the point $$$(x - 1, y + 1)$$$, and if it goes the direction U, then it will move to the point $$$(x, y + 2)$$$.You task is to determine the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Queue; import java.util.Set; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; public class q5 { public static void main(String[] args) throws IOException { Reader.init(System.in); PrintWriter out=new PrintWriter(System.out); StringBuffer output=new StringBuffer(""); int x1=Reader.nextInt(); int y1=Reader.nextInt(); int x2=Reader.nextInt(); int y2=Reader.nextInt(); int n=Reader.nextInt(); int[] xchange=new int[n+1]; int[] ychange=new int[n+1]; String s=Reader.next(); for(int i=0;i<n;i++) { if(s.charAt(i)=='U') { xchange[i+1]=xchange[i]; ychange[i+1]=ychange[i]; ychange[i+1]++; } else if(s.charAt(i)=='D') { xchange[i+1]=xchange[i]; ychange[i+1]=ychange[i]; ychange[i+1]--; } else if(s.charAt(i)=='L') { xchange[i+1]=xchange[i]; ychange[i+1]=ychange[i]; xchange[i+1]--; } else { xchange[i+1]=xchange[i]; ychange[i+1]=ychange[i]; xchange[i+1]++; } } long low=1,high=(long)2e14; long ans=-1; while(low<=high) { long middle=(low+high)/2; long v1=middle/n;int v2=(int)(middle%n); long x1change=x1+v1*xchange[n]+xchange[v2]; long y1change=y1+v1*ychange[n]+ychange[v2]; long v=Math.abs(x2-x1change)+Math.abs(y2-y1change); if(v<=middle) { ans=middle; high=middle-1; } else low=middle+1; } output.append(ans); out.write(output.toString()); out.flush(); } } class NoD{ int a,b; String s; NoD(int aa,int bb){ a=aa;b=bb; s=a+" "+b; } @Override public boolean equals(Object o) { if(o!=null && o.getClass()==getClass()) { NoD c= (NoD) o; return c.a==a && c.b==b; } return false; } @Override public int hashCode() { return s.hashCode(); } } class Reader { static BufferedReader reader; static StringTokenizer tokenizer; /** call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input) ); tokenizer = new StringTokenizer(""); } /** get next word */ static String nextLine() throws IOException{ return reader.readLine(); } static String next() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt( next() ); } static long nextLong() throws IOException { return Long.parseLong( next() ); } static double nextDouble() throws IOException { return Double.parseDouble( next() ); } }
Java
["0 0\n4 6\n3\nUUU", "0 3\n0 0\n3\nUDD", "0 0\n0 1\n1\nL"]
2 seconds
["5", "3", "-1"]
NoteIn the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: $$$(0, 0)$$$ $$$\rightarrow$$$ $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ $$$\rightarrow$$$ $$$(3, 3)$$$ $$$\rightarrow$$$ $$$(4, 4)$$$ $$$\rightarrow$$$ $$$(4, 6)$$$.In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 1)$$$ $$$\rightarrow$$$ $$$(0, 0)$$$.In the third example the ship can never reach the point $$$(0, 1)$$$.
Java 8
standard input
[ "binary search" ]
3967727db1225c4b6072d9f18e0dce00
The first line contains two integers $$$x_1, y_1$$$ ($$$0 \le x_1, y_1 \le 10^9$$$) — the initial coordinates of the ship. The second line contains two integers $$$x_2, y_2$$$ ($$$0 \le x_2, y_2 \le 10^9$$$) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The fourth line contains the string $$$s$$$ itself, consisting only of letters U, D, L and R.
1,900
The only line should contain the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$. If it's impossible then print "-1".
standard output
PASSED
d0ba33cbba7e256050415ff36821e678
train_000.jsonl
1550504400
You a captain of a ship. Initially you are standing in a point $$$(x_1, y_1)$$$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $$$(x_2, y_2)$$$. You know the weather forecast — the string $$$s$$$ of length $$$n$$$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $$$s_1$$$, the second day — $$$s_2$$$, the $$$n$$$-th day — $$$s_n$$$ and $$$(n+1)$$$-th day — $$$s_1$$$ again and so on. Ship coordinates change the following way: if wind blows the direction U, then the ship moves from $$$(x, y)$$$ to $$$(x, y + 1)$$$; if wind blows the direction D, then the ship moves from $$$(x, y)$$$ to $$$(x, y - 1)$$$; if wind blows the direction L, then the ship moves from $$$(x, y)$$$ to $$$(x - 1, y)$$$; if wind blows the direction R, then the ship moves from $$$(x, y)$$$ to $$$(x + 1, y)$$$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $$$(x, y)$$$ it will move to the point $$$(x - 1, y + 1)$$$, and if it goes the direction U, then it will move to the point $$$(x, y + 2)$$$.You task is to determine the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$.
256 megabytes
import java.io.*; import java.util.*; public class Task { public static void main(String[] args) throws IOException { new Task().go(); } PrintWriter out; Reader in; BufferedReader br; Task() throws IOException { try { //br = new BufferedReader( new FileReader("input.txt") ); in = new Reader("input.txt"); out = new PrintWriter( new BufferedWriter(new FileWriter("output.txt")) ); } catch (Exception e) { //br = new BufferedReader( new InputStreamReader( System.in ) ); in = new Reader(); out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out)) ); } } void go() throws IOException { int t = 1; while (t > 0) { solve(); //out.println(); t--; } out.flush(); out.close(); } int inf = 2000000000; int mod = 1000000007; double eps = 0.000000001; int n; int m; int[] a; ArrayList<Integer>[] g; void solve() throws IOException { int x1 = in.nextInt(); int y1 = in.nextInt(); int x2 = in.nextInt(); int y2 = in.nextInt(); int n = in.nextInt(); String s = in.next(); long[] cnt = new long[255]; for (int i = 0; i < n; i++) { int d = s.charAt(i); cnt[d]++; } long max = 1000000000000000L; long l = 0; long r = max; int[] dirs = {'R', 'L', 'U', 'D'}; while (r > l) { long t = (l + r) / 2; long x = x1; long y = y1; for (int d : dirs) switch (d) { case 'R': x += cnt[d] * (t / n); break; case 'L': x -= cnt[d] * (t / n); break; case 'U': y += cnt[d] * (t / n); break; case 'D': y -= cnt[d] * (t / n); break; } for (int i = 0; i < t % n; i++) switch (s.charAt(i)) { case 'R': x++; break; case 'L': x--; break; case 'U': y++; break; case 'D': y--; break; } //System.err.println(t); //System.err.println(Math.abs(x - x2) + Math.abs(y - y2)); if (Math.abs(x - x2) + Math.abs(y - y2) <= t) r = t; else l = t + 1; } if (r == max) out.println(-1); else out.println(r); } class Pair implements Comparable<Pair>{ int a; int b; Pair(int a, int b) { this.a = a; this.b = b; } public int compareTo(Pair p) { if (a > p.a) return 1; if (a < p.a) return -1; if (b > p.b) return 1; if (b < p.b) return -1; return 0; } } class Item { int a; int b; int c; Item(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } } class Reader { BufferedReader br; StringTokenizer tok; Reader(String file) throws IOException { br = new BufferedReader( new FileReader(file) ); } Reader() throws IOException { br = new BufferedReader( new InputStreamReader(System.in) ); } String next() throws IOException { while (tok == null || !tok.hasMoreElements()) tok = new StringTokenizer(br.readLine()); return tok.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.valueOf(next()); } long nextLong() throws NumberFormatException, IOException { return Long.valueOf(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.valueOf(next()); } String nextLine() throws IOException { return br.readLine(); } int[] nextIntArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } ArrayList<Integer>[] nextGraph(int n, int m) throws IOException { ArrayList<Integer>[] g = new ArrayList[n]; for (int i = 0; i < n; i++) g[i] = new ArrayList<>(); for (int i = 0; i < m; i++) { int x = nextInt() - 1; int y = nextInt() - 1; g[x].add(y); g[y].add(x); } return g; } } }
Java
["0 0\n4 6\n3\nUUU", "0 3\n0 0\n3\nUDD", "0 0\n0 1\n1\nL"]
2 seconds
["5", "3", "-1"]
NoteIn the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: $$$(0, 0)$$$ $$$\rightarrow$$$ $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ $$$\rightarrow$$$ $$$(3, 3)$$$ $$$\rightarrow$$$ $$$(4, 4)$$$ $$$\rightarrow$$$ $$$(4, 6)$$$.In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 1)$$$ $$$\rightarrow$$$ $$$(0, 0)$$$.In the third example the ship can never reach the point $$$(0, 1)$$$.
Java 8
standard input
[ "binary search" ]
3967727db1225c4b6072d9f18e0dce00
The first line contains two integers $$$x_1, y_1$$$ ($$$0 \le x_1, y_1 \le 10^9$$$) — the initial coordinates of the ship. The second line contains two integers $$$x_2, y_2$$$ ($$$0 \le x_2, y_2 \le 10^9$$$) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The fourth line contains the string $$$s$$$ itself, consisting only of letters U, D, L and R.
1,900
The only line should contain the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$. If it's impossible then print "-1".
standard output
PASSED
46082fcf03587a7906df34d2d92c7e84
train_000.jsonl
1550504400
You a captain of a ship. Initially you are standing in a point $$$(x_1, y_1)$$$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $$$(x_2, y_2)$$$. You know the weather forecast — the string $$$s$$$ of length $$$n$$$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $$$s_1$$$, the second day — $$$s_2$$$, the $$$n$$$-th day — $$$s_n$$$ and $$$(n+1)$$$-th day — $$$s_1$$$ again and so on. Ship coordinates change the following way: if wind blows the direction U, then the ship moves from $$$(x, y)$$$ to $$$(x, y + 1)$$$; if wind blows the direction D, then the ship moves from $$$(x, y)$$$ to $$$(x, y - 1)$$$; if wind blows the direction L, then the ship moves from $$$(x, y)$$$ to $$$(x - 1, y)$$$; if wind blows the direction R, then the ship moves from $$$(x, y)$$$ to $$$(x + 1, y)$$$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $$$(x, y)$$$ it will move to the point $$$(x - 1, y + 1)$$$, and if it goes the direction U, then it will move to the point $$$(x, y + 2)$$$.You task is to determine the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$.
256 megabytes
import java.util.*; public class CodeForces1117C{ static long dx,dy; static int x1,y1,x2,y2; public static void main(String[] args) { Scanner input = new Scanner(System.in); x1 = input.nextInt(); y1 = input.nextInt(); x2 = input.nextInt(); y2 = input.nextInt(); int n = input.nextInt(); char[] s = input.next().toCharArray(); dx = 0L; dy = 0L; for(int i = 0;i<n;i++){ if(s[i] == 'U') dy++; if(s[i] == 'D') dy--; if(s[i] == 'R') dx++; if(s[i] == 'L') dx--; } long lo = 0, hi = (long)1e18; while(lo <= hi){ long mid = (hi+lo)/2; if(!good(mid,s)){ lo = mid+1; } else{ hi = mid-1; } } if(lo >= 1e15){ System.out.println(-1); } else{ System.out.println(lo); } } public static boolean good(long test,char[] s){ long full = test/s.length; long posx = x1 + dx*full, posy = y1 + dy*full; for(int id = 0;;id++){ if(full*s.length+id == test){ break; } if(s[id] == 'U') posy++; if(s[id] == 'D') posy--; if(s[id] == 'R') posx++; if(s[id] == 'L') posx--; } return Math.abs(posx-x2) + Math.abs(posy-y2) <= test; } }
Java
["0 0\n4 6\n3\nUUU", "0 3\n0 0\n3\nUDD", "0 0\n0 1\n1\nL"]
2 seconds
["5", "3", "-1"]
NoteIn the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: $$$(0, 0)$$$ $$$\rightarrow$$$ $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ $$$\rightarrow$$$ $$$(3, 3)$$$ $$$\rightarrow$$$ $$$(4, 4)$$$ $$$\rightarrow$$$ $$$(4, 6)$$$.In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 1)$$$ $$$\rightarrow$$$ $$$(0, 0)$$$.In the third example the ship can never reach the point $$$(0, 1)$$$.
Java 8
standard input
[ "binary search" ]
3967727db1225c4b6072d9f18e0dce00
The first line contains two integers $$$x_1, y_1$$$ ($$$0 \le x_1, y_1 \le 10^9$$$) — the initial coordinates of the ship. The second line contains two integers $$$x_2, y_2$$$ ($$$0 \le x_2, y_2 \le 10^9$$$) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The fourth line contains the string $$$s$$$ itself, consisting only of letters U, D, L and R.
1,900
The only line should contain the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$. If it's impossible then print "-1".
standard output
PASSED
4a9a950ad27766ed7713e63c620580b8
train_000.jsonl
1550504400
You a captain of a ship. Initially you are standing in a point $$$(x_1, y_1)$$$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $$$(x_2, y_2)$$$. You know the weather forecast — the string $$$s$$$ of length $$$n$$$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $$$s_1$$$, the second day — $$$s_2$$$, the $$$n$$$-th day — $$$s_n$$$ and $$$(n+1)$$$-th day — $$$s_1$$$ again and so on. Ship coordinates change the following way: if wind blows the direction U, then the ship moves from $$$(x, y)$$$ to $$$(x, y + 1)$$$; if wind blows the direction D, then the ship moves from $$$(x, y)$$$ to $$$(x, y - 1)$$$; if wind blows the direction L, then the ship moves from $$$(x, y)$$$ to $$$(x - 1, y)$$$; if wind blows the direction R, then the ship moves from $$$(x, y)$$$ to $$$(x + 1, y)$$$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $$$(x, y)$$$ it will move to the point $$$(x - 1, y + 1)$$$, and if it goes the direction U, then it will move to the point $$$(x, y + 2)$$$.You task is to determine the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); CMagicShip solver = new CMagicShip(); solver.solve(1, in, out); out.close(); } static class CMagicShip { public void solve(int testNumber, InputReader in, PrintWriter out) { long x1 = in.nextInt(); long y1 = in.nextInt(); long x2 = in.nextInt(); long y2 = in.nextInt(); int n = in.nextInt(); String s = in.next(); Point[] pref = new Point[n + 1]; pref[0] = new Point(0, 0); for (int i = 1; i < n + 1; i++) { pref[i] = new Point(pref[i - 1].x, pref[i - 1].y); switch (s.charAt(i - 1)) { case 'U': pref[i].y++; break; case 'D': pref[i].y--; break; case 'R': pref[i].x++; break; case 'L': pref[i].x--; break; } } long lo = 1; long hi = (long) 2e14; while (lo <= hi) { long k = (lo + hi) / 2; long x_wind = (k / n) * pref[n].x + pref[(int) (k % n)].x; long y_wind = (k / n) * pref[n].y + pref[(int) (k % n)].y; long dist = Math.abs(x2 - x1 - x_wind) + Math.abs(y2 - y1 - y_wind); if (dist <= k) { hi = k - 1; } else { lo = k + 1; } } long k = (hi == (long) 2e14) ? -1 : lo; out.println(k); } class Point { long x; long y; Point(long x, long y) { this.x = x; this.y = y; } public String toString() { return "(" + x + ", " + y + ")"; } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["0 0\n4 6\n3\nUUU", "0 3\n0 0\n3\nUDD", "0 0\n0 1\n1\nL"]
2 seconds
["5", "3", "-1"]
NoteIn the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: $$$(0, 0)$$$ $$$\rightarrow$$$ $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ $$$\rightarrow$$$ $$$(3, 3)$$$ $$$\rightarrow$$$ $$$(4, 4)$$$ $$$\rightarrow$$$ $$$(4, 6)$$$.In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 1)$$$ $$$\rightarrow$$$ $$$(0, 0)$$$.In the third example the ship can never reach the point $$$(0, 1)$$$.
Java 8
standard input
[ "binary search" ]
3967727db1225c4b6072d9f18e0dce00
The first line contains two integers $$$x_1, y_1$$$ ($$$0 \le x_1, y_1 \le 10^9$$$) — the initial coordinates of the ship. The second line contains two integers $$$x_2, y_2$$$ ($$$0 \le x_2, y_2 \le 10^9$$$) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The fourth line contains the string $$$s$$$ itself, consisting only of letters U, D, L and R.
1,900
The only line should contain the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$. If it's impossible then print "-1".
standard output
PASSED
c8ff2bb03106972c64e51ec39b99a8f9
train_000.jsonl
1550504400
You a captain of a ship. Initially you are standing in a point $$$(x_1, y_1)$$$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $$$(x_2, y_2)$$$. You know the weather forecast — the string $$$s$$$ of length $$$n$$$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $$$s_1$$$, the second day — $$$s_2$$$, the $$$n$$$-th day — $$$s_n$$$ and $$$(n+1)$$$-th day — $$$s_1$$$ again and so on. Ship coordinates change the following way: if wind blows the direction U, then the ship moves from $$$(x, y)$$$ to $$$(x, y + 1)$$$; if wind blows the direction D, then the ship moves from $$$(x, y)$$$ to $$$(x, y - 1)$$$; if wind blows the direction L, then the ship moves from $$$(x, y)$$$ to $$$(x - 1, y)$$$; if wind blows the direction R, then the ship moves from $$$(x, y)$$$ to $$$(x + 1, y)$$$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $$$(x, y)$$$ it will move to the point $$$(x - 1, y + 1)$$$, and if it goes the direction U, then it will move to the point $$$(x, y + 2)$$$.You task is to determine the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; import java.awt.Point; public class Main { //static final long MOD = 998244353L; //static final long INF = -1000000000000000007L; static final long MOD = 1000000007L; //static final int INF = 1000000007; public static void main(String[] args) { FastScanner sc = new FastScanner(); PrintWriter pw = new PrintWriter(System.out); long[] p1 = new long[]{sc.nl(),sc.nl()}; long[] p2 = new long[]{sc.nl(),sc.nl()}; int N = sc.ni(); String s = sc.next(); int[] nums = new int[N]; for (int i = 0; i < N; i++) { if (s.charAt(i)=='U') { nums[i] = 0; } else if (s.charAt(i)=='D') { nums[i] = 1; } else if (s.charAt(i)=='L') { nums[i] = 2; } else { nums[i] = 3; } } long[][] pref = new long[N+1][2]; int[][] dirs = {{0,1},{0,-1},{-1,0},{1,0}}; for (int i = 1; i <= N; i++) { pref[i][0] = pref[i-1][0]+dirs[nums[i-1]][0]; pref[i][1] = pref[i-1][1]+dirs[nums[i-1]][1]; } long L = 0; long R = (long)(1e17); while (L < R) { long mid = ((L+R)/2); long windX = (mid/N)*pref[N][0]+pref[(int)(mid%N)][0]; long windY = (mid/N)*pref[N][1]+pref[(int)(mid%N)][1]; long sailX = Math.abs(p2[0]-(p1[0]+windX)); long sailY = Math.abs(p2[1]-(p1[1]+windY)); if (sailX+sailY <= mid) { R = mid; } else { L = mid+1; } } if (L==(long)(1e17)) { pw.println(-1); } else { pw.println(L); } pw.close(); } public static int[][] sort(int[][] array) { //Sort an array (immune to quicksort TLE) Random rgen = new Random(); for (int i = 0; i < array.length; i++) { int randomPosition = rgen.nextInt(array.length); int[] temp = array[i]; array[i] = array[randomPosition]; array[randomPosition] = temp; } Arrays.sort(array, new Comparator<int[]>() { @Override public int compare(int[] arr1, int[] arr2) { //return arr1[0]-arr2[0]; //ascending order if (arr1[0] != arr2[0]) { return arr1[0]-arr2[0]; } else { return arr1[1]-arr2[1]; } } }); return array; } public static long[][] sort(long[][] array) { //Sort an array (immune to quicksort TLE) Random rgen = new Random(); for (int i = 0; i < array.length; i++) { int randomPosition = rgen.nextInt(array.length); long[] temp = array[i]; array[i] = array[randomPosition]; array[randomPosition] = temp; } Arrays.sort(array, new Comparator<long[]>() { @Override public int compare(long[] arr1, long[] arr2) { return 0; } }); return array; } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { 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 ni() { return Integer.parseInt(next()); } long nl() { return Long.parseLong(next()); } double nd() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["0 0\n4 6\n3\nUUU", "0 3\n0 0\n3\nUDD", "0 0\n0 1\n1\nL"]
2 seconds
["5", "3", "-1"]
NoteIn the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: $$$(0, 0)$$$ $$$\rightarrow$$$ $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ $$$\rightarrow$$$ $$$(3, 3)$$$ $$$\rightarrow$$$ $$$(4, 4)$$$ $$$\rightarrow$$$ $$$(4, 6)$$$.In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 1)$$$ $$$\rightarrow$$$ $$$(0, 0)$$$.In the third example the ship can never reach the point $$$(0, 1)$$$.
Java 8
standard input
[ "binary search" ]
3967727db1225c4b6072d9f18e0dce00
The first line contains two integers $$$x_1, y_1$$$ ($$$0 \le x_1, y_1 \le 10^9$$$) — the initial coordinates of the ship. The second line contains two integers $$$x_2, y_2$$$ ($$$0 \le x_2, y_2 \le 10^9$$$) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The fourth line contains the string $$$s$$$ itself, consisting only of letters U, D, L and R.
1,900
The only line should contain the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$. If it's impossible then print "-1".
standard output
PASSED
2f4c81c0a98e6c0922c99a191e1b4744
train_000.jsonl
1550504400
You a captain of a ship. Initially you are standing in a point $$$(x_1, y_1)$$$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $$$(x_2, y_2)$$$. You know the weather forecast — the string $$$s$$$ of length $$$n$$$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $$$s_1$$$, the second day — $$$s_2$$$, the $$$n$$$-th day — $$$s_n$$$ and $$$(n+1)$$$-th day — $$$s_1$$$ again and so on. Ship coordinates change the following way: if wind blows the direction U, then the ship moves from $$$(x, y)$$$ to $$$(x, y + 1)$$$; if wind blows the direction D, then the ship moves from $$$(x, y)$$$ to $$$(x, y - 1)$$$; if wind blows the direction L, then the ship moves from $$$(x, y)$$$ to $$$(x - 1, y)$$$; if wind blows the direction R, then the ship moves from $$$(x, y)$$$ to $$$(x + 1, y)$$$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $$$(x, y)$$$ it will move to the point $$$(x - 1, y + 1)$$$, and if it goes the direction U, then it will move to the point $$$(x, y + 2)$$$.You task is to determine the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$.
256 megabytes
//package sept; import java.io.*; import java.util.*; public class TimePass implements Runnable { InputStream is; PrintWriter out; String INPUT = ""; //boolean debug=false; boolean debug=true; static long mod=998244353; static long mod2=1000000007; void solve() throws IOException { int x1=ni(),y1=ni(); int x2=ni(),y2=ni(); int n=ni(); char[] a=ns(n); int reqUp=y2-y1,reqRt=x2-x1; int netUp=0,netRt=0; int ud=0,lr=0; long diffUp=0,diffRt=0; int[][] net=new int[n][2]; for(int i=0;i<n;i++) { if(a[i]=='U') { netUp++; lr++; } else if(a[i]=='D') { netUp--; } else if(a[i]=='L') { ud++; netRt--; } else { netRt++; ud++; } net[i][0]=netUp; net[i][1]=netRt; diffUp=reqUp-netUp; diffRt=reqRt-netRt; if(Math.abs(diffUp)+Math.abs(diffRt)<=(i+1)) { out.println(i+1); return; } } long low=0,high=(long)1e15; long mid=0; int cnt=0; while(low<high) { mid=(low+high)/2; diffUp=reqUp-mid/n*netUp; diffRt=reqRt-mid/n*netRt; if(mid%n!=0) { int tmp=(int)(mid%n)-1; diffUp-=net[tmp][0]; diffRt-=net[tmp][1]; } if(Math.abs(diffUp)+Math.abs(diffRt)<=mid) { high=mid; } else low=mid+1; cnt++; //out.println(mid); if(cnt>=100)break; } if(high==(long)1e15) out.println(-1); else out.println(high); //else out.println(-1); } static int comp(char[] a,int st,int end) { int len=end-st+1; if(len==3)return 2; if(len==2)return -1; int mid=(st+end)/2; if(len%2!=0)mid--; int ch2=1; for(int i=0;i<len;i++) { if(a[st+i]!=a[len-1]) { ch2=0; break; } } if(ch2==1) { return -1; } int ch=1; for(int i=0;i<len/4;i++) { if(a[i+st]!=a[mid-i]) { ch=0; break; } } if(ch==1)return 2*comp(a,st,mid); if(len%2==0)return 1; return 2; } static int[] xor; static void dfs(int u,int[] a,int[][] g,int[] vis) { xor[u]=a[u]; vis[u]=1; for(int v:g[u]) { if(vis[v]==0) { dfs(v,a,g,vis); xor[u]=xor[u]^xor[v]; } } } static int[][] packD(int n,int[] from,int[] to) { int[][] g=new int[n][]; int[] p=new int[n]; for(int f:from) { p[f]++; } int m=from.length; for(int i=0;i<n;i++) { g[i]=new int[p[i]]; } for(int i=0;i<m;i++) { g[from[i]][--p[from[i]]]=to[i]; } return g; } static class Pair { int a,b; public Pair(int a,int b) { this.a=a; this.b=b; //this.ind=ind; } } static long lcm(int a,int b) { long val=a; val*=b; return (val/gcd(a,b)); } static long gcd(long a,long b) { if(a==0)return b; return gcd(b%a,a); } static int pow(int a, int b, int p) { long ans = 1, base = a; while (b!=0) { if ((b & 1)!=0) { ans *= base; ans%= p; } base *= base; base%= p; b >>= 1; } return (int)ans; } static int inv(int x, int p) { return pow(x, p - 2, p); } public static long[] radixSort(long[] f){ return radixSort(f, f.length); } public static long[] radixSort(long[] f, int n) { long[] to = new long[n]; { int[] b = new int[65537]; for(int i = 0;i < n;i++)b[1+(int)(f[i]&0xffff)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < n;i++)to[b[(int)(f[i]&0xffff)]++] = f[i]; long[] d = f; f = to;to = d; } { int[] b = new int[65537]; for(int i = 0;i < n;i++)b[1+(int)(f[i]>>>16&0xffff)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < n;i++)to[b[(int)(f[i]>>>16&0xffff)]++] = f[i]; long[] d = f; f = to;to = d; } { int[] b = new int[65537]; for(int i = 0;i < n;i++)b[1+(int)(f[i]>>>32&0xffff)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < n;i++)to[b[(int)(f[i]>>>32&0xffff)]++] = f[i]; long[] d = f; f = to;to = d; } { int[] b = new int[65537]; for(int i = 0;i < n;i++)b[1+(int)(f[i]>>>48&0xffff)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < n;i++)to[b[(int)(f[i]>>>48&0xffff)]++] = f[i]; long[] d = f; f = to;to = d; } return f; } public void run() { if(debug)oj=true; is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); try { solve(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception {new Thread(null,new TimePass(),"Main",1<<26).start();} private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["0 0\n4 6\n3\nUUU", "0 3\n0 0\n3\nUDD", "0 0\n0 1\n1\nL"]
2 seconds
["5", "3", "-1"]
NoteIn the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: $$$(0, 0)$$$ $$$\rightarrow$$$ $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ $$$\rightarrow$$$ $$$(3, 3)$$$ $$$\rightarrow$$$ $$$(4, 4)$$$ $$$\rightarrow$$$ $$$(4, 6)$$$.In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 1)$$$ $$$\rightarrow$$$ $$$(0, 0)$$$.In the third example the ship can never reach the point $$$(0, 1)$$$.
Java 8
standard input
[ "binary search" ]
3967727db1225c4b6072d9f18e0dce00
The first line contains two integers $$$x_1, y_1$$$ ($$$0 \le x_1, y_1 \le 10^9$$$) — the initial coordinates of the ship. The second line contains two integers $$$x_2, y_2$$$ ($$$0 \le x_2, y_2 \le 10^9$$$) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The fourth line contains the string $$$s$$$ itself, consisting only of letters U, D, L and R.
1,900
The only line should contain the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$. If it's impossible then print "-1".
standard output
PASSED
b299722fc5842b559c00578f87c1f6f3
train_000.jsonl
1550504400
You a captain of a ship. Initially you are standing in a point $$$(x_1, y_1)$$$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $$$(x_2, y_2)$$$. You know the weather forecast — the string $$$s$$$ of length $$$n$$$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $$$s_1$$$, the second day — $$$s_2$$$, the $$$n$$$-th day — $$$s_n$$$ and $$$(n+1)$$$-th day — $$$s_1$$$ again and so on. Ship coordinates change the following way: if wind blows the direction U, then the ship moves from $$$(x, y)$$$ to $$$(x, y + 1)$$$; if wind blows the direction D, then the ship moves from $$$(x, y)$$$ to $$$(x, y - 1)$$$; if wind blows the direction L, then the ship moves from $$$(x, y)$$$ to $$$(x - 1, y)$$$; if wind blows the direction R, then the ship moves from $$$(x, y)$$$ to $$$(x + 1, y)$$$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $$$(x, y)$$$ it will move to the point $$$(x - 1, y + 1)$$$, and if it goes the direction U, then it will move to the point $$$(x, y + 2)$$$.You task is to determine the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$.
256 megabytes
//package sept; import java.io.*; import java.util.*; public class TimePass implements Runnable { InputStream is; PrintWriter out; String INPUT = ""; //boolean debug=false; boolean debug=true; static long mod=998244353; static long mod2=1000000007; void solve() throws IOException { int x1=ni(),y1=ni(); int x2=ni(),y2=ni(); int n=ni(); char[] a=ns(n); long reqUp=y2-y1,reqRt=x2-x1; long netUp=0,netRt=0; int ud=0,lr=0; long diffUp=0,diffRt=0; long[][] net=new long[n][2]; for(int i=0;i<n;i++) { if(a[i]=='U') { netUp++; lr++; } else if(a[i]=='D') { netUp--; } else if(a[i]=='L') { ud++; netRt--; } else { netRt++; ud++; } net[i][0]=netUp; net[i][1]=netRt; diffUp=reqUp-netUp; diffRt=reqRt-netRt; if(Math.abs(diffUp)+Math.abs(diffRt)<=(i+1)) { out.println(i+1); return; } } long low=0,high=(long)1e18; long mid=0; int cnt=0; while(low<high) { mid=(low+high)/2; diffUp=reqUp-mid/n*netUp; diffRt=reqRt-mid/n*netRt; if(mid%n!=0) { int tmp=(int)(mid%n)-1; diffUp-=net[tmp][0]; diffRt-=net[tmp][1]; } if(Math.abs(diffUp)+Math.abs(diffRt)<=mid) { high=mid; } else low=mid; cnt++; //out.println(mid); if(cnt>=10000)break; } diffUp=reqUp-high/n*netUp; diffRt=reqRt-high/n*netRt; if(high%n!=0) { int tmp=(int)(high%n)-1; diffUp-=net[tmp][0]; diffRt-=net[tmp][1]; } if(Math.abs(diffUp)+Math.abs(diffRt)>high) out.println(-1); else out.println(high); //else out.println(-1); } static int comp(char[] a,int st,int end) { int len=end-st+1; if(len==3)return 2; if(len==2)return -1; int mid=(st+end)/2; if(len%2!=0)mid--; int ch2=1; for(int i=0;i<len;i++) { if(a[st+i]!=a[len-1]) { ch2=0; break; } } if(ch2==1) { return -1; } int ch=1; for(int i=0;i<len/4;i++) { if(a[i+st]!=a[mid-i]) { ch=0; break; } } if(ch==1)return 2*comp(a,st,mid); if(len%2==0)return 1; return 2; } static int[] xor; static void dfs(int u,int[] a,int[][] g,int[] vis) { xor[u]=a[u]; vis[u]=1; for(int v:g[u]) { if(vis[v]==0) { dfs(v,a,g,vis); xor[u]=xor[u]^xor[v]; } } } static int[][] packD(int n,int[] from,int[] to) { int[][] g=new int[n][]; int[] p=new int[n]; for(int f:from) { p[f]++; } int m=from.length; for(int i=0;i<n;i++) { g[i]=new int[p[i]]; } for(int i=0;i<m;i++) { g[from[i]][--p[from[i]]]=to[i]; } return g; } static class Pair { int a,b; public Pair(int a,int b) { this.a=a; this.b=b; //this.ind=ind; } } static long lcm(int a,int b) { long val=a; val*=b; return (val/gcd(a,b)); } static long gcd(long a,long b) { if(a==0)return b; return gcd(b%a,a); } static int pow(int a, int b, int p) { long ans = 1, base = a; while (b!=0) { if ((b & 1)!=0) { ans *= base; ans%= p; } base *= base; base%= p; b >>= 1; } return (int)ans; } static int inv(int x, int p) { return pow(x, p - 2, p); } public static long[] radixSort(long[] f){ return radixSort(f, f.length); } public static long[] radixSort(long[] f, int n) { long[] to = new long[n]; { int[] b = new int[65537]; for(int i = 0;i < n;i++)b[1+(int)(f[i]&0xffff)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < n;i++)to[b[(int)(f[i]&0xffff)]++] = f[i]; long[] d = f; f = to;to = d; } { int[] b = new int[65537]; for(int i = 0;i < n;i++)b[1+(int)(f[i]>>>16&0xffff)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < n;i++)to[b[(int)(f[i]>>>16&0xffff)]++] = f[i]; long[] d = f; f = to;to = d; } { int[] b = new int[65537]; for(int i = 0;i < n;i++)b[1+(int)(f[i]>>>32&0xffff)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < n;i++)to[b[(int)(f[i]>>>32&0xffff)]++] = f[i]; long[] d = f; f = to;to = d; } { int[] b = new int[65537]; for(int i = 0;i < n;i++)b[1+(int)(f[i]>>>48&0xffff)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < n;i++)to[b[(int)(f[i]>>>48&0xffff)]++] = f[i]; long[] d = f; f = to;to = d; } return f; } public void run() { if(debug)oj=true; is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); try { solve(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception {new Thread(null,new TimePass(),"Main",1<<26).start();} private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["0 0\n4 6\n3\nUUU", "0 3\n0 0\n3\nUDD", "0 0\n0 1\n1\nL"]
2 seconds
["5", "3", "-1"]
NoteIn the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: $$$(0, 0)$$$ $$$\rightarrow$$$ $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ $$$\rightarrow$$$ $$$(3, 3)$$$ $$$\rightarrow$$$ $$$(4, 4)$$$ $$$\rightarrow$$$ $$$(4, 6)$$$.In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 1)$$$ $$$\rightarrow$$$ $$$(0, 0)$$$.In the third example the ship can never reach the point $$$(0, 1)$$$.
Java 8
standard input
[ "binary search" ]
3967727db1225c4b6072d9f18e0dce00
The first line contains two integers $$$x_1, y_1$$$ ($$$0 \le x_1, y_1 \le 10^9$$$) — the initial coordinates of the ship. The second line contains two integers $$$x_2, y_2$$$ ($$$0 \le x_2, y_2 \le 10^9$$$) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The fourth line contains the string $$$s$$$ itself, consisting only of letters U, D, L and R.
1,900
The only line should contain the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$. If it's impossible then print "-1".
standard output
PASSED
b06e05750f002de1f192bb2ad274dde6
train_000.jsonl
1550504400
You a captain of a ship. Initially you are standing in a point $$$(x_1, y_1)$$$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $$$(x_2, y_2)$$$. You know the weather forecast — the string $$$s$$$ of length $$$n$$$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $$$s_1$$$, the second day — $$$s_2$$$, the $$$n$$$-th day — $$$s_n$$$ and $$$(n+1)$$$-th day — $$$s_1$$$ again and so on. Ship coordinates change the following way: if wind blows the direction U, then the ship moves from $$$(x, y)$$$ to $$$(x, y + 1)$$$; if wind blows the direction D, then the ship moves from $$$(x, y)$$$ to $$$(x, y - 1)$$$; if wind blows the direction L, then the ship moves from $$$(x, y)$$$ to $$$(x - 1, y)$$$; if wind blows the direction R, then the ship moves from $$$(x, y)$$$ to $$$(x + 1, y)$$$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $$$(x, y)$$$ it will move to the point $$$(x - 1, y + 1)$$$, and if it goes the direction U, then it will move to the point $$$(x, y + 2)$$$.You task is to determine the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$.
256 megabytes
//package sept; import java.io.*; import java.util.*; public class TimePass implements Runnable { InputStream is; PrintWriter out; String INPUT = ""; //boolean debug=false; boolean debug=true; static long mod=998244353; static long mod2=1000000007; void solve() throws IOException { int x1=ni(),y1=ni(); int x2=ni(),y2=ni(); int n=ni(); char[] a=ns(n); long reqUp=y2-y1,reqRt=x2-x1; long netUp=0,netRt=0; int ud=0,lr=0; long diffUp=0,diffRt=0; long[][] net=new long[n][2]; for(int i=0;i<n;i++) { if(a[i]=='U') { netUp++; lr++; } else if(a[i]=='D') { netUp--; } else if(a[i]=='L') { ud++; netRt--; } else { netRt++; ud++; } net[i][0]=netUp; net[i][1]=netRt; diffUp=reqUp-netUp; diffRt=reqRt-netRt; if(Math.abs(diffUp)+Math.abs(diffRt)<=(i+1)) { out.println(i+1); return; } } long low=0,high=(long)1e18; long mid=0; int cnt=0; while(low<high) { mid=(low+high)/2; diffUp=reqUp-mid/n*netUp; diffRt=reqRt-mid/n*netRt; if(mid%n!=0) { int tmp=(int)(mid%n)-1; diffUp-=net[tmp][0]; diffRt-=net[tmp][1]; } if(Math.abs(diffUp)+Math.abs(diffRt)<=mid) { high=mid; } else low=mid+1; cnt++; //out.println(mid); //if(cnt>=10000)break; } //out.println(cnt); diffUp=reqUp-high/n*netUp; diffRt=reqRt-high/n*netRt; if(high%n!=0) { int tmp=(int)(high%n)-1; diffUp-=net[tmp][0]; diffRt-=net[tmp][1]; } if(Math.abs(diffUp)+Math.abs(diffRt)>high) out.println(-1); else out.println(high); //else out.println(-1); } static int comp(char[] a,int st,int end) { int len=end-st+1; if(len==3)return 2; if(len==2)return -1; int mid=(st+end)/2; if(len%2!=0)mid--; int ch2=1; for(int i=0;i<len;i++) { if(a[st+i]!=a[len-1]) { ch2=0; break; } } if(ch2==1) { return -1; } int ch=1; for(int i=0;i<len/4;i++) { if(a[i+st]!=a[mid-i]) { ch=0; break; } } if(ch==1)return 2*comp(a,st,mid); if(len%2==0)return 1; return 2; } static int[] xor; static void dfs(int u,int[] a,int[][] g,int[] vis) { xor[u]=a[u]; vis[u]=1; for(int v:g[u]) { if(vis[v]==0) { dfs(v,a,g,vis); xor[u]=xor[u]^xor[v]; } } } static int[][] packD(int n,int[] from,int[] to) { int[][] g=new int[n][]; int[] p=new int[n]; for(int f:from) { p[f]++; } int m=from.length; for(int i=0;i<n;i++) { g[i]=new int[p[i]]; } for(int i=0;i<m;i++) { g[from[i]][--p[from[i]]]=to[i]; } return g; } static class Pair { int a,b; public Pair(int a,int b) { this.a=a; this.b=b; //this.ind=ind; } } static long lcm(int a,int b) { long val=a; val*=b; return (val/gcd(a,b)); } static long gcd(long a,long b) { if(a==0)return b; return gcd(b%a,a); } static int pow(int a, int b, int p) { long ans = 1, base = a; while (b!=0) { if ((b & 1)!=0) { ans *= base; ans%= p; } base *= base; base%= p; b >>= 1; } return (int)ans; } static int inv(int x, int p) { return pow(x, p - 2, p); } public static long[] radixSort(long[] f){ return radixSort(f, f.length); } public static long[] radixSort(long[] f, int n) { long[] to = new long[n]; { int[] b = new int[65537]; for(int i = 0;i < n;i++)b[1+(int)(f[i]&0xffff)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < n;i++)to[b[(int)(f[i]&0xffff)]++] = f[i]; long[] d = f; f = to;to = d; } { int[] b = new int[65537]; for(int i = 0;i < n;i++)b[1+(int)(f[i]>>>16&0xffff)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < n;i++)to[b[(int)(f[i]>>>16&0xffff)]++] = f[i]; long[] d = f; f = to;to = d; } { int[] b = new int[65537]; for(int i = 0;i < n;i++)b[1+(int)(f[i]>>>32&0xffff)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < n;i++)to[b[(int)(f[i]>>>32&0xffff)]++] = f[i]; long[] d = f; f = to;to = d; } { int[] b = new int[65537]; for(int i = 0;i < n;i++)b[1+(int)(f[i]>>>48&0xffff)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < n;i++)to[b[(int)(f[i]>>>48&0xffff)]++] = f[i]; long[] d = f; f = to;to = d; } return f; } public void run() { if(debug)oj=true; is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); try { solve(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception {new Thread(null,new TimePass(),"Main",1<<26).start();} private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["0 0\n4 6\n3\nUUU", "0 3\n0 0\n3\nUDD", "0 0\n0 1\n1\nL"]
2 seconds
["5", "3", "-1"]
NoteIn the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: $$$(0, 0)$$$ $$$\rightarrow$$$ $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ $$$\rightarrow$$$ $$$(3, 3)$$$ $$$\rightarrow$$$ $$$(4, 4)$$$ $$$\rightarrow$$$ $$$(4, 6)$$$.In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 1)$$$ $$$\rightarrow$$$ $$$(0, 0)$$$.In the third example the ship can never reach the point $$$(0, 1)$$$.
Java 8
standard input
[ "binary search" ]
3967727db1225c4b6072d9f18e0dce00
The first line contains two integers $$$x_1, y_1$$$ ($$$0 \le x_1, y_1 \le 10^9$$$) — the initial coordinates of the ship. The second line contains two integers $$$x_2, y_2$$$ ($$$0 \le x_2, y_2 \le 10^9$$$) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The fourth line contains the string $$$s$$$ itself, consisting only of letters U, D, L and R.
1,900
The only line should contain the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$. If it's impossible then print "-1".
standard output
PASSED
2f673ecd32c98f7ab63d4e9427874497
train_000.jsonl
1521698700
There is a matrix A of size x × y filled with integers. For every , Ai, j = y(i - 1) + j. Obviously, every integer from [1..xy] occurs exactly once in this matrix. You have traversed some path in this matrix. Your path can be described as a sequence of visited cells a1, a2, ..., an denoting that you started in the cell containing the number a1, then moved to the cell with the number a2, and so on.From the cell located in i-th line and j-th column (we denote this cell as (i, j)) you can move into one of the following cells: (i + 1, j) — only if i &lt; x; (i, j + 1) — only if j &lt; y; (i - 1, j) — only if i &gt; 1; (i, j - 1) — only if j &gt; 1.Notice that making a move requires you to go to an adjacent cell. It is not allowed to stay in the same cell. You don't know x and y exactly, but you have to find any possible values for these numbers such that you could start in the cell containing the integer a1, then move to the cell containing a2 (in one step), then move to the cell containing a3 (also in one step) and so on. Can you choose x and y so that they don't contradict with your sequence of moves?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Main { public static void main(String[] args) { MyScanner sc = new MyScanner(); int n = sc.nextInt(); int len = 1; int prev = sc.nextInt(); int max = prev; int maxInterval = 1; List<Interval> intervals = new ArrayList<>(); intervals.add(new Interval(prev, prev)); for (int i = 1; i < n; i++) { int cur = sc.nextInt(); max = Math.max(cur, max); int diff = Math.abs(cur - prev); if (diff > 1) { if (len == 1) { len = diff; } else { if (len != diff) { System.out.println("NO"); return; } } } else if (diff == 0) { System.out.println("NO"); return; } else if (diff == 1 && len > 1) { if ((cur + len - 1) / len != (prev + len - 1) / len) { System.out.println("NO"); return; } } Interval in = new Interval(cur, cur); int index = Collections.binarySearch(intervals, in, Comparator.comparing(Interval::getFrom)); if (index < 0) { index = -(index + 1); if (index == 0) { if (intervals.get(0).getFrom() - in.getFrom() == 1) { intervals.get(0).extend(in.getFrom(), len); maxInterval = Math.max(maxInterval, intervals.get(0).getLength()); } else { intervals.add(0, in); } } else if (index == intervals.size()) { Interval lastIn = intervals.get(index - 1); if (in.getFrom() - lastIn.getTo() == 1) { lastIn.extend(in.getFrom(), len); maxInterval = Math.max(maxInterval, lastIn.getLength()); } else if (in.getFrom() > lastIn.getTo()) { intervals.add(in); } } else { Interval prevIn = intervals.get(index - 1); Interval nextIn = intervals.get(index); if (in.getFrom() - prevIn.getTo() == 1) { prevIn.extend(in.getFrom(), len); maxInterval = Math.max(maxInterval, prevIn.getLength()); } else if (nextIn.getFrom() - in.getFrom() == 1) { nextIn.extend(in.getFrom(), len); maxInterval = Math.max(maxInterval, nextIn.getLength()); } else if (in.getFrom() - prevIn.getTo() > 1 && nextIn.getFrom() - in.getFrom() > 1) { intervals.add(index, in); } if (nextIn.getFrom() - prevIn.getTo() == 1) { prevIn.merge(nextIn, len); intervals.remove(nextIn); maxInterval = Math.max(maxInterval, prevIn.getLength()); } } } prev = cur; if (maxInterval > len && len > 1) { System.out.println("NO"); return; } } if (len > 1) { for (Interval interval : intervals) { if ((interval.getFrom() + len - 1) / len != (interval.getTo() + len - 1) / len) { System.out.println("NO"); return; } } } System.out.println("YES"); System.out.println(Math.min((max / len + 1), 1000000000) + " " + len); } static class Interval { int from; int to; public Interval(int from, int to) { this.from = from; this.to = to; } int getLength() { return to - from + 1; } boolean extend(int pos, int len) { boolean result = false; if (pos - to == 1) { if (len == 1 || (from + len - 1) / len == (to + len) / len) { to++; result = true; } } else if (from - pos == 1) { if (len == 1 || (from + len - 2) / len == (to + len - 1) / len) { from--; result = true; } } return result; } void merge(Interval interval, int len) { if (len > 1) { int x = (interval.getFrom() + len - 1) / len; if (x == (interval.getTo() + len - 1) / len && x == (from + len - 1) / len && x == (to + len - 1) / len) { this.from = Math.min(this.from, interval.from); this.to = Math.max(this.to, interval.to); } } else { this.from = Math.min(this.from, interval.from); this.to = Math.max(this.to, interval.to); } } public int getFrom() { return from; } public int getTo() { return to; } } 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; } } }
Java
["8\n1 2 3 6 9 8 5 2", "6\n1 2 1 2 5 3", "2\n1 10"]
1 second
["YES\n3 3", "NO", "YES\n4 9"]
NoteThe matrix and the path on it in the first test looks like this: Also there exist multiple correct answers for both the first and the third examples.
Java 8
standard input
[ "implementation" ]
3b725f11009768904514d87e2c7714ee
The first line contains one integer number n (1 ≤ n ≤ 200000) — the number of cells you visited on your path (if some cell is visited twice, then it's listed twice). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the integers in the cells on your path.
1,700
If all possible values of x and y such that 1 ≤ x, y ≤ 109 contradict with the information about your path, print NO. Otherwise, print YES in the first line, and in the second line print the values x and y such that your path was possible with such number of lines and columns in the matrix. Remember that they must be positive integers not exceeding 109.
standard output
PASSED
5758f37f288bbb6861a452c46d04fe13
train_000.jsonl
1521698700
There is a matrix A of size x × y filled with integers. For every , Ai, j = y(i - 1) + j. Obviously, every integer from [1..xy] occurs exactly once in this matrix. You have traversed some path in this matrix. Your path can be described as a sequence of visited cells a1, a2, ..., an denoting that you started in the cell containing the number a1, then moved to the cell with the number a2, and so on.From the cell located in i-th line and j-th column (we denote this cell as (i, j)) you can move into one of the following cells: (i + 1, j) — only if i &lt; x; (i, j + 1) — only if j &lt; y; (i - 1, j) — only if i &gt; 1; (i, j - 1) — only if j &gt; 1.Notice that making a move requires you to go to an adjacent cell. It is not allowed to stay in the same cell. You don't know x and y exactly, but you have to find any possible values for these numbers such that you could start in the cell containing the integer a1, then move to the cell containing a2 (in one step), then move to the cell containing a3 (also in one step) and so on. Can you choose x and y so that they don't contradict with your sequence of moves?
256 megabytes
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Scanner; import java.util.Stack; public class C { static long totalDay = 0; static int k; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int[] arr = new int[n]; int max = 0; for (int i = 0 ; i < n ; i++) { arr[i] = scanner.nextInt(); max = Math.max(arr[i],max); } if (n == 1) { System.out.println("YES"); System.out.println("1 " + max); return; } HashSet<Integer> absStep= new HashSet<Integer>(); for (int i = 1 ; i<n; i++ ) { int diff = arr[i] - arr[i-1]; absStep.add(Math.abs(diff)); } if(absStep.size() > 2 || absStep.contains(new Integer(0))) System.out.println("NO"); else if (absStep.size() == 1){ System.out.println("YES"); if (absStep.contains(new Integer(1))) { System.out.println("1 " + max); }else { int numCol = (int)absStep.toArray()[0]; System.out.println((int)Math.ceil((double)max/numCol) + " " + numCol); } }else { if (!absStep.contains(new Integer(1)) || absStep.contains(new Integer(0))) { System.out.println("NO"); }else { int numCol = 0; for (Integer i : absStep) { if (i != 1) numCol = i; } int col = arr[0]%numCol; if (col == 0) col = numCol; int row = (int) Math.ceil(arr[0]/(double)numCol); int maxRow = row; int maxNumStep = 0; for (int i = 1 ; i<n; i++ ) { int diff = arr[i] - arr[i-1]; if (Math.abs(diff) == 1) { col = col + diff; if (col == 0 || col > numCol) { System.out.println("NO"); return; } }else { row = row + diff/numCol; maxRow = Math.max(row, maxRow); if (row == 0) { System.out.println("NO"); return; } } } System.out.println("YES"); System.out.println(maxRow + " " + numCol); } } } }
Java
["8\n1 2 3 6 9 8 5 2", "6\n1 2 1 2 5 3", "2\n1 10"]
1 second
["YES\n3 3", "NO", "YES\n4 9"]
NoteThe matrix and the path on it in the first test looks like this: Also there exist multiple correct answers for both the first and the third examples.
Java 8
standard input
[ "implementation" ]
3b725f11009768904514d87e2c7714ee
The first line contains one integer number n (1 ≤ n ≤ 200000) — the number of cells you visited on your path (if some cell is visited twice, then it's listed twice). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the integers in the cells on your path.
1,700
If all possible values of x and y such that 1 ≤ x, y ≤ 109 contradict with the information about your path, print NO. Otherwise, print YES in the first line, and in the second line print the values x and y such that your path was possible with such number of lines and columns in the matrix. Remember that they must be positive integers not exceeding 109.
standard output
PASSED
37148f8a4276b3d28e37097b189cf012
train_000.jsonl
1521698700
There is a matrix A of size x × y filled with integers. For every , Ai, j = y(i - 1) + j. Obviously, every integer from [1..xy] occurs exactly once in this matrix. You have traversed some path in this matrix. Your path can be described as a sequence of visited cells a1, a2, ..., an denoting that you started in the cell containing the number a1, then moved to the cell with the number a2, and so on.From the cell located in i-th line and j-th column (we denote this cell as (i, j)) you can move into one of the following cells: (i + 1, j) — only if i &lt; x; (i, j + 1) — only if j &lt; y; (i - 1, j) — only if i &gt; 1; (i, j - 1) — only if j &gt; 1.Notice that making a move requires you to go to an adjacent cell. It is not allowed to stay in the same cell. You don't know x and y exactly, but you have to find any possible values for these numbers such that you could start in the cell containing the integer a1, then move to the cell containing a2 (in one step), then move to the cell containing a3 (also in one step) and so on. Can you choose x and y so that they don't contradict with your sequence of moves?
256 megabytes
import java.io.*; import java.util.*; public class C implements Runnable{ public static void main (String[] args) {new Thread(null, new C(), "_cf", 1 << 28).start();} public void run() { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); System.err.println("Go!"); int n = fs.nextInt(); int[] a = fs.nextIntArray(n); if(n==1) { System.out.println("YES"); System.out.printf("%d %d\n", a[0], a[0]); return; } int max = 0; for(Integer i : a) max = Math.max(max, i); int y = -1; for(int i = 1; i < n; i++) { int d = Math.abs(a[i] - a[i-1]); if(d == 0) exit("NO"); if(d > 1) { y = d; } } if(y < 0) { System.out.println("YES"); System.out.printf("1 %d\n", max); return; } int x = max / y + (max % y > 0 ? 1 : 0); for(int i = 0; i < n - 1; i++) { int d = Math.abs(a[i] - a[i + 1]); if(d != y) { if(d != 1) exit("NO"); int mn = Math.min(a[i], a[i + 1]); int mx = Math.max(a[i], a[i + 1]); if(mn % y == 0 && mx % y == 1) exit("NO"); } } if(x > (int)1e9 || y > (int)1e9) exit("NO"); System.out.println("YES"); System.out.println(x + " " + y); out.close(); } void exit(String s) { System.out.println(s); System.exit(0); } void sort (int[] a) { int n = a.length; for(int i = 0; i < 50; i++) { Random r = new Random(); int x = r.nextInt(n), y = r.nextInt(n); int temp = a[x]; a[x] = a[y]; a[y] = temp; } Arrays.sort(a); } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { try { br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new FileReader("testdata.out")); st = new StringTokenizer(""); } catch (Exception e){e.printStackTrace();} } public String next() { if (st.hasMoreTokens()) return st.nextToken(); try {st = new StringTokenizer(br.readLine());} catch (Exception e) {e.printStackTrace();} return st.nextToken(); } public int nextInt() {return Integer.parseInt(next());} public long nextLong() {return Long.parseLong(next());} public double nextDouble() {return Double.parseDouble(next());} public String nextLine() { String line = ""; try {line = br.readLine();} catch (Exception e) {e.printStackTrace();} return line; } public Integer[] nextIntegerArray(int n) { Integer[] a = new Integer[n]; for(int i = 0; i < n; i++) a[i] = nextInt(); return a; } public int[] nextIntArray(int n) { int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = nextInt(); return a; } public char[] nextCharArray() {return nextLine().toCharArray();} } }
Java
["8\n1 2 3 6 9 8 5 2", "6\n1 2 1 2 5 3", "2\n1 10"]
1 second
["YES\n3 3", "NO", "YES\n4 9"]
NoteThe matrix and the path on it in the first test looks like this: Also there exist multiple correct answers for both the first and the third examples.
Java 8
standard input
[ "implementation" ]
3b725f11009768904514d87e2c7714ee
The first line contains one integer number n (1 ≤ n ≤ 200000) — the number of cells you visited on your path (if some cell is visited twice, then it's listed twice). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the integers in the cells on your path.
1,700
If all possible values of x and y such that 1 ≤ x, y ≤ 109 contradict with the information about your path, print NO. Otherwise, print YES in the first line, and in the second line print the values x and y such that your path was possible with such number of lines and columns in the matrix. Remember that they must be positive integers not exceeding 109.
standard output
PASSED
90a8b795f79321c5079e20b86d840411
train_000.jsonl
1521698700
There is a matrix A of size x × y filled with integers. For every , Ai, j = y(i - 1) + j. Obviously, every integer from [1..xy] occurs exactly once in this matrix. You have traversed some path in this matrix. Your path can be described as a sequence of visited cells a1, a2, ..., an denoting that you started in the cell containing the number a1, then moved to the cell with the number a2, and so on.From the cell located in i-th line and j-th column (we denote this cell as (i, j)) you can move into one of the following cells: (i + 1, j) — only if i &lt; x; (i, j + 1) — only if j &lt; y; (i - 1, j) — only if i &gt; 1; (i, j - 1) — only if j &gt; 1.Notice that making a move requires you to go to an adjacent cell. It is not allowed to stay in the same cell. You don't know x and y exactly, but you have to find any possible values for these numbers such that you could start in the cell containing the integer a1, then move to the cell containing a2 (in one step), then move to the cell containing a3 (also in one step) and so on. Can you choose x and y so that they don't contradict with your sequence of moves?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Rustam Musin ([email protected]) */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); int[] a = in.readIntArray(n); int delta = 1; for (int i = 0; i + 1 < n; i++) { int d = Math.abs(a[i] - a[i + 1]); if (d == 1) { continue; } if ((d == 0) || ((delta != 1) && (d != delta))) { out.print("NO"); return; } delta = d; } if (delta > 1) { for (int i = 0; i + 1 < n; i++) { int d = Math.abs(a[i] - a[i + 1]); int r1 = (a[i] - 1) / delta; int r2 = (a[i + 1] - 1) / delta; if (d == 1 && r1 != r2) { out.print("NO"); return; } } } out.printLine("YES"); out.print((int) 1e9, delta); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int[] readIntArray(int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = readInt(); } return array; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["8\n1 2 3 6 9 8 5 2", "6\n1 2 1 2 5 3", "2\n1 10"]
1 second
["YES\n3 3", "NO", "YES\n4 9"]
NoteThe matrix and the path on it in the first test looks like this: Also there exist multiple correct answers for both the first and the third examples.
Java 8
standard input
[ "implementation" ]
3b725f11009768904514d87e2c7714ee
The first line contains one integer number n (1 ≤ n ≤ 200000) — the number of cells you visited on your path (if some cell is visited twice, then it's listed twice). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the integers in the cells on your path.
1,700
If all possible values of x and y such that 1 ≤ x, y ≤ 109 contradict with the information about your path, print NO. Otherwise, print YES in the first line, and in the second line print the values x and y such that your path was possible with such number of lines and columns in the matrix. Remember that they must be positive integers not exceeding 109.
standard output
PASSED
d7562338fbe0a9523809ccb5f502b56b
train_000.jsonl
1521698700
There is a matrix A of size x × y filled with integers. For every , Ai, j = y(i - 1) + j. Obviously, every integer from [1..xy] occurs exactly once in this matrix. You have traversed some path in this matrix. Your path can be described as a sequence of visited cells a1, a2, ..., an denoting that you started in the cell containing the number a1, then moved to the cell with the number a2, and so on.From the cell located in i-th line and j-th column (we denote this cell as (i, j)) you can move into one of the following cells: (i + 1, j) — only if i &lt; x; (i, j + 1) — only if j &lt; y; (i - 1, j) — only if i &gt; 1; (i, j - 1) — only if j &gt; 1.Notice that making a move requires you to go to an adjacent cell. It is not allowed to stay in the same cell. You don't know x and y exactly, but you have to find any possible values for these numbers such that you could start in the cell containing the integer a1, then move to the cell containing a2 (in one step), then move to the cell containing a3 (also in one step) and so on. Can you choose x and y so that they don't contradict with your sequence of moves?
256 megabytes
import java.util.*; import java.util.stream.*; import java.io.*; import java.math.*; public class Main { static boolean FROM_FILE = false; static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { if (FROM_FILE) { try { br = new BufferedReader(new FileReader("input.txt")); } catch (IOException error) { } } else { 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; } } static int max(int... nums) { int res = Integer.MIN_VALUE; for (int num: nums) res = Math.max(res, num); return res; } static int min(int... nums) { int res = Integer.MAX_VALUE; for (int num: nums) res = Math.min(res, num); return res; } static long max(long... nums) { long res = Long.MIN_VALUE; for (long num: nums) res = Math.max(res, num); return res; } static long min(long... nums) { long res = Long.MAX_VALUE; for (long num: nums) res = Math.min(res, num); return res; } static FastReader fr = new FastReader(); static PrintWriter out; public static void main(String[] args) { if (FROM_FILE) { try { out = new PrintWriter(new FileWriter("output.txt")); } catch (IOException error) { } } else { out = new PrintWriter(new OutputStreamWriter(System.out)); } new Main().run(); out.flush(); out.close(); } void run() { int n = fr.nextInt(); int[] nums = new int[n]; for (int i = 0; i < n; i += 1) nums[i] = fr.nextInt(); boolean flag = true; int width = 1, maxNum = max(nums); for (int i = 1; i < n; i += 1) { int diff = nums[i] - nums[i - 1]; if (diff == 0) { flag = false; break; } if (Math.abs(diff) != 1) { if (width != 1 && width != Math.abs(diff)) { flag = false; break; } width = Math.abs(diff); } } if (!flag) { out.println("NO"); return; } if (width != 1) { for (int i = 1; i < n; i += 1) { int diff = nums[i] - nums[i - 1]; if (Math.abs(diff) == 1) { if (diff == 1 && nums[i - 1] % width == 0) { flag = false; break; } if (diff == -1 && nums[i] % width == 0) { flag = false; break; } } } } if (!flag) { out.println("NO"); return; } out.println("YES"); int height = (maxNum + width - 1) / width; out.println(height + " " + width); } }
Java
["8\n1 2 3 6 9 8 5 2", "6\n1 2 1 2 5 3", "2\n1 10"]
1 second
["YES\n3 3", "NO", "YES\n4 9"]
NoteThe matrix and the path on it in the first test looks like this: Also there exist multiple correct answers for both the first and the third examples.
Java 8
standard input
[ "implementation" ]
3b725f11009768904514d87e2c7714ee
The first line contains one integer number n (1 ≤ n ≤ 200000) — the number of cells you visited on your path (if some cell is visited twice, then it's listed twice). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the integers in the cells on your path.
1,700
If all possible values of x and y such that 1 ≤ x, y ≤ 109 contradict with the information about your path, print NO. Otherwise, print YES in the first line, and in the second line print the values x and y such that your path was possible with such number of lines and columns in the matrix. Remember that they must be positive integers not exceeding 109.
standard output
PASSED
e0de4f445aa80ea75edab8db77221dba
train_000.jsonl
1521698700
There is a matrix A of size x × y filled with integers. For every , Ai, j = y(i - 1) + j. Obviously, every integer from [1..xy] occurs exactly once in this matrix. You have traversed some path in this matrix. Your path can be described as a sequence of visited cells a1, a2, ..., an denoting that you started in the cell containing the number a1, then moved to the cell with the number a2, and so on.From the cell located in i-th line and j-th column (we denote this cell as (i, j)) you can move into one of the following cells: (i + 1, j) — only if i &lt; x; (i, j + 1) — only if j &lt; y; (i - 1, j) — only if i &gt; 1; (i, j - 1) — only if j &gt; 1.Notice that making a move requires you to go to an adjacent cell. It is not allowed to stay in the same cell. You don't know x and y exactly, but you have to find any possible values for these numbers such that you could start in the cell containing the integer a1, then move to the cell containing a2 (in one step), then move to the cell containing a3 (also in one step) and so on. Can you choose x and y so that they don't contradict with your sequence of moves?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.FilterInputStream; import java.io.BufferedInputStream; import java.io.InputStream; /** * @author khokharnikunj8 */ public class Main { public static void main(String[] args) { new Thread(null, new Runnable() { public void run() { new Main().solve(); } }, "1", 1 << 26).start(); } void solve() { InputStream inputStream = System.in; OutputStream outputStream = System.out; ScanReader in = new ScanReader(inputStream); PrintWriter out = new PrintWriter(outputStream); ProblemCMatrixWalk solver = new ProblemCMatrixWalk(); solver.solve(1, in, out); out.close(); } static class ProblemCMatrixWalk { public void solve(int testNumber, ScanReader in, PrintWriter out) { int n = in.scanInt(); boolean flag = true; long x = 1000000000; long y = 1000000000; int ar[] = new int[n]; long yy = -1; for (int i = 0; i < n; i++) ar[i] = in.scanInt(); for (int i = 1; i < n; i++) { if (ar[i] == ar[i - 1]) flag = false; if (Math.abs(ar[i] - ar[i - 1]) != 1) { if (ar[i] < ar[i - 1]) yy = ar[i - 1] - ar[i]; else yy = ar[i] - ar[i - 1]; break; } } if (yy != -1 && flag) { for (int i = 1; i < n; i++) { if (ar[i] == ar[i - 1]) flag = false; long xx11 = (long) Math.ceil((double) ar[i] / yy) - 1; long xx12 = (long) Math.ceil((double) ar[i - 1] / yy) - 1; long yy11 = ar[i] - (((long) Math.ceil((double) ar[i] / yy) - 1) * yy); long yy12 = ar[i - 1] - (((long) Math.ceil((double) ar[i - 1] / yy) - 1) * yy); if (yy11 > yy || yy12 > yy) flag = false; if (Math.abs(ar[i] - ar[i - 1]) == 1) { if (xx11 != xx12 || Math.abs(yy11 - yy12) != 1) flag = false; } else { if (ar[i] < ar[i - 1]) { if (ar[i] + yy != ar[i - 1] || yy11 != yy12 || xx11 != xx12 - 1) flag = false; } else { if (ar[i] != ar[i - 1] + yy || yy11 != yy12 || xx11 - 1 != xx12) flag = false; } } } } if (flag) { out.println("YES"); if (yy == -1) out.println(x + " " + y); else out.println(x + " " + yy); } else out.println("NO"); } } static class ScanReader { private byte[] buf = new byte[4 * 1024]; private int index; private BufferedInputStream in; private int total; public ScanReader(InputStream inputStream) { in = new BufferedInputStream(inputStream); } private int scan() { if (index >= total) { index = 0; try { total = in.read(buf); } catch (Exception e) { e.printStackTrace(); } if (total <= 0) return -1; } return buf[index++]; } public int scanInt() { int integer = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { integer *= 10; integer += n - '0'; n = scan(); } } return neg * integer; } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; else return false; } } }
Java
["8\n1 2 3 6 9 8 5 2", "6\n1 2 1 2 5 3", "2\n1 10"]
1 second
["YES\n3 3", "NO", "YES\n4 9"]
NoteThe matrix and the path on it in the first test looks like this: Also there exist multiple correct answers for both the first and the third examples.
Java 8
standard input
[ "implementation" ]
3b725f11009768904514d87e2c7714ee
The first line contains one integer number n (1 ≤ n ≤ 200000) — the number of cells you visited on your path (if some cell is visited twice, then it's listed twice). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the integers in the cells on your path.
1,700
If all possible values of x and y such that 1 ≤ x, y ≤ 109 contradict with the information about your path, print NO. Otherwise, print YES in the first line, and in the second line print the values x and y such that your path was possible with such number of lines and columns in the matrix. Remember that they must be positive integers not exceeding 109.
standard output
PASSED
aa4e1ec694edbe6735b3cb384146b706
train_000.jsonl
1521698700
There is a matrix A of size x × y filled with integers. For every , Ai, j = y(i - 1) + j. Obviously, every integer from [1..xy] occurs exactly once in this matrix. You have traversed some path in this matrix. Your path can be described as a sequence of visited cells a1, a2, ..., an denoting that you started in the cell containing the number a1, then moved to the cell with the number a2, and so on.From the cell located in i-th line and j-th column (we denote this cell as (i, j)) you can move into one of the following cells: (i + 1, j) — only if i &lt; x; (i, j + 1) — only if j &lt; y; (i - 1, j) — only if i &gt; 1; (i, j - 1) — only if j &gt; 1.Notice that making a move requires you to go to an adjacent cell. It is not allowed to stay in the same cell. You don't know x and y exactly, but you have to find any possible values for these numbers such that you could start in the cell containing the integer a1, then move to the cell containing a2 (in one step), then move to the cell containing a3 (also in one step) and so on. Can you choose x and y so that they don't contradict with your sequence of moves?
256 megabytes
import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.Scanner; import java.util.StringTokenizer; public class C { public static void main(String[] args) { try (final Scanner sc = new Scanner(System.in)) { final int N = sc.nextInt(); final long[] array = new long[N]; for(int i = 0; i < N; i++){ array[i] = sc.nextLong() - 1; } if(N == 1){ System.out.println("YES"); System.out.println(100000000 + " " + 1000000000); return; } final long[] diffs = new long[N - 1]; for(int i = 0; i < N - 1; i++){ diffs[i] = array[i + 1] - array[i]; } long possible_W = -1; for(final long diff : diffs){ if(Math.abs(diff) == 1){ continue; } final long W = Math.abs(diff); //System.out.println(W); if(W == 0){ System.out.println("NO"); return; } if(possible_W < 0){ possible_W = W; }else if(possible_W != W){ System.out.println("NO"); return; } } final long MAX = 1000000000; if(possible_W < 0){ System.out.println("YES"); System.out.println(MAX + " " + (Arrays.stream(array).max().getAsLong() + 1)); return; } long curr_x = array[0] % possible_W; long curr_y = array[0] / possible_W; for(final long diff : diffs){ if(Math.abs(diff) != 1){ curr_y += diff / possible_W; if(curr_y < 0 || curr_y >= MAX){ System.out.println("NO"); return; } }else{ curr_x += diff; if(curr_x < 0 || curr_x >= possible_W){ System.out.println("NO"); return; } } } System.out.println("YES"); System.out.println(MAX + " " + possible_W); } } public static class Scanner implements Closeable { private BufferedReader br; private StringTokenizer tok; public Scanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } private void getLine() { try { while (!hasNext()) { tok = new StringTokenizer(br.readLine()); } } catch (IOException e) { /* ignore */ } } private boolean hasNext() { return tok != null && tok.hasMoreTokens(); } public String next() { getLine(); return tok.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public void close() { try { br.close(); } catch (IOException e) { /* ignore */ } } } }
Java
["8\n1 2 3 6 9 8 5 2", "6\n1 2 1 2 5 3", "2\n1 10"]
1 second
["YES\n3 3", "NO", "YES\n4 9"]
NoteThe matrix and the path on it in the first test looks like this: Also there exist multiple correct answers for both the first and the third examples.
Java 8
standard input
[ "implementation" ]
3b725f11009768904514d87e2c7714ee
The first line contains one integer number n (1 ≤ n ≤ 200000) — the number of cells you visited on your path (if some cell is visited twice, then it's listed twice). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the integers in the cells on your path.
1,700
If all possible values of x and y such that 1 ≤ x, y ≤ 109 contradict with the information about your path, print NO. Otherwise, print YES in the first line, and in the second line print the values x and y such that your path was possible with such number of lines and columns in the matrix. Remember that they must be positive integers not exceeding 109.
standard output
PASSED
012f81fd3d3ce3161dd51e292fde6a91
train_000.jsonl
1521698700
There is a matrix A of size x × y filled with integers. For every , Ai, j = y(i - 1) + j. Obviously, every integer from [1..xy] occurs exactly once in this matrix. You have traversed some path in this matrix. Your path can be described as a sequence of visited cells a1, a2, ..., an denoting that you started in the cell containing the number a1, then moved to the cell with the number a2, and so on.From the cell located in i-th line and j-th column (we denote this cell as (i, j)) you can move into one of the following cells: (i + 1, j) — only if i &lt; x; (i, j + 1) — only if j &lt; y; (i - 1, j) — only if i &gt; 1; (i, j - 1) — only if j &gt; 1.Notice that making a move requires you to go to an adjacent cell. It is not allowed to stay in the same cell. You don't know x and y exactly, but you have to find any possible values for these numbers such that you could start in the cell containing the integer a1, then move to the cell containing a2 (in one step), then move to the cell containing a3 (also in one step) and so on. Can you choose x and y so that they don't contradict with your sequence of moves?
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int y=0; int last = 0; int ans = 1; int max = Integer.MIN_VALUE; int[] data = new int[200000]; for(int i=0;i<n;i++){ int t = scanner.nextInt(); data[i] = t; if(t>max){ max = t; } if(i!=0){ if(Math.abs(t-last)==0){ ans = 0; break; } if(y!=0&&t%y==1){ if(t-last==1){ ans = 0; break; } } if(y!=0&&t%y==0){ if(last-t==1){ ans = 0; break; } } if(Math.abs(t-last)!=1){ if(y!=0&&Math.abs(t-last)!=y){ ans = 0; break; } y = Math.abs(t-last); } } last = t; } for(int i=0;i<n;i++){ int t = data[i]; if(i!=0){ if(y!=0&&t%y==1){ if(t-last==1){ ans = 0; break; } } if(y!=0&&t%y==0){ if(last-t==1){ ans = 0; break; } } } last = t; } if(ans==0){ System.out.println("NO"); }else{ System.out.println("YES"); if(y==0){ y = 1; } if(max%y==0){ System.out.print(max/y); }else{ System.out.print(max/y+1); } System.out.println(" "+y); } } }
Java
["8\n1 2 3 6 9 8 5 2", "6\n1 2 1 2 5 3", "2\n1 10"]
1 second
["YES\n3 3", "NO", "YES\n4 9"]
NoteThe matrix and the path on it in the first test looks like this: Also there exist multiple correct answers for both the first and the third examples.
Java 8
standard input
[ "implementation" ]
3b725f11009768904514d87e2c7714ee
The first line contains one integer number n (1 ≤ n ≤ 200000) — the number of cells you visited on your path (if some cell is visited twice, then it's listed twice). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the integers in the cells on your path.
1,700
If all possible values of x and y such that 1 ≤ x, y ≤ 109 contradict with the information about your path, print NO. Otherwise, print YES in the first line, and in the second line print the values x and y such that your path was possible with such number of lines and columns in the matrix. Remember that they must be positive integers not exceeding 109.
standard output
PASSED
5b53f3bfe379acceff67444f6d27a483
train_000.jsonl
1521698700
There is a matrix A of size x × y filled with integers. For every , Ai, j = y(i - 1) + j. Obviously, every integer from [1..xy] occurs exactly once in this matrix. You have traversed some path in this matrix. Your path can be described as a sequence of visited cells a1, a2, ..., an denoting that you started in the cell containing the number a1, then moved to the cell with the number a2, and so on.From the cell located in i-th line and j-th column (we denote this cell as (i, j)) you can move into one of the following cells: (i + 1, j) — only if i &lt; x; (i, j + 1) — only if j &lt; y; (i - 1, j) — only if i &gt; 1; (i, j - 1) — only if j &gt; 1.Notice that making a move requires you to go to an adjacent cell. It is not allowed to stay in the same cell. You don't know x and y exactly, but you have to find any possible values for these numbers such that you could start in the cell containing the integer a1, then move to the cell containing a2 (in one step), then move to the cell containing a3 (also in one step) and so on. Can you choose x and y so that they don't contradict with your sequence of moves?
256 megabytes
import java.io.*; import java.util.*; public class CFC { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; private static final long MOD = 1000L * 1000L * 1000L + 7; private static final int[] dx = {0, -1, 0, 1}; private static final int[] dy = {1, 0, -1, 0}; private static final String yes = "YES"; private static final String no = "NO"; int y; void solve() throws IOException { int n = nextInt(); int[] arr = nextIntArr(n); y = Integer.MIN_VALUE; for (int i = 1; i < n; i++) { int diff = arr[i] - arr[i - 1]; if (diff == 1 || diff == -1) { continue; } if (diff == 0) { outln(no); return; } if (diff > 0) { if (y == Integer.MIN_VALUE) { y = diff; } else { if (y != diff) { outln(no); return; } } } else { if (y == Integer.MIN_VALUE) { y = -diff; } else { if (y != -diff) { outln(no); return; } } } } if (y == Integer.MIN_VALUE) { outln(yes); outln((MOD - 7) + " " + (MOD - 7)); } else { for (int i = 1; i < n; i++) { int[] p1 = getLoc(arr[i] - 1); int[] p2 = getLoc(arr[i - 1] - 1); int dist = Math.abs(p1[0] - p2[0]); dist += Math.abs(p1[1] - p2[1]); if (dist != 1) { outln(no); return; } } outln(yes); outln((MOD - 7) + " " + y); } } int[] getLoc(int pos) { int[] res = new int[2]; res[0] = pos / y; res[1] = pos % y; return res; } void shuffle(int[] a) { int n = a.length; for(int i = 0; i < n; i++) { int r = i + (int) (Math.random() * (n - i)); int tmp = a[i]; a[i] = a[r]; a[r] = tmp; } } int gcd(int a, int b) { while(a != 0 && b != 0) { int c = b; b = a % b; a = c; } return a + b; } private void outln(Object o) { out.println(o); } private void out(Object o) { out.print(o); } public CFC() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } public static void main(String[] args) throws IOException { new CFC(); } public long[] nextLongArr(int n) throws IOException{ long[] res = new long[n]; for(int i = 0; i < n; i++) res[i] = nextLong(); return res; } public int[] nextIntArr(int n) throws IOException { int[] res = new int[n]; for(int i = 0; i < n; i++) res[i] = nextInt(); return res; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } public String nextString() { try { return br.readLine(); } catch (IOException e) { eof = true; return null; } } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
Java
["8\n1 2 3 6 9 8 5 2", "6\n1 2 1 2 5 3", "2\n1 10"]
1 second
["YES\n3 3", "NO", "YES\n4 9"]
NoteThe matrix and the path on it in the first test looks like this: Also there exist multiple correct answers for both the first and the third examples.
Java 8
standard input
[ "implementation" ]
3b725f11009768904514d87e2c7714ee
The first line contains one integer number n (1 ≤ n ≤ 200000) — the number of cells you visited on your path (if some cell is visited twice, then it's listed twice). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the integers in the cells on your path.
1,700
If all possible values of x and y such that 1 ≤ x, y ≤ 109 contradict with the information about your path, print NO. Otherwise, print YES in the first line, and in the second line print the values x and y such that your path was possible with such number of lines and columns in the matrix. Remember that they must be positive integers not exceeding 109.
standard output
PASSED
6645bcf96cf5e19a682e0ee49aa13495
train_000.jsonl
1521698700
There is a matrix A of size x × y filled with integers. For every , Ai, j = y(i - 1) + j. Obviously, every integer from [1..xy] occurs exactly once in this matrix. You have traversed some path in this matrix. Your path can be described as a sequence of visited cells a1, a2, ..., an denoting that you started in the cell containing the number a1, then moved to the cell with the number a2, and so on.From the cell located in i-th line and j-th column (we denote this cell as (i, j)) you can move into one of the following cells: (i + 1, j) — only if i &lt; x; (i, j + 1) — only if j &lt; y; (i - 1, j) — only if i &gt; 1; (i, j - 1) — only if j &gt; 1.Notice that making a move requires you to go to an adjacent cell. It is not allowed to stay in the same cell. You don't know x and y exactly, but you have to find any possible values for these numbers such that you could start in the cell containing the integer a1, then move to the cell containing a2 (in one step), then move to the cell containing a3 (also in one step) and so on. Can you choose x and y so that they don't contradict with your sequence of moves?
256 megabytes
import java.util.*; import java.io.*; import static java.lang.Math.abs; public class Main { static class Reader { BufferedReader in; Reader() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); } Reader(String name) throws IOException { in = new BufferedReader(new FileReader(name)); } StringTokenizer tokin = new StringTokenizer(""); String next() throws IOException { while (!tokin.hasMoreTokens()) { tokin = new StringTokenizer(in.readLine()); } return tokin.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } } static class Writer { PrintWriter cout; Writer() throws IOException { cout = new PrintWriter(System.out); } Writer(String name) throws IOException { cout = new PrintWriter(new FileWriter(name)); } StringBuilder out = new StringBuilder(); void print(Object a) { out.append(a); } void println(Object a) { out.append(a + "\n"); } void close() { cout.print(out.toString()); cout.close(); } } public static void main(String args[]) throws IOException { Reader in = new Reader(); Writer out = new Writer(); int n = in.nextInt(); long a[] = new long[n]; long y = -1; boolean must = true; for (int i = 0; i < n; i++) { a[i] = in.nextLong(); if (i > 0) { if (a[i] == a[i - 1]) must = false; long d = abs(a[i] - a[i - 1]); if (d > 1) { if (y == -1) { y = d; } else { if (d != y) must = false; } } } } if (y == -1 && must) { out.print("YES\n1 1000000000"); } else { if (!must) { out.print("NO"); } else { long y1; if (a[0] % y != 0) y1 = a[0] % y; else y1 = y; ///long x1 = (a[0] - y1) / y; for (int i = 1; i < n; i++) { long d = a[i] - a[i - 1]; if (abs(d) == 1) { if (y1 + d <= y && y1 + d >= 1) { y1 += d; } else { must = false; break; } } } if (must) { out.print("YES\n"); out.print("1000000000 " + y); } else { out.print("NO"); } } } out.close(); } }
Java
["8\n1 2 3 6 9 8 5 2", "6\n1 2 1 2 5 3", "2\n1 10"]
1 second
["YES\n3 3", "NO", "YES\n4 9"]
NoteThe matrix and the path on it in the first test looks like this: Also there exist multiple correct answers for both the first and the third examples.
Java 8
standard input
[ "implementation" ]
3b725f11009768904514d87e2c7714ee
The first line contains one integer number n (1 ≤ n ≤ 200000) — the number of cells you visited on your path (if some cell is visited twice, then it's listed twice). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the integers in the cells on your path.
1,700
If all possible values of x and y such that 1 ≤ x, y ≤ 109 contradict with the information about your path, print NO. Otherwise, print YES in the first line, and in the second line print the values x and y such that your path was possible with such number of lines and columns in the matrix. Remember that they must be positive integers not exceeding 109.
standard output
PASSED
07a7db970ac32426222806990bf6ed3b
train_000.jsonl
1521698700
There is a matrix A of size x × y filled with integers. For every , Ai, j = y(i - 1) + j. Obviously, every integer from [1..xy] occurs exactly once in this matrix. You have traversed some path in this matrix. Your path can be described as a sequence of visited cells a1, a2, ..., an denoting that you started in the cell containing the number a1, then moved to the cell with the number a2, and so on.From the cell located in i-th line and j-th column (we denote this cell as (i, j)) you can move into one of the following cells: (i + 1, j) — only if i &lt; x; (i, j + 1) — only if j &lt; y; (i - 1, j) — only if i &gt; 1; (i, j - 1) — only if j &gt; 1.Notice that making a move requires you to go to an adjacent cell. It is not allowed to stay in the same cell. You don't know x and y exactly, but you have to find any possible values for these numbers such that you could start in the cell containing the integer a1, then move to the cell containing a2 (in one step), then move to the cell containing a3 (also in one step) and so on. Can you choose x and y so that they don't contradict with your sequence of moves?
256 megabytes
import java.io.*; import java.lang.*; public class CF954C{ public static void main(String args[]) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s[] = br.readLine().split(" "); int n = Integer.parseInt(s[0]); s = br.readLine().split(" "); int[] a = new int[n]; int max = 0; for(int i=0;i<n;i++){ a[i] = Integer.parseInt(s[i]); max = Math.max(max, a[i]); } int y = 1; boolean set = false; for(int i=1;i<n;i++){ if(a[i] == a[i-1]){ System.out.println("NO"); return; } if(a[i-1] + 1 != a[i] && a[i-1] - 1 != a[i] && a[i-1] - y != a[i] && a[i-1] + y != a[i] ){ if(!set){ if(a[i] > a[i-1]){ y = a[i] - a[i-1]; }else{ y = a[i-1] - a[i]; } set = true; break; }else{ System.out.println("NO"); return; } } } for(int i=1;i<n;i++){ if(a[i-1]%y == 0 && a[i-1] + 1 == a[i] && y != 1){ System.out.println("NO"); return; } if(a[i]%y == 0 && a[i-1] == a[i] + 1 && y!= 1){ System.out.println("NO"); return; } if(a[i-1] + 1 != a[i] && a[i-1] - 1 != a[i] && a[i-1] - y != a[i] && a[i-1] + y != a[i] ){ System.out.println("NO"); return; } } System.out.println("YES"); System.out.println(1000000000 +" "+y); } }
Java
["8\n1 2 3 6 9 8 5 2", "6\n1 2 1 2 5 3", "2\n1 10"]
1 second
["YES\n3 3", "NO", "YES\n4 9"]
NoteThe matrix and the path on it in the first test looks like this: Also there exist multiple correct answers for both the first and the third examples.
Java 8
standard input
[ "implementation" ]
3b725f11009768904514d87e2c7714ee
The first line contains one integer number n (1 ≤ n ≤ 200000) — the number of cells you visited on your path (if some cell is visited twice, then it's listed twice). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the integers in the cells on your path.
1,700
If all possible values of x and y such that 1 ≤ x, y ≤ 109 contradict with the information about your path, print NO. Otherwise, print YES in the first line, and in the second line print the values x and y such that your path was possible with such number of lines and columns in the matrix. Remember that they must be positive integers not exceeding 109.
standard output
PASSED
b0bb69231fe51f5526c2ce978bde13dd
train_000.jsonl
1521698700
There is a matrix A of size x × y filled with integers. For every , Ai, j = y(i - 1) + j. Obviously, every integer from [1..xy] occurs exactly once in this matrix. You have traversed some path in this matrix. Your path can be described as a sequence of visited cells a1, a2, ..., an denoting that you started in the cell containing the number a1, then moved to the cell with the number a2, and so on.From the cell located in i-th line and j-th column (we denote this cell as (i, j)) you can move into one of the following cells: (i + 1, j) — only if i &lt; x; (i, j + 1) — only if j &lt; y; (i - 1, j) — only if i &gt; 1; (i, j - 1) — only if j &gt; 1.Notice that making a move requires you to go to an adjacent cell. It is not allowed to stay in the same cell. You don't know x and y exactly, but you have to find any possible values for these numbers such that you could start in the cell containing the integer a1, then move to the cell containing a2 (in one step), then move to the cell containing a3 (also in one step) and so on. Can you choose x and y so that they don't contradict with your sequence of moves?
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class ProblemC { String fileName = "prizes"; public void solve() throws IOException { int n = nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); int delta = -1; boolean b = true; for (int i = 1; i < n; i++) { if (a[i] - a[i - 1] != 0) { if (Math.abs(a[i] - a[i - 1]) != 1) { if (delta == -1) delta = Math.abs(a[i] - a[i - 1]); else { if (delta != Math.abs(a[i] - a[i - 1])) b = false; } } } else b = false; } // out.println(delta); delta = Math.abs(delta); for (int i = 1; i < n; i++) { if (Math.abs(a[i] - a[i - 1]) != delta && Math.abs((a[i] - 1) % delta - (a[i - 1] - 1) % delta) != 1) { b = false; // out.print(i + " "); } if (((a[i]) % delta == 0 && a[i - 1] - a[i] == 1 || (a[i - 1] % delta == 0 && a[i] - a[i - 1] == 1)) && delta != 1) b = false; } if (b) { out.println("YES"); out.println((int) Math.pow(10, 9) + " " + Math.abs(delta)); } else { out.println("NO"); } } public void run() { try { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out, true); // out = new PrintWriter(fileName + ".out"); // br = new BufferedReader(new FileReader(fileName + ".in")); // out = new PrintWriter(fileName + ".out"); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } BufferedReader br; StringTokenizer in; static PrintWriter out; public String nextToken() throws IOException { while (in == null || !in.hasMoreTokens()) { in = new StringTokenizer(br.readLine()); } return in.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public static void main(String[] args) throws IOException { new ProblemC().run(); } }
Java
["8\n1 2 3 6 9 8 5 2", "6\n1 2 1 2 5 3", "2\n1 10"]
1 second
["YES\n3 3", "NO", "YES\n4 9"]
NoteThe matrix and the path on it in the first test looks like this: Also there exist multiple correct answers for both the first and the third examples.
Java 8
standard input
[ "implementation" ]
3b725f11009768904514d87e2c7714ee
The first line contains one integer number n (1 ≤ n ≤ 200000) — the number of cells you visited on your path (if some cell is visited twice, then it's listed twice). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the integers in the cells on your path.
1,700
If all possible values of x and y such that 1 ≤ x, y ≤ 109 contradict with the information about your path, print NO. Otherwise, print YES in the first line, and in the second line print the values x and y such that your path was possible with such number of lines and columns in the matrix. Remember that they must be positive integers not exceeding 109.
standard output
PASSED
f17516a87c94df9d1d0f25237881689d
train_000.jsonl
1521698700
There is a matrix A of size x × y filled with integers. For every , Ai, j = y(i - 1) + j. Obviously, every integer from [1..xy] occurs exactly once in this matrix. You have traversed some path in this matrix. Your path can be described as a sequence of visited cells a1, a2, ..., an denoting that you started in the cell containing the number a1, then moved to the cell with the number a2, and so on.From the cell located in i-th line and j-th column (we denote this cell as (i, j)) you can move into one of the following cells: (i + 1, j) — only if i &lt; x; (i, j + 1) — only if j &lt; y; (i - 1, j) — only if i &gt; 1; (i, j - 1) — only if j &gt; 1.Notice that making a move requires you to go to an adjacent cell. It is not allowed to stay in the same cell. You don't know x and y exactly, but you have to find any possible values for these numbers such that you could start in the cell containing the integer a1, then move to the cell containing a2 (in one step), then move to the cell containing a3 (also in one step) and so on. Can you choose x and y so that they don't contradict with your sequence of moves?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.OutputStream; import java.io.Writer; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author palayutm */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); ProblemCMatrixWalk solver = new ProblemCMatrixWalk(); solver.solve(1, in, out); out.close(); } static class ProblemCMatrixWalk { public void solve(int testNumber, InputReader in, OutputWriter out) { int X = (int) 1e9, Y = -1; int n = in.nextInt(); int[] a = in.nextIntArray(n); for (int i = 1; i < n; i++) { int t = Math.abs(a[i] - a[i - 1]); if (t != 1) { if (Y != -1 && t != Y || t == 0) { out.println("NO"); return; } Y = t; } } if (Y == -1) Y = (int) 1e9; for (int i = 1; i < n; i++) { int x1 = (a[i] - 1) / Y, y1 = a[i] - x1 * Y; int x2 = (a[i - 1] - 1) / Y, y2 = a[i - 1] - x2 * Y; if (Math.abs(x1 - x2) + Math.abs(y1 - y2) > 1) { out.println("NO"); return; } } out.println("YES"); out.println(X + " " + Y); } } static class InputReader { private InputStream stream; private byte[] inbuf = new byte[1024]; private int lenbuf = 0; private int ptrbuf = 0; public InputReader(InputStream stream) { this.stream = stream; } private int readByte() { if (lenbuf == -1) throw new UnknownError(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = stream.read(inbuf); } catch (IOException e) { throw new UnknownError(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } public int nextInt() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } public int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } } static class OutputWriter extends PrintWriter { public OutputWriter(OutputStream out) { super(out); } public OutputWriter(Writer out) { super(out); } public void close() { super.close(); } } }
Java
["8\n1 2 3 6 9 8 5 2", "6\n1 2 1 2 5 3", "2\n1 10"]
1 second
["YES\n3 3", "NO", "YES\n4 9"]
NoteThe matrix and the path on it in the first test looks like this: Also there exist multiple correct answers for both the first and the third examples.
Java 8
standard input
[ "implementation" ]
3b725f11009768904514d87e2c7714ee
The first line contains one integer number n (1 ≤ n ≤ 200000) — the number of cells you visited on your path (if some cell is visited twice, then it's listed twice). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the integers in the cells on your path.
1,700
If all possible values of x and y such that 1 ≤ x, y ≤ 109 contradict with the information about your path, print NO. Otherwise, print YES in the first line, and in the second line print the values x and y such that your path was possible with such number of lines and columns in the matrix. Remember that they must be positive integers not exceeding 109.
standard output
PASSED
6c41222d10f8736d6e22968d882d193b
train_000.jsonl
1557671700
Let $$$c$$$ be some positive integer. Let's call an array $$$a_1, a_2, \ldots, a_n$$$ of positive integers $$$c$$$-array, if for all $$$i$$$ condition $$$1 \leq a_i \leq c$$$ is satisfied. Let's call $$$c$$$-array $$$b_1, b_2, \ldots, b_k$$$ a subarray of $$$c$$$-array $$$a_1, a_2, \ldots, a_n$$$, if there exists such set of $$$k$$$ indices $$$1 \leq i_1 &lt; i_2 &lt; \ldots &lt; i_k \leq n$$$ that $$$b_j = a_{i_j}$$$ for all $$$1 \leq j \leq k$$$. Let's define density of $$$c$$$-array $$$a_1, a_2, \ldots, a_n$$$ as maximal non-negative integer $$$p$$$, such that any $$$c$$$-array, that contains $$$p$$$ numbers is a subarray of $$$a_1, a_2, \ldots, a_n$$$.You are given a number $$$c$$$ and some $$$c$$$-array $$$a_1, a_2, \ldots, a_n$$$. For all $$$0 \leq p \leq n$$$ find the number of sequences of indices $$$1 \leq i_1 &lt; i_2 &lt; \ldots &lt; i_k \leq n$$$ for all $$$1 \leq k \leq n$$$, such that density of array $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ is equal to $$$p$$$. Find these numbers by modulo $$$998\,244\,353$$$, because they can be too large.
256 megabytes
// https://codeforces.com/contest/1158/submission/54045740 (ecnerwala) // upsolve with rainboy import java.io.*; import java.util.*; public class CF1158F { static final int MD = 998244353; static long power(int a, int k) { if (k == 0) return 1; long p = power(a, k / 2); p = p * p % MD; if (k % 2 == 1) p = p * a % MD; return p; } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int c = Integer.parseInt(st.nextToken()); st = new StringTokenizer(br.readLine()); int[] aa = new int[n]; for (int i = 0; i < n; i++) aa[i] = Integer.parseInt(st.nextToken()) - 1; int[] p2 = new int[n + 1]; int[] p2m1 = new int[n + 1]; int[] p2m1_ = new int[n + 1]; for (int i = 0, p = 1; i <= n; i++) { p2m1_[i] = (int) power(p2m1[i] = (p2[i] = p) - 1, MD - 2); p = p * 2 % MD; } int[][] dp = new int[n + 1][n / c + 1]; dp[0][0] = 1; if (c > 10) { int[] kk = new int[c]; for (int j = 0; j < n; j++) { Arrays.fill(kk, 0); long w = 1; int bad = c - 1; for (int i = j; i >= 0; i--) { if (aa[i] != aa[j]) { if (kk[aa[i]] == 0) bad--; else w = w * p2m1_[kk[aa[i]]] % MD; w = w * p2m1[++kk[aa[i]]] % MD; } if (bad == 0) for (int l = 0; l <= i / c; l++) { int x = dp[i][l]; if (x != 0) dp[j + 1][l + 1] = (int) ((dp[j + 1][l + 1] + w * x) % MD); } } } } else { int[][] dq = new int[1 << c][n / c + 1]; dq[0][0] = 1; for (int j = 0; j < n; j++) { for (int b = (1 << c) - 1; b >= 0; b--) { int b_ = b | 1 << aa[j]; for (int l = 0; l <= j / c; l++) dq[b_][l] = (dq[b_][l] + dq[b][l]) % MD; } for (int l = 0; l < (j + 1) / c; l++) { int x = dq[(1 << c) - 1][l]; if (x != 0) { dp[j + 1][l + 1] = x; dq[0][l + 1] = (dq[0][l + 1] + x) % MD; dq[(1 << c) - 1][l] = 0; } } } } int[] ans = new int[n + 1]; for (int i = 0; i <= n; i++) for (int l = 0; l <= n / c; l++) ans[l] = (int) ((ans[l] + (long) dp[i][l] * p2[n - i]) % MD); ans[0] = (ans[0] - 1 + MD) % MD; for (int i = 0; i < n; i++) ans[i] = (ans[i] - ans[i + 1] + MD) % MD; StringBuilder sb = new StringBuilder(); for (int i = 0; i <= n; i++) sb.append(ans[i] + " "); System.out.println(sb); } }
Java
["4 1\n1 1 1 1", "3 3\n1 2 3", "5 2\n1 2 1 2 1"]
6 seconds
["0 4 6 4 1", "6 1 0 0", "10 17 4 0 0 0"]
NoteIn the first example, it's easy to see that the density of array will always be equal to its length. There exists $$$4$$$ sequences with one index, $$$6$$$ with two indices, $$$4$$$ with three and $$$1$$$ with four.In the second example, the only sequence of indices, such that the array will have non-zero density is all indices because in other cases there won't be at least one number from $$$1$$$ to $$$3$$$ in the array, so it won't satisfy the condition of density for $$$p \geq 1$$$.
Java 8
standard input
[ "dp", "math" ]
95c277d67c04fc644989c3112c2b5ae7
The first line contains two integers $$$n$$$ and $$$c$$$, separated by spaces ($$$1 \leq n, c \leq 3\,000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$, separated by spaces ($$$1 \leq a_i \leq c$$$).
3,500
Print $$$n + 1$$$ numbers $$$s_0, s_1, \ldots, s_n$$$. $$$s_p$$$ should be equal to the number of sequences of indices $$$1 \leq i_1 &lt; i_2 &lt; \ldots &lt; i_k \leq n$$$ for all $$$1 \leq k \leq n$$$ by modulo $$$998\,244\,353$$$, such that the density of array $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ is equal to $$$p$$$.
standard output