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
listlengths
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
fa52c22821395153860e35174cf0db91
train_001.jsonl
1542378900
The only difference between easy and hard versions is the constraints.Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $$$n$$$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $$$i$$$-th picture has beauty $$$a_i$$$.Vova wants to repost exactly $$$x$$$ pictures in such a way that: each segment of the news feed of at least $$$k$$$ consecutive pictures has at least one picture reposted by Vova; the sum of beauty values of reposted pictures is maximum possible. For example, if $$$k=1$$$ then Vova has to repost all the pictures in the news feed. If $$$k=2$$$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
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 * * @author Vadim */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); r521f solver = new r521f(); solver.solve(1, in, out); out.close(); } static class r521f { public void solve(int testNumber, FastScanner in, PrintWriter out) { int n = in.ni(); int k = in.ni(); int x = in.ni(); int[] a = in.na(n); long[][] sts = new long[x + 1][n * 4]; for (int i = 0; i < k; i++) { SegmentTree.updateMax(sts[0], i, a[i]); } for (int step = 1; step < x; step++) { for (int i = 0; i < n; i++) { long max = 0; if (i > 0) { max = SegmentTree.max(sts[step - 1], Math.max(0, i - k), i - 1); } if (max > 0) SegmentTree.updateMax(sts[step], i, max + a[i]); } } long ans = SegmentTree.max(sts[x - 1], Math.max(0, n - k), n - 1); if (ans == 0) out.println(-1); else out.println(ans); } } static class FastScanner { private BufferedReader in; private StringTokenizer st; public FastScanner(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); } public String ns() { while (st == null || !st.hasMoreTokens()) { try { String rl = in.readLine(); if (rl == null) { return null; } st = new StringTokenizer(rl); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int ni() { return Integer.parseInt(ns()); } public int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } } static class SegmentTree { public static long max(long t[], int l, int r) { return max(t, 1, 0, t.length / 4 - 1, l, r); } public static long max(long t[], int v, int tl, int tr, int l, int r) { if (l > r) return 0; if (l == tl && r == tr) return t[v]; int tm = (tl + tr) / 2; return Math.max(max(t, v * 2, tl, tm, l, Math.min(r, tm)), max(t, v * 2 + 1, tm + 1, tr, Math.max(l, tm + 1), r)); } public static void updateMax(long t[], int l, long new_val) { updateMax(t, 1, 0, t.length / 4 - 1, l, new_val); } public static void updateMax(long t[], int v, int tl, int tr, int pos, long new_val) { if (tl == tr) t[v] = new_val; else { int tm = (tl + tr) / 2; if (pos <= tm) updateMax(t, v * 2, tl, tm, pos, new_val); else updateMax(t, v * 2 + 1, tm + 1, tr, pos, new_val); t[v] = Math.max(t[v * 2], t[v * 2 + 1]); } } } }
Java
["5 2 3\n5 1 3 10 1", "6 1 5\n10 30 30 70 10 10", "4 3 1\n1 100 1 1"]
2 seconds
["18", "-1", "100"]
null
Java 8
standard input
[ "dp" ]
c1d48f546f79b0fd58539a1eb32917dd
The first line of the input contains three integers $$$n, k$$$ and $$$x$$$ ($$$1 \le k, x \le n \le 200$$$) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the beauty of the $$$i$$$-th picture.
1,900
Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement. Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.
standard output
PASSED
aebdad70fce020219d3986948b4b73c6
train_001.jsonl
1542378900
The only difference between easy and hard versions is the constraints.Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $$$n$$$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $$$i$$$-th picture has beauty $$$a_i$$$.Vova wants to repost exactly $$$x$$$ pictures in such a way that: each segment of the news feed of at least $$$k$$$ consecutive pictures has at least one picture reposted by Vova; the sum of beauty values of reposted pictures is maximum possible. For example, if $$$k=1$$$ then Vova has to repost all the pictures in the news feed. If $$$k=2$$$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
256 megabytes
import java.io.*; import java.util.*; public class Solution{ InputStream is; static PrintWriter out; String INPUT = ""; static long mod = (long)1e9+7L; long[][][] dp; long[] a; public void solve(){ int n = ni(), k = ni(), x = ni(); a = new long[n]; for(int i = 0; i < n; i++)a[i] = nl(); dp = new long[n][x+1][k]; for(int i = 0; i < n; i++)for(int j = 0; j <= x; j++)Arrays.fill(dp[i][j], -1); long res = f(n-1, x, 0, k); out.println(res < 0 ? "-1" : res); } long f(int n, int x, int p, int k){ if(n < 0 && x == 0)return 0; if(n < 0)return Long.MIN_VALUE; //System.out.println(n +" "+x+" "+p); if(dp[n][x][p] != -1)return dp[n][x][p]; if(x == 0 && (n+1) < k)return dp[n][x][p] = 0; if(x == 0)return dp[n][x][p] = Long.MIN_VALUE; if(p == (k-1)) return dp[n][x][p] = a[n] + f(n-1, x-1, 0, k); return dp[n][x][p] = Math.max(f(n-1, x-1, 0, k) + a[n], f(n-1, x, p+1, k)); } void run(){ is = new DataInputStream(System.in); out = new PrintWriter(System.out); int t=1;while(t-->0)solve(); out.flush(); } public static void main(String[] args)throws Exception{new Solution().run();} long mod(long v, long m){if(v<0){long q=(Math.abs(v)+m-1L)/m;v=v+q*m;}return v%m;} long mod(long v){if(v<0){long q=(Math.abs(v)+mod-1L)/mod;v=v+q*mod;}return v%mod;} //Fast I/O code is copied from uwi code. 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(); } } static int i(long x){return (int)Math.round(x);} static class Pair implements Comparable<Pair>{ long fs,sc; Pair(long a,long b){ fs=a;sc=b; } public int compareTo(Pair p){ if(this.fs>p.fs)return 1; else if(this.fs<p.fs)return -1; else{ return i(this.sc-p.sc); } //return i(this.sc-p.sc); } public String toString(){ return "("+fs+","+sc+")"; } } }
Java
["5 2 3\n5 1 3 10 1", "6 1 5\n10 30 30 70 10 10", "4 3 1\n1 100 1 1"]
2 seconds
["18", "-1", "100"]
null
Java 8
standard input
[ "dp" ]
c1d48f546f79b0fd58539a1eb32917dd
The first line of the input contains three integers $$$n, k$$$ and $$$x$$$ ($$$1 \le k, x \le n \le 200$$$) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the beauty of the $$$i$$$-th picture.
1,900
Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement. Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.
standard output
PASSED
2fc3492ea3f91cd1635ecb7e8ade0e0d
train_001.jsonl
1542378900
The only difference between easy and hard versions is the constraints.Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $$$n$$$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $$$i$$$-th picture has beauty $$$a_i$$$.Vova wants to repost exactly $$$x$$$ pictures in such a way that: each segment of the news feed of at least $$$k$$$ consecutive pictures has at least one picture reposted by Vova; the sum of beauty values of reposted pictures is maximum possible. For example, if $$$k=1$$$ then Vova has to repost all the pictures in the news feed. If $$$k=2$$$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
256 megabytes
import java.io.*; import java.util.*; public class Main implements Runnable { FastReader scn; PrintWriter out; String INPUT = ""; void solve() { int n = scn.nextInt(), k = scn.nextInt(), x = scn.nextInt(); int[] arr = scn.nextIntArray(n); dp = new long[n + 1][x + 1][k + 1]; long rv = func(arr, 0, x, k, 1); out.println(rv); } long[][][] dp; long func(int[] arr, int pos, int x, int k, int prev) { if (pos == arr.length) { if (x != 0 || prev > k) { return (Long.MIN_VALUE / (2 * arr.length)); } return 0; } if (arr.length - pos < x || prev > k) { return (Long.MIN_VALUE / (2 * arr.length)); } if (dp[pos][x][prev] != 0) { return dp[pos][x][prev]; } long rv = 0; if (prev == k && x > 0) { rv = func(arr, pos + 1, x - 1, k, 1); if (rv == -1) { return dp[pos][x][prev] = rv; } rv += arr[pos]; } else { long a = func(arr, pos + 1, x, k, prev + 1), b = -1; if (x > 0) { b = func(arr, pos + 1, x - 1, k, 1); } if (a <= -1 && b <= -1) { return dp[pos][x][prev] = -1; } if (a == -1) { rv = b + arr[pos]; } else if (b == -1) { rv = a; } else { rv = Math.max(a, b + arr[pos]); } } return dp[pos][x][prev] = rv; } public void run() { 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) { new Thread(null, new Main(), "Main", 1 << 26).start(); } 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; } int[] uniq(int[] arr) { Arrays.sort(arr); int[] rv = new int[arr.length]; int pos = 0; rv[pos++] = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] != arr[i - 1]) { rv[pos++] = arr[i]; } } return Arrays.copyOf(rv, pos); } } }
Java
["5 2 3\n5 1 3 10 1", "6 1 5\n10 30 30 70 10 10", "4 3 1\n1 100 1 1"]
2 seconds
["18", "-1", "100"]
null
Java 8
standard input
[ "dp" ]
c1d48f546f79b0fd58539a1eb32917dd
The first line of the input contains three integers $$$n, k$$$ and $$$x$$$ ($$$1 \le k, x \le n \le 200$$$) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the beauty of the $$$i$$$-th picture.
1,900
Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement. Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.
standard output
PASSED
0edd072a9f819c42989ac11789e2bda8
train_001.jsonl
1542378900
The only difference between easy and hard versions is the constraints.Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $$$n$$$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $$$i$$$-th picture has beauty $$$a_i$$$.Vova wants to repost exactly $$$x$$$ pictures in such a way that: each segment of the news feed of at least $$$k$$$ consecutive pictures has at least one picture reposted by Vova; the sum of beauty values of reposted pictures is maximum possible. For example, if $$$k=1$$$ then Vova has to repost all the pictures in the news feed. If $$$k=2$$$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
256 megabytes
import java.io.*; import java.util.*; public class Main implements Runnable { FastReader scn; PrintWriter out; String INPUT = ""; void solve() { int n = scn.nextInt(), k = scn.nextInt(), x = scn.nextInt(); int[] arr = new int[n + 1]; for(int i = 1; i <= n; i++) { arr[i] = scn.nextInt(); } long[][] dp = new long[n + 1][x + 1]; for (int i = 0; i <= n; i++) { for (int j = 0; j <= x; j++) { dp[i][j] = -1; } } dp[0][0] = 0; for (int i = 1; i <= n; i++) { for (int j = 1; j <= x; j++) { for(int pos = 1; pos <= k; pos++) { if(i - pos < 0) { break; } if(dp[i - pos][j - 1] == -1) { continue; } dp[i][j] = Math.max(dp[i][j], dp[i - pos][j - 1] + arr[i]); } } } long ans = -1; for(int i = n - k + 1; i <= n; i++) { ans = Math.max(ans, dp[i][x]); } out.println(ans); } public void run() { 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) { new Thread(null, new Main(), "Main", 1 << 26).start(); } 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; } int[] uniq(int[] arr) { Arrays.sort(arr); int[] rv = new int[arr.length]; int pos = 0; rv[pos++] = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] != arr[i - 1]) { rv[pos++] = arr[i]; } } return Arrays.copyOf(rv, pos); } } }
Java
["5 2 3\n5 1 3 10 1", "6 1 5\n10 30 30 70 10 10", "4 3 1\n1 100 1 1"]
2 seconds
["18", "-1", "100"]
null
Java 8
standard input
[ "dp" ]
c1d48f546f79b0fd58539a1eb32917dd
The first line of the input contains three integers $$$n, k$$$ and $$$x$$$ ($$$1 \le k, x \le n \le 200$$$) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the beauty of the $$$i$$$-th picture.
1,900
Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement. Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.
standard output
PASSED
e781b120aa30295509090c9add96bda1
train_001.jsonl
1542378900
The only difference between easy and hard versions is the constraints.Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $$$n$$$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $$$i$$$-th picture has beauty $$$a_i$$$.Vova wants to repost exactly $$$x$$$ pictures in such a way that: each segment of the news feed of at least $$$k$$$ consecutive pictures has at least one picture reposted by Vova; the sum of beauty values of reposted pictures is maximum possible. For example, if $$$k=1$$$ then Vova has to repost all the pictures in the news feed. If $$$k=2$$$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class main { public static void main(String[] args) { // TODO Auto-generated method stub Scanner in = new Scanner(System.in); int pics = in.nextInt(); int skips = in.nextInt(); int posts = in.nextInt(); int[] arr = new int[pics]; for(int i = 0;i<pics;i++) arr[i] = in.nextInt(); long dp[][] = new long[pics+1][posts+1]; for(int i = 0;i<dp.length;i++) { Arrays.fill(dp[i], Long.MIN_VALUE); } dp[0][posts]=0; long max = 0; for(int i =1;i<=pics;++i) { for(int j = 0;j<posts;++j) { for(int k = 1;k<=skips;++k) { if(i-k<0)break; if(dp[i-k][j+1]==Long.MIN_VALUE) continue; dp[i][j] = Math.max(dp[i][j], dp[i-k][j+1]+arr[i-1]); } } } boolean flag = false; for(int i = pics-skips+1;i<=pics;i++) { if(dp[i][0]!=Long.MIN_VALUE) flag = true; max = Math.max(max, dp[i][0]); } if(flag) System.out.println(max); else System.out.println(-1); } }
Java
["5 2 3\n5 1 3 10 1", "6 1 5\n10 30 30 70 10 10", "4 3 1\n1 100 1 1"]
2 seconds
["18", "-1", "100"]
null
Java 8
standard input
[ "dp" ]
c1d48f546f79b0fd58539a1eb32917dd
The first line of the input contains three integers $$$n, k$$$ and $$$x$$$ ($$$1 \le k, x \le n \le 200$$$) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the beauty of the $$$i$$$-th picture.
1,900
Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement. Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.
standard output
PASSED
1878e96121fb141bc9ede73ad061672d
train_001.jsonl
1542378900
The only difference between easy and hard versions is the constraints.Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $$$n$$$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $$$i$$$-th picture has beauty $$$a_i$$$.Vova wants to repost exactly $$$x$$$ pictures in such a way that: each segment of the news feed of at least $$$k$$$ consecutive pictures has at least one picture reposted by Vova; the sum of beauty values of reposted pictures is maximum possible. For example, if $$$k=1$$$ then Vova has to repost all the pictures in the news feed. If $$$k=2$$$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
256 megabytes
import java.io.*; import java.util.*; public class A{ static long INF=(long)1e18; static long [][][]memo; static int n,k,a[]; static long dp(int idx,int dis,int left) { if(dis==k || left<0) return -INF; if(idx==n) return left==0?0:-INF; if(memo[idx][dis][left]!=-1) return memo[idx][dis][left]; long ans=dp(idx+1,dis+1,left); ans=Math.max(ans, dp(idx+1,0,left-1)+a[idx]); return memo[idx][dis][left]=ans; } public static void main(String[] args) throws IOException { Scanner sc=new Scanner(); PrintWriter out=new PrintWriter(System.out); n=sc.nextInt(); k=sc.nextInt(); int x=sc.nextInt(); a=new int [n]; memo=new long [n][k][x+1]; for(int i=0;i<n;i++) { a[i]=sc.nextInt(); for(int j=0;j<k;j++) Arrays.fill(memo[i][j], -1); } long ans=dp(0,0,x); out.println(ans>0?ans:-1); out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner(){ br=new BufferedReader(new InputStreamReader(System.in)); } Scanner(String fileName) throws FileNotFoundException{ br=new BufferedReader(new FileReader(fileName)); } String next() throws IOException { while(st==null || !st.hasMoreTokens()) st=new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { return br.readLine(); } int nextInt() throws IOException{ return Integer.parseInt(next()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } } }
Java
["5 2 3\n5 1 3 10 1", "6 1 5\n10 30 30 70 10 10", "4 3 1\n1 100 1 1"]
2 seconds
["18", "-1", "100"]
null
Java 8
standard input
[ "dp" ]
c1d48f546f79b0fd58539a1eb32917dd
The first line of the input contains three integers $$$n, k$$$ and $$$x$$$ ($$$1 \le k, x \le n \le 200$$$) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the beauty of the $$$i$$$-th picture.
1,900
Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement. Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.
standard output
PASSED
ed9c5363d01e7b075a6d691f820782b1
train_001.jsonl
1542378900
The only difference between easy and hard versions is the constraints.Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $$$n$$$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $$$i$$$-th picture has beauty $$$a_i$$$.Vova wants to repost exactly $$$x$$$ pictures in such a way that: each segment of the news feed of at least $$$k$$$ consecutive pictures has at least one picture reposted by Vova; the sum of beauty values of reposted pictures is maximum possible. For example, if $$$k=1$$$ then Vova has to repost all the pictures in the news feed. If $$$k=2$$$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
256 megabytes
import java.io.*; import java.util.*; public class l { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////// ///////// //////// ///////// //////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOOOOO SSSSSSS EEEEEEEEEEEEE ///////// //////// HHHH HHHH EEEEEEEEEEEEE MMMMMM MMMMMM OOO OOO SSSS SSS EEEEEEEEEEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMM MMM MMMM OOO OOO SSSS SSS EEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMMMMM MMMM OOO OOO SSSS EEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSSSSSS EEEEE ///////// //////// HHHHHHHHHHHHHHHH EEEEEEEEEEE MMMM MMMM OOO OOO SSSSSS EEEEEEEEEEE ///////// //////// HHHHHHHHHHHHHHHH EEEEEEEEEEE MMMM MMMM OOO OOO SSSSSSS EEEEEEEEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSSS EEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSS SSSS EEEEE ///////// //////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOO OOO SSS SSSS EEEEEEEEEEEEE ///////// //////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOOOOO SSSSSSS EEEEEEEEEEEEE ///////// //////// ///////// //////// ///////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static int mod = (int) (1e9 + 7); static int n; static StringBuilder sol; static class pair implements Comparable<pair> { int val, cost; public pair(int x, int y) { val = x; cost = y; } public int compareTo(pair o) { if (o.val==val)return cost-o.cost; return val-o.val; } public String toString() { return val + " " + cost; } } static class tri implements Comparable<tri> { int lef, righ, idx; tri(int a, int b, int c) { lef = a; righ = b; idx = c; } public int compareTo(tri o) { if (lef == o.lef) return righ - o.righ; return lef - o.lef; } public String toString() { return lef + " " + righ + " " + idx; } } static char[][]g; static long[][]memo; static long inf= (long) 1e16; static ArrayList<Character>arr; static long dp(int idx,int rem){ if (idx>=a.length){ if (rem==0)return 0; return -inf; } if (rem<=0)return -inf; if (memo[idx][rem]!=-1)return memo[idx][rem]; long ans = -inf; for (int i=idx;i-idx<k;i++){ ans=Math.max(ans,a[idx]+dp(i+1,rem-1)); } return memo[idx][rem]=ans; } static int[]a; static int k; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); //FileWriter f = new FileWriter("C:\\Users\\Ibrahim\\out.txt"); PrintWriter pw = new PrintWriter(System.out); int n= sc.nextInt(); k= sc.nextInt(); int x = sc.nextInt(); a= new int[n]; for (int i =0;i<n;i++){ a[i]=sc.nextInt(); } memo= new long[n+1][x+1]; for (long[]z:memo)Arrays.fill(z,-1); long ans =-inf; for (int i =0;i<k&&i<n;i++){ ans=Math.max(ans,dp(i,x)); } pw.println(ans<0?-1:ans); pw.flush(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(FileReader r) { br = new BufferedReader(r); } public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public 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 boolean ready() throws IOException { return br.ready(); } } }
Java
["5 2 3\n5 1 3 10 1", "6 1 5\n10 30 30 70 10 10", "4 3 1\n1 100 1 1"]
2 seconds
["18", "-1", "100"]
null
Java 8
standard input
[ "dp" ]
c1d48f546f79b0fd58539a1eb32917dd
The first line of the input contains three integers $$$n, k$$$ and $$$x$$$ ($$$1 \le k, x \le n \le 200$$$) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the beauty of the $$$i$$$-th picture.
1,900
Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement. Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.
standard output
PASSED
da8879db96116cd8d0c9cafa7f37983f
train_001.jsonl
1542378900
The only difference between easy and hard versions is the constraints.Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $$$n$$$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $$$i$$$-th picture has beauty $$$a_i$$$.Vova wants to repost exactly $$$x$$$ pictures in such a way that: each segment of the news feed of at least $$$k$$$ consecutive pictures has at least one picture reposted by Vova; the sum of beauty values of reposted pictures is maximum possible. For example, if $$$k=1$$$ then Vova has to repost all the pictures in the news feed. If $$$k=2$$$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
256 megabytes
import java.util.*; import java.io.*; import java.util.Map.Entry; public class Codeforces { static int[] pic; static int n, x, k; static long INF = (long)-1e16; static long[][][] memo; public static long dp(int idx, int p, int left){ if(p > x){ return INF; } if(idx == n){ return 0; } if(memo[idx][p][left] != -1){ return memo[idx][p][left]; } long take, leave; if(left == k - 1){ take = pic[idx] + dp(idx + 1, p + 1, 0); leave = INF; }else { take = pic[idx] + dp(idx + 1, p + 1, 0); leave = dp(idx + 1, p, left + 1); } return memo[idx][p][left] = Math.max(take, leave); } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); n = Integer.parseInt(st.nextToken()); k = Integer.parseInt(st.nextToken()); x = Integer.parseInt(st.nextToken()); pic = new int[n]; st = new StringTokenizer(br.readLine()); for(int i = 0; i < n; i++){ pic[i] = Integer.parseInt(st.nextToken()); } memo = new long[201][201][201]; for(int i = 0; i < memo.length; i++){ for(int j = 0; j < memo[i].length; j++){ Arrays.fill(memo[i][j], -1); } } long res = dp(0,0,0); System.out.println(res < 0 ? - 1 : res); } }
Java
["5 2 3\n5 1 3 10 1", "6 1 5\n10 30 30 70 10 10", "4 3 1\n1 100 1 1"]
2 seconds
["18", "-1", "100"]
null
Java 8
standard input
[ "dp" ]
c1d48f546f79b0fd58539a1eb32917dd
The first line of the input contains three integers $$$n, k$$$ and $$$x$$$ ($$$1 \le k, x \le n \le 200$$$) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the beauty of the $$$i$$$-th picture.
1,900
Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement. Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.
standard output
PASSED
a716cc13f2df113e9628864c3ee701a6
train_001.jsonl
1542378900
The only difference between easy and hard versions is the constraints.Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $$$n$$$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $$$i$$$-th picture has beauty $$$a_i$$$.Vova wants to repost exactly $$$x$$$ pictures in such a way that: each segment of the news feed of at least $$$k$$$ consecutive pictures has at least one picture reposted by Vova; the sum of beauty values of reposted pictures is maximum possible. For example, if $$$k=1$$$ then Vova has to repost all the pictures in the news feed. If $$$k=2$$$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
256 megabytes
/* USER: caoash3 LANG: JAVA TASK: */ import java.io.*; import java.util.*; public class kittens { static final boolean stdin = true; static final String filename = ""; static FastScanner br; static PrintWriter pw; public static void main(String[] args) throws IOException { if (stdin) { br = new FastScanner(); pw = new PrintWriter(new OutputStreamWriter(System.out)); } else { br = new FastScanner(filename + ".in"); pw = new PrintWriter(new FileWriter(filename + ".out")); } X solver = new X(); solver.solve(br, pw); } static class X { static long oo = Long.MAX_VALUE; public void solve(FastScanner br, PrintWriter pw) throws IOException { int N = br.nextInt(); int K = br.nextInt(); int X = br.nextInt(); long[] a = new long[N]; for(int i = 0; i < N; i++) { a[i] = br.nextInt(); } long[][] dp = new long[N+1][X+1]; for(int i = 1; i <= N; i++) { Arrays.fill(dp[i], -1 * Long.MAX_VALUE); } for(int i = 1; i <= N; i++) { for(int j = 1; j <= X; j++) { long max = -1 * Long.MAX_VALUE; for(int k = 1; k <= K; k++) { if(i - k < 0) { continue; } if(dp[i-k][j-1] == -1) { max = Math.max(max,-1 * Long.MAX_VALUE); } else { max = Math.max(max, dp[i-k][j-1]+a[i-1]); } } dp[i][j] = max; } } long ans = -1 * Long.MAX_VALUE; for(int i = N-K+1; i <= N; i++) { ans = Math.max(dp[i][X], ans); } pw.println(ans < 0 ? -1 : ans); pw.close(); } } //fastscanner class public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["5 2 3\n5 1 3 10 1", "6 1 5\n10 30 30 70 10 10", "4 3 1\n1 100 1 1"]
2 seconds
["18", "-1", "100"]
null
Java 8
standard input
[ "dp" ]
c1d48f546f79b0fd58539a1eb32917dd
The first line of the input contains three integers $$$n, k$$$ and $$$x$$$ ($$$1 \le k, x \le n \le 200$$$) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the beauty of the $$$i$$$-th picture.
1,900
Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement. Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.
standard output
PASSED
0ccaa6de45d234df158dcf5c4e743c90
train_001.jsonl
1542378900
The only difference between easy and hard versions is the constraints.Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $$$n$$$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $$$i$$$-th picture has beauty $$$a_i$$$.Vova wants to repost exactly $$$x$$$ pictures in such a way that: each segment of the news feed of at least $$$k$$$ consecutive pictures has at least one picture reposted by Vova; the sum of beauty values of reposted pictures is maximum possible. For example, if $$$k=1$$$ then Vova has to repost all the pictures in the news feed. If $$$k=2$$$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
256 megabytes
/* USER: caoash3 LANG: JAVA TASK: */ import java.io.*; import java.util.*; public class kittens { static final boolean stdin = true; static final String filename = ""; static FastScanner br; static PrintWriter pw; public static void main(String[] args) throws IOException { if (stdin) { br = new FastScanner(); pw = new PrintWriter(new OutputStreamWriter(System.out)); } else { br = new FastScanner(filename + ".in"); pw = new PrintWriter(new FileWriter(filename + ".out")); } X solver = new X(); solver.solve(br, pw); } static class X { static long oo = Long.MAX_VALUE; public void solve(FastScanner br, PrintWriter pw) throws IOException { int N = br.nextInt(); int K = br.nextInt(); int X = br.nextInt(); long[] a = new long[N]; for(int i = 0; i < N; i++) { a[i] = br.nextInt(); } long[][] dp = new long[N+1][X+1]; for(int i = 1; i <= N; i++) { Arrays.fill(dp[i], -1 * Long.MAX_VALUE); } for(int i = 1; i <= N; i++) { for(int j = 1; j <= X; j++) { long max = -1 * Long.MAX_VALUE; for(int k = 1; k <= K; k++) { if(i - k < 0) { continue; } if(dp[i-k][j-1] == -1) { max = Math.max(max,-1 * Long.MAX_VALUE); } else { max = Math.max(max, dp[i-k][j-1]+a[i-1]); } } dp[i][j] = max; } } // for(int i = 0; i <= N; i++) { // for(int j = 0; j <= X; j++) { // if(dp[i][j] < 0) { // pw.print(-1 + " "); // } // else { // pw.print(dp[i][j] + " "); // } // } // pw.println(); // } long ans = -1 * Long.MAX_VALUE; for(int i = N-K+1; i <= N; i++) { ans = Math.max(dp[i][X], ans); } pw.println(ans < 0 ? -1 : ans); pw.close(); } } //fastscanner class public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["5 2 3\n5 1 3 10 1", "6 1 5\n10 30 30 70 10 10", "4 3 1\n1 100 1 1"]
2 seconds
["18", "-1", "100"]
null
Java 8
standard input
[ "dp" ]
c1d48f546f79b0fd58539a1eb32917dd
The first line of the input contains three integers $$$n, k$$$ and $$$x$$$ ($$$1 \le k, x \le n \le 200$$$) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the beauty of the $$$i$$$-th picture.
1,900
Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement. Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.
standard output
PASSED
4eb0fddfd39b103770d9e61e3758f61b
train_001.jsonl
1542378900
The only difference between easy and hard versions is the constraints.Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $$$n$$$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $$$i$$$-th picture has beauty $$$a_i$$$.Vova wants to repost exactly $$$x$$$ pictures in such a way that: each segment of the news feed of at least $$$k$$$ consecutive pictures has at least one picture reposted by Vova; the sum of beauty values of reposted pictures is maximum possible. For example, if $$$k=1$$$ then Vova has to repost all the pictures in the news feed. If $$$k=2$$$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
256 megabytes
import java.util.*; import java.io.*; import static java.lang.Math.*; public class Main { 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", 10000000); t.start(); } static class O implements Runnable { public void run() { try { magic(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } } static class FastReader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public FastReader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public FastReader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; 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(); } } //variables here static int n,k,x; static long arr[], dp[][]; static void magic() throws IOException { reader = new FastReader(); writer = new PrintWriter(System.out, true); n = reader.nextInt(); k = reader.nextInt(); x = reader.nextInt(); arr = new long[n]; dp = new long[n][x+1]; for(int i=0;i<n;++i) { arr[i] = reader.nextInt(); } for(int i=n-1;i>=0;--i) { if(n-i-1<k) { dp[i][1] = arr[i]; } else { dp[i][1] = Long.MIN_VALUE; } } for(int bomb=2;bomb<=x;++bomb) { for(int j=n-1;j>=0;--j) { long max = Long.MIN_VALUE; for(int next=j+1;next-j-1<k && next<n;++next) { max = max(max, dp[next][bomb-1]); } if(max!=Long.MIN_VALUE) { dp[j][bomb] = arr[j] + max; } else { dp[j][bomb] = max; } } } long ans = Long.MIN_VALUE; for(int i=0;i<=k-1;++i) { ans = max(ans, dp[i][x]); } if(ans==Long.MIN_VALUE) { ans = -1; } writer.println(ans); } }
Java
["5 2 3\n5 1 3 10 1", "6 1 5\n10 30 30 70 10 10", "4 3 1\n1 100 1 1"]
2 seconds
["18", "-1", "100"]
null
Java 8
standard input
[ "dp" ]
c1d48f546f79b0fd58539a1eb32917dd
The first line of the input contains three integers $$$n, k$$$ and $$$x$$$ ($$$1 \le k, x \le n \le 200$$$) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the beauty of the $$$i$$$-th picture.
1,900
Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement. Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.
standard output
PASSED
edc8a857cc4a9287817f7d208fcfc0a8
train_001.jsonl
1542378900
The only difference between easy and hard versions is the constraints.Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $$$n$$$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $$$i$$$-th picture has beauty $$$a_i$$$.Vova wants to repost exactly $$$x$$$ pictures in such a way that: each segment of the news feed of at least $$$k$$$ consecutive pictures has at least one picture reposted by Vova; the sum of beauty values of reposted pictures is maximum possible. For example, if $$$k=1$$$ then Vova has to repost all the pictures in the news feed. If $$$k=2$$$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
256 megabytes
import java.io.*; import java.util.*; public class Pictures { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] line = br.readLine().split(" "); int n = Integer.parseInt(line[0]); int k = Integer.parseInt(line[1]); int x = Integer.parseInt(line[2]); line = br.readLine().split(" "); long[] a = new long[n]; for(int i = 0; i < n; i++) { a[i] = Long.parseLong(line[i]); } long[][] dp = new long[n+1][x+1]; for(int i = 0; i <= n; i++) { for(int j = 0; j <= x; j++) { dp[i][j] = -Long.MAX_VALUE; } } dp[0][x] = 0; for(int i = 1; i <=n; i++) { for(int j = 0; j < x; j++) { for(int p = 1; p <= k; p++) { if(i - p < 0) break; if( dp[i-p][j+1] == -Long.MAX_VALUE ) continue; dp[i][j] = Math.max(dp[i][j], dp[i-p][j+1] + a[i-1]); } } } //print(dp); long res = -Long.MAX_VALUE; for (int i = n - k + 1; i <= n; i++) { res = Math.max(res, maxElement(dp[i])); } if (res == -Long.MAX_VALUE) res = -1; System.out.println(res); } private static long maxElement(long[] array) { long res = array[0]; for(int i = 1; i < array.length; i++) { res = Math.max(res, array[i]); } return res; } private static void print(long[][] array) { for(int i = 0; i < array.length; i++) { System.out.println(Arrays.toString(array[i])); } } }
Java
["5 2 3\n5 1 3 10 1", "6 1 5\n10 30 30 70 10 10", "4 3 1\n1 100 1 1"]
2 seconds
["18", "-1", "100"]
null
Java 8
standard input
[ "dp" ]
c1d48f546f79b0fd58539a1eb32917dd
The first line of the input contains three integers $$$n, k$$$ and $$$x$$$ ($$$1 \le k, x \le n \le 200$$$) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the beauty of the $$$i$$$-th picture.
1,900
Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement. Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.
standard output
PASSED
a15a1ee3f72c28125d3dbb9eeb5374c7
train_001.jsonl
1542378900
The only difference between easy and hard versions is the constraints.Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $$$n$$$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $$$i$$$-th picture has beauty $$$a_i$$$.Vova wants to repost exactly $$$x$$$ pictures in such a way that: each segment of the news feed of at least $$$k$$$ consecutive pictures has at least one picture reposted by Vova; the sum of beauty values of reposted pictures is maximum possible. For example, if $$$k=1$$$ then Vova has to repost all the pictures in the news feed. If $$$k=2$$$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class Main { static class RMQ { long[] data = new long[16384]; public RMQ() { } public void init(long[] init) { Arrays.fill(data, -1); _init(init, 0, 0, 5002); } private void _init(long[] init, int v, int vLeft, int vRight) { if (vRight - vLeft == 1) { data[v] = init[vLeft]; } else { int mid = (vLeft + vRight) >> 1; int leftChild = (v << 1) + 1; int rightChild = leftChild + 1; _init(init, leftChild, vLeft, mid); _init(init, rightChild, mid, vRight); data[v] = Math.max(data[leftChild], data[rightChild]); } } private long _query(int left, int right, int v, int vLeft, int vRight) { if (vLeft >= left && vRight <= right) { return data[v]; } int mid = (vLeft + vRight) >> 1; int leftChild = (v << 1) + 1; int rightChild = leftChild + 1; long max = Long.MIN_VALUE; if (mid > left) { max = Math.max(max, _query(left, right, leftChild, vLeft, mid)); } if (mid < right) { max = Math.max(max, _query(left, right, rightChild, mid, vRight)); } return max; } public long query(int left, int right) { return _query(left, right, 0, 0, 5002); } } static class SlidingMax { private int size; public SlidingMax(int size) { this.size = size; } } public static void main(String[] args) { long start = System.currentTimeMillis(); Scanner s = new Scanner(System.in); int n = s.nextInt(), k = s.nextInt(), x = s.nextInt(); int[] a = new int[n + 1]; for (int i = 0; i < n; i++) { a[i + 1] = s.nextInt(); } long[] current = new long[5005]; long[] next = new long[5005]; Arrays.fill(next, -1); next[0] = 0; RMQ rmq = new RMQ(); for (int turn = 0; turn < x; turn++) { long[] nextNext = current; current = next; next = nextNext; Arrays.fill(next, -1); rmq.init(current); for (int i = 1; i <= n; i++) { long rangeMax = rmq.query(Math.max(0, i - k), i); if (rangeMax != -1) { next[i] = rangeMax + a[i]; } } } rmq.init(next); System.out.println(rmq.query(n - k + 1, n + 1)); // System.out.println(System.currentTimeMillis() - start); } }
Java
["5 2 3\n5 1 3 10 1", "6 1 5\n10 30 30 70 10 10", "4 3 1\n1 100 1 1"]
2 seconds
["18", "-1", "100"]
null
Java 8
standard input
[ "dp" ]
c1d48f546f79b0fd58539a1eb32917dd
The first line of the input contains three integers $$$n, k$$$ and $$$x$$$ ($$$1 \le k, x \le n \le 200$$$) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the beauty of the $$$i$$$-th picture.
1,900
Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement. Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.
standard output
PASSED
7b0bce0a000a463fdbc378ba0cf82d5a
train_001.jsonl
1542378900
The only difference between easy and hard versions is the constraints.Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $$$n$$$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $$$i$$$-th picture has beauty $$$a_i$$$.Vova wants to repost exactly $$$x$$$ pictures in such a way that: each segment of the news feed of at least $$$k$$$ consecutive pictures has at least one picture reposted by Vova; the sum of beauty values of reposted pictures is maximum possible. For example, if $$$k=1$$$ then Vova has to repost all the pictures in the news feed. If $$$k=2$$$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Main { static BufferedReader reader; static StringTokenizer tokenizer; static PrintWriter writer; static String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(nextToken()); } static long nextLong() throws IOException { return Long.parseLong(nextToken()); } static void banana() throws IOException { int n = nextInt(); int k = nextInt(); int x = nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } long[][][] dp = new long[n + 1][x + 1][k]; for (int i = 0; i <= n; i++) { for (int j = 0; j <= x; j++) { for (int h = 0; h < k; h++) { dp[i][j][h] = -1; } } } dp[0][0][0] = 0; for (int i = 0; i < n; i++) { for (int ch = x; ch >= 0; ch--) { for (int sk = k - 1; sk >= 0; sk--) { if (sk > 0 && dp[i][ch][sk - 1] != -1) { dp[i + 1][ch][sk] = Math.max(dp[i + 1][ch][sk], dp[i][ch][sk - 1]); } } for (int sk = k - 1; sk >= 0; sk--) { if (ch > 0 && dp[i][ch - 1][sk] != -1) { dp[i + 1][ch][0] = Math.max(dp[i + 1][ch][0], dp[i][ch - 1][sk]+a[i]); } } } // writer.println(i); // for (int j = 0; j <= x; j++) { // for (int h = 0; h < k; h++) { // writer.print(" " + dp[j][h]); // } // } // writer.println(); } long ans = -1; for (int sk = 0; sk < k; sk++) { ans = Math.max(ans, dp[n][x][sk]); } writer.println(ans); } public static void main(String[] args) throws IOException { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; writer = new PrintWriter(System.out); banana(); reader.close(); writer.close(); } static class Pair { int x; int y; public Pair(int x, int y) { this.x = x; this.y = y; } } }
Java
["5 2 3\n5 1 3 10 1", "6 1 5\n10 30 30 70 10 10", "4 3 1\n1 100 1 1"]
2 seconds
["18", "-1", "100"]
null
Java 8
standard input
[ "dp" ]
c1d48f546f79b0fd58539a1eb32917dd
The first line of the input contains three integers $$$n, k$$$ and $$$x$$$ ($$$1 \le k, x \le n \le 200$$$) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the beauty of the $$$i$$$-th picture.
1,900
Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement. Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.
standard output
PASSED
70637c5f3ec821efab871861a591ee00
train_001.jsonl
1542378900
The only difference between easy and hard versions is the constraints.Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $$$n$$$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $$$i$$$-th picture has beauty $$$a_i$$$.Vova wants to repost exactly $$$x$$$ pictures in such a way that: each segment of the news feed of at least $$$k$$$ consecutive pictures has at least one picture reposted by Vova; the sum of beauty values of reposted pictures is maximum possible. For example, if $$$k=1$$$ then Vova has to repost all the pictures in the news feed. If $$$k=2$$$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Main { static BufferedReader reader; static StringTokenizer tokenizer; static PrintWriter writer; static String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(nextToken()); } static long nextLong() throws IOException { return Long.parseLong(nextToken()); } static void banana() throws IOException { int n = nextInt(); int k = nextInt(); int x = nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } long[][] dp = new long[n + 1][x + 1]; for (int i = 0; i <= n; i++) { for (int j = 0; j <= x; j++) { dp[i][j] = -1; } } for (int q = 0; q < k; q++) { dp[q][0] = 0; } for (int i = 0; i < n; i++) { for (int ch = 0; ch < x; ch++) { if (dp[i][ch] != -1) { long cand = dp[i][ch] + a[i]; for (int add = k; add >= 1; add--) { if (i + add <= n) { long have = dp[i + add][ch + 1]; if (cand > have) { dp[i + add][ch + 1] = cand; } else { break; } } } } } } writer.println(dp[n][x]); } public static void main(String[] args) throws IOException { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; writer = new PrintWriter(System.out); banana(); reader.close(); writer.close(); } static class Pair { int x; int y; public Pair(int x, int y) { this.x = x; this.y = y; } } }
Java
["5 2 3\n5 1 3 10 1", "6 1 5\n10 30 30 70 10 10", "4 3 1\n1 100 1 1"]
2 seconds
["18", "-1", "100"]
null
Java 8
standard input
[ "dp" ]
c1d48f546f79b0fd58539a1eb32917dd
The first line of the input contains three integers $$$n, k$$$ and $$$x$$$ ($$$1 \le k, x \le n \le 200$$$) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the beauty of the $$$i$$$-th picture.
1,900
Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement. Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.
standard output
PASSED
81be56d90aa0747e5677e94e1300fd90
train_001.jsonl
1542378900
The only difference between easy and hard versions is the constraints.Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $$$n$$$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $$$i$$$-th picture has beauty $$$a_i$$$.Vova wants to repost exactly $$$x$$$ pictures in such a way that: each segment of the news feed of at least $$$k$$$ consecutive pictures has at least one picture reposted by Vova; the sum of beauty values of reposted pictures is maximum possible. For example, if $$$k=1$$$ then Vova has to repost all the pictures in the news feed. If $$$k=2$$$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Main { static BufferedReader reader; static StringTokenizer tokenizer; static PrintWriter writer; static String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(nextToken()); } static long nextLong() throws IOException { return Long.parseLong(nextToken()); } static void banana() throws IOException { int n = nextInt(); int k = nextInt(); int x = nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } long[][] dp = new long[n + 1][x + 1]; for (int i = 0; i <= n; i++) { for (int j = 0; j <= x; j++) { dp[i][j] = -1; } } for (int q = 0; q < k; q++) { dp[q][0] = 0; } for (int i = 0; i < n; i++) { for (int ch = 0; ch < x; ch++) { if (dp[i][ch] != -1) { for (int add = 1; add <= k; add++) { if (i + add <= n) { dp[i + add][ch + 1] = Math.max(dp[i + add][ch + 1], dp[i][ch] + a[i]); } } } } } writer.println(dp[n][x]); } public static void main(String[] args) throws IOException { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; writer = new PrintWriter(System.out); banana(); reader.close(); writer.close(); } static class Pair { int x; int y; public Pair(int x, int y) { this.x = x; this.y = y; } } }
Java
["5 2 3\n5 1 3 10 1", "6 1 5\n10 30 30 70 10 10", "4 3 1\n1 100 1 1"]
2 seconds
["18", "-1", "100"]
null
Java 8
standard input
[ "dp" ]
c1d48f546f79b0fd58539a1eb32917dd
The first line of the input contains three integers $$$n, k$$$ and $$$x$$$ ($$$1 \le k, x \le n \le 200$$$) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the beauty of the $$$i$$$-th picture.
1,900
Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement. Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.
standard output
PASSED
1795b7207c900ca657b217a0565ee624
train_001.jsonl
1542378900
The only difference between easy and hard versions is the constraints.Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $$$n$$$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $$$i$$$-th picture has beauty $$$a_i$$$.Vova wants to repost exactly $$$x$$$ pictures in such a way that: each segment of the news feed of at least $$$k$$$ consecutive pictures has at least one picture reposted by Vova; the sum of beauty values of reposted pictures is maximum possible. For example, if $$$k=1$$$ then Vova has to repost all the pictures in the news feed. If $$$k=2$$$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Main { static BufferedReader reader; static StringTokenizer tokenizer; static PrintWriter writer; static String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(nextToken()); } static long nextLong() throws IOException { return Long.parseLong(nextToken()); } static void banana() throws IOException { int n = nextInt(); int k = nextInt(); int x = nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } long[][][] dp = new long[2][x + 1][k]; for (int i = 0; i < 2; i++) { for (int j = 0; j <= x; j++) { for (int h = 0; h < k; h++) { dp[i][j][h] = -1; } } } dp[1][0][0] = 0; for (int i = 0; i < n; i++) { int q = i % 2; int q1 = q ^ 1; for (int j = 0; j <= x; j++) { for (int h = 0; h < k; h++) { dp[q][j][h] = -1; } } for (int ch = x; ch >= 0; ch--) { for (int sk = k - 1; sk >= 0; sk--) { if (sk > 0 && dp[q1][ch][sk - 1] != -1) { dp[q][ch][sk] = Math.max(dp[q][ch][sk], dp[q1][ch][sk - 1]); } } for (int sk = k - 1; sk >= 0; sk--) { if (ch > 0 && dp[q1][ch - 1][sk] != -1) { dp[q][ch][0] = Math.max(dp[q][ch][0], dp[q1][ch - 1][sk] + a[i]); } } } // writer.println(i); // for (int j = 0; j <= x; j++) { // for (int h = 0; h < k; h++) { // writer.print(" " + dp[j][h]); // } // } // writer.println(); } long ans = -1; for (int sk = 0; sk < k; sk++) { ans = Math.max(ans, dp[1 - n % 2][x][sk]); } writer.println(ans); } public static void main(String[] args) throws IOException { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; writer = new PrintWriter(System.out); banana(); reader.close(); writer.close(); } static class Pair { int x; int y; public Pair(int x, int y) { this.x = x; this.y = y; } } }
Java
["5 2 3\n5 1 3 10 1", "6 1 5\n10 30 30 70 10 10", "4 3 1\n1 100 1 1"]
2 seconds
["18", "-1", "100"]
null
Java 8
standard input
[ "dp" ]
c1d48f546f79b0fd58539a1eb32917dd
The first line of the input contains three integers $$$n, k$$$ and $$$x$$$ ($$$1 \le k, x \le n \le 200$$$) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the beauty of the $$$i$$$-th picture.
1,900
Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement. Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.
standard output
PASSED
40b63c5f8ba3ec254fe838cfca4e4d4e
train_001.jsonl
1542378900
The only difference between easy and hard versions is the constraints.Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $$$n$$$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $$$i$$$-th picture has beauty $$$a_i$$$.Vova wants to repost exactly $$$x$$$ pictures in such a way that: each segment of the news feed of at least $$$k$$$ consecutive pictures has at least one picture reposted by Vova; the sum of beauty values of reposted pictures is maximum possible. For example, if $$$k=1$$$ then Vova has to repost all the pictures in the news feed. If $$$k=2$$$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Main { static BufferedReader reader; static StringTokenizer tokenizer; static PrintWriter writer; static String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(nextToken()); } static long nextLong() throws IOException { return Long.parseLong(nextToken()); } static void banana() throws IOException { int n = nextInt(); int k = nextInt(); int x = nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } long[][] dp = new long[n + 1][x + 1]; for (int i = 0; i <= n; i++) { for (int j = 0; j <= x; j++) { dp[i][j] = -1; } } for (int q = 0; q < k; q++) { dp[q][0] = 0; } for (int i = 0; i < n; i++) { for (int ch = 0; ch < x; ch++) { if (dp[i][ch] != -1) { long cand = dp[i][ch] + a[i]; for (int add = k; add >= 1; add--) { if (i + add <= n) { long have = dp[i + add][ch + 1]; if (cand > have) { dp[i + add][ch + 1] = cand; } } } } } } writer.println(dp[n][x]); } public static void main(String[] args) throws IOException { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; writer = new PrintWriter(System.out); banana(); reader.close(); writer.close(); } static class Pair { int x; int y; public Pair(int x, int y) { this.x = x; this.y = y; } } }
Java
["5 2 3\n5 1 3 10 1", "6 1 5\n10 30 30 70 10 10", "4 3 1\n1 100 1 1"]
2 seconds
["18", "-1", "100"]
null
Java 8
standard input
[ "dp" ]
c1d48f546f79b0fd58539a1eb32917dd
The first line of the input contains three integers $$$n, k$$$ and $$$x$$$ ($$$1 \le k, x \le n \le 200$$$) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the beauty of the $$$i$$$-th picture.
1,900
Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement. Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.
standard output
PASSED
1294c7a5780fb104cbd4f76038ba80dc
train_001.jsonl
1542378900
The only difference between easy and hard versions is the constraints.Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $$$n$$$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $$$i$$$-th picture has beauty $$$a_i$$$.Vova wants to repost exactly $$$x$$$ pictures in such a way that: each segment of the news feed of at least $$$k$$$ consecutive pictures has at least one picture reposted by Vova; the sum of beauty values of reposted pictures is maximum possible. For example, if $$$k=1$$$ then Vova has to repost all the pictures in the news feed. If $$$k=2$$$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
256 megabytes
import java.util.*; public class Ideone { public static void main (String[] args) throws java.lang.Exception { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); int x = sc.nextInt(); int[] arr = new int[n]; for(int i = 0; i<n; i++) arr[i] = sc.nextInt(); long[][] grid = new long[x+1][n+1]; grid[0][0] = 0; long INF = 1234567890123L; for(int i = 1; i<=n; i++){ grid[0][i] = -INF; } for(int i = 1; i<=x; i++){ for(int j = 0; j<=n; j++){ long max = -INF; for(int m = 1; m<=k; m++){ if(j-m>=0) max = Math.max(max, grid[i-1][j-m]); } if(max >= 0) grid[i][j] = max+arr[j-1]; else grid[i][j] = -INF; } } long ans = -1; for(int i = 0; i<k; i++){ ans = Math.max(ans, grid[x][n-i]); } System.out.println(ans); } }
Java
["5 2 3\n5 1 3 10 1", "6 1 5\n10 30 30 70 10 10", "4 3 1\n1 100 1 1"]
2 seconds
["18", "-1", "100"]
null
Java 8
standard input
[ "dp" ]
c1d48f546f79b0fd58539a1eb32917dd
The first line of the input contains three integers $$$n, k$$$ and $$$x$$$ ($$$1 \le k, x \le n \le 200$$$) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the beauty of the $$$i$$$-th picture.
1,900
Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement. Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.
standard output
PASSED
38391ee02f40b71e041d7d0f456bef23
train_001.jsonl
1542378900
The only difference between easy and hard versions is the constraints.Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $$$n$$$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $$$i$$$-th picture has beauty $$$a_i$$$.Vova wants to repost exactly $$$x$$$ pictures in such a way that: each segment of the news feed of at least $$$k$$$ consecutive pictures has at least one picture reposted by Vova; the sum of beauty values of reposted pictures is maximum possible. For example, if $$$k=1$$$ then Vova has to repost all the pictures in the news feed. If $$$k=2$$$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
256 megabytes
import java.util.*; import java.io.*; public class picturesWithKittensEasy { static FS sc = new FS(); static PrintWriter pw = new PrintWriter(System.out); static final long max = Long.MAX_VALUE / 8; static int n, k, x; static int[] arr; static long[][][] dp; public static void main(String[] args) { n = sc.nextInt(); k = sc.nextInt(); x = sc.nextInt(); arr = new int[n]; for(int i = 0; i < n; ++i) arr[i] = sc.nextInt(); dp = new long[n + 1][x + 1][k]; for(long[][] z : dp) { for(long[] y : z) Arrays.fill(y, -1); } long out = go(0, x, 0); if(out < 0) out = -1; System.out.println(out); } static long go(int idx, int num, int past) { if(dp[idx][num][past] != -1) return dp[idx][num][past]; if(idx == n) return dp[idx][num][past] = (num == 0 ? 0 : -max); long take = -max; if(num > 0) take = arr[idx] + go(idx + 1, num - 1, 0); long dont = -max; if(past + 1 < k) dont = go(idx + 1, num, past + 1); return dp[idx][num][past] = Math.max(take, dont); } static class FS { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while(!st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch(Exception e) {} } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } } }
Java
["5 2 3\n5 1 3 10 1", "6 1 5\n10 30 30 70 10 10", "4 3 1\n1 100 1 1"]
2 seconds
["18", "-1", "100"]
null
Java 8
standard input
[ "dp" ]
c1d48f546f79b0fd58539a1eb32917dd
The first line of the input contains three integers $$$n, k$$$ and $$$x$$$ ($$$1 \le k, x \le n \le 200$$$) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the beauty of the $$$i$$$-th picture.
1,900
Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement. Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.
standard output
PASSED
f583af4bb515c37d62e71c91387c5972
train_001.jsonl
1542378900
The only difference between easy and hard versions is the constraints.Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $$$n$$$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $$$i$$$-th picture has beauty $$$a_i$$$.Vova wants to repost exactly $$$x$$$ pictures in such a way that: each segment of the news feed of at least $$$k$$$ consecutive pictures has at least one picture reposted by Vova; the sum of beauty values of reposted pictures is maximum possible. For example, if $$$k=1$$$ then Vova has to repost all the pictures in the news feed. If $$$k=2$$$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
256 megabytes
import java.util.*; import java.io.*; public class picturesWithKittensEasy { static FS sc = new FS(); static PrintWriter pw = new PrintWriter(System.out); static final long max = Long.MAX_VALUE / 8; static int n, k, x; static int[] arr; static long[][] dp; public static void main(String[] args) { n = sc.nextInt(); k = sc.nextInt(); x = sc.nextInt(); // 1-index arr arr = new int[n + 1]; for(int i = 1; i <= n; ++i) arr[i] = sc.nextInt(); dp = new long[n + 1][x + 1]; for(long[] z : dp) Arrays.fill(z, -1); // dp solves for maximum subset with given state // assuming we are necessarily going to take arr[idx] long out = go(0, x); if(out < 0) out = -1; System.out.println(out); } static long go(int idx, int num) { if(dp[idx][num] != -1) return dp[idx][num]; // we have no more pictures to take; // see if we are too far away from end if(num == 0) return dp[idx][num] = (n - idx < k ? arr[idx] : -max); long out = -max; for(int i = 1; i <= k; ++i) { int next = idx + i; if(next > n) break; long curr = arr[idx] + go(next, num - 1); out = Math.max(out, curr); } return dp[idx][num] = out; } static class FS { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while(!st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch(Exception e) {} } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } } }
Java
["5 2 3\n5 1 3 10 1", "6 1 5\n10 30 30 70 10 10", "4 3 1\n1 100 1 1"]
2 seconds
["18", "-1", "100"]
null
Java 8
standard input
[ "dp" ]
c1d48f546f79b0fd58539a1eb32917dd
The first line of the input contains three integers $$$n, k$$$ and $$$x$$$ ($$$1 \le k, x \le n \le 200$$$) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the beauty of the $$$i$$$-th picture.
1,900
Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement. Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.
standard output
PASSED
f91b7c84160a21febcd5468261566cdb
train_001.jsonl
1542378900
The only difference between easy and hard versions is the constraints.Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $$$n$$$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $$$i$$$-th picture has beauty $$$a_i$$$.Vova wants to repost exactly $$$x$$$ pictures in such a way that: each segment of the news feed of at least $$$k$$$ consecutive pictures has at least one picture reposted by Vova; the sum of beauty values of reposted pictures is maximum possible. For example, if $$$k=1$$$ then Vova has to repost all the pictures in the news feed. If $$$k=2$$$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
256 megabytes
import java.util.*; import java.io.*; public class picturesWithKittensEasy { static FS sc = new FS(); static PrintWriter pw = new PrintWriter(System.out); static final long max = Long.MAX_VALUE / 8; static int n, k, x; static int[] arr; static long[][] dp; public static void main(String[] args) { n = sc.nextInt(); k = sc.nextInt(); x = sc.nextInt(); // 1-index arr arr = new int[n + 1]; for(int i = 1; i <= n; ++i) arr[i] = sc.nextInt(); dp = new long[n + 1][x + 1]; for(int num = 0; num <= x; ++num) { for(int idx = n; idx >= 0; --idx) { dp[idx][num] = -max; if(num == 0) { if(n - idx < k) dp[idx][num] = arr[idx]; continue; } for(int i = 1; i <= k; ++i) { int next = idx + i; if(next > n) break; long curr = arr[idx] + dp[next][num - 1]; dp[idx][num] = Math.max(dp[idx][num], curr); } } } long out = dp[0][x]; if(out < 0) out = -1; System.out.println(out); } static class FS { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while(!st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch(Exception e) {} } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } } }
Java
["5 2 3\n5 1 3 10 1", "6 1 5\n10 30 30 70 10 10", "4 3 1\n1 100 1 1"]
2 seconds
["18", "-1", "100"]
null
Java 8
standard input
[ "dp" ]
c1d48f546f79b0fd58539a1eb32917dd
The first line of the input contains three integers $$$n, k$$$ and $$$x$$$ ($$$1 \le k, x \le n \le 200$$$) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the beauty of the $$$i$$$-th picture.
1,900
Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement. Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.
standard output
PASSED
c57279a2bb1dd6216c77536a10d11bf5
train_001.jsonl
1542378900
The only difference between easy and hard versions is the constraints.Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $$$n$$$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $$$i$$$-th picture has beauty $$$a_i$$$.Vova wants to repost exactly $$$x$$$ pictures in such a way that: each segment of the news feed of at least $$$k$$$ consecutive pictures has at least one picture reposted by Vova; the sum of beauty values of reposted pictures is maximum possible. For example, if $$$k=1$$$ then Vova has to repost all the pictures in the news feed. If $$$k=2$$$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
256 megabytes
//codeforces_1077F1 import java.io.*; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import static java.lang.Math.*; import java.math.*; public class Main{ static PrintWriter go = new PrintWriter(System.out); static int n,x,minLength; static int[] l; static long[][] memo; public static void main(String args[]) throws IOException,FileNotFoundException { BufferedReader gi = new BufferedReader(new InputStreamReader(System.in)); l = parseArray(gi); n = l[0]; minLength = l[1]; x = l[2]; l = parseArray(gi); long ans = -1; memo = new long[n][x+1]; for ( int k = 0; k < n; k++){ for ( int j = 0; j < x + 1; j++){ memo[k][j] = -1; } } if ( n/minLength > x ){ go.println(-1); go.close(); return; } for ( int k = 0; k < minLength; k++){ ans = max(ans, dp( k, x )); } go.println(ans<0?-1:ans); go.close(); } static long naive(int source, int steps){ if ( (n - source)/minLength > steps || steps < 0 ){ return -1; } if ( steps == 1 && (n - source - 1) >= minLength ){ return -1; } if ( steps == 0 ){ return 0; } if ( source == n-1 ){ return l[source]; } long rez = -1; for ( int k = source + 1; k < min(n,source + minLength + 1) ; k++){ rez = max(rez, naive(k, steps - 1)); } if ( rez == -1 ){ return -1; } rez += l[source]; return rez; } static long dp(int source, int steps){ if ( (n - source)/minLength > steps || steps < 0 ){ return -1; } if ( steps == 1 && (n - source - 1) >= minLength ){ return -1; } if ( steps == 0 ){ return memo[source][steps] = 0; } if ( source == n-1 ){ return memo[source][steps] = l[source]; } long rez = -1; if ( memo[source][steps] != -1 ){ return memo[source][steps]; } for ( int k = source + 1; k < min(n,source + minLength + 1) ; k++){ rez = max(rez, dp(k, steps - 1)); } if ( rez < 0 ){ return memo[source][steps] = -2; } rez += l[source]; return memo[source][steps] = rez; } static int[] parseArray(BufferedReader gi) throws IOException{ String[] line = gi.readLine().trim().split(" "); int[] rez = new int[line.length]; for ( int k = 0; k < line.length; k++){ rez[k] = Integer.parseInt(line[k]); } return rez; } }
Java
["5 2 3\n5 1 3 10 1", "6 1 5\n10 30 30 70 10 10", "4 3 1\n1 100 1 1"]
2 seconds
["18", "-1", "100"]
null
Java 8
standard input
[ "dp" ]
c1d48f546f79b0fd58539a1eb32917dd
The first line of the input contains three integers $$$n, k$$$ and $$$x$$$ ($$$1 \le k, x \le n \le 200$$$) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the beauty of the $$$i$$$-th picture.
1,900
Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement. Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.
standard output
PASSED
b410b9004cd8293b4452905caf42b1ef
train_001.jsonl
1542378900
The only difference between easy and hard versions is the constraints.Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $$$n$$$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $$$i$$$-th picture has beauty $$$a_i$$$.Vova wants to repost exactly $$$x$$$ pictures in such a way that: each segment of the news feed of at least $$$k$$$ consecutive pictures has at least one picture reposted by Vova; the sum of beauty values of reposted pictures is maximum possible. For example, if $$$k=1$$$ then Vova has to repost all the pictures in the news feed. If $$$k=2$$$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
256 megabytes
import java.util.Scanner; // https://codeforces.com/problemset/problem/1077/F1 public class PicturesWithKittens { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int d = sc.nextInt(); int x = sc.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); } // dp[i][j]: using only elements of a up to a[i], and the element at a[i], // and using exactly j elements, what is the best beauty? long[][] dp = new long[n + 1][x + 1]; for (int i = 0; i <= n; i++) { for (int j = 0; j <= x; j++) { dp[i][j] = Long.MIN_VALUE; } } dp[0][0] = 0; for (int j = 0; j < x; j++) { for (int i = j; i <= n; i++) { for (int k = 1; k <= d; k++) { if (i - k >= 0) { dp[i][j + 1] = Math.max(dp[i][j + 1], dp[i - k][j] + a[i - 1]); } } } } long max = -1; for (int i = n - d + 1; i <= n; i++) { max = Math.max(max, dp[i][x]); } System.out.println(max); } }
Java
["5 2 3\n5 1 3 10 1", "6 1 5\n10 30 30 70 10 10", "4 3 1\n1 100 1 1"]
2 seconds
["18", "-1", "100"]
null
Java 8
standard input
[ "dp" ]
c1d48f546f79b0fd58539a1eb32917dd
The first line of the input contains three integers $$$n, k$$$ and $$$x$$$ ($$$1 \le k, x \le n \le 200$$$) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the beauty of the $$$i$$$-th picture.
1,900
Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement. Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.
standard output
PASSED
9e5afa2c108979590c5fd8586d7378a3
train_001.jsonl
1542378900
The only difference between easy and hard versions is the constraints.Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $$$n$$$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $$$i$$$-th picture has beauty $$$a_i$$$.Vova wants to repost exactly $$$x$$$ pictures in such a way that: each segment of the news feed of at least $$$k$$$ consecutive pictures has at least one picture reposted by Vova; the sum of beauty values of reposted pictures is maximum possible. For example, if $$$k=1$$$ then Vova has to repost all the pictures in the news feed. If $$$k=2$$$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
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.Arrays; 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 sumit */ 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); TaskF1 solver = new TaskF1(); solver.solve(1, in, out); out.close(); } static class TaskF1 { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int k = in.nextInt(); int x = in.nextInt(); int arr[] = in.nextIntArray(n); long dp[][] = new long[n + 1][x + 1]; for (int i = 0; i <= n; i++) Arrays.fill(dp[i], -1); for (int i = 0; i < k; i++) dp[i][1] = arr[i]; for (int i = 0; i < n; i++) { for (int j = 1; j <= x; j++) { for (int m = Math.max(0, i - k); m < i; m++) { if (dp[m][j - 1] != -1) { dp[i][j] = Math.max(dp[i][j], dp[m][j - 1] + arr[i]); } } } } long ans = -1; for (int j = n - k; j < n; j++) { ans = Math.max(ans, dp[j][x]); } out.printLine(ans); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; 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 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 & 15; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int arraySize) { int array[] = new int[arraySize]; for (int i = 0; i < arraySize; i++) array[i] = nextInt(); return array; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -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); } } }
Java
["5 2 3\n5 1 3 10 1", "6 1 5\n10 30 30 70 10 10", "4 3 1\n1 100 1 1"]
2 seconds
["18", "-1", "100"]
null
Java 8
standard input
[ "dp" ]
c1d48f546f79b0fd58539a1eb32917dd
The first line of the input contains three integers $$$n, k$$$ and $$$x$$$ ($$$1 \le k, x \le n \le 200$$$) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the beauty of the $$$i$$$-th picture.
1,900
Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement. Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.
standard output
PASSED
75cc6108af4a3dacdc6c9903fc320e26
train_001.jsonl
1407690000
Piegirl was asked to implement two table join operation for distributed database system, minimizing the network traffic.Suppose she wants to join two tables, A and B. Each of them has certain number of rows which are distributed on different number of partitions. Table A is distributed on the first cluster consisting of m partitions. Partition with index i has ai rows from A. Similarly, second cluster containing table B has n partitions, i-th one having bi rows from B. In one network operation she can copy one row from any partition to any other partition. At the end, for each row from A and each row from B there should be a partition that has both rows. Determine the minimal number of network operations to achieve this.
256 megabytes
import java.util.List; import java.util.Scanner; import java.io.OutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; 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; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { public void solve(int testNumber, Scanner in, PrintWriter out){ int m,n; m=in.nextInt(); n=in.nextInt(); ArrayList<Long> Ai=new ArrayList<Long>(m); Long sumA=new Long(0); for(int i=0;i<m;++i){ Ai.add(in.nextLong()); sumA+=Ai.get(i); } ArrayList<Long> Bi=new ArrayList<Long>(n); Long sumB=new Long(0); for(int i=0;i<n;++i){ Bi.add(in.nextLong()); sumB+=Bi.get(i); } Collections.sort(Ai); Collections.sort(Bi); Long As=sumA; Long Bs=sumB; for(int i=0;i<Ai.size()-1;++i){ Bs+=min(Ai.get(i),sumB); } for(int i=0;i<Bi.size()-1;++i){ As+=min(Bi.get(i),sumA); } out.println(min(As,Bs)); } private Long min(Long a,Long b){ return a>b? b:a; } }
Java
["2 2\n2 6\n3 100", "2 3\n10 10\n1 1 1"]
1 second
["11", "6"]
NoteIn the first example it makes sense to move all the rows to the second partition of the second cluster which is achieved in 2 + 6 + 3 = 11 operationsIn the second example Piegirl can copy each row from B to the both partitions of the first cluster which needs 2·3 = 6 copy operations.
Java 8
standard input
[ "greedy" ]
f56597c8c3d17d73b8ede2d81fe5cbe7
First line contains two integer numbers, m and n (1 ≤ m, n ≤ 105). Second line contains description of the first cluster with m space separated integers, ai (1 ≤ ai ≤ 109). Similarly, third line describes second cluster with n space separated integers, bi (1 ≤ bi ≤ 109).
1,900
Print one integer — minimal number of copy operations.
standard output
PASSED
44a3034ad486ccf73e90c39b941b9ae6
train_001.jsonl
1407690000
Piegirl was asked to implement two table join operation for distributed database system, minimizing the network traffic.Suppose she wants to join two tables, A and B. Each of them has certain number of rows which are distributed on different number of partitions. Table A is distributed on the first cluster consisting of m partitions. Partition with index i has ai rows from A. Similarly, second cluster containing table B has n partitions, i-th one having bi rows from B. In one network operation she can copy one row from any partition to any other partition. At the end, for each row from A and each row from B there should be a partition that has both rows. Determine the minimal number of network operations to achieve this.
256 megabytes
import java.io.FileNotFoundException; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.File; import java.io.Writer; import java.util.List; import java.io.IOException; import java.io.InputStreamReader; import java.io.FileReader; import java.util.ArrayList; import java.util.StringTokenizer; import java.io.ByteArrayOutputStream; import java.util.Collections; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author abra */ 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); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB extends SimpleSavingChelperSolution { public void solve(int testNumber) { int n = in.nextInt(); int m = in.nextInt(); long[] a = in.nextLongArray(n); long[] b = in.nextLongArray(m); List<Long> at = new ArrayList<>(); List<Long> bt = new ArrayList<>(); for (Long i : a) { at.add(i); } for (Long i : b) { bt.add(i); } Collections.sort(at); Collections.sort(bt); for (int i = 0; i < a.length; i++) { a[i] = at.get(i); } for (int i = 0; i < b.length; i++) { b[i] = bt.get(i); } long ans = Long.MAX_VALUE; long aSum = 0; long bSum = 0; for (long i : a) { aSum += i; } for (long i : b) { bSum += i; } long bLeft = bSum; long prev = Long.MAX_VALUE; for (int i = m - 1; i >= 0; i--) { bLeft -= b[i]; long t = aSum * (m - i) + bLeft; ans = Math.min(ans, t); if (prev < t) { break; } prev = t; } long aLeft = aSum; prev = Long.MAX_VALUE; for (int i = n - 1; i >= 0; i--) { aLeft -= a[i]; long t = bSum * (n - i) + aLeft; ans = Math.min(ans, t); if (prev < t) { break; } prev = t; } out.println(ans); } } abstract class SimpleSavingChelperSolution extends SavingChelperSolution { public String processOutputPreCheck(int testNumber, String output) { return output; } public String processOutputPostCheck(int testNumber, String output) { return output; } } class InputReader { BufferedReader br; StringTokenizer in; public InputReader(String fileName) { try { br = new BufferedReader(new FileReader(fileName)); } catch (IOException e) { throw new RuntimeException(e); } } public InputReader(InputStream inputStream) { br = new BufferedReader(new InputStreamReader(inputStream)); } boolean hasMoreTokens() { while (in == null || !in.hasMoreTokens()) { String s = nextLine(); if (s == null) { return false; } in = new StringTokenizer(s); } return true; } public String nextString() { return hasMoreTokens() ? in.nextToken() : null; } public String nextLine() { try { in = null; // riad legacy return br.readLine(); } catch (Exception e) { e.printStackTrace(); return null; } } public int nextInt() { return Integer.parseInt(nextString()); } public long nextLong() { return Long.parseLong(nextString()); } public long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } } abstract class SavingChelperSolution { protected int testNumber; public InputReader in; public OutputWriter out; private OutputWriter toFile; private boolean local = new File("chelper.properties").exists(); public OutputWriter debug = local ? new OutputWriter(System.out) : new OutputWriter(new OutputStream() { @Override public void write(int b) { } }); public SavingChelperSolution() { try { toFile = new OutputWriter("last_test_output.txt"); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } public abstract void solve(int testNumber); public abstract String processOutputPreCheck(int testNumber, String output); public abstract String processOutputPostCheck(int testNumber, String output); public void solve(int testNumber, InputReader in, OutputWriter out) { this.testNumber = testNumber; ByteArrayOutputStream substituteOutContents = new ByteArrayOutputStream(); OutputWriter substituteOut = new OutputWriter(substituteOutContents); this.in = in; this.out = substituteOut; solve(testNumber); substituteOut.flush(); String result = substituteOutContents.toString(); result = processOutputPreCheck(testNumber, result); out.print(result); out.flush(); if (local) { debug.flush(); result = processOutputPostCheck(testNumber, result); toFile.print(result); toFile.flush(); } } } class OutputWriter extends PrintWriter { public OutputWriter(String fileName) throws FileNotFoundException { super(fileName); } public OutputWriter(OutputStream outputStream) { super(outputStream); } public OutputWriter(Writer writer) { super(writer); } }
Java
["2 2\n2 6\n3 100", "2 3\n10 10\n1 1 1"]
1 second
["11", "6"]
NoteIn the first example it makes sense to move all the rows to the second partition of the second cluster which is achieved in 2 + 6 + 3 = 11 operationsIn the second example Piegirl can copy each row from B to the both partitions of the first cluster which needs 2·3 = 6 copy operations.
Java 8
standard input
[ "greedy" ]
f56597c8c3d17d73b8ede2d81fe5cbe7
First line contains two integer numbers, m and n (1 ≤ m, n ≤ 105). Second line contains description of the first cluster with m space separated integers, ai (1 ≤ ai ≤ 109). Similarly, third line describes second cluster with n space separated integers, bi (1 ≤ bi ≤ 109).
1,900
Print one integer — minimal number of copy operations.
standard output
PASSED
df9655e438fa3f4c01bfe38def29539e
train_001.jsonl
1407690000
Piegirl was asked to implement two table join operation for distributed database system, minimizing the network traffic.Suppose she wants to join two tables, A and B. Each of them has certain number of rows which are distributed on different number of partitions. Table A is distributed on the first cluster consisting of m partitions. Partition with index i has ai rows from A. Similarly, second cluster containing table B has n partitions, i-th one having bi rows from B. In one network operation she can copy one row from any partition to any other partition. At the end, for each row from A and each row from B there should be a partition that has both rows. Determine the minimal number of network operations to achieve this.
256 megabytes
import java.util.*; import java.io.*; public class b { public static void main(String[] args) throws IOException { input.init(System.in); int n = input.nextInt(), m = input.nextInt(); int[] as = new int[n], bs = new int[m]; for(int i = 0; i<n; i++) as[i] = input.nextInt(); for(int i = 0; i<m; i++) bs[i] = input.nextInt(); System.out.println(Math.min(go(as, bs), go(bs, as))); } static long go(int[] a, int[] b) { long sum = 0; for(int x : b) sum += x; long res = 0; int max = 0; for(int i = 0; i<a.length; i++) { max = Math.max(max, a[i]); res += Math.min(a[i], sum); } return res + sum - Math.min(max, sum); } public static class input { 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 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 double nextDouble() throws IOException { return Double.parseDouble( next() ); } static long nextLong() throws IOException { return Long.parseLong( next() ); } } }
Java
["2 2\n2 6\n3 100", "2 3\n10 10\n1 1 1"]
1 second
["11", "6"]
NoteIn the first example it makes sense to move all the rows to the second partition of the second cluster which is achieved in 2 + 6 + 3 = 11 operationsIn the second example Piegirl can copy each row from B to the both partitions of the first cluster which needs 2·3 = 6 copy operations.
Java 8
standard input
[ "greedy" ]
f56597c8c3d17d73b8ede2d81fe5cbe7
First line contains two integer numbers, m and n (1 ≤ m, n ≤ 105). Second line contains description of the first cluster with m space separated integers, ai (1 ≤ ai ≤ 109). Similarly, third line describes second cluster with n space separated integers, bi (1 ≤ bi ≤ 109).
1,900
Print one integer — minimal number of copy operations.
standard output
PASSED
1d39a3ddfe8aa410992d80f9e68c90a3
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class D { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int x = sc.nextInt(); sc.nextLine(); ArrayList<Integer> s = new ArrayList<Integer>(); for (int i = 0; i < n; i++) s.add(sc.nextInt()); int cnt = 0; Collections.sort(s); do { int ex = ((s.size() + 1) / 2) - 1; if (s.get(ex) == x) break; s.add(x); cnt++; Collections.sort(s); } while (true); System.out.println(cnt); } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
c7372aa7e9f1c6d4e4eb3fee47b6dd1f
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
import java.util.*; public class Main{ public static void main(String[] args){ Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); int[] a = new int[10000]; Arrays.fill(a,100100); for(int i = 0; i<n;i++) a[i+1] = in.nextInt(); a[0] = 0; Arrays.sort(a); int med = (1+n)/2; int ans = 0; while(a[med] != m){ a[++n] = m; Arrays.sort(a); med = (n+1)/2; ans++; } System.out.print(ans); } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
7efb0e9fae7ef96cbddf1d0401f178b7
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
import java.util.*; public class C166 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int x = in.nextInt(); int min = Integer.MIN_VALUE; int max = Integer.MAX_VALUE; LinkedList<Integer> a = new LinkedList<Integer>(); for (int i = 0; i < n; i++) a.add(in.nextInt()); int steps = 0; if (!a.contains(x)) { a.add(new Integer(x)); ++steps; } Collections.sort(a); // System.out.println(a); int s = a.size(); while (true) { if ((s % 2 == 0 && a.get((s / 2) - 1) == x) || (s % 2 != 0 && a.get(s / 2) == x)) { System.out.println(steps); return; } int curr_median = (s % 2 == 0 ? a.get((s / 2) - 1) : a.get(s / 2)); if (x < curr_median) a.addFirst(min); else a.addLast(max); // System.out.println(a); ++steps; s = a.size(); } } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
a4bf4aa5429d481c5d1e5b111c44cfd5
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) throws Exception{ new Main().run(); } private void run() throws Exception{ Scanner input = new Scanner(System.in); int n = input.nextInt(); int median = input.nextInt(); int large = 0; int small = 0; int equal = 0; for(int i = 0; i < n; i++){ int num = input.nextInt(); if(num > median) large++; else if(num == median) equal++; else small++; } if(equal == 0) { if(large > small){ System.out.println(large-small); } else if(large == small){ System.out.println(1); } else{ System.out.println(small-large+1); } return; } else{ if(large > small){ while(large > small && equal != 0){ small++; equal--; } System.out.println(large - small); } else if(large == small){ System.out.println(0); } else{ while(small > large && equal != 0){ large++; equal--; } if(equal == 0) System.out.println(small - large + 1); else System.out.println(small - large); } } } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
291cba048a51f5bdd375e4e67d1d18ed
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
import java.io.IOException; import java.util.Arrays; import java.util.InputMismatchException; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Egor Kulikov (egor@egork.net) */ 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(); } } class TaskC { public void solve(int testNumber, InputReader in, OutputWriter out) { int count = in.readInt(); int x = in.readInt(); int[] array = IOUtils.readIntArray(in, count); Arrays.sort(array); int answer = 0; while (array[(array.length - 1) / 2] != x) { array = Arrays.copyOf(array, array.length + 1); array[array.length - 1] = x; Arrays.sort(array); answer++; } out.printLine(answer); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; 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 static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(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(); } } 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; } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
00e64a50c0a9fe864b8373e8cf2ebba7
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); int[] arr = new int[n]; int less = 0; int bigger = 0; int equal = 0; for (int i = 0; i < n; ++i) { arr[i] = sc.nextInt(); if (arr[i]==k) equal++; if (arr[i]<k) less++; } bigger = n - less - equal; int ans = 0; if (equal == 0) { ans++; equal=1; } if ( (less+bigger+equal+1)/2 > less && (less+bigger+equal+1)/2 < less+equal) { System.out.print(ans); return; } int temp1 = Math.abs((equal - 1) + bigger - less); int temp2 = Math.abs((equal - 1) + less - bigger); if (temp1 < temp2) { ans += temp1; if ((equal - 1) + bigger - less < 0) { if ((temp1+less+equal+bigger)/2 == (temp1+less+equal+bigger+1)/2) ans--; } else { if ((temp1+less+equal+bigger)/2 == (temp1+less+equal+bigger+1)/2-1) ans--; } } else { ans += temp2; if ((equal - 1) + less - bigger < 0) { if ((temp2+less+equal+bigger)/2 == (temp2+less+equal+bigger+1)/2-1) ans--; } else { if ((temp2+less+equal+bigger)/2 == (temp2+less+equal+bigger+1)/2) ans--; } } System.out.print(ans); } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
0fa36fad71943307865834f662780c13
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; public class aaatwo { public static void main(String args[]) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); StringTokenizer tok = new StringTokenizer(in.readLine()); int n = Integer.parseInt(tok.nextToken()), x = Integer.parseInt(tok .nextToken()); int arr[] = new int[n]; tok = new StringTokenizer(in.readLine()); for (int i = 0; i < n; i++) { arr[i] = Integer.parseInt(tok.nextToken()); } Arrays.sort(arr); int less = 0, more = 0, same = 0; for (int i = 0; i < n; i++) { if (arr[i] < x) less++; else if (arr[i] > x) more++; else same++; } // System.out.println(less + " " + more); int dif = abs(less - more); if (more == less) { if (same == 0) System.out.println(1); else System.out.println(0); return; } if (same == 0) { if (more > less) System.out.println(dif); else System.out.println(dif + 1); return; } if (more > less) { System.out.println(max(0, dif - same)); return; } System.out.println(max(0, dif - (same - 1))); } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
5a25288c540f0359b80f392b894b638d
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
import java.util.ArrayList; import java.util.Scanner; import java.util.Collections; public class problem166C { public void run() { Scanner in = new Scanner(System.in); int n = in.nextInt(); int x = in.nextInt(); int i; ArrayList<Integer> a = new ArrayList<Integer>(); boolean isHasNotX = true; for (i = 0; i < n; i++) { int number = in.nextInt(); a.add(number); if (number == x) isHasNotX = false; } in.close(); int ans = 0; if (isHasNotX) { a.add(x); ans++; } Collections.sort(a); int firstOccurence = 0; while (a.get(firstOccurence) < x) firstOccurence++; int lastOccurence = firstOccurence; n = a.size(); while ((lastOccurence < n) && (a.get(lastOccurence) == x)) lastOccurence++; lastOccurence--; int median = (n + 1) / 2; if ((firstOccurence + 1 <= median) && (median <= lastOccurence + 1)) { System.out.println(ans); return; } while (firstOccurence + 1 > median) { n++; median = (n + 1) / 2; ans++; } while (lastOccurence + 1 < median) { n++; lastOccurence++; median = (n + 1) / 2; ans++; } System.out.println(ans); } public static void main(String[] args) { new problem166C().run(); } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
c5c485b83e7e3139d487d2e18dce0b9e
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
import java.io.*; import java.util.*; public class CC { String s = null; String[] ss = null; public void run() throws Exception{ BufferedReader br = null; File file = new File("input.txt"); if(file.exists()){ br = new BufferedReader(new FileReader("input.txt")); } else{ br = new BufferedReader(new InputStreamReader(System.in)); } s = br.readLine(); ss = s.split(" "); int n = Integer.parseInt(ss[0]); int x = Integer.parseInt(ss[1]); s = br.readLine(); ss = s.split(" "); Integer[] d = new Integer[n]; boolean found = false; for(int i = 0; i < n; i++){ d[i] = Integer.parseInt(ss[i]); if(d[i] == x){ found = true; } } Arrays.sort(d); List<Integer> list = new LinkedList<Integer>(); int ans = 0; for(int i = 0; i < d.length; i++){ if(!found && d[i] > x){ list.add(x); found = true; ans++; n++; } list.add(d[i]); } if(!found){ list.add(x); ans++; } int pos = (list.size() + 1) / 2 - 1; while(list.get(pos).intValue() != x){ if(list.get(pos).intValue() > x){ if(pos-1 < 0){ list.add(0, list.get(0).intValue()); } else{ if(list.get(pos-1).intValue() <= x){ list.add(pos, x); } else{ list.add(0, list.get(0).intValue()); } } } else{ if(list.get(pos+1).intValue() <= x){ list.add(list.get(list.size()-1).intValue()); } else{ list.add(pos+1, x); } } ans++; pos = (list.size() + 1) / 2 - 1; } System.out.println(ans); } public static void main(String[] args) throws Exception{ CC t = new CC(); t.run(); } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
3dea7dfecc2dcbf028ce734a141a5c26
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
import java.util.*; public class maximus { public static void main(String [] args){ Scanner in=new Scanner(System.in); int n=in.nextInt(); int x=in.nextInt(); int array[]=new int[n + 1]; for(int i=1;i<=n;i++) array[i]=in.nextInt(); Arrays.sort(array); int max=Integer.MIN_VALUE; int min=Integer.MAX_VALUE; int temp=0; //for(int i=0;i<=n;i++)System.out.print(array[i]+" "); //System.out.println(); for(int i=1;i<=n;i++) if(array[i]==x){ min=Math.min(min,i); max=Math.max(max,i); } //System.out.println(min+" "+max+" "+n+" "+x); if(min==Integer.MAX_VALUE){ for(int i=1;i<=n;i++){ //System.out.println(array[i]+" "+x); if(array[i] > x){ min=max=i; n++; temp++; break; } } } //System.out.println(min+" "+max+" "+n+" "+x); if(min==Integer.MAX_VALUE){ min=max=n+1; temp++; n++; } //System.out.println(min+" "+max+" "+n+" "+x); if((n+1)/2 <=max && (n+1)/2 >=min){ System.out.print(temp); return; } if((n+1)/2 > max){ while((n+1)/2!=max){ n++; temp++; max++; } System.out.print(temp); return; } if((n+1)/2 < min){ while(min!=(n+1)/2){ n++; temp++; } System.out.print(temp); } } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
d00ea634d2972b0d8319451c3f507cdb
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class Median2 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int x = scan.nextInt(); int[] array = new int[n]; boolean found = false; for (int i = 0; i < array.length; i++) { array[i] = scan.nextInt(); if (array[i] == x) { found = true; } } int min1 = 0, min2 = 0; if (!found) { int[] temp = array.clone(); array = new int[n + 1]; for (int i = 0; i < temp.length; i++) { array[i] = temp[i]; } min1++; min2++; array[n] = x; } Arrays.sort(array); int medianIndex = (array.length + 1) / 2 - 1; int index = -1; for (int i = 0; i < array.length; i++) { if (array[i] == x) { index = i; break; } } min1 += solve(medianIndex, index, array,x); for (int i = 0; i < array.length; i++) { if (array[i] == x) { index = i; } } min2 += solve(medianIndex, index, array,x); System.out.println(Math.min(min1, min2)); } public static int solve(int medianIndex, int index, int[] array, int x) { if (array[medianIndex ]== x) { return 0; } else if (medianIndex > index) { // int after = int after = array.length - index - 1; int before = index; int count = 0; while (before + 1 < after) { if (after == before || after == before + 1) break; count++; before++; } return count; } else if (medianIndex < index) { int after = array.length - index - 1; int before = index; int count = 0; while (after + 1 <= before) { if (after == before || after == before + 1) break; count++; after++; } return count; } return index; } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
38e2578dd05d81bf0a950f0a9d6da36a
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
import java.util.*; public class Main { public void doIt(){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int x = sc.nextInt(); //入力 ArrayList<Integer> array = new ArrayList<Integer>(n); for(int i=0; i < n; i++){ array.add(sc.nextInt()); } //ソートする Collections.sort(array); //カウンタを用意 int count = 0; while(true){ //中央値を求める int medianIndex = (array.size() + 1)/2; int median = array.get(medianIndex - 1); if(median == x){ break; } else if(x < median){ array.add(medianIndex -1, x); //ソートする Collections.sort(array); count++; } else{ array.add(medianIndex, x); //ソートする Collections.sort(array); count++; } } System.out.println(count); } public static void main(String[] args) { Main obj = new Main(); obj.doIt(); } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
fb15b5189306a971e5c253615fb30c26
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
//package codeforces; import java.util.*; public class Main { Scanner scan=new Scanner(System.in); void run(){ int n=scan.nextInt(); int k=scan.nextInt(); int ans=0; int pp[]=new int[n*2+1]; for(int i=0;i<n;i++) pp[i]=scan.nextInt(); Arrays.sort(pp,0,n); while(pp[(n+ans+1)/2-1]!=k){ pp[n+ans]=k; ans++; Arrays.sort(pp,0,ans+n); } System.out.println(ans); } public static void main(String args[]) { new Main().run(); } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
9fb18502fbca7067c53f8905c281ff41
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
import java.util.*; public class Main { void C(){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int x = sc.nextInt(); ArrayList<Integer> a = new ArrayList<Integer>(); for(int i=0; i<n; i++){ a.add(sc.nextInt()); } Collections.sort(a); int count=0,med=0,size=0; boolean flag=false; while(true){ size = a.size(); if(size % 2 != 0){ med = a.get(size/2); }else{ med = a.get(size/2-1); } //System.out.println(a); //System.out.println("med : "+med); if(med == x){ System.out.println(count); break; } else if(med > x){ //小さい方に追加 if(flag){ a.add(0, 0); }else{ flag=true; if(a.contains(x)){ a.add(0, 0); }else{ a.add(0, x); Collections.sort(a); } } } else if(med < x){ //大きい方に追加 if(flag){ a.add(100001); }else{ flag=true; if(a.contains(x)){ a.add(100001); }else{ a.add(x); Collections.sort(a); } } } count++; } } void A(){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt()-1; PT[] pt = new PT[n]; for(int i=0; i<n; i++){ pt[i] = new PT(sc.nextInt()*-1, sc.nextInt()*-1); } Arrays.sort(pt); int temp = pt[k].p; //System.out.println(pt[k].p); int f=0; for(int i=0; i<n; i++){ if(temp == pt[i].p){ f = i; break; } } //System.out.println("f"+f); int[] dic = new int[51]; for(int i=f; i<n; i++){ if(temp == pt[i].p){ dic[pt[i].t*-1]++; //System.out.println(pt[i].t*-1); } else break; } int c=0; for(int i=1; i<51; i++){ c += dic[i]; if(c > k-f){ System.out.println(dic[i]); break; } } } class PT implements Comparable<PT>{ int p,t; PT(int p, int t){ this.p=p; this.t=t; } @Override public int compareTo(PT arg0) { if(p > arg0.p) return 1; if(p < arg0.p) return -1; return 0; } } public static void main(String[] args) { new Main().C(); } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
33ea697cdaf437c0e7b5299bf7560b37
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class Round113_C { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int k = in.nextInt(); int[] a = new int[n + 1]; for (int i = 0; i < n; i++) a[i] = in.nextInt(); a[n] = 1 << 25; Arrays.sort(a); int X = Arrays.binarySearch(a, k); int c = 0; int l = n - 1; int tmp = 0; if (X < 0) { a[n] = k; Arrays.sort(a); c++; tmp++; l = n; X = Arrays.binarySearch(a, k); } int ans = 0; c = 0; int x = X; int left = x; int rigth = l - x; c += Math.abs(left - rigth); if (left < rigth) c--; ans = c + tmp; for (int i = X - 1; i > -1; i--) { if (a[i] == a[X]) { c = 0; x = i; left = x; rigth = l - x; c += Math.abs(left - rigth); if (left < rigth) c--; ans = Math.min(ans, c + tmp); } else break; } for (int i = X + 1; i <= l; i++) { if (a[i] == a[X]) { c = 0; x = i; left = x; rigth = l - x; c += Math.abs(left - rigth); if (left < rigth) c--; ans = Math.min(ans, c + tmp); } else break; } System.out.println(ans); } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
aad25b2949e5103a348d79a1654dc04c
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
import java.util.*; public class C { Scanner sc = new Scanner(System.in); void doIt() { int n = sc.nextInt(), x = sc.nextInt(); ArrayList<Integer> data = new ArrayList<Integer>(); for(int i = 0; i < n; i++) { data.add(sc.nextInt()); } int step = 0; for(step = 0; ; step++) { Collections.sort(data); //System.out.println(data); int mid = data.get((data.size() - 1) / 2); if(mid == x) break; data.add(x); } System.out.println(step); } public static void main(String[] args) { new C().doIt(); } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
9d8a4d563e5135d7988e2c2e7c885439
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
import java.util.*; import java.io.*; public class a { public static void main(String[] args) throws IOException { //input.init(System.in); Scanner input = new Scanner(System.in); int n = input.nextInt(), k = input.nextInt(); int less = 0, eq = 0, greater = 0; for(int i = 0; i<n; i++) { int x = input.nextInt(); if(x<k)less++; else if(x==k)eq++; else greater++; } int res = 0; while(true) { int pos = (less+eq+greater+1)/2; if(pos>less && pos<=less+eq) break; else { res++; eq++; } } System.out.println(res); } public static long gcd(long a, long b) { if(b == 0) return a; return gcd(b, a%b); } public static class input { 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 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 double nextDouble() throws IOException { return Double.parseDouble( next() ); } static long nextLong() throws IOException { return Long.parseLong( next() ); } } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
af21d793259d92bf7643ddcef58e484e
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class Solution { public static PrintWriter out; public static StreamTokenizer in; public static BufferedReader ins; static int nextInt() throws IOException { in.nextToken(); return (int)in.nval; } public static void main (String []args) throws IOException { out = new PrintWriter (new OutputStreamWriter (System.out)); ins = new BufferedReader (new InputStreamReader (System.in)); in = new StreamTokenizer (new BufferedReader (new InputStreamReader(System.in))); int n = nextInt(); int x = nextInt(); ArrayList < Integer > a = new ArrayList < Integer> (); for(int i = 0; i < n; ++i) { a.add(nextInt()); } int ans = 0; while(true) { int []arr = new int [a.size()]; for(int i = 0; i < a.size(); ++i) { arr[i] = a.get(i); } Arrays.sort(arr); if(arr[(arr.length - 1) / 2] == x) { System.out.println(ans); break; } a.add(x); ans = ans + 1; } } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
232568682562d6d7fb57f8840b69b4ef
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.*; public class C { private void solve() throws IOException { int n = nextInt(); int x = nextInt(); int[] a = new int[n]; boolean found = false; for (int i = 0; i < n; i++) { a[i] = nextInt(); if (a[i] == x) found = true; } int res = 0; int[] b = null; if (!found) { b = new int[n + 1]; for (int i = 0; i < a.length; i++) { b[i] = a[i]; } b[b.length - 1] = x; res++; } else { b = new int[n]; for (int i = 0; i < a.length; i++) { b[i] = a[i]; } } Arrays.sort(b); if (b.length == 2) { if (b[0] == x) { pl(res); return; } else if (b[1] >= x) { pl(res + 1); return; } } int index = -1; int index1 = -1; int index2 = -1; int c1 = 0; int c2 = 0; boolean found1 = false; boolean found2 = false; for (int i = (int) Math.floor((n + 1) / 2) - 1; i >= 0; i--) { if (b[i] == x) { index1 = i; found1 = true; break; } c1++; } for (int i = (int) Math.floor((n + 1) / 2) + 1; i < b.length; i++) { if (b[i] == x) { index2 = i; found2 = true; break; } c2++; } if (!found1) c1 = Integer.MAX_VALUE; if (!found2) c2 = Integer.MAX_VALUE; if (c1 < c2) index = index1; else if (c1 > c2) index = index2; else { pl(res); return; } index++; if (index != Math.floor((n + 1) / 2)) { int before = index - 1; int after = b.length - index; int dif = Math.abs(before - after); if (after < before) { if ((dif + b.length) % 2 == 0) pl(res + (dif - 1)); else pl(res + dif); } else if (after > before) { if ((dif + b.length) % 2 != 0) pl(res + (dif - 1)); else pl(res + dif); } else { pl(res); } return; } pl(res); } public static void main(String[] args) { new C().run(); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; public void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; writer = new PrintWriter(System.out); solve(); reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } BigInteger nextBigInteger() throws IOException { return new BigInteger(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } void p(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.flush(); writer.print(objects[i]); writer.flush(); } } void pl(Object... objects) { p(objects); writer.flush(); writer.println(); writer.flush(); } int cc; void pf() { writer.printf("Case #%d: ", ++cc); writer.flush(); } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
1a064deac1a2d9363274023421fe8164
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; public class B { public static void main( final String[] args ) throws Exception { final BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) ); String[] parts = br.readLine().split( " " ); final int n = Integer.parseInt( parts[0] ); final int x = Integer.parseInt( parts[1] ); parts = br.readLine().split( " " ); final int[] a = new int[ n ]; for ( int i = 0; i < n; i++ ) { a[i] = Integer.parseInt( parts[i] ); } System.out.println( solve( n, x, a ) ); } public static int solve( final int n, final int x, final int[] a ) { final ArrayList<Integer> list = new ArrayList<Integer>(); for ( final int ai : a ) { list.add( ai ); } Collections.sort( list ); int idx = Collections.binarySearch( list, x ); int cnt = 0; if ( idx < 0 ) { list.add( x ); Collections.sort( list ); idx = Collections.binarySearch( list, x ); ++cnt; } int med = ( list.size() + 1 ) / 2; while ( idx + 1 != med ) { if ( idx < med ) { list.add( 0, list.get( 0 ) ); } else { list.add( list.get( list.size() - 1 ) ); } idx = Collections.binarySearch( list, x ); ++cnt; med = ( list.size() + 1 ) / 2; } return cnt; } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
b9bbff54ec0dbda7439de72ac85ac725
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
import java.util.Scanner; public class Prob166C { public static void main(String[] Args) { Scanner in = new Scanner(System.in); int length = in.nextInt(); int required = in.nextInt(); int below = 0; int equals = 0; int above = 0; for (int i = 0; i < length; i++) { int x = in.nextInt(); if (x < required) below++; else if (x > required) above++; else equals++; } int answer = equals > 0 ? 0 : 1; if (above >= below) { above -= below; answer = Math.max(answer, above - equals); } else { below -= above; answer = Math.max(answer, below - equals + 1); } System.out.println(answer); } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
82a9afa6d23c1fbbfa3dc8c6266ffbf0
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
import java.util.*; import java.io.*; import java.math.BigInteger; public class C113B{ static BufferedReader br; public static void main(String args[])throws Exception{ br=new BufferedReader(new InputStreamReader(System.in)); int nm[]=toIntArray(); int n=nm[0]; int x=nm[1]; int nms[]=toIntArray(); boolean ok=false; for(int i=0;i<n;i++){ if(nms[i]==x){ ok=true; break; } } if(!ok){ nm=new int[n+1]; for(int i=0;i<n;i++){ nm[i]=nms[i]; } nm[n]=x; } else{ nm=new int[n]; for(int i=0;i<n;i++){ nm[i]=nms[i]; } } Arrays.sort(nm); int m=(nm.length+1)/2-1; if(nm[m]==x){ if(!ok) System.out.println("1"); else System.out.println("0"); return; } int ind=0; if(nm[m]<x){ for(int i=m+1;i<nm.length;i++){ if(nm[i]==x){ ind=i; break; } } int res=ind+1-(nm.length-ind); if(!ok) res++; System.out.println(res); } else{ for (int i = m - 1; i >= 0; i--) { if(nm[i]==x){ ind=i; break; } } int res=nm.length-1-ind-(ind+1); if(!ok)res++; System.out.println(res); } } /****************************************************************/ public static int[] toIntArray()throws Exception{ String str[]=br.readLine().split(" "); int k[]=new int[str.length]; for(int i=0;i<str.length;i++){ k[i]=Integer.parseInt(str[i]); } return k; } public static int toInt()throws Exception{ return Integer.parseInt(br.readLine()); } public static long[] toLongArray()throws Exception{ String str[]=br.readLine().split(" "); long k[]=new long[str.length]; for(int i=0;i<str.length;i++){ k[i]=Long.parseLong(str[i]); } return k; } public static long toLong()throws Exception{ return Long.parseLong(br.readLine()); } public static double[] toDoubleArray()throws Exception{ String str[]=br.readLine().split(" "); double k[]=new double[str.length]; for(int i=0;i<str.length;i++){ k[i]=Double.parseDouble(str[i]); } return k; } public static double toDouble()throws Exception{ return Double.parseDouble(br.readLine()); } public static String toStr()throws Exception{ return br.readLine(); } public static String[] toStrArray()throws Exception{ String str[]=br.readLine().split(" "); return str; } /****************************************************************/ }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
b423d00f0f47bef18a14c33c013d42f3
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class C { /** * @param args */ public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int k = scan.nextInt(); ArrayList<Integer> a = new ArrayList<Integer>(n); boolean f = false; for (int i = 0; i < n; i++) { a.add(scan.nextInt()); if (a.get(i) == k) f = true; } if (!f) { a.add(k); n++; } Collections.sort(a); int pos = Collections.binarySearch(a, k); int mid = ((n + 1) / 2) -1; if(pos > mid){ // System.out.println(pos+ (f? 0:1)); int x = 0 ; while(a.get(mid) != k) { a.add(0); mid = ((a.size() + 1) / 2) -1; x++; } System.out.println(x+(f? 0:1)); }else if(pos < mid){ // int x = n-1; // if((x & 1) == 0) // x--; // System.out.println(x+(f? 0:1)); int x = 0 ; while(a.get(mid) != k) { a.add(0, 0); mid = ((a.size() + 1) / 2) -1; x++; } System.out.println(x+(f? 0:1)); }else System.out.println(0+(f? 0:1)); } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
2fd6506963d6f5e3b61c46a568ce7521
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
import java.util.*; public class Main{ public static void main(String[] args){ Solver.solve(); } } class Solver{ public static void solve() { Scanner in = new Scanner(System.in); int n = in.nextInt(); int x = in.nextInt(); int[] p = new int[1111]; for (int i=0;i<n;i++) { p[i] = in.nextInt(); } int ans; for (int step = 0;;step++) { Arrays.sort(p,0,n); int check = p[((n + 1)/2) - 1]; if (check==x) { ans = step; break; } p[n] = x; ++n; } System.out.println(ans); } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
a136bc93b0c43b2f2675fabd65e879b9
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class C { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int old = n; int x = in.nextInt(); int less = 0; int more = 0; int equal = 0; for (int i = 0; i < n; i++) { int temp = in.nextInt(); if (temp < x) less++; else if (temp > x) more++; else equal++; } if (equal == 0) { equal++; n++; } int med = (n + 1) / 2; if (med > less) { while (true) { if (med <= equal + less) break; n++; less++; med = (n + 1) / 2; } } else { while (true) { if (med > less) break; n++; med = (n + 1) / 2; } } System.out.println(n - old); } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
007d39007c5d4eb9afd05ae1cddd914b
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
import java.io.*; import java.util.*; public class C113 implements Runnable { public StringTokenizer st; public BufferedReader in; public PrintWriter out; public static void main(String[] args) { new Thread(new C113()).start(); } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); solve(); } catch (Exception e) { e.printStackTrace(); System.exit(9000); } finally { out.flush(); out.close(); } } public String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } public int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws NumberFormatException, IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextToken()); } public static int lower_bound(ArrayList<Integer> list, int first, int last, int val) { int len = last - first; int half; int middle; while (len > 0) { half = len >>> 1; middle = first + half; if (list.get(middle) < val) { first = middle + 1; len = len - half - 1; } else len = half; } return first; } public static int upper_bound(ArrayList<Integer> list, int first, int last, int val) { int len = last - first; int half; int middle; while (len > 0) { half = len >>> 1; middle = first + half; if (val < list.get(middle)) len = half; else { first = middle + 1; len = len - half - 1; } } return first; } public void solve() throws NumberFormatException, IOException { int n = nextInt(), x = nextInt(); ArrayList<Integer> a = new ArrayList<Integer>(); for (int i = 0; i< n; i++) { a.add(nextInt()); } Collections.sort(a); int left = lower_bound(a, 0, a.size(), x); int right = upper_bound(a, 0, a.size(), x); //System.out.println(left + " " + right); if ((left < n && a.get(left) == x) && left+1 <= ((n+1) / 2) && ((n+1) / 2) < right+1) { out.print(0); //System.out.println("FIRST"); return; } int res = 0; if (right+1 <= ((n+1) / 2)) { while (right+1 <= ((n+1) / 2)) { right++; n++; res++; } out.print(res); //System.out.println("SECOND"); return; } if (left+1 > ((n+1) / 2)) { while (left+1 > ((n+1) / 2)) { n++; res++; } out.print(res); //System.out.println("THIRD"); return; } out.print(1); //System.out.println("FOURTH"); return; } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
5f31a0ca16a61debccdcffa71898f448
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
import static java.util.Arrays.sort; import java.io.*; import java.util.*; public class C { private static void solve() throws IOException { int n = nextInt(), x = nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } sort(a); int less = 0, greater = 0; for (int i : a) { if (i < x) { ++less; } if (i > x) { ++greater; } } int equal = n - less - greater; int answer = add(less, equal, greater); out.println(answer); } static int add(int less, int equal, int greater) { int answer = 0; while (less >= greater + equal || greater > less + equal) { answer++; equal++; } return answer; } public static void main(String[] args) { try { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } catch (Throwable e) { e.printStackTrace(); System.exit(239); } } static BufferedReader br; static StringTokenizer st; static PrintWriter out; static String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { String line = br.readLine(); if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(nextToken()); } static long nextLong() throws IOException { return Long.parseLong(nextToken()); } static double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
fc26e08d3331a520beddc53acc5e5d9a
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class CodeforcesRound113Div2 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int med = scan.nextInt(); int[] array = new int[n]; for (int i = 0; i < n; i++) array[i] = scan.nextInt(); Arrays.sort(array); int equal = 0; int less = 0; int great = 0; for (int i = 0; i < n; i++) if (array[i] == med) { equal++; } else if (array[i] < med) { less++; } else if (array[i] > med) { great++; } int answer=0; while(less>=great+equal||great>less+equal){ answer++; equal++; } System.out.println(answer); } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
96ad49530f21df676e40b566497112d1
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
import java.util.*; public class C{ public static void main(String[] args){ Scanner s = new Scanner(System.in); int n = s.nextInt(); int x = s.nextInt(); ArrayList<Integer> arr = new ArrayList<Integer>(); for(int i=0;i<n;i++){ arr.add(s.nextInt()); } Collections.sort(arr); int total=0; while(true){ int median = arr.get((arr.size()+1)/2 - 1); if(x == median){ break; }else{ arr.add(x); } Collections.sort(arr); total++; } System.out.println(total); } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
2d71207aa00b5a63d6d0309256d7e0b5
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.StringTokenizer; /** * 111118315581 * * -3 3 2 3 2 3 2 3 -3 3 -3 3 -3 3 2 3 * * @author pttrung */ public class C { public static long x, y, gcd; public static int Mod = 1000000007; public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(); PrintWriter out = new PrintWriter(System.out); // PrintWriter out = new PrintWriter(new FileOutputStream(new File("output.txt"))); int n = in.nextInt(); int x = in.nextInt(); ArrayList<Integer> list = new ArrayList(); boolean have = false; for (int i = 0; i < n; i++) { int a = in.nextInt(); list.add(a); if (a == x) { have = true; } } int result = 0; if (!have) { list.add(x); } Collections.sort(list); int mid = (list.size() + 1) / 2; int index = -1; for(int i = 0; i < list.size() ; i++){ if(list.get(i) == x){ if(index == -1){ index = i + 1; }else if(Math.abs(i + 1 - mid) < Math.abs(index - mid)){ index = i + 1; } } } boolean add = index < mid; while(index != mid){ result++; if(add ){ index++; } mid = (list.size() + 1 + result)/2; } out.println(result + (have ? 0 : 1)); out.close(); } public static int gcd(int a, int b) { if (b == 0) { return a; } return gcd(b, a % b); } public static void extendEuclid(long a, long b) { if (b == 0) { x = 1; y = 0; gcd = a; return; } extendEuclid(b, a % b); long x1 = y; long y1 = x - (a / b) * y; x = x1; y = y1; } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() throws FileNotFoundException { // System.setOut(new PrintStream(new BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("basketball_game.txt")))); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
0213302bf2498bc40dba8b640609b04b
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
import java.util.Scanner; public class P166C { public static void main(String[] args) { Scanner myScanner = new Scanner(System.in); int n = myScanner.nextInt(); int x = myScanner.nextInt(); int less = 0; int equal = 0; int greater = 0; int cursize = n; for (int i = 0; i < n; i++) { int next = myScanner.nextInt(); if (next < x) less++; else if (next > x) greater++; else equal++; } while (less + equal <= (cursize - 1)/2) { equal++; cursize++; } while (greater + equal <= cursize/2) { greater++; cursize++; } System.out.println(cursize - n); } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
ac7302e4f17149a3c596dd19f7737939
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
import java.util.Scanner; import java.util.TreeSet; public class ClassB { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(), x = in.nextInt(); int a = 0; int b = 0; for (int i = 0; i < n; ++i) { int t = in.nextInt(); if (t < x) a++; else if (t > x) b++; } int ans = 0; while (a >= (n + 1) / 2) { n++; ans++; } while (n - b < (n + 1) / 2) { n++; ans++; } if (a + b == n) { n++; ans++; } System.out.println(ans); } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
8595a9bdf484fcf2f4b08e612509615c
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws Exception { Scanner in = new Scanner(System.in); //Scanner in = new Scanner(new FileReader("Input")); PrintWriter out = new PrintWriter(System.out); Task solver = new Task(); int testCases = 1; for (int i = 1; i <= testCases; ++i) solver.solve(i, in, out); in.close(); out.close(); } } class Task { public void solve(int testNumber, Scanner in, PrintWriter out) { int res = 0; int n = in.nextInt(); int x = in.nextInt(); int[] array = new int[n]; for (int i = 0; i < n; ++i) array[i] = in.nextInt(); Arrays.sort(array); int left, right, index; index = Arrays.binarySearch(array, x); if (index < 0) { index = -(index + 1); left = index; right = index; ++n; ++res; while (!(left <= median(n) && median(n) <= right)) { ++n; ++right; ++res; } } else { left = index; right = index; while (left >= 0 && left < n && array[left] == x) --left; while (right >= 0 && right < n && array[right] == x) ++right; while (!(left < median(n) && median(n) < right)) { ++n; ++right; ++res; } } out.println(res); } public int median(int n) { return (n + 1) / 2 - 1; } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
5dac9bc8dd5e64f4453d185d06d30323
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class CF_166C { /** * @param args */ public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int x = in.nextInt(); int[] arr = new int[n]; for(int i = 0; i < n; i++) { arr[i] = in.nextInt(); } Arrays.sort(arr); int idx = 0; int res = 0; if(arr[0] > x) { idx = 0; n++; res++; } else if(arr[n-1] < x) { idx = n; } else { idx = ((n + 1) / 2) - 1; while(arr[idx] < x) { idx++; } while(arr[idx] > x) { idx--; } if(arr[idx] != x) { n++; res++; idx++; } } idx++; int bef = idx - 1; int aft = n - idx; if(aft < bef) { res += bef - aft; } else if (bef < aft) { res += aft - bef - 1; } System.out.println(res); } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
cd9c251f431338b7b88a653692e3ba03
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
//package round113; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; public class C { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(), x = ni(); int[] a = new int[n]; for(int i = 0;i < n;i++){ a[i] = ni(); } Arrays.sort(a); int m = (n-1)/2; if(a[m] == x){ out.println(0); }else{ int ind = Arrays.binarySearch(a, x); if(ind >= 0){ if(x < a[m]){ for(int i = n-1;i >= 0;i--){ if(a[i] == x){ for(int k = 1;;k++){ if(k+i == (n+k-1)/2){ out.println(k); return; } } } } }else{ for(int i = 0;i < n;i++){ if(a[i] == x){ for(int k = 1;;k++){ if(i == (n+k-1)/2){ out.println(k); return; } } } } } }else{ ind = -ind-1; if(x < a[m]){ for(int k = 0;;k++){ if(ind+k == (n+1+k-1)/2){ out.println(k+1); return; } } }else{ for(int k = 0;;k++){ if(ind == (n+1+k-1)/2){ out.println(k+1); return; } } } } } } 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(); } public int ni() { try { int num = 0; boolean minus = false; while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-')); if(num == '-'){ num = 0; minus = true; }else{ num -= '0'; } while(true){ int b = is.read(); if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } } } catch (IOException e) { } return -1; } public long nl() { try { long num = 0; boolean minus = false; while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-')); if(num == '-'){ num = 0; minus = true; }else{ num -= '0'; } while(true){ int b = is.read(); if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } } } catch (IOException e) { } return -1; } public String ns() { try{ int b = 0; StringBuilder sb = new StringBuilder(); while((b = is.read()) != -1 && (b == '\r' || b == '\n' || b == ' ')); if(b == -1)return ""; sb.append((char)b); while(true){ b = is.read(); if(b == -1)return sb.toString(); if(b == '\r' || b == '\n' || b == ' ')return sb.toString(); sb.append((char)b); } } catch (IOException e) { } return ""; } public char[] ns(int n) { char[] buf = new char[n]; try{ int b = 0, p = 0; while((b = is.read()) != -1 && (b == ' ' || b == '\r' || b == '\n')); if(b == -1)return null; buf[p++] = (char)b; while(p < n){ b = is.read(); if(b == -1 || b == ' ' || b == '\r' || b == '\n')break; buf[p++] = (char)b; } return Arrays.copyOf(buf, p); } catch (IOException e) { } return null; } double nd() { return Double.parseDouble(ns()); } boolean oj = System.getProperty("ONLINE_JUDGE") != null; void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
0bccdfa7908a5d17a2371a9af86d36d5
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class C { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = null; private void solve() throws IOException { int n = nextInt(); int x = nextInt(); int a[] = new int[1000000]; for(int i = 1; i <= n; i++) { a[i] = nextInt(); } int k = n; mergesort(a, 1, k); int counter = 0; while(true) { int m = (k + 1) / 2; if(a[m] > x || a[m] < x) { k++; for(int i = k; i > m; i--) { a[i] = a[i - 1]; } a[m] = x; mergesort(a, 1, k); counter++; } else { break; } } System.out.println(counter); } public static void mergesort(int[ ] data, int first, int n) { int n1; // Size of the first half of the array int n2; // Size of the second half of the array if (n > 1) { // Compute sizes of the two halves n1 = n / 2; n2 = n - n1; mergesort(data, first, n1); // Sort data[first] through data[first+n1-1] mergesort(data, first + n1, n2); // Sort data[first+n1] to the end // Merge the two sorted halves. merge(data, first, n1, n2); } } private static void merge(int[ ] data, int first, int n1, int n2) // Precondition: data has at least n1 + n2 components starting at data[first]. The first // n1 elements (from data[first] to data[first + n1 – 1] are sorted from smallest // to largest, and the last n2 (from data[first + n1] to data[first + n1 + n2 - 1]) are also // sorted from smallest to largest. // Postcondition: Starting at data[first], n1 + n2 elements of data // have been rearranged to be sorted from smallest to largest. // Note: An OutOfMemoryError can be thrown if there is insufficient // memory for an array of n1+n2 ints. { int[ ] temp = new int[n1+n2]; // Allocate the temporary array int copied = 0; // Number of elements copied from data to temp int copied1 = 0; // Number copied from the first half of data int copied2 = 0; // Number copied from the second half of data int i; // Array index to copy from temp back into data // Merge elements, copying from two halves of data to the temporary array. while ((copied1 < n1) && (copied2 < n2)) { if (data[first + copied1] < data[first + n1 + copied2]) temp[copied++] = data[first + (copied1++)]; else temp[copied++] = data[first + n1 + (copied2++)]; } // Copy any remaining entries in the left and right subarrays. while (copied1 < n1) temp[copied++] = data[first + (copied1++)]; while (copied2 < n2) temp[copied++] = data[first + n1 + (copied2++)]; // Copy from temp back to the data array. for (i = 0; i < n1+n2; i++) data[first + i] = temp[i]; } String nextToken() throws IOException { if (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(bf.readLine()); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } public static void main(String args[]) throws IOException { new C().solve(); } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
4332c4943e600ed40c5e481ffde06c4e
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
import java.util.*; import java.io.*; public class C{ public static void main(String args[]) { Scanner in = new Scanner(System.in); int n=in.nextInt(), key = in.nextInt(); int[] a = new int[1001]; for (int i=1;i<=n;i++) a[i]=in.nextInt(); for (int i=1;i<n;i++) for (int j = i+1;j<=n;j++) if (a[i]>a[j]) { int yed=a[i];a[i]=a[j];a[j]=yed; } int r = (n+1)/2,k=0,l=0,r1=0; for (int i=1;i<=n;i++) { if (a[i]==key && (k==0 || Math.abs(i-r) < Math.abs(k-r))) k = i; if (a[i]<key) l = i; } r = (n+1)/2; int ans=0; if (k==0) {k = l+1; n++; r = (n+1)/2;ans++;} while (k!=r) {n++;ans++;r = (n+1)/2;if (k<r) k++;}; System.out.println(ans); } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
4c5a8f780a7d3894afe6ac39d3ed382a
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.Arrays; import java.util.Enumeration; import java.util.Iterator; import java.util.Properties; /** * Works good for CF * @author cykeltillsalu */ public class Prac { //some local config static boolean test = false; static String testDataFile = "testdata.txt"; static String feedFile = "feed.txt"; CompetitionType type = CompetitionType.CF; private static String ENDL = "\n"; // solution private void solve() throws Throwable { int n = iread(), x = iread(); int[] r = new int[n]; for (int i = 0; i < n; i++) { r[i] = iread(); } Arrays.sort(r); int same = 0; int less = 0, greater = 0; for (int i = 0; i < r.length; i++) { if(r[i] < x){ less ++; } else if(r[i] == x){ same ++; } else { greater ++; } } int needed = 0; if( same == 0){ same ++; needed ++; } while(same > 1){ if(greater > less){ greater --; } else { less --; } same --; } int diff = Math.abs(greater - less); if(greater > less){ diff--; } System.out.println(diff + needed); out.flush(); } public int iread() throws Exception { return Integer.parseInt(wread()); } public double dread() throws Exception { return Double.parseDouble(wread()); } public long lread() throws Exception { return Long.parseLong(wread()); } public String wread() throws IOException { StringBuilder b = new StringBuilder(); int c; c = in.read(); while (c >= 0 && c <= ' ') c = in.read(); if (c < 0) return ""; while (c > ' ') { b.append((char) c); c = in.read(); } return b.toString(); } public static void main(String[] args) throws Throwable { if(test){ //run all cases from testfile: BufferedReader testdataReader = new BufferedReader(new FileReader(testDataFile)); String readLine = testdataReader.readLine(); int casenr = 0; out: while (true) { BufferedWriter w = new BufferedWriter(new FileWriter(feedFile)); if(!readLine.equalsIgnoreCase("input")){ break; } while (true) { readLine = testdataReader.readLine(); if(readLine.equalsIgnoreCase("output")){ break; } w.write(readLine + "\n"); } w.close(); System.out.println("Answer on case "+(++casenr)+": "); new Prac().solve(); System.out.println("Expected answer: "); while (true) { readLine = testdataReader.readLine(); if(readLine == null){ break out; } if(readLine.equalsIgnoreCase("input")){ break; } System.out.println(readLine); } System.out.println("----------------"); } testdataReader.close(); } else { // run on server new Prac().solve(); } out.close(); } public Prac() throws Throwable { if (test) { in = new BufferedReader(new FileReader(new File(feedFile))); } } InputStreamReader inp = new InputStreamReader(System.in); BufferedReader in = new BufferedReader(inp); static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); enum CompetitionType {CF, OTHER}; }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
bd0a4e549f9e42c73dac85f7f021e4e0
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class C { String line; StringTokenizer inputParser; BufferedReader is; FileInputStream fstream; DataInputStream in; String FInput=""; void openInput(String file) { if(file==null)is = new BufferedReader(new InputStreamReader(System.in));//stdin else { try{ fstream = new FileInputStream(file); in = new DataInputStream(fstream); is = new BufferedReader(new InputStreamReader(in)); }catch(Exception e) { System.err.println(e); } } } void readNextLine() { try { line = is.readLine(); inputParser = new StringTokenizer(line, " "); //System.err.println("Input: " + line); } catch (IOException e) { System.err.println("Unexpected IO ERROR: " + e); } } int NextInt() { String n = inputParser.nextToken(); int val = Integer.parseInt(n); //System.out.println("I read this number: " + val); return val; } String NextString() { String n = inputParser.nextToken(); return n; } void closeInput() { try { is.close(); } catch (IOException e) { System.err.println("Unexpected IO ERROR: " + e); } } public void readFInput() { for(;;) { try { readNextLine(); FInput+=line+" "; } catch(Exception e) { break; } } inputParser = new StringTokenizer(FInput, " "); } long NextLong() { String n = inputParser.nextToken(); long val = Long.parseLong(n); return val; } public static void main(String [] argv) { String filePath=null; if(argv.length>0)filePath=argv[0]; new C(filePath); } public C(String inputFile) { openInput(inputFile); int ret=0; readNextLine(); int n=NextInt(); int x=NextInt(); readNextLine(); int [] p =new int [n]; for(int i=0; i<n; i++) { p[i]=NextInt(); } Arrays.sort(p); int N=n; int id=(n+1)/2-1; if(p[id]<x) { while(id<n&&p[id]<x) { ret++; N++; if((N&1)==1)id++; } } else if(p[id]>x) { while(id>=0&&p[id]>x) { ret++; N++; if((N&1)==0)id--; } } System.out.println(ret); closeInput(); } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
f685f9b152892d345c3155b9f5ba6de6
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.util.Arrays; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Nova */ 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(); } } class TaskC { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int x = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = in.nextInt(); Arrays.sort(a); int lesser = 0; int equal = 0; for (int i = 0; i < n; i++) { if (a[i] < x) lesser++; if (a[i] == x) equal++; } int res = 0; if (equal == 0) { res++; equal++; n++; } while (!((lesser < (n + 1) / 2) && (lesser + equal >= (n + 1) / 2))) { if (lesser >= (n + 1) / 2) { n++; res++; } else { lesser++; n++; res++; } } out.println(res); } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); 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()); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(outputStream); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
64b2aca9ea5790dbc7480267c5a43647
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
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.Arrays; import java.util.Collections; import java.util.Locale; import java.util.StringTokenizer; public class C { private void solve() throws IOException { int n = nextInt(); int x = nextInt(); boolean f = false; ArrayList<Integer> a = new ArrayList<Integer>(10000); for (int i = 0; i < n; i++) { int t = nextInt(); a.add(t); if (t == x) { f = true; } } int res = 0; if (!f) { a.add(x); res++; } Collections.sort(a); int mid = a.get((a.size() - 1) / 2); while (mid != x) { if (mid < x) { a.add(1000000); } else { a.add(0, 0); } res++; mid = a.get((a.size() - 1) / 2); } println(res); } private String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } private int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextToken()); } private double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } private void print(Object o) { writer.print(o); } private void println(Object o) { writer.println(o); } private void printf(String format, Object... o) { writer.printf(format, o); } public static void main(String[] args) { long time = System.currentTimeMillis(); Locale.setDefault(Locale.US); new C().run(); System.err.printf("%.3f\n", 1e-3 * (System.currentTimeMillis() - time)); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; private void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); writer = new PrintWriter(System.out); solve(); reader.close(); writer.close(); } catch (IOException e) { e.printStackTrace(); System.exit(13); } } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
3eabfd23681b5403add3068f17c1b9e7
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; 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); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int ans = 0; int reqMedian = in.nextInt(); int[] A = new int[n]; for(int i = 0; i < n; i++) { A[i] = in.nextInt(); } if(find(A, reqMedian) == false) { int lessCount = countLess(A, reqMedian); int moreCount = countMore(A, reqMedian); if(lessCount < moreCount) ans = moreCount - lessCount; else ans = lessCount + 1 - moreCount; } else { int lessCount = countLess(A, reqMedian); int moreCount = countMore(A, reqMedian); int eqCount = countEqual(A, reqMedian); if(lessCount < moreCount && lessCount + eqCount < moreCount) { ans = moreCount - lessCount - eqCount; } if(moreCount < lessCount && moreCount + eqCount < lessCount + 1) { ans = lessCount - moreCount - eqCount + 1; } } out.println(ans); } public int countEqual(int[] A, int x) { int cnt = 0; for(int item : A) if(item == x) cnt++; return cnt; } public boolean find(int[] A, int x) { for(int item : A) if(item == x) return true; return false; } public int countLess(int[] A, int x) { int cnt = 0; for(int item : A) if(item < x) cnt++; return cnt; } public int countMore(int[] A, int x) { int cnt = 0; for(int item : A) if(item > x) cnt++; return cnt; } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); 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
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
f410ebb487a9f9989d07f07146f48038
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
import java.util.Arrays; import java.util.HashSet; /** * @author piuspratik (Piyush Das) */ public class TaskC { void run(){ int n = nextInt(), x = nextInt(); int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = nextInt(); Arrays.sort(a); int start = -1, end = n; for(int i = 0; i < n; i++) { if(a[i] < x) { start = Math.max(start, i); } if(a[i] > x) { end = Math.min(end, i); } } int ans = Integer.MAX_VALUE; for(int add = 0; add <= 2 * n; add++) { int median = (n + add + 1) / 2 - 1; int nend = end + add; if(median >= start + 1 && median <= nend - 1) { ans = Math.min(ans, add); } } System.out.println(ans); } int nextInt(){ try{ int c = System.in.read(); if(c == -1) return c; while(c != '-' && (c < '0' || '9' < c)){ c = System.in.read(); if(c == -1) return c; } if(c == '-') return -nextInt(); int res = 0; do{ res *= 10; res += c - '0'; c = System.in.read(); }while('0' <= c && c <= '9'); return res; }catch(Exception e){ return -1; } } long nextLong(){ try{ int c = System.in.read(); if(c == -1) return -1; while(c != '-' && (c < '0' || '9' < c)){ c = System.in.read(); if(c == -1) return -1; } if(c == '-') return -nextLong(); long res = 0; do{ res *= 10; res += c-'0'; c = System.in.read(); }while('0' <= c && c <= '9'); return res; }catch(Exception e){ return -1; } } double nextDouble(){ return Double.parseDouble(next()); } String next(){ try{ StringBuilder res = new StringBuilder(""); int c = System.in.read(); while(Character.isWhitespace(c)) c = System.in.read(); do{ res.append((char)c); }while(!Character.isWhitespace(c=System.in.read())); return res.toString(); }catch(Exception e){ return null; } } String nextLine(){ try{ StringBuilder res = new StringBuilder(""); int c = System.in.read(); while(c == '\r' || c == '\n') c = System.in.read(); do{ res.append((char)c); c = System.in.read(); }while(c != '\r' && c != '\n'); return res.toString(); }catch(Exception e){ return null; } } public static void main(String[] args){ new TaskC().run(); } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
cedfa23eef454fe455580a612bc3521a
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
import java.util.*; public class Median166C { public static void main(String[] args) { // Set up scanner Scanner sc = new Scanner(System.in); // System.out.println("Enter n"); int n = sc.nextInt(); // System.out.println("Enter x"); // The desired median-add if not there int x = sc.nextInt(); int answer = 0; boolean isthere = false; ArrayList<Integer> a = new ArrayList<Integer>(); for (int i=0; i<n; i++) { // System.out.println("Enter next value"); int y = sc.nextInt(); if (y == x) { isthere = true; } a.add(y); } if (isthere == false) { a.add(x); answer = 1; } Collections.sort(a); if (a.size() % 2 == 0) // Do all work if length even { int ptr = a.size()/2 - 1; if (a.get(ptr) == x) { System.out.println(answer); return; } if (a.get(ptr) < x) { int toadd = -1; while (a.get(ptr) < x) { ptr++; toadd+=2; } System.out.println(answer + toadd); return; } if (a.get(ptr) > x) { int toadd = 0; while (a.get(ptr) > x) { ptr--; toadd+=2; } System.out.println(answer + toadd); return; } } if (a.size() % 2 == 1) // Do all work if length odd { int ptr = a.size()/2; if (a.get(ptr) == x) { System.out.println(answer); return; } if (a.get(ptr) < x) { int toadd = 0; while (a.get(ptr) < x) { ptr++; toadd+=2; } System.out.println(answer + toadd); return; } if (a.get(ptr) > x) { int toadd = -1; while (a.get(ptr) > x) { ptr--; toadd+=2; } System.out.println(answer + toadd); return; } } } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
c6014453e167c448202e463245e435f1
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
import java.util.Arrays; import java.util.Scanner; import static java.lang.Math.*; public class c113 { public static void debug(Object... obs) { System.out.println(Arrays.deepToString(obs)); } public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); int n=sc.nextInt(); int oldn = n; int x=sc.nextInt(); int num[]=new int[n]; for(int i=0;i<n;i++) { num[i]=sc.nextInt(); } Arrays.sort(num); int mindif = Integer.MAX_VALUE; int at=-1; int med = (n+1)/2 - 1; for(int i=0;i<n;i++) { if(num[i]==x && Math.abs(i-med) < mindif) { mindif = Math.abs(i-med); at = i; } } //debug(mindif); int cnt=0; if(at == -1) { cnt++; int num2[]=new int[n+1]; System.arraycopy(num, 0, num2, 0, n); num2[n] = x; Arrays.sort(num2); n++; med = (n+1)/2 - 1; for(int i=0;i<n;i++) { if(num2[i]==x && Math.abs(i-med) < mindif) { mindif = Math.abs(i-med); at = i; } } } //debug(med,at); while(at != med) { if(at > med) { if(n%2==0) { med++; } } else { if(n%2!=0) { med--; } } //debug(med,at); n++; cnt++; } System.out.println(cnt); } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
988ded201974c83b1aa4b39c08f6d0c9
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class Solution { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); StringTokenizer st = new StringTokenizer(in.readLine()); int n = Integer.parseInt(st.nextToken()), x = Integer.parseInt(st.nextToken()); int[] a = new int[100500]; Arrays.fill(a, Integer.MAX_VALUE); st = new StringTokenizer(in.readLine()); for (int i = 0; i < n; i++) a[i] = Integer.parseInt(st.nextToken()); Arrays.sort(a); int rb = n - 1; int ans = 0; while (true) { int m = ((rb + 2) / 2) - 1; if (a[m] == x) break; ans++; int j = rb; while (j >= 0 && x < a[j]) { a[j + 1] = a[j]; a[j] = x; j--; } rb++; } out.println(ans); out.close(); } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
5bc64e68018185fbb82937c4707eb1c4
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
/** * Created by IntelliJ IDEA. * Date: 3/16/12 * Time: 6:30 PM * @author Andrew Porokhin, andrew.porokhin@gmail.com */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class ProblemC implements Runnable { void solve() throws NumberFormatException, IOException { // TODO: Write your code here ... final int n = nextInt(); final int k = nextInt(); final int[] c = new int[n]; final int m = (n+1)/2 - 1; for (int i = 0; i < n; i++) { c[i] = nextInt(); } Arrays.sort(c); // System.out.print("Insert " + k + " into: "); // System.out.println(Arrays.toString(c)); int index = Arrays.binarySearch(c, k); long insertSelf = 0; long l = 0; long r = 0; if (index >= 0) { int si = index; int ei = index; while (si > 0 && c[si - 1] == k) { si--; } while (ei < n - 1 && c[ei + 1] == k) { ei++; } if (m >= si) { if (m <= ei) { index = m; } else { index = ei; } } else { index = si; } // int ll = si; // int rr = n - ei - 1; // int kc = ei - si; l = index; r = n - l - 1; // System.out.printf("f: %d %d\n", l, r); // long max = l > r // ? l - r // : r - l - 1; // System.out.println(max); } else { l = (-index - 1); r = n - l; insertSelf = 1; // System.out.printf("nf: %d %d\n", l, r); // long max = l > r ? l - r : r - l; // System.out.println((n+max)%2==0 ? max : max + 1); } if (l > r) { System.out.println(insertSelf + l - r); } else if (r > l) { System.out.println(insertSelf + r - l - 1); } else { System.out.println(insertSelf); } } StringTokenizer st; BufferedReader in; PrintWriter out; public static void main(String[] args) { // Introduce thread in order to increase stack size new ProblemC().run(); } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); } catch (Exception e) { throw new RuntimeException(e); } finally { out.flush(); out.close(); } } String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextToken()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(nextToken()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextToken()); } static class Pair<T,V> { final T a; final V b; Pair(T a, V b) { this.a = a; this.b = b; } Pair<T,V> setA(T newA) { return new Pair<T,V>(newA, b); } Pair<T,V> setB(V newB) { return new Pair<T,V>(a, newB); } @Override public String toString() { return a.toString() + ", " + b.toString(); } } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
d05bad794d24ac41cf5919cebf4c86f4
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Test { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scan = new Scanner(System.in); int n=scan.nextInt(); int x=scan.nextInt(); int res=0; boolean isX=false; List<Integer> s= new ArrayList<Integer>(500); for(int i=0;i<n;i++){ int curr= scan.nextInt(); if(curr==x){ isX=true; } s.add(curr); } if(!isX){ s.add(x); res++; } java.util.Collections.sort(s); while( !s.get( (s.size()-1)/2 ).equals(x) ){ int size=s.size(); int curr=s.get( (size-1)/2 ); if(curr<x){ s.add(size,10000); } else s.add(0,1); res++; } System.out.println(res); } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
99f80cfc02bb6bb29171510822593fd5
train_002.jsonl
1332516600
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
256 megabytes
import java.util.*; import java.io.*; import java.awt.Point; import static java.lang.Math.*; public class P166C { public static void main(String[] args) throws Exception { Scanner in = new Scanner(System.in); int n = in.nextInt(); int x = in.nextInt(); List<Integer> L = new ArrayList<Integer>(); for(int i=0; i<n; i++) { L.add(in.nextInt()); } int ans = 0; while(median(L) != x) { //System.out.println(L+" "+median(L)); L.add(x); ans++; } System.out.println(ans); } public static int median(List<Integer> L) { Collections.sort(L); return L.get((L.size()+1)/2-1); } }
Java
["3 10\n10 20 30", "3 4\n1 2 3"]
2 seconds
["1", "4"]
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Java 6
standard input
[ "sortings", "greedy", "math" ]
1a73bda2b9c2038d6ddf39918b90da61
The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
1,500
Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.
standard output
PASSED
6d37ef3bdaa2f6babb795a231b609b73
train_002.jsonl
1600526100
This is the hard version of the problem. The difference between the versions is that in the easy version all prices $$$a_i$$$ are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All $$$n$$$ ice spheres are placed in a row and they are numbered from $$$1$$$ to $$$n$$$ from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered.
256 megabytes
import java.util.*; import java.io.*; public class Main { static class Scan { private byte[] buf=new byte[1024]; private int index; private InputStream in; private int total; public Scan() { in=System.in; } public int scan()throws IOException { if(total<0) throw new InputMismatchException(); if(index>=total) { index=0; total=in.read(buf); if(total<=0) return -1; } return buf[index++]; } public int scanInt()throws IOException { 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(); } else throw new InputMismatchException(); } return neg*integer; } public double scanDouble()throws IOException { double doub=0; int n=scan(); while(isWhiteSpace(n)) n=scan(); int neg=1; if(n=='-') { neg=-1; n=scan(); } while(!isWhiteSpace(n)&&n!='.') { if(n>='0'&&n<='9') { doub*=10; doub+=n-'0'; n=scan(); } else throw new InputMismatchException(); } if(n=='.') { n=scan(); double temp=1; while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { temp/=10; doub+=(n-'0')*temp; n=scan(); } else throw new InputMismatchException(); } } return doub*neg; } public String scanString()throws IOException { StringBuilder sb=new StringBuilder(); int n=scan(); while(isWhiteSpace(n)) n=scan(); while(!isWhiteSpace(n)) { sb.append((char)n); n=scan(); } return sb.toString(); } private boolean isWhiteSpace(int n) { if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1) return true; return false; } } public static void sort(int arr[],int l,int r) { //sort(arr,0,n-1); if(l==r) { return; } int mid=(l+r)/2; sort(arr,l,mid); sort(arr,mid+1,r); merge(arr,l,mid,mid+1,r); } public static void merge(int arr[],int l1,int r1,int l2,int r2) { int tmp[]=new int[r2-l1+1]; int indx1=l1,indx2=l2; //sorting the two halves using a tmp array for(int i=0;i<tmp.length;i++) { if(indx1>r1) { tmp[i]=arr[indx2]; indx2++; continue; } if(indx2>r2) { tmp[i]=arr[indx1]; indx1++; continue; } if(arr[indx1]<arr[indx2]) { tmp[i]=arr[indx1]; indx1++; continue; } tmp[i]=arr[indx2]; indx2++; } //Copying the elements of tmp into the main array for(int i=0,j=l1;i<tmp.length;i++,j++) { arr[j]=tmp[i]; } } public static void sort(long arr[],int l,int r) { //sort(arr,0,n-1); if(l==r) { return; } int mid=(l+r)/2; sort(arr,l,mid); sort(arr,mid+1,r); merge(arr,l,mid,mid+1,r); } public static void merge(long arr[],int l1,int r1,int l2,int r2) { long tmp[]=new long[r2-l1+1]; int indx1=l1,indx2=l2; //sorting the two halves using a tmp array for(int i=0;i<tmp.length;i++) { if(indx1>r1) { tmp[i]=arr[indx2]; indx2++; continue; } if(indx2>r2) { tmp[i]=arr[indx1]; indx1++; continue; } if(arr[indx1]<arr[indx2]) { tmp[i]=arr[indx1]; indx1++; continue; } tmp[i]=arr[indx2]; indx2++; } //Copying the elements of tmp into the main array for(int i=0,j=l1;i<tmp.length;i++,j++) { arr[j]=tmp[i]; } } public static void main(String args[]) throws IOException { Scan input=new Scan(); StringBuilder ans=new StringBuilder(""); int n=input.scanInt(); int arr[]=new int[n]; for(int i=0;i<n;i++) { arr[i]=input.scanInt(); } sort(arr,0,n-1); int indx1=0,indx2=n-1; int fin[]=new int[n]; for(int i=0;i<n;i++) { if(i%2==0) { fin[i]=arr[indx2]; indx2--; } else { fin[i]=arr[indx1]; indx1++; } } indx1=1; indx2=n-1; if(indx2%2==0) { indx2--; } for(int i=indx1,j=indx2;i<j;i+=2,j-=2) { int tmp=fin[i]; fin[i]=fin[j]; fin[j]=tmp; } indx1=1; indx2=n-1; if(indx2%2==0) { indx2--; } if(indx2==n-1) { for(int i=1;i<n-1;i++) { if((fin[i]==fin[i-1] || fin[i]==fin[i+1]) && (fin[indx2]!=fin[i-1] && fin[indx2]!=fin[i+1])) { int tmp=fin[indx2]; fin[indx2]=fin[i]; fin[i]=tmp; break; } } } for(int i=0;i<n;i++) { ans.append(fin[i]+" "); } int cnt=0; for(int i=1;i<n-1;i++) { if(fin[i]<fin[i-1] && fin[i]<fin[i+1]) { cnt++; } } System.out.println(cnt+"\n"+ans); } }
Java
["7\n1 3 2 2 4 5 4"]
1 second
["3\n3 1 4 2 4 2 5"]
NoteIn the sample it's not possible to place the ice spheres in any order so that Sage would buy $$$4$$$ of them. If the spheres are placed in the order $$$(3, 1, 4, 2, 4, 2, 5)$$$, then Sage will buy one sphere for $$$1$$$ and two spheres for $$$2$$$ each.
Java 11
standard input
[ "greedy", "constructive algorithms", "two pointers", "sortings", "binary search", "brute force" ]
6443dffb38285b6deb74f2371d8d0cac
The first line contains a single integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ — the number of ice spheres in the shop. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — the prices of ice spheres.
1,500
In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them.
standard output
PASSED
80a7174f87e1c9e67744e3c14347e2a8
train_002.jsonl
1600526100
This is the hard version of the problem. The difference between the versions is that in the easy version all prices $$$a_i$$$ are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All $$$n$$$ ice spheres are placed in a row and they are numbered from $$$1$$$ to $$$n$$$ from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered.
256 megabytes
import java.io.*; import java.util.*; public class Codeforces { public static void main(String args[])throws Exception { BufferedReader bu=new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb=new StringBuilder(); int n=Integer.parseInt(bu.readLine()); String s[]=bu.readLine().split(" "); int i,ans=0; Integer a[]=new Integer[n]; //cant hack me this time for(i=0;i<n;i++) a[i]=Integer.parseInt(s[i]); Arrays.sort(a); int b[]=new int[n],j=0; i=n-1; while(j<n) { b[j]=a[i]; j+=2; i--; } j=1; while(j<n) { b[j]=a[i]; j+=2; i--; } if(n%2==0 && n>2) { if(!(b[1]<b[0] && b[1]<b[2])) { int tem=b[n-1]; b[n-1]=b[1]; b[1]=tem; } } for(i=1;i<n-1;i++) if(b[i]<b[i-1] && b[i]<b[i+1]) ans++; sb.append(ans+"\n"); for(i=0;i<n;i++) sb.append(b[i]+" "); System.out.print(sb); } }
Java
["7\n1 3 2 2 4 5 4"]
1 second
["3\n3 1 4 2 4 2 5"]
NoteIn the sample it's not possible to place the ice spheres in any order so that Sage would buy $$$4$$$ of them. If the spheres are placed in the order $$$(3, 1, 4, 2, 4, 2, 5)$$$, then Sage will buy one sphere for $$$1$$$ and two spheres for $$$2$$$ each.
Java 11
standard input
[ "greedy", "constructive algorithms", "two pointers", "sortings", "binary search", "brute force" ]
6443dffb38285b6deb74f2371d8d0cac
The first line contains a single integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ — the number of ice spheres in the shop. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — the prices of ice spheres.
1,500
In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them.
standard output
PASSED
911c7dbe56f6e60673ea9f7e3e784535
train_002.jsonl
1600526100
This is the hard version of the problem. The difference between the versions is that in the easy version all prices $$$a_i$$$ are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All $$$n$$$ ice spheres are placed in a row and they are numbered from $$$1$$$ to $$$n$$$ from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; public class Solution_1419D2 { private static final long MODULO = 1_000_000_007L; //prime modulo public static void main(String[] args) { try { Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); int n = in.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = in.nextInt(); } if (arr.length <= 2) { System.out.println(0); System.out.println(listToStr(arr)); return; } Arrays.sort(arr); int baseLen = arr.length % 2 == 0 ? arr.length / 2 : arr.length - arr.length / 2; List<Integer> lst = new ArrayList<>(); int largeStart = arr.length - 1; lst.add(arr[largeStart]); largeStart--; List<Integer> remainders = new ArrayList<>(); int count = 0; for (int i = arr.length - baseLen - 1; i >= 0; i--) { int a = arr[i]; if (largeStart >= arr.length - baseLen && a < lst.get(lst.size() - 1) && a < arr[largeStart]) { count += 1; lst.add(a); lst.add(arr[largeStart]); largeStart--; } else { remainders.add(a); } } for (; largeStart >= arr.length - baseLen; largeStart--) { lst.add(arr[largeStart]); } System.out.println(count); List<Integer> l = new ArrayList<>(lst); l.addAll(remainders); System.out.println(listToStr(l)); } catch (Exception e) { System.err.println(e.getMessage()); e.printStackTrace(); } } public static String listToStr(List<Integer> l) { StringBuilder str = new StringBuilder(); for (int i = 0; i < l.size(); i++) { if (i != 0) { str.append(" "); } str.append(l.get(i)); } return str.toString(); } public static String listToStr(int[] l) { StringBuilder str = new StringBuilder(); for (int i = 0; i < l.length; i++) { if (i != 0) { str.append(" "); } str.append(l[i]); } return str.toString(); } public static String arrToStr(int[][] arr) { StringBuilder str = new StringBuilder(); for (int[] ints : arr) { String s = Arrays.toString(ints).replace(",", ""); str.append("\n").append(s.substring(1, s.length() - 1)); } return str.toString(); } static long exponentiation(long base, long exp) { long t = 1L; while (exp > 0) { if (exp % 2 != 0) { t = (t * base) % MODULO; } base = (base * base) % MODULO; exp /= 2; } return t % MODULO; } }
Java
["7\n1 3 2 2 4 5 4"]
1 second
["3\n3 1 4 2 4 2 5"]
NoteIn the sample it's not possible to place the ice spheres in any order so that Sage would buy $$$4$$$ of them. If the spheres are placed in the order $$$(3, 1, 4, 2, 4, 2, 5)$$$, then Sage will buy one sphere for $$$1$$$ and two spheres for $$$2$$$ each.
Java 11
standard input
[ "greedy", "constructive algorithms", "two pointers", "sortings", "binary search", "brute force" ]
6443dffb38285b6deb74f2371d8d0cac
The first line contains a single integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ — the number of ice spheres in the shop. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — the prices of ice spheres.
1,500
In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them.
standard output
PASSED
fe84e517bf3aa4dad4ab6a4bd86215e9
train_002.jsonl
1600526100
This is the hard version of the problem. The difference between the versions is that in the easy version all prices $$$a_i$$$ are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All $$$n$$$ ice spheres are placed in a row and they are numbered from $$$1$$$ to $$$n$$$ from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Random; import java.util.StringTokenizer; public class D { public static void main(String[] args) { FastScanner fs=new FastScanner(); //int T=fs.nextInt(); for (int tt=0; tt<1; tt++) { int n=fs.nextInt(); int[] a=fs.readArray(n); ruffleSort(a); ArrayList<Integer> fin=new ArrayList<>(); int nr=n/2,pos=0; for(int i=nr;i<n-1;i++) { fin.add(a[i]); if(a[i]>a[pos] && a[i+1]>a[pos]) { fin.add(a[pos]); pos++; } } fin.add(a[n-1]); int last=a[n-1]; while(pos<nr && last>a[pos] && a[nr-1]>a[pos]) { last=a[nr-1]; fin.add(a[pos++]); fin.add(a[nr---1]); } for(int i=pos; i<nr; i++) fin.add(a[i]); System.out.println(pos); for(int i=0; i<n; i++) { System.out.print(fin.get(i)+" "); } } } static final Random random=new Random(); static void ruffleSort(int[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n), temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["7\n1 3 2 2 4 5 4"]
1 second
["3\n3 1 4 2 4 2 5"]
NoteIn the sample it's not possible to place the ice spheres in any order so that Sage would buy $$$4$$$ of them. If the spheres are placed in the order $$$(3, 1, 4, 2, 4, 2, 5)$$$, then Sage will buy one sphere for $$$1$$$ and two spheres for $$$2$$$ each.
Java 11
standard input
[ "greedy", "constructive algorithms", "two pointers", "sortings", "binary search", "brute force" ]
6443dffb38285b6deb74f2371d8d0cac
The first line contains a single integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ — the number of ice spheres in the shop. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — the prices of ice spheres.
1,500
In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them.
standard output
PASSED
2799a550351173d8421656f4b2c563d8
train_002.jsonl
1600526100
This is the hard version of the problem. The difference between the versions is that in the easy version all prices $$$a_i$$$ are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All $$$n$$$ ice spheres are placed in a row and they are numbered from $$$1$$$ to $$$n$$$ from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class C { public static void main(String[] args) { FastScanner sc = new FastScanner(); int n = sc.nextInt(); int a[] = sc.readArray(n); int b[] = new int[n]; int k = 0; Arrays.sort(a); for(int i = 1 ; i < n ; i+= 2) { b[i] = a[k++]; System.out.println(); } for(int i = 0 ; i < n ; i+= 2) { b[i] = a[k++]; } int count = 0; for(int p = 1 ;p < n ;p++) { if(p+1 < n) { if(b[p] < b[p-1] && b[p] < b[p +1]) { count++; } } } System.out.println(count); for(int item : b) { System.out.print(item + " "); } } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); public String next() { while (!st.hasMoreElements()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } public long nextLong() {return Long.parseLong(next());} public double nextDouble() {return Double.parseDouble(next());} int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } } }
Java
["7\n1 3 2 2 4 5 4"]
1 second
["3\n3 1 4 2 4 2 5"]
NoteIn the sample it's not possible to place the ice spheres in any order so that Sage would buy $$$4$$$ of them. If the spheres are placed in the order $$$(3, 1, 4, 2, 4, 2, 5)$$$, then Sage will buy one sphere for $$$1$$$ and two spheres for $$$2$$$ each.
Java 11
standard input
[ "greedy", "constructive algorithms", "two pointers", "sortings", "binary search", "brute force" ]
6443dffb38285b6deb74f2371d8d0cac
The first line contains a single integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ — the number of ice spheres in the shop. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — the prices of ice spheres.
1,500
In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them.
standard output
PASSED
3fcd66455bb9c2909a0fc609e290c74c
train_002.jsonl
1600526100
This is the hard version of the problem. The difference between the versions is that in the easy version all prices $$$a_i$$$ are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All $$$n$$$ ice spheres are placed in a row and they are numbered from $$$1$$$ to $$$n$$$ from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered.
256 megabytes
import java.io.*; import java.util.*; import static java.util.Collections.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class cf { private static final int MOD = (int) (1e9 + 7), MOD_FFT = 998244353; private static final Reader r = new Reader(); private static final PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); private static final boolean thread = false; static final boolean HAS_TEST_CASES = false; static final int SCAN_LINE_LENGTH = 1000002; static int n, a[], e[][]; private static Vector<Integer> adj[], v = new Vector<>(); static void solve() throws Exception { int n = ni(); a = na(n); sort(a); int b[] = new int[n]; for (int i = 0, j = (n) / 2, k = 0; k < n; k++) { if (k % 2 == 0) b[k] = a[j++]; else b[k] = a[i++]; } int ans = 0; for (int k = 1; k < b.length - 1; k++) { if (b[k - 1] > b[k] && b[k] < b[k + 1]) ans++; } pn(ans); for (int i : b) { p(i + " "); } pn(); } public static void main(final String[] args) throws Exception { if (!thread) { final int testcases = HAS_TEST_CASES ? ni() : 1; for (int i = 1; i <= testcases; i++) { // pni(i + " t"); // out.print("Case #" + (i + 1) + ": "); try { solve(); } catch (final Exception e) { // pni("idk Exception"); // e.printStackTrace(System.err); // System.exit(0); throw e; } } out.flush(); } r.close(); out.close(); } private static void swap(final int i, final int j) { final int temp = a[i]; a[i] = a[j]; a[j] = temp; } private static boolean isMulOverflow(final long A, final long B) { if (A == 0 || B == 0) return false; final long result = A * B; if (A == result / B) return true; return false; } private static int gcd(final int a, final int b) { if (b == 0) return a; return gcd(b, a % b); } private static class Pair<T, E> implements Comparable<Pair<T, E>> { T fir; E snd; Pair() { } Pair(final T x, final E y) { this.fir = x; this.snd = y; } @Override @SuppressWarnings("unchecked") public int compareTo(final Pair<T, E> o) { final int c = ((Comparable<T>) fir).compareTo(o.fir); return c != 0 ? c : ((Comparable<E>) snd).compareTo(o.snd); } } private static class pi implements Comparable<pi> { int fir, snd; pi() { } pi(final int a, final int b) { fir = a; snd = b; } public int compareTo(final pi o) { return fir == o.fir ? snd - o.snd : fir - o.fir; } } private static <T> void checkV(final Vector<T> adj[], final int i) { adj[i] = adj[i] == null ? new Vector<>() : adj[i]; } private static int[] na(final int n) throws Exception { final int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = ni(); } return a; } private static int[] na1(final int n) throws Exception { final int[] a = new int[n + 1]; for (int i = 1; i < a.length; i++) { a[i] = ni(); } return a; } private static String n() throws IOException { return r.readToken(); } private static String nln() throws IOException { return r.readLine(); } private static int ni() throws IOException { return r.nextInt(); } private static long nl() throws IOException { return r.nextLong(); } private static double nd() throws IOException { return r.nextDouble(); } private static void p(final Object o) { out.print(o); } private static void pn(final Object o) { out.println(o); } private static void pn() { out.println(""); } private static void pi(final Object o) { out.print(o); out.flush(); } private static void pni() { out.println(""); out.flush(); } private static void pni(final Object o) { out.println(o); out.flush(); } private static class Reader { private final int BUFFER_SIZE = 1 << 17; private final DataInputStream din; private final byte[] buffer; private int bufferPointer, bytesRead; // private StringTokenizer st; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(final String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } final byte[] buf = new byte[SCAN_LINE_LENGTH]; public String readLine() throws IOException { int cnt = 0; int c; o: while ((c = read()) != -1) { if (c == '\n') if (cnt == 0) continue o; else break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public String readToken() throws IOException { int cnt = 0; int c; o: while ((c = read()) != -1) { if (!(c >= 33 && c <= 126)) if (cnt == 0) continue o; else 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(); final 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(); final 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(); final boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } static { if (thread) new Thread(null, new Runnable() { @Override public void run() { try { final int testcases = HAS_TEST_CASES ? ni() : 1; for (int i = 1; i <= testcases; i++) { // out.print("Case #" + (i + 1) + ": "); try { solve(); } catch (final ArrayIndexOutOfBoundsException e) { e.printStackTrace(System.err); System.exit(-1); } catch (final Exception e) { pni("idk Exception in solve"); e.printStackTrace(System.err); System.exit(-1); } } out.flush(); } catch (final Throwable t) { t.printStackTrace(System.err); System.exit(-1); } } }, "rec", (1L << 28)).start(); } @SuppressWarnings({ "unchecked", }) private static <T> T deepCopy(final T old) { try { return (T) deepCopyObject(old); } catch (final IOException | ClassNotFoundException e) { e.printStackTrace(System.err); System.exit(-1); } return null; } private static Object deepCopyObject(final Object oldObj) throws IOException, ClassNotFoundException { ObjectOutputStream oos = null; ObjectInputStream ois = null; try { final ByteArrayOutputStream bos = new ByteArrayOutputStream(); // A oos = new ObjectOutputStream(bos); // B // serialize and pass the object oos.writeObject(oldObj); // C oos.flush(); // D final ByteArrayInputStream bin = new ByteArrayInputStream(bos.toByteArray()); // E ois = new ObjectInputStream(bin); // F // return the new object return ois.readObject(); // G } catch (final ClassNotFoundException e) { pni("Exception in ObjectCloner = " + e); throw (e); } finally { oos.close(); ois.close(); } } }
Java
["7\n1 3 2 2 4 5 4"]
1 second
["3\n3 1 4 2 4 2 5"]
NoteIn the sample it's not possible to place the ice spheres in any order so that Sage would buy $$$4$$$ of them. If the spheres are placed in the order $$$(3, 1, 4, 2, 4, 2, 5)$$$, then Sage will buy one sphere for $$$1$$$ and two spheres for $$$2$$$ each.
Java 11
standard input
[ "greedy", "constructive algorithms", "two pointers", "sortings", "binary search", "brute force" ]
6443dffb38285b6deb74f2371d8d0cac
The first line contains a single integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ — the number of ice spheres in the shop. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — the prices of ice spheres.
1,500
In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them.
standard output
PASSED
a8bf2041f8875cc8ea6f4faffc1f9763
train_002.jsonl
1600526100
This is the hard version of the problem. The difference between the versions is that in the easy version all prices $$$a_i$$$ are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All $$$n$$$ ice spheres are placed in a row and they are numbered from $$$1$$$ to $$$n$$$ from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered.
256 megabytes
//package hiougyf; import java.io.*; import java.util.*; import java.util.Map.Entry; public class Solution { public static void main(String[] args){ Scanner sc =new Scanner(System.in); int n=sc.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) { a[i]=sc.nextInt(); } Arrays.sort(a); int j=0; int b[]=new int[n]; for(int i=0;i<n;i++) { if(i%2!=0) { b[i]=a[j]; j++; } } //j=n-1; for(int i=0;i<n;i++) { if(b[i]==0) { b[i]=a[j]; j++; } } int ans=0; for(int i=1;i<n-1;i++) { if(b[i]<b[i+1]&&b[i]<b[i-1]) ans++; } System.out.println(ans); for(int jj:b)System.out.print(jj+" "); } public static int floorSqrt(int x) { // Base Cases if (x == 0 || x == 1) return x; // Do Binary Search for floor(sqrt(x)) int start = 1, end = x, ans=0; while (start <= end) { int mid = (start + end) / 2; // If x is a perfect square if (mid*mid == x) return mid; // Since we need floor, we update answer when mid*mid is // smaller than x, and move closer to sqrt(x) if (mid*mid < x) { start = mid + 1; ans = mid; } else // If mid*mid is greater than x end = mid-1; } return ans; } static int div(int n,int b) { int g=-1; for(int i=2;i<=Math.sqrt(n);i++) { if(n%i==0&&i!=b) { g=i; break; } } return g; } public static int gcd(int a, int b) { if (a == 0) return b; return gcd(b%a, a); } public static int lcm(int a, int b) { return (a*b)/gcd(a, b); } public static boolean isPrime1(int n) { if (n <= 1) { return false; } if (n == 2) { return true; } for (int i = 2; i <= Math.sqrt(n) + 1; i++) { if (n % i == 0) { return false; } } return true; } public static boolean isPrime(int n) { if (n <= 1) { return false; } if (n == 2) { return true; } if (n % 2 == 0) { return false; } for (int i = 3; i <= Math.sqrt(n) + 1; i = i + 2) { if (n % i == 0) { return false; } } return true; } }
Java
["7\n1 3 2 2 4 5 4"]
1 second
["3\n3 1 4 2 4 2 5"]
NoteIn the sample it's not possible to place the ice spheres in any order so that Sage would buy $$$4$$$ of them. If the spheres are placed in the order $$$(3, 1, 4, 2, 4, 2, 5)$$$, then Sage will buy one sphere for $$$1$$$ and two spheres for $$$2$$$ each.
Java 11
standard input
[ "greedy", "constructive algorithms", "two pointers", "sortings", "binary search", "brute force" ]
6443dffb38285b6deb74f2371d8d0cac
The first line contains a single integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ — the number of ice spheres in the shop. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — the prices of ice spheres.
1,500
In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them.
standard output
PASSED
bdf72050395e3471e3691b1e345434ac
train_002.jsonl
1600526100
This is the hard version of the problem. The difference between the versions is that in the easy version all prices $$$a_i$$$ are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All $$$n$$$ ice spheres are placed in a row and they are numbered from $$$1$$$ to $$$n$$$ from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered.
256 megabytes
//package hiougyf; import java.io.*; import java.util.*; import java.util.Map.Entry; public class Solution { public static void main(String[] args){ Scanner sc =new Scanner(System.in); int n=sc.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) { a[i]=sc.nextInt(); } Arrays.sort(a); int j=0; int b[]=new int[n]; for(int i=0;i<n;i++) { if(i%2!=0) { b[i]=a[j]; j++; } } j=n-1; for(int i=n-1;i>=0;i--) { if(b[i]==0) { b[i]=a[j]; j--; } } int ans=0; for(int i=1;i<n-1;i++) { if(b[i]<b[i+1]&&b[i]<b[i-1]) ans++; } System.out.println(ans); for(int jj:b)System.out.print(jj+" "); } public static int floorSqrt(int x) { // Base Cases if (x == 0 || x == 1) return x; // Do Binary Search for floor(sqrt(x)) int start = 1, end = x, ans=0; while (start <= end) { int mid = (start + end) / 2; // If x is a perfect square if (mid*mid == x) return mid; // Since we need floor, we update answer when mid*mid is // smaller than x, and move closer to sqrt(x) if (mid*mid < x) { start = mid + 1; ans = mid; } else // If mid*mid is greater than x end = mid-1; } return ans; } static int div(int n,int b) { int g=-1; for(int i=2;i<=Math.sqrt(n);i++) { if(n%i==0&&i!=b) { g=i; break; } } return g; } public static int gcd(int a, int b) { if (a == 0) return b; return gcd(b%a, a); } public static int lcm(int a, int b) { return (a*b)/gcd(a, b); } public static boolean isPrime1(int n) { if (n <= 1) { return false; } if (n == 2) { return true; } for (int i = 2; i <= Math.sqrt(n) + 1; i++) { if (n % i == 0) { return false; } } return true; } public static boolean isPrime(int n) { if (n <= 1) { return false; } if (n == 2) { return true; } if (n % 2 == 0) { return false; } for (int i = 3; i <= Math.sqrt(n) + 1; i = i + 2) { if (n % i == 0) { return false; } } return true; } }
Java
["7\n1 3 2 2 4 5 4"]
1 second
["3\n3 1 4 2 4 2 5"]
NoteIn the sample it's not possible to place the ice spheres in any order so that Sage would buy $$$4$$$ of them. If the spheres are placed in the order $$$(3, 1, 4, 2, 4, 2, 5)$$$, then Sage will buy one sphere for $$$1$$$ and two spheres for $$$2$$$ each.
Java 11
standard input
[ "greedy", "constructive algorithms", "two pointers", "sortings", "binary search", "brute force" ]
6443dffb38285b6deb74f2371d8d0cac
The first line contains a single integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ — the number of ice spheres in the shop. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — the prices of ice spheres.
1,500
In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them.
standard output
PASSED
962f4ba9e9c687891a212f4d70275dfb
train_002.jsonl
1600526100
This is the hard version of the problem. The difference between the versions is that in the easy version all prices $$$a_i$$$ are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All $$$n$$$ ice spheres are placed in a row and they are numbered from $$$1$$$ to $$$n$$$ from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered.
256 megabytes
import java.util.*; public class A{ public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int a[]=new int [n]; for(int i=0;i<n;i++) { a[i]=sc.nextInt(); } Arrays.parallelSort(a); int b[]=new int[n]; int j=0; for(int i=1;i<n;i+=2) { b[i]=a[j++]; } for(int i=0;i<n;i+=2) { b[i]=a[j++]; } int count=0; for(int i=1;i<n-1;i++) { if(b[i]<b[i+1]&&b[i]<b[i-1]) { count++; } } System.out.println(count); for(int i:b) { System.out.print(i+" "); } System.out.println(); } }
Java
["7\n1 3 2 2 4 5 4"]
1 second
["3\n3 1 4 2 4 2 5"]
NoteIn the sample it's not possible to place the ice spheres in any order so that Sage would buy $$$4$$$ of them. If the spheres are placed in the order $$$(3, 1, 4, 2, 4, 2, 5)$$$, then Sage will buy one sphere for $$$1$$$ and two spheres for $$$2$$$ each.
Java 11
standard input
[ "greedy", "constructive algorithms", "two pointers", "sortings", "binary search", "brute force" ]
6443dffb38285b6deb74f2371d8d0cac
The first line contains a single integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ — the number of ice spheres in the shop. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — the prices of ice spheres.
1,500
In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them.
standard output
PASSED
b6ea180e2e586463a74ece363f717d7c
train_002.jsonl
1589707200
You are given a string $$$s$$$ such that each its character is either 1, 2, or 3. You have to choose the shortest contiguous substring of $$$s$$$ such that it contains each of these three characters at least once.A contiguous substring of string $$$s$$$ is a string that can be obtained from $$$s$$$ by removing some (possibly zero) characters from the beginning of $$$s$$$ and some (possibly zero) characters from the end of $$$s$$$.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class daniel { public static void main(String args[])throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); OutputStream out=new BufferedOutputStream(System.out); int t=Integer.parseInt(br.readLine()); while(t-->0) { char a[]=br.readLine().toCharArray(); int l=a.length; int ans = Integer.MAX_VALUE; int z[]=new int[4]; int start = 0; int end=0; int q=0; for(;end<l;end++) { int c=a[end]-'0'; if(z[c]==0) q++; z[c]++; if(q==3) { if(ans>end-start+1) ans=end-start+1; for(;start<=end;start++) { int c1=a[start]-'0'; if(z[c1]==1) { z[c1]=0; q--; start++; break; } else { if(ans>end-start) ans=end-start; z[c1]--; } } } //System.out.print(b); } if(ans== Integer.MAX_VALUE) ans=0; System.out.println(ans); } }}
Java
["7\n123\n12222133333332\n112233\n332211\n12121212\n333333\n31121"]
2 seconds
["3\n3\n4\n4\n0\n0\n4"]
NoteConsider the example test:In the first test case, the substring 123 can be used.In the second test case, the substring 213 can be used.In the third test case, the substring 1223 can be used.In the fourth test case, the substring 3221 can be used.In the fifth test case, there is no character 3 in $$$s$$$.In the sixth test case, there is no character 1 in $$$s$$$.In the seventh test case, the substring 3112 can be used.
Java 8
standard input
[ "dp", "two pointers", "implementation", "binary search" ]
6cb06a02077750327602a1a7eeac770f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 20000$$$) — the number of test cases. Each test case consists of one line containing the string $$$s$$$ ($$$1 \le |s| \le 200000$$$). It is guaranteed that each character of $$$s$$$ is either 1, 2, or 3. The sum of lengths of all strings in all test cases does not exceed $$$200000$$$.
1,200
For each test case, print one integer — the length of the shortest contiguous substring of $$$s$$$ containing all three types of characters at least once. If there is no such substring, print $$$0$$$ instead.
standard output
PASSED
455536ac1a99e8bc57cab9d139eec681
train_002.jsonl
1589707200
You are given a string $$$s$$$ such that each its character is either 1, 2, or 3. You have to choose the shortest contiguous substring of $$$s$$$ such that it contains each of these three characters at least once.A contiguous substring of string $$$s$$$ is a string that can be obtained from $$$s$$$ by removing some (possibly zero) characters from the beginning of $$$s$$$ and some (possibly zero) characters from the end of $$$s$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int tst = Integer.parseInt(br.readLine()); ArrayList<pair> lst = new ArrayList<>(); StringBuilder sb = new StringBuilder(""); int len = 0; while(--tst>=0){ lst.clear(); String s = br.readLine(); lst.add(new pair(s.charAt(0), 1)); for(int i = 1; i<s.length(); i++){ len = lst.size(); if(lst.get(len-1).x != s.charAt(i)){ lst.add(new pair(s.charAt(i), 1)); } else lst.get(len-1).n++; } len = lst.size(); int ans = Integer.MAX_VALUE; for(int i = 1; i<len-1; i++){ if(lst.get(i-1).x != lst.get(i+1).x){ int m = lst.get(i).n+2; if(ans>m) ans = m; } } if(ans == Integer.MAX_VALUE) sb.append(0).append('\n'); else sb.append(ans).append('\n'); } System.out.println(sb); } } class pair{ char x; int n; pair(char x, int n){ this.x = x; this.n = n; } }
Java
["7\n123\n12222133333332\n112233\n332211\n12121212\n333333\n31121"]
2 seconds
["3\n3\n4\n4\n0\n0\n4"]
NoteConsider the example test:In the first test case, the substring 123 can be used.In the second test case, the substring 213 can be used.In the third test case, the substring 1223 can be used.In the fourth test case, the substring 3221 can be used.In the fifth test case, there is no character 3 in $$$s$$$.In the sixth test case, there is no character 1 in $$$s$$$.In the seventh test case, the substring 3112 can be used.
Java 8
standard input
[ "dp", "two pointers", "implementation", "binary search" ]
6cb06a02077750327602a1a7eeac770f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 20000$$$) — the number of test cases. Each test case consists of one line containing the string $$$s$$$ ($$$1 \le |s| \le 200000$$$). It is guaranteed that each character of $$$s$$$ is either 1, 2, or 3. The sum of lengths of all strings in all test cases does not exceed $$$200000$$$.
1,200
For each test case, print one integer — the length of the shortest contiguous substring of $$$s$$$ containing all three types of characters at least once. If there is no such substring, print $$$0$$$ instead.
standard output
PASSED
ff0d274d1b9a55b3fa38356efdba7ada
train_002.jsonl
1589707200
You are given a string $$$s$$$ such that each its character is either 1, 2, or 3. You have to choose the shortest contiguous substring of $$$s$$$ such that it contains each of these three characters at least once.A contiguous substring of string $$$s$$$ is a string that can be obtained from $$$s$$$ by removing some (possibly zero) characters from the beginning of $$$s$$$ and some (possibly zero) characters from the end of $$$s$$$.
256 megabytes
import java.util.*; import java.io.*; import java.math.BigInteger; public class Solution { static class Pair<A,B> { A parent; B rank; Pair(A parent,B rank) { this.rank=rank; this.parent=parent; } } static class Node{ int left; int right; Node(int l,int r) { left=l; right=r; } } static int m=1000000007; public static void main (String[] args) throws IOException { StringBuilder sb = new StringBuilder(); FastReader s1 = new FastReader(); int t=s1.I(); while(t--!=0) { char ar[] = s1.next().toCharArray(); int n=ar.length; HashMap<Character,Integer> hm = new HashMap<>(); int l=0; int r=0; int ans=Integer.MAX_VALUE; while(true) { // System.out.println(hm+" "+r+" "+l); if(hm.size()!=3 && r<n) { hm.putIfAbsent(ar[r], 0); hm.replace(ar[r],hm.get(ar[r])+1); r++; // System.out.println("here1 "); } if(hm.size()==3) { int len=r-l; if(len<ans) ans=len; hm.replace(ar[l], hm.get(ar[l])-1); if(hm.get(ar[l])==0) hm.remove(ar[l]); l++; if(l>r) r=l; // System.out.println("here2 "+l+" "+r); } if(hm.size()<3 && r>=n) break; } if(ans!=Integer.MAX_VALUE) sb.append(ans+"\n"); else sb.append(0+"\n"); /* 3 122223331 32323221 11111111222222222223*/ } System.out.println(sb); } static long computeXOR(long n) { if (n % 4 == 0) return n; if (n % 4 == 1) return 1; if (n % 4 == 2) return n + 1; return 0; } static ArrayList<Integer> primeFactor(int n) { ArrayList<Integer> ans = new ArrayList<>(); if(n%2==0) ans.add(2); while (n%2==0) { n /= 2; } for (int i = 3; i <= Math.sqrt(n); i+= 2) { if(n%i==0) ans.add(i); while (n%i == 0) { n /= i; } } if (n > 2) ans.add(n); return ans; } 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 I() { return Integer.parseInt(next()); } long L() { return Long.parseLong(next()); } double D() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static long gcd(long a,long b) { if(a%b==0) return b; return gcd(b,a%b); } static float power(float x, int y) { float temp; if( y == 0) return 1; temp = power(x, y/2); if (y%2 == 0) return temp*temp; else { if(y > 0) return x * temp * temp; else return (temp * temp) / x; } } static long pow(long x, long y) { int p = 1000000007; long res = 1; x = x % p; if(x<0) x+=p; while (y > 0) { if((y & 1)==1){ res = (res * x) % p; if(res<0) res+=p; } y = y >> 1; x = (x * x) % p; } return res; } static void sieveOfEratosthenes(int n) { ArrayList<Integer> prime=new ArrayList<Integer>(); boolean Prime[] = new boolean[n+1]; for(int i=2;i<n;i++) Prime[i] = true; for(int p = 2; p*p <=n; p++) { if(Prime[p] == true) { prime.add(p); for(int i = p*p; i <= n; i += p) Prime[i] = false; } } } }
Java
["7\n123\n12222133333332\n112233\n332211\n12121212\n333333\n31121"]
2 seconds
["3\n3\n4\n4\n0\n0\n4"]
NoteConsider the example test:In the first test case, the substring 123 can be used.In the second test case, the substring 213 can be used.In the third test case, the substring 1223 can be used.In the fourth test case, the substring 3221 can be used.In the fifth test case, there is no character 3 in $$$s$$$.In the sixth test case, there is no character 1 in $$$s$$$.In the seventh test case, the substring 3112 can be used.
Java 8
standard input
[ "dp", "two pointers", "implementation", "binary search" ]
6cb06a02077750327602a1a7eeac770f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 20000$$$) — the number of test cases. Each test case consists of one line containing the string $$$s$$$ ($$$1 \le |s| \le 200000$$$). It is guaranteed that each character of $$$s$$$ is either 1, 2, or 3. The sum of lengths of all strings in all test cases does not exceed $$$200000$$$.
1,200
For each test case, print one integer — the length of the shortest contiguous substring of $$$s$$$ containing all three types of characters at least once. If there is no such substring, print $$$0$$$ instead.
standard output
PASSED
987d6c685738d0f2511df94b70752f7c
train_002.jsonl
1589707200
You are given a string $$$s$$$ such that each its character is either 1, 2, or 3. You have to choose the shortest contiguous substring of $$$s$$$ such that it contains each of these three characters at least once.A contiguous substring of string $$$s$$$ is a string that can be obtained from $$$s$$$ by removing some (possibly zero) characters from the beginning of $$$s$$$ and some (possibly zero) characters from the end of $$$s$$$.
256 megabytes
import java.io.BufferedOutputStream; import java.io.PrintWriter; import java.util.Scanner; public class TernaryString { public static void main(String[] args) { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int t = in.nextInt(); for (int i = 0; i < t; i++) { solve(i, in, out); } in.close(); out.close(); } public static void solve(int testNumber, Scanner in, PrintWriter out) { String s = in.next(); int inf = 2000000; int one = inf; int two = inf; int three = inf; int answer = inf; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '1') { one = i; } if (s.charAt(i) == '2') { two = i; } if (s.charAt(i) == '3') { three = i; } answer = Math.min(answer, Math.max(one, Math.max(two, three)) - Math.min(one, Math.min(two, three)) + 1); } out.println(answer > 200000 ? 0 : answer); } }
Java
["7\n123\n12222133333332\n112233\n332211\n12121212\n333333\n31121"]
2 seconds
["3\n3\n4\n4\n0\n0\n4"]
NoteConsider the example test:In the first test case, the substring 123 can be used.In the second test case, the substring 213 can be used.In the third test case, the substring 1223 can be used.In the fourth test case, the substring 3221 can be used.In the fifth test case, there is no character 3 in $$$s$$$.In the sixth test case, there is no character 1 in $$$s$$$.In the seventh test case, the substring 3112 can be used.
Java 8
standard input
[ "dp", "two pointers", "implementation", "binary search" ]
6cb06a02077750327602a1a7eeac770f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 20000$$$) — the number of test cases. Each test case consists of one line containing the string $$$s$$$ ($$$1 \le |s| \le 200000$$$). It is guaranteed that each character of $$$s$$$ is either 1, 2, or 3. The sum of lengths of all strings in all test cases does not exceed $$$200000$$$.
1,200
For each test case, print one integer — the length of the shortest contiguous substring of $$$s$$$ containing all three types of characters at least once. If there is no such substring, print $$$0$$$ instead.
standard output
PASSED
998e394c7c41bbafd7fe9ecc12868679
train_002.jsonl
1443430800
Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area. Advertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no empty space left. When you put a logo on the billboard, you should rotate it so that the sides were parallel to the sides of the billboard.Your task is to determine if it is possible to put the logos of all the three companies on some square billboard without breaking any of the described rules.
256 megabytes
import java.util.Scanner; public class billboard { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int a1 = sc.nextInt(); int a2 = sc.nextInt(); if (a1>a2) { int d = a1; a1 = a2; a2 = d; } int b1 = sc.nextInt(); int b2 = sc.nextInt(); if (b1>b2) { int e = b1; b1 = b2; b2 = e; } int c1 = sc.nextInt(); int c2 = sc.nextInt(); if (c1>c2) { int f = c1; c1 = c2; c2 = f; } if (a1==b1 && b1==c1 && (a1==a2+b2+c2)) { System.out.println(a2+b2+c2); for (int i=0;i<a2;i++) { for (int j=0;j<a1;j++) {System.out.print("A");} System.out.println(); } for (int i=0;i<b2;i++) { for (int j=0;j<a1;j++) {System.out.print("B");} System.out.println(); } for (int i=0;i<c2;i++) { for (int j=0;j<a1;j++) {System.out.print("C");} System.out.println(); } } else if (a1==b1 && b1==c2 && (a1==a2+b2+c1)) { System.out.println(a2+b2+c1); for (int i=0;i<a2;i++) { for (int j=0;j<a1;j++) {System.out.print("A");} System.out.println(); } for (int i=0;i<b2;i++) { for (int j=0;j<a1;j++) {System.out.print("B");} System.out.println(); } for (int i=0;i<c1;i++) { for (int j=0;j<a1;j++) {System.out.print("C");} System.out.println(); } } else if (a1==b2 && b2==c1 && (a1==a2+b1+c2)) { System.out.println(a2+b1+c2); for (int i=0;i<a2;i++) { for (int j=0;j<a1;j++) {System.out.print("A");} System.out.println(); } for (int i=0;i<b1;i++) { for (int j=0;j<a1;j++) {System.out.print("B");} System.out.println(); } for (int i=0;i<c2;i++) { for (int j=0;j<a1;j++) {System.out.print("C");} System.out.println(); } } else if (a1==b2 && b2==c2 && (a1==a2+b1+c1)) { System.out.println(a2+b1+c1); for (int i=0;i<a2;i++) { for (int j=0;j<a1;j++) {System.out.print("A");} System.out.println(); } for (int i=0;i<b1;i++) { for (int j=0;j<a1;j++) {System.out.print("B");} System.out.println(); } for (int i=0;i<c1;i++) { for (int j=0;j<a1;j++) {System.out.print("C");} System.out.println(); } } else if (a2==b1 && b1==c1 && (a2==a1+b2+c2)) { System.out.println(a1+b2+c2); for (int i=0;i<a1;i++) { for (int j=0;j<a2;j++) {System.out.print("A");} System.out.println(); } for (int i=0;i<b2;i++) { for (int j=0;j<a2;j++) {System.out.print("B");} System.out.println(); } for (int i=0;i<c2;i++) { for (int j=0;j<a2;j++) {System.out.print("C");} System.out.println(); } } else if (a2==b1 && b1==c2 && (a2==a1+b2+c1)) { System.out.println(a1+b2+c1); for (int i=0;i<a1;i++) { for (int j=0;j<a2;j++) {System.out.print("A");} System.out.println(); } for (int i=0;i<b2;i++) { for (int j=0;j<a2;j++) {System.out.print("B");} System.out.println(); } for (int i=0;i<c1;i++) { for (int j=0;j<a2;j++) {System.out.print("C");} System.out.println(); } } else if (a2==b2 && b2==c1 && (a2==a1+b1+c2)) { System.out.println(a1+b1+c2); for (int i=0;i<a1;i++) { for (int j=0;j<a2;j++) {System.out.print("A");} System.out.println(); } for (int i=0;i<b1;i++) { for (int j=0;j<a2;j++) {System.out.print("B");} System.out.println(); } for (int i=0;i<c2;i++) { for (int j=0;j<a2;j++) {System.out.print("C");} System.out.println(); } } else if (a2==b2 && b2==c2 && (a2==a1+b1+c1)) { System.out.println(a1+b1+c1); for (int i=0;i<a1;i++) { for (int j=0;j<a2;j++) {System.out.print("A");} System.out.println(); } for (int i=0;i<b1;i++) { for (int j=0;j<a2;j++) {System.out.print("B");} System.out.println(); } for (int i=0;i<c1;i++) { for (int j=0;j<a2;j++) {System.out.print("C");} System.out.println(); } } else if ((b1==c1 && b2+c2==a2 && b1+a1==a2) || (b2==c2 && b1+c1==a2 && b2+a1==a2) || (b1==c2 && b2+c1==a2 && b1+a1==a2) || (b2==c1 && b1+c2==a2 && b2+a1==a2)) { int temp = 0; if (b1 == c2) { temp = c1; c1 = c2; c2 = temp; } else if (b2 == c1) { temp = b2; b2 = b1; b1 = temp; } else if (b2 == c2) { temp = c1; c1 = c2; c2 = temp; temp = b2; b2 = b1; b1 = temp; } if (b2+c2 == a2) { temp = a2; a2 = a1; a1 = temp; } System.out.println(a2+b1); for (int i=0;i<a2;i++) { for (int j=0;j<a1;j++) { System.out.print("A"); } System.out.println(); } for (int i=0;i<b1;i++) { for (int j=0;j<b2;j++) { System.out.print("B"); } for (int k=0;k<c2;k++) { System.out.print("C"); } System.out.println(); } } else { int temp = 0; temp = b1; b1 = a1; a1 = temp; temp = b2; b2=a2;a2=temp; if ((b1==c1 && b2+c2==a2 && b1+a1==a2) || (b2==c2 && b1+c1==a2 && b2+a1==a2) || (b1==c2 && b2+c1==a2 && b1+a1==a2) || (b2==c1 && b1+c2==a2 && b2+a1==a2)) { if (b1 == c2) { temp = c1; c1 = c2; c2 = temp; } else if (b2 == c1) { temp = b2; b2 = b1; b1 = temp; } else if (b2 == c2) { temp = c1; c1 = c2; c2 = temp; temp = b2; b2 = b1; b1 = temp; } if (b2+c2 == a2) { temp = a2; a2 = a1; a1 = temp; } System.out.println(a2+b1); for (int i=0;i<a2;i++) { for (int j=0;j<a1;j++) { System.out.print("B"); } System.out.println(); } for (int i=0;i<b1;i++) { for (int j=0;j<b2;j++) { System.out.print("A"); } for (int k=0;k<c2;k++) { System.out.print("C"); } System.out.println(); } } else { temp=c1;c1=a1;a1=temp;temp=c2;c2=a2;a2=temp; if ((b1==c1 && b2+c2==a2 && b1+a1==a2) || (b2==c2 && b1+c1==a2 && b2+a1==a2) || (b1==c2 && b2+c1==a2 && b1+a1==a2) || (b2==c1 && b1+c2==a2 && b2+a1==a2)) { if (b1 == c2) { temp = c1; c1 = c2; c2 = temp; } else if (b2 == c1) { temp = b2; b2 = b1; b1 = temp; } else if (b2 == c2) { temp = c1; c1 = c2; c2 = temp; temp = b2; b2 = b1; b1 = temp; } if (b2+c2 == a2) { temp = a2; a2 = a1; a1 = temp; } System.out.println(a2+b1); for (int i=0;i<a2;i++) { for (int j=0;j<a1;j++) { System.out.print("C"); } System.out.println(); } for (int i=0;i<b1;i++) { for (int j=0;j<b2;j++) { System.out.print("A"); } for (int k=0;k<c2;k++) { System.out.print("B"); } System.out.println(); } } else {System.out.println(-1);} } } } }
Java
["5 1 2 5 5 2", "4 4 2 6 4 2"]
1 second
["5\nAAAAA\nBBBBB\nBBBBB\nCCCCC\nCCCCC", "6\nBBBBBB\nBBBBBB\nAAAACC\nAAAACC\nAAAACC\nAAAACC"]
null
Java 7
standard input
[ "geometry", "constructive algorithms", "bitmasks", "math", "implementation", "brute force" ]
2befe5da2df57d23934601cbe4d4f151
The first line of the input contains six positive integers x1, y1, x2, y2, x3, y3 (1 ≤ x1, y1, x2, y2, x3, y3 ≤ 100), where xi and yi determine the length and width of the logo of the i-th company respectively.
1,700
If it is impossible to place all the three logos on a square shield, print a single integer "-1" (without the quotes). If it is possible, print in the first line the length of a side of square n, where you can place all the three logos. Each of the next n lines should contain n uppercase English letters "A", "B" or "C". The sets of the same letters should form solid rectangles, provided that: the sizes of the rectangle composed from letters "A" should be equal to the sizes of the logo of the first company, the sizes of the rectangle composed from letters "B" should be equal to the sizes of the logo of the second company, the sizes of the rectangle composed from letters "C" should be equal to the sizes of the logo of the third company, Note that the logos of the companies can be rotated for printing on the billboard. The billboard mustn't have any empty space. If a square billboard can be filled with the logos in multiple ways, you are allowed to print any of them. See the samples to better understand the statement.
standard output
PASSED
1c12a1701220557c6becc9285b25755c
train_002.jsonl
1443430800
Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area. Advertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no empty space left. When you put a logo on the billboard, you should rotate it so that the sides were parallel to the sides of the billboard.Your task is to determine if it is possible to put the logos of all the three companies on some square billboard without breaking any of the described rules.
256 megabytes
import java.util.*; public class D581 { public static void main(String[] args) { Scanner input = new Scanner(System.in); int[] xs = new int[3], ys = new int[3]; for(int i = 0; i<3; i++) { xs[i] = input.nextInt(); ys[i] = input.nextInt(); if(xs[i] > ys[i]) { int temp = xs[i]; xs[i] = ys[i]; ys[i] = temp; } } int max = Math.max(Math.max(ys[0], ys[1]), ys[2]); int tot = xs[0]*ys[0]+xs[1]*ys[1]+xs[2]*ys[2]; if(max*max != tot) System.out.println(-1); else { boolean[] used = new boolean[3]; int row = 0; char[][] res = new char[max][max]; for(int i = 0; i<3; i++) { if(ys[i] == max) { used[i] = true; for(int j = 0; j<xs[i]; j++) for(int k = 0; k<max; k++) { res[row+j][k] = (char)('A'+i); } row += xs[i]; } } int left = max - row; int col = 0; for(int i = 0; i<3; i++) { if(used[i]) continue; for(int j = row; j<max; j++) for(int k = 0; k<(ys[i] + xs[i] - left); k++) { res[j][k+col] = (char)('A'+i); } col += ys[i] + xs[i] - left; } System.out.println(max); for(int i = 0; i<max; i++) System.out.println(new String(res[i])); } } }
Java
["5 1 2 5 5 2", "4 4 2 6 4 2"]
1 second
["5\nAAAAA\nBBBBB\nBBBBB\nCCCCC\nCCCCC", "6\nBBBBBB\nBBBBBB\nAAAACC\nAAAACC\nAAAACC\nAAAACC"]
null
Java 7
standard input
[ "geometry", "constructive algorithms", "bitmasks", "math", "implementation", "brute force" ]
2befe5da2df57d23934601cbe4d4f151
The first line of the input contains six positive integers x1, y1, x2, y2, x3, y3 (1 ≤ x1, y1, x2, y2, x3, y3 ≤ 100), where xi and yi determine the length and width of the logo of the i-th company respectively.
1,700
If it is impossible to place all the three logos on a square shield, print a single integer "-1" (without the quotes). If it is possible, print in the first line the length of a side of square n, where you can place all the three logos. Each of the next n lines should contain n uppercase English letters "A", "B" or "C". The sets of the same letters should form solid rectangles, provided that: the sizes of the rectangle composed from letters "A" should be equal to the sizes of the logo of the first company, the sizes of the rectangle composed from letters "B" should be equal to the sizes of the logo of the second company, the sizes of the rectangle composed from letters "C" should be equal to the sizes of the logo of the third company, Note that the logos of the companies can be rotated for printing on the billboard. The billboard mustn't have any empty space. If a square billboard can be filled with the logos in multiple ways, you are allowed to print any of them. See the samples to better understand the statement.
standard output
PASSED
e8ae0898ffd31d7106f4879e3a1fda37
train_002.jsonl
1443430800
Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area. Advertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no empty space left. When you put a logo on the billboard, you should rotate it so that the sides were parallel to the sides of the billboard.Your task is to determine if it is possible to put the logos of all the three companies on some square billboard without breaking any of the described rules.
256 megabytes
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.util.ArrayList; import java.util.Collections; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { InputStream inputStream = System.in; OutputStream outputStream = System.out; BufferedWriter out = new BufferedWriter(new OutputStreamWriter( outputStream, "ASCII")); CustomScanner sc = new CustomScanner(inputStream); solve(sc, out); out.flush(); out.close(); } static class Logo implements Comparable<Logo> { char c; int x, y; public Logo(char c, int x, int y) { this.c=c; if (x<y) { this.x=y; this.y=x; } else { this.x=x; this.y=y; } } @Override public int compareTo(Logo l) { if (x==l.x) return l.y-y; return l.x-x; } } static void solve(CustomScanner sc, BufferedWriter out) throws IOException { ArrayList<Logo> list = new ArrayList<>(3); for (int i=0; i<3; i++) list.add(new Logo((char)('A'+i), sc.nextInt(), sc.nextInt())); Collections.sort(list); Logo l1 = list.get(0); Logo l2 = list.get(1); Logo l3 = list.get(2); if (l2.x + l3.x == l1.x && l2.y==l3.y && l2.y+l1.y==l1.x) { // Print out.write(Integer.toString(l1.x)); out.newLine(); for (int i=0; i<l1.y; i++) { for (int j=0; j<l1.x; j++) out.write(l1.c); out.newLine(); } for (int i=0; i<l2.y; i++) { for (int j=0; j<l2.x; j++) out.write(l2.c); for (int j=0; j<l3.x; j++) out.write(l3.c); out.newLine(); } } else if (l2.x == l1.x && l1.x==l3.x && l1.y+l2.y+l3.y==l1.x) { // Print out.write(Integer.toString(l1.x)); out.newLine(); for (int i=0; i<l1.y; i++) { for (int j=0; j<l1.x; j++) out.write(l1.c); out.newLine(); } for (int i=0; i<l2.y; i++) { for (int j=0; j<l2.x; j++) out.write(l2.c); out.newLine(); } for (int i=0; i<l3.y; i++) { for (int j=0; j<l3.x; j++) out.write(l3.c); out.newLine(); } } else if (l2.x+l3.y==l1.x && l2.y==l3.x && l1.y+l2.y==l1.x) { // Print out.write(Integer.toString(l1.x)); out.newLine(); for (int i=0; i<l1.y; i++) { for (int j=0; j<l1.x; j++) out.write(l1.c); out.newLine(); } for (int i=0; i<l2.y; i++) { for (int j=0; j<l2.x; j++) out.write(l2.c); for (int j=0; j<l3.y; j++) out.write(l3.c); out.newLine(); } } else if (l2.y+l3.x==l1.x && l2.x==l3.y && l1.y+l2.x==l1.x) { // Print out.write(Integer.toString(l1.x)); out.newLine(); for (int i=0; i<l1.y; i++) { for (int j=0; j<l1.x; j++) out.write(l1.c); out.newLine(); } for(int i=0; i<l2.x; i++) { for (int j=0; j<l2.y; j++) out.write(l2.c); for (int j=0; j>l3.x; j++) out.write(l3.c); out.newLine(); } } else if (l2.y+l3.y==l1.x && l2.x==l3.x && l1.y+l2.x==l1.x) { // Print out.write(Integer.toString(l1.x)); out.newLine(); for (int i=0; i<l1.y; i++) { for (int j=0; j<l1.x; j++) out.write(l1.c); out.newLine(); } for (int i=0; i<l2.x; i++) { for (int j=0; j<l2.y; j++) out.write(l2.c); for (int j=0; j<l3.y; j++) out.write(l3.c); out.newLine(); } } else out.write("-1"); out.newLine(); } static class CustomScanner { BufferedReader br; StringTokenizer st; public CustomScanner(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); } private String next() { while (st == null || !st.hasMoreElements()) { 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 double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5 1 2 5 5 2", "4 4 2 6 4 2"]
1 second
["5\nAAAAA\nBBBBB\nBBBBB\nCCCCC\nCCCCC", "6\nBBBBBB\nBBBBBB\nAAAACC\nAAAACC\nAAAACC\nAAAACC"]
null
Java 7
standard input
[ "geometry", "constructive algorithms", "bitmasks", "math", "implementation", "brute force" ]
2befe5da2df57d23934601cbe4d4f151
The first line of the input contains six positive integers x1, y1, x2, y2, x3, y3 (1 ≤ x1, y1, x2, y2, x3, y3 ≤ 100), where xi and yi determine the length and width of the logo of the i-th company respectively.
1,700
If it is impossible to place all the three logos on a square shield, print a single integer "-1" (without the quotes). If it is possible, print in the first line the length of a side of square n, where you can place all the three logos. Each of the next n lines should contain n uppercase English letters "A", "B" or "C". The sets of the same letters should form solid rectangles, provided that: the sizes of the rectangle composed from letters "A" should be equal to the sizes of the logo of the first company, the sizes of the rectangle composed from letters "B" should be equal to the sizes of the logo of the second company, the sizes of the rectangle composed from letters "C" should be equal to the sizes of the logo of the third company, Note that the logos of the companies can be rotated for printing on the billboard. The billboard mustn't have any empty space. If a square billboard can be filled with the logos in multiple ways, you are allowed to print any of them. See the samples to better understand the statement.
standard output
PASSED
136de237c2ab9b3cf590ba1b1ba27184
train_002.jsonl
1443430800
Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area. Advertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no empty space left. When you put a logo on the billboard, you should rotate it so that the sides were parallel to the sides of the billboard.Your task is to determine if it is possible to put the logos of all the three companies on some square billboard without breaking any of the described rules.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class Codeforces { StringTokenizer tok; BufferedReader in; PrintWriter out; final boolean OJ = System.getProperty("ONLINE_JUDGE") != null; String filename = null; void init() { try { if (OJ) { if (filename == null) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } } else { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } } catch (Exception e) { throw new RuntimeException(e); } } String readString() { try { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } catch (Throwable t) { throw new RuntimeException(t); } } int readInt() { return Integer.parseInt(readString()); } long readLong() { return Long.parseLong(readString()); } public static void main(String[] args) { new Codeforces().run(); } void run() { init(); long time = System.currentTimeMillis(); solve(); System.err.println(System.currentTimeMillis() - time); out.close(); } class IntWrap implements Comparable<IntWrap> { int x; IntWrap(int x) { this.x = x; } @Override public int compareTo(IntWrap o) { return Integer.compare(o.x % 10, x % 10); } } void check(int n, int x1, int y1, int x2, int y2, int x3, int y3, char[] let) { if (x1 == n && x2 == n && x3 == n && y1 + y2 + y3 == n) { out.println(n); for (int i=0;i<y1;i++) { for (int j=0;j<n;j++) { out.print(let[0]); } out.println(); } for (int i=0;i<y2;i++) { for (int j=0;j<n;j++) { out.print(let[1]); } out.println(); } for (int i=0;i<y3;i++) { for (int j=0;j<n;j++) { out.print(let[2]); } out.println(); } out.close(); System.exit(0); } if (x1 + x2 == n && y1 == y2 && y1 + y3 == n && x3 == n) { out.println(n); for (int i=0;i<y1;i++) { for (int j=0;j<x1;j++) { out.print(let[0]); } for (int j=x1;j<n;j++) { out.print(let[1]); } out.println(); } for (int i=y1;i<n;i++) { for (int j=0;j<n;j++) out.print(let[2]); out.println(); } out.close(); System.exit(0); } } void brut(int pos, int[] cx, int[] cy, char[] let, int n) { if (pos == 3) { check(n, cx[0], cy[0], cx[1], cy[1], cx[2], cy[2], let); return; } for (int i=pos;i<3;i++) { int t = cx[i]; cx[i] = cx[pos]; cx[pos] = t; t = cy[i]; cy[i] = cy[pos]; cy[pos] = t; char ct = let[i]; let[i] = let[pos]; let[pos] = ct; brut(pos + 1, cx,cy,let,n); t = cx[i]; cx[i] = cx[pos]; cx[pos] = t; t = cy[i]; cy[i] = cy[pos]; cy[pos] = t; ct = let[i]; let[i] = let[pos]; let[pos] = ct; } } void solve() { int[] x = new int[3]; int[] y = new int[3]; for (int i=0;i<3;i++) { x[i] = readInt(); y[i] = readInt(); } for (int i=1;i<300;i++) { for (int j=0;j<8;j++) { int[] cx = new int[3]; int[] cy = new int[3]; for (int bit =0;bit<3;bit++) { if ((j & (1 << bit)) != 0) { cx[bit] = x[bit]; cy[bit] = y[bit]; } else { cx[bit] = y[bit]; cy[bit] = x[bit]; } } brut(0,cx,cy,new char[] {'A','B','C'}, i); } } out.println(-1); } }
Java
["5 1 2 5 5 2", "4 4 2 6 4 2"]
1 second
["5\nAAAAA\nBBBBB\nBBBBB\nCCCCC\nCCCCC", "6\nBBBBBB\nBBBBBB\nAAAACC\nAAAACC\nAAAACC\nAAAACC"]
null
Java 7
standard input
[ "geometry", "constructive algorithms", "bitmasks", "math", "implementation", "brute force" ]
2befe5da2df57d23934601cbe4d4f151
The first line of the input contains six positive integers x1, y1, x2, y2, x3, y3 (1 ≤ x1, y1, x2, y2, x3, y3 ≤ 100), where xi and yi determine the length and width of the logo of the i-th company respectively.
1,700
If it is impossible to place all the three logos on a square shield, print a single integer "-1" (without the quotes). If it is possible, print in the first line the length of a side of square n, where you can place all the three logos. Each of the next n lines should contain n uppercase English letters "A", "B" or "C". The sets of the same letters should form solid rectangles, provided that: the sizes of the rectangle composed from letters "A" should be equal to the sizes of the logo of the first company, the sizes of the rectangle composed from letters "B" should be equal to the sizes of the logo of the second company, the sizes of the rectangle composed from letters "C" should be equal to the sizes of the logo of the third company, Note that the logos of the companies can be rotated for printing on the billboard. The billboard mustn't have any empty space. If a square billboard can be filled with the logos in multiple ways, you are allowed to print any of them. See the samples to better understand the statement.
standard output
PASSED
0ffeca69e334eb6ee2aee7ef6a030b6b
train_002.jsonl
1443430800
Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area. Advertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no empty space left. When you put a logo on the billboard, you should rotate it so that the sides were parallel to the sides of the billboard.Your task is to determine if it is possible to put the logos of all the three companies on some square billboard without breaking any of the described rules.
256 megabytes
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.net.URL; import java.util.*; /** * Created by smalex on 28/09/15. */ public class P581D { private static class Logo implements Comparable<Logo> { private final int x; private final int y; private final char name; public Logo(char name, int x, int y) { this.name = name; this.x = Math.min(x, y); this.y = Math.max(x, y); } public char getName() { return name; } public int getX() { return x; } public int getY() { return y; } @Override public String toString() { return "Logo{" + "x=" + x + ", y=" + y + '}'; } @Override public int compareTo(Logo o) { return Integer.compare(o.y, y); } } public static void main(String[] args) throws Exception { new P581D().run(); } private void run() throws Exception { Scanner scanner = new Scanner(System.in); List<Logo> logos = new ArrayList<>(); for (int i = 0; i < 3; i++) { logos.add(new Logo((char) ('A' + i), scanner.nextInt(), scanner.nextInt())); } scanner.close(); Collections.sort(logos); if (solveCase0(logos)) { return; } else if (solveCase1(logos)) { return; } System.out.println(-1); } private boolean solveCase1(List<Logo> logos) { Logo widest = logos.get(0); Logo b = logos.get(1); Logo c = logos.get(2); if (b.getY() + c.getY() == widest.getY() && b.getX() == c.getX() && b.getX() + widest.getX() == widest.getY()) { createResult(logos, widest.getY(), widest.getX(), b.getY(), c.getY(), b.getX()); return true; } if (b.getY() + c.getX() == widest.getY() && b.getX() == c.getY() && b.getX() + widest.getX() == widest.getY()) { createResult(logos, widest.getY(), widest.getX(), b.getY(), c.getX(), b.getX()); return true; } if (b.getX() + c.getY() == widest.getY() && b.getY() == c.getX() && b.getY() + widest.getX() == widest.getY()) { createResult(logos, widest.getY(), widest.getX(), b.getX(), c.getY(), b.getY()); return true; } if (b.getX() + c.getX() == widest.getY() && b.getY() == c.getY() && b.getY() + widest.getX() == widest.getY()) { createResult(logos, widest.getY(), widest.getX(), b.getX(), c.getX(), b.getY()); return true; } return false; } private void createResult(List<Logo> logos, int y, int x, int y1, int y2, int x0) { char[][] rows = new char[y][y]; int start = 0; for (int i = 0; i < x; i++, start++) { Arrays.fill(rows[start], logos.get(0).name); } for (int i = x; i < y; i++) { Arrays.fill(rows[i], 0, y1, logos.get(1).name); Arrays.fill(rows[i], y1, y1 + y2, logos.get(2).name); } System.out.println(y); printRows(rows); } private boolean solveCase0(List<Logo> logos) { for (int i = 1; i < logos.size(); i++) { Logo prevLogo = logos.get(i - 1); Logo logo = logos.get(i); if (logo.getY() != prevLogo.getY()) { return false; } } int res = 0; for (Logo logo : logos) { res += logo.getX(); } if (res == logos.get(0).getY()) { char[][] rows = new char[res][res]; int start = 0; for (Logo logo : logos) { for (int i = 0; i < logo.getX(); i++, start++) { Arrays.fill(rows[start], logo.getName()); } } System.out.println(res); printRows(rows); return true; } return false; } private void printRows(char[][] rows) { for (char[] row : rows) { System.out.println(new String(row)); } } private InputStream getInputStream() throws FileNotFoundException { if ("smalex".equals(System.getenv("USER"))) { Class clazz = getClass(); URL resource = clazz.getResource(clazz.getSimpleName() + ".in"); if (resource == null) { System.out.println("file not exists"); return System.in; } return new FileInputStream(new File(resource.getFile())); } else { return System.in; } } }
Java
["5 1 2 5 5 2", "4 4 2 6 4 2"]
1 second
["5\nAAAAA\nBBBBB\nBBBBB\nCCCCC\nCCCCC", "6\nBBBBBB\nBBBBBB\nAAAACC\nAAAACC\nAAAACC\nAAAACC"]
null
Java 7
standard input
[ "geometry", "constructive algorithms", "bitmasks", "math", "implementation", "brute force" ]
2befe5da2df57d23934601cbe4d4f151
The first line of the input contains six positive integers x1, y1, x2, y2, x3, y3 (1 ≤ x1, y1, x2, y2, x3, y3 ≤ 100), where xi and yi determine the length and width of the logo of the i-th company respectively.
1,700
If it is impossible to place all the three logos on a square shield, print a single integer "-1" (without the quotes). If it is possible, print in the first line the length of a side of square n, where you can place all the three logos. Each of the next n lines should contain n uppercase English letters "A", "B" or "C". The sets of the same letters should form solid rectangles, provided that: the sizes of the rectangle composed from letters "A" should be equal to the sizes of the logo of the first company, the sizes of the rectangle composed from letters "B" should be equal to the sizes of the logo of the second company, the sizes of the rectangle composed from letters "C" should be equal to the sizes of the logo of the third company, Note that the logos of the companies can be rotated for printing on the billboard. The billboard mustn't have any empty space. If a square billboard can be filled with the logos in multiple ways, you are allowed to print any of them. See the samples to better understand the statement.
standard output
PASSED
768af1ce9190a4f6b4ae628f12200c24
train_002.jsonl
1443430800
Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area. Advertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no empty space left. When you put a logo on the billboard, you should rotate it so that the sides were parallel to the sides of the billboard.Your task is to determine if it is possible to put the logos of all the three companies on some square billboard without breaking any of the described rules.
256 megabytes
import java.util.*; import java.lang.Math; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int x1 = sc.nextInt(), y1 = sc.nextInt(), x2 = sc.nextInt(), y2 = sc.nextInt(), x3 = sc.nextInt(), y3 = sc.nextInt(); int square = x1*y1 + x2*y2 + x3*y3; int s = (int) Math.floor(Math.sqrt(square)); if(s * s != square) { System.out.println(-1); } else if(x1 != s && x2 != s && x3 != s && y1 != s && y2 != s && y3 != s) { System.out.println(-1); } else { // Упорядочим так, чтобы x был больше y. if(x1 < y1) { int t = x1; x1 = y1; y1 = t; } if(x2 < y2) { int t = x2; x2 = y2; y2 = t; } if(x3 < y3) { int t = x3; x3 = y3; y3 = t; } if(x1 == s && x2 == s && x3 == s) { System.out.println(s); for(int i = 0; i < y1; i++) { for(int j = 0; j < s; j++) { System.out.print('A'); } System.out.println(); } for(int i = 0; i < y2; i++) { for(int j = 0; j < s; j++) { System.out.print('B'); } System.out.println(); } for(int i = 0; i < y3; i++) { for(int j = 0; j < s; j++) { System.out.print('C'); } System.out.println(); } } else if(x1 == s) { System.out.println(s); for(int i = 0; i < y1; i++) { for(int j = 0; j < x1; j++) { System.out.print('A'); } System.out.println(); } if (y2 == s - y1) { for(int i = 0; i < y2; i++) { for(int j = 0; j < x2; j++) { System.out.print('B'); } for(int j = 0; j < s - x2; j++) { System.out.print('C'); } System.out.println(); } } else if(x2 == s - y1) { for(int i = 0; i < x2; i++) { for(int j = 0; j < y2; j++) { System.out.print('B'); } for(int j = 0; j < s - y2; j++) { System.out.print('C'); } System.out.println(); } } else if(y3 == s - x1) { for(int i = 0; i < y3; i++) { for(int j = 0; j < x3; j++) { System.out.print('C'); } for(int j = 0; j < s - x3; j++) { System.out.print('B'); } System.out.println(); } } else if(x3 == s - x1) { for(int i = 0; i < x3; i++) { for(int j = 0; j < y3; j++) { System.out.print('C'); } for(int j = 0; j < s - y3; j++) { System.out.print('B'); } System.out.println(); } } } else if(x2 == s) { System.out.println(s); for(int i = 0; i < y2; i++) { for(int j = 0; j < x2; j++) { System.out.print('B'); } System.out.println(); } if (y1 == s - y2) { for(int i = 0; i < y1; i++) { for(int j = 0; j < x1; j++) { System.out.print('A'); } for(int j = 0; j < s - x1; j++) { System.out.print('C'); } System.out.println(); } } else if(x1 == s - y2) { for(int i = 0; i < x1; i++) { for(int j = 0; j < y1; j++) { System.out.print('A'); } for(int j = 0; j < s - y1; j++) { System.out.print('C'); } System.out.println(); } } else if(y3 == s - x1) { for(int i = 0; i < y3; i++) { for(int j = 0; j < x3; j++) { System.out.print('C'); } for(int j = 0; j < s - x3; j++) { System.out.print('A'); } System.out.println(); } } else if(x3 == s - x1) { for(int i = 0; i < x3; i++) { for(int j = 0; j < y3; j++) { System.out.print('C'); } for(int j = 0; j < s - y3; j++) { System.out.print('A'); } System.out.println(); } } } else if(x3 == s) { System.out.println(s); for(int i = 0; i < y3; i++) { for(int j = 0; j < x3; j++) { System.out.print('C'); } System.out.println(); } if (y2 == s - y3) { for(int i = 0; i < y2; i++) { for(int j = 0; j < x2; j++) { System.out.print('B'); } for(int j = 0; j < s - x2; j++) { System.out.print('A'); } System.out.println(); } } else if(x2 == s - y3) { for(int i = 0; i < x2; i++) { for(int j = 0; j < y2; j++) { System.out.print('B'); } for(int j = 0; j < s - y2; j++) { System.out.print('A'); } System.out.println(); } } else if(y1 == s - x3) { for(int i = 0; i < y1; i++) { for(int j = 0; j < x1; j++) { System.out.print('A'); } for(int j = 0; j < s - x1; j++) { System.out.print('B'); } System.out.println(); } } else if(x1 == s - x3) { for(int i = 0; i < x1; i++) { for(int j = 0; j < y1; j++) { System.out.print('A'); } for(int j = 0; j < s - y1; j++) { System.out.print('B'); } System.out.println(); } } } } } }
Java
["5 1 2 5 5 2", "4 4 2 6 4 2"]
1 second
["5\nAAAAA\nBBBBB\nBBBBB\nCCCCC\nCCCCC", "6\nBBBBBB\nBBBBBB\nAAAACC\nAAAACC\nAAAACC\nAAAACC"]
null
Java 7
standard input
[ "geometry", "constructive algorithms", "bitmasks", "math", "implementation", "brute force" ]
2befe5da2df57d23934601cbe4d4f151
The first line of the input contains six positive integers x1, y1, x2, y2, x3, y3 (1 ≤ x1, y1, x2, y2, x3, y3 ≤ 100), where xi and yi determine the length and width of the logo of the i-th company respectively.
1,700
If it is impossible to place all the three logos on a square shield, print a single integer "-1" (without the quotes). If it is possible, print in the first line the length of a side of square n, where you can place all the three logos. Each of the next n lines should contain n uppercase English letters "A", "B" or "C". The sets of the same letters should form solid rectangles, provided that: the sizes of the rectangle composed from letters "A" should be equal to the sizes of the logo of the first company, the sizes of the rectangle composed from letters "B" should be equal to the sizes of the logo of the second company, the sizes of the rectangle composed from letters "C" should be equal to the sizes of the logo of the third company, Note that the logos of the companies can be rotated for printing on the billboard. The billboard mustn't have any empty space. If a square billboard can be filled with the logos in multiple ways, you are allowed to print any of them. See the samples to better understand the statement.
standard output
PASSED
c6fe7d832e8a2718e206a1537c8a6a1b
train_002.jsonl
1443430800
Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area. Advertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no empty space left. When you put a logo on the billboard, you should rotate it so that the sides were parallel to the sides of the billboard.Your task is to determine if it is possible to put the logos of all the three companies on some square billboard without breaking any of the described rules.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; public class P7 { private static char[][] answer; private static final int X1 = 0; private static final int Y1 = 1; private static final int X2 = 2; private static final int Y2 = 3; private static final int X3 = 4; private static final int Y3 = 5; private static boolean fit(int x1, int y1, int x2, int y2, int x3, int y3, int totalArea, int side) { if (Math.pow(side, 2) == totalArea && x1 <= side && y1 <= side && x2 <= side && y2 <= side && x3 <= side && y3 <= side) { return true; } else { return false; } } private static void fill(int h, int w, int x0, int y0, char c) { for (int i = x0; i < h + x0; i++) { for (int j = y0; j < w + y0; j++) { answer[i][j] = c; } } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); OutputStream out = new BufferedOutputStream(System.out); String[] input = br.readLine().split(" "); int[] sides = new int[input.length]; boolean[] filled = { false, false, false }; char[] bb = { 'A', 'B', 'C' }; for (int i = 0; i < sides.length; i++) { sides[i] = Integer.parseInt(input[i]); } int totalArea = sides[X1] * sides[Y1] + sides[X2] * sides[Y2] + sides[X3] * sides[Y3]; int side = ((Number) Math.sqrt(totalArea)).intValue(); answer = new char[side][side]; int nextX = 0, nextY = 0; if (fit(sides[X1], sides[Y1], sides[X2], sides[Y2], sides[X3], sides[Y3], totalArea, side)) { for (int i = 0; i < sides.length; i++) { if (sides[i] == side) { filled[i / 2] = true; if (i % 2 == 0) { fill(sides[i + 1], sides[i], nextY, nextX, bb[i / 2]); nextY += sides[i + 1]; } else { fill(sides[i - 1], sides[i], nextY, nextX, bb[i / 2]); nextY += sides[i - 1]; } } } for (int i = 0; i < sides.length - 2; i++) { int j; if (i % 2 == 0) { j = i + 2; } else { j = i + 1; } for (; j < sides.length; j++) { if (sides[i] + sides[j] == side && !filled[i / 2] && !filled[j / 2]) { filled[i / 2] = true; filled[j / 2] = true; if (i % 2 == 0) { fill(sides[i + 1], sides[i], nextY, nextX, bb[i / 2]); } else { fill(sides[i - 1], sides[i], nextY, nextX, bb[i / 2]); } nextX += sides[i]; if (j % 2 == 0) { fill(sides[j + 1], sides[j], nextY, nextX, bb[j / 2]); } else { fill(sides[j - 1], sides[j], nextY, nextX, bb[j / 2]); } } } } if (filled[0] && filled[1] && filled[2]) { out.write(Integer.toString(side).getBytes()); for (int i = 0; i < side; i++) { out.write("\n".getBytes()); for (int j = 0; j < side; j++) { out.write(answer[i][j]); } } } else { out.write("-1".getBytes()); } out.flush(); } else { out.write("-1".getBytes()); out.flush(); } } }
Java
["5 1 2 5 5 2", "4 4 2 6 4 2"]
1 second
["5\nAAAAA\nBBBBB\nBBBBB\nCCCCC\nCCCCC", "6\nBBBBBB\nBBBBBB\nAAAACC\nAAAACC\nAAAACC\nAAAACC"]
null
Java 7
standard input
[ "geometry", "constructive algorithms", "bitmasks", "math", "implementation", "brute force" ]
2befe5da2df57d23934601cbe4d4f151
The first line of the input contains six positive integers x1, y1, x2, y2, x3, y3 (1 ≤ x1, y1, x2, y2, x3, y3 ≤ 100), where xi and yi determine the length and width of the logo of the i-th company respectively.
1,700
If it is impossible to place all the three logos on a square shield, print a single integer "-1" (without the quotes). If it is possible, print in the first line the length of a side of square n, where you can place all the three logos. Each of the next n lines should contain n uppercase English letters "A", "B" or "C". The sets of the same letters should form solid rectangles, provided that: the sizes of the rectangle composed from letters "A" should be equal to the sizes of the logo of the first company, the sizes of the rectangle composed from letters "B" should be equal to the sizes of the logo of the second company, the sizes of the rectangle composed from letters "C" should be equal to the sizes of the logo of the third company, Note that the logos of the companies can be rotated for printing on the billboard. The billboard mustn't have any empty space. If a square billboard can be filled with the logos in multiple ways, you are allowed to print any of them. See the samples to better understand the statement.
standard output
PASSED
ef7abef8fa1b1dd61adb6740114a52e2
train_002.jsonl
1443430800
Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area. Advertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no empty space left. When you put a logo on the billboard, you should rotate it so that the sides were parallel to the sides of the billboard.Your task is to determine if it is possible to put the logos of all the three companies on some square billboard without breaking any of the described rules.
256 megabytes
import java.io.*; import java.util.*; public class D { FastScanner in; PrintWriter out; int i = 0, j = 0; char[][] billboard; int nextY, nextX; void solve() { /**************START**************/ int x1 = in.nextInt(); int big = x1; int y1 = in.nextInt(); big = Math.max(big, y1); int x2 = in.nextInt(); big = Math.max(big, x2); int y2 = in.nextInt(); big = Math.max(big, y2); int x3 = in.nextInt(); big = Math.max(big, x3); int y3 = in.nextInt(); big = Math.max(big, y3); int square = x1 * y1 + x2 * y2 + x3 * y3; int wall = (int)Math.sqrt(square); if (wall * wall != square || big != wall || x1 + y1 == 2 || x2 + y2 == 2 || x3 + y3 == 2) { out.println("-1"); } else { out.println(wall); billboard = new char[wall][wall]; for (i = 0; i < wall; i++) { Arrays.fill(billboard[i], 'C'); } //Place A top left (biggest side going across) int aWidth = Math.max(x1, y1); int aHeight = Math.min(x1, y1); for (i = 0; i < aHeight; i++) { for (j = 0; j < aWidth; j++) { billboard[i][j] = 'A'; } } if (aWidth == wall) { if (x2 == wall - aHeight) { for (i = 0; i < x2; i++) { for (j = 0; j < y2; j++) { billboard[i+aHeight][j] = 'B'; } } } else if (y2 == wall - aHeight) { for (i = 0; i < y2; i++) { for (j = 0; j < x2; j++) { billboard[i+aHeight][j] = 'B'; } } } else { int bHeight = Math.min(x2, y2); for (i = 0; i < bHeight; i++) { for (j = 0; j < wall; j++) { billboard[i+aHeight][j] = 'B'; } } } } else { if (wall - aWidth == x2) { for (i = 0 ; i < y2; i++) { for (j = 0; j < x2; j++) { billboard[i][j + aWidth] = 'B'; } } } else if (wall - aWidth == y2) { for (i = 0 ; i < x2; i++) { for (j = 0; j < y2; j++) { billboard[i][j + aWidth] = 'B'; } } } else if (aHeight + x2 == wall) { for (i = 0; i < x2; i++) { for (j = 0; j < y2; j++) { billboard[i+aHeight][j] = 'B'; } } } else { for (i = 0; i < y2; i++) { for (j = 0; j < x2; j++) { billboard[i+aHeight][j] = 'B'; } } } } for (i = 0; i < wall; i++) { for (j = 0; j < wall; j++) { out.print(billboard[i][j]); } out.print("\n"); } } /***************END***************/ } public static void main(String[] args) { new D().runIO(); } void runIO() { in = new FastScanner(System.in); out = new PrintWriter(System.out); solve(); out.close(); } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String next() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } boolean hasMoreTokens() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return false; st = new StringTokenizer(s); } return true; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["5 1 2 5 5 2", "4 4 2 6 4 2"]
1 second
["5\nAAAAA\nBBBBB\nBBBBB\nCCCCC\nCCCCC", "6\nBBBBBB\nBBBBBB\nAAAACC\nAAAACC\nAAAACC\nAAAACC"]
null
Java 7
standard input
[ "geometry", "constructive algorithms", "bitmasks", "math", "implementation", "brute force" ]
2befe5da2df57d23934601cbe4d4f151
The first line of the input contains six positive integers x1, y1, x2, y2, x3, y3 (1 ≤ x1, y1, x2, y2, x3, y3 ≤ 100), where xi and yi determine the length and width of the logo of the i-th company respectively.
1,700
If it is impossible to place all the three logos on a square shield, print a single integer "-1" (without the quotes). If it is possible, print in the first line the length of a side of square n, where you can place all the three logos. Each of the next n lines should contain n uppercase English letters "A", "B" or "C". The sets of the same letters should form solid rectangles, provided that: the sizes of the rectangle composed from letters "A" should be equal to the sizes of the logo of the first company, the sizes of the rectangle composed from letters "B" should be equal to the sizes of the logo of the second company, the sizes of the rectangle composed from letters "C" should be equal to the sizes of the logo of the third company, Note that the logos of the companies can be rotated for printing on the billboard. The billboard mustn't have any empty space. If a square billboard can be filled with the logos in multiple ways, you are allowed to print any of them. See the samples to better understand the statement.
standard output
PASSED
bd796396d1daff6cdf3ee4def6025513
train_002.jsonl
1443430800
Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area. Advertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no empty space left. When you put a logo on the billboard, you should rotate it so that the sides were parallel to the sides of the billboard.Your task is to determine if it is possible to put the logos of all the three companies on some square billboard without breaking any of the described rules.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Calendar; 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.SortedSet; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; /** * # * @author pttrung */ public class D_Round_322_Div2 { public static long MOD = 1000000007; public static void main(String[] args) throws FileNotFoundException { // PrintWriter out = new PrintWriter(new FileOutputStream(new File( // "output.txt"))); PrintWriter out = new PrintWriter(System.out); Scanner in = new Scanner(); Point[] data = new Point[3]; int total = 0; for (int i = 0; i < 3; i++) { data[i] = new Point(in.nextInt(), in.nextInt()); total += data[i].x * data[i].y; } int n = isSquare(total); if (n == -1) { out.println(-1); } else { //System.out.println(n); boolean found = false; int[] pre = {0, 1, 2}; do { for (int i = 0; i < (1 << 3); i++) { char[][] re = order(pre, i, n, data); if (re != null) { found = true; out.println(n); for (int j = 0; j < n; j++) { for (int k = 0; k < n; k++) { out.print(re[j][k]); } out.println(); } break; } } } while (nextPer(pre) && !found); if (!found) { out.println(-1); } } out.close(); } static char[][] order(int[] pre, int mask, int n, Point[] data) { char[][] result = new char[n][n]; boolean[][] mark = new boolean[n][n]; // System.out.println("HE HE"); for (int i = 0; i < 3; i++) { boolean found = false; for (int k = 0; k < n && !found; k++) { for (int h = 0; h < n; h++) { if (!mark[k][h]) { // System.out.println(Arrays.toString(pre) + " " // + Integer.toBinaryString(mask) + " " + k + " " // + h + " " + pre[i]); if (((1 << pre[i]) & mask) == 0) { for (int p = 0; p < data[pre[i]].x; p++) { for (int q = 0; q < data[pre[i]].y; q++) { if (k + p >= n || q + h >= n || mark[k + p][q + h]) { return null; } mark[k + p][q + h] = true; result[k + p][q + h] = (char) (pre[i] + 'A'); } } } else { for (int p = 0; p < data[pre[i]].y; p++) { for (int q = 0; q < data[pre[i]].x; q++) { if (k + p >= n || q + h >= n || mark[k + p][q + h]) { return null; } mark[k + p][q + h] = true; result[k + p][q + h] = (char) (pre[i] + 'A'); } } } // for (char[] c : result) { // System.out.println(Arrays.toString(c)); // } found = true; break; } } } } // System.out.println(Arrays.toString(pre) + " " + Integer.toBinaryString(mask)); return result; } static int isSquare(int v) { for (int i = 1; i * i <= v; i++) { if (i * i == v) { return i; } } return -1; } public static int[] KMP(String val) { int i = 0; int j = -1; int[] result = new int[val.length() + 1]; result[0] = -1; while (i < val.length()) { while (j >= 0 && val.charAt(j) != val.charAt(i)) { j = result[j]; } j++; i++; result[i] = j; } return result; } public static boolean nextPer(int[] data) { int i = data.length - 1; while (i > 0 && data[i] < data[i - 1]) { i--; } if (i == 0) { return false; } int j = data.length - 1; while (data[j] < data[i - 1]) { j--; } int temp = data[i - 1]; data[i - 1] = data[j]; data[j] = temp; Arrays.sort(data, i, data.length); return true; } public static int digit(long n) { int result = 0; while (n > 0) { n /= 10; result++; } return result; } public static double dist(long a, long b, long x, long y) { double val = (b - a) * (b - a) + (x - y) * (x - y); val = Math.sqrt(val); double other = x * x + a * a; other = Math.sqrt(other); return val + other; } public static class Point implements Comparable<Point> { int x, y; public Point(int start, int end) { this.x = start; this.y = end; } @Override public int hashCode() { int hash = 5; hash = 47 * hash + this.x; hash = 47 * hash + this.y; return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Point other = (Point) obj; if (this.x != other.x) { return false; } if (this.y != other.y) { return false; } return true; } @Override public int compareTo(Point o) { return x - o.x; } } public static class FT { long[] data; FT(int n) { data = new long[n]; } public void update(int index, long value) { while (index < data.length) { data[index] += value; index += (index & (-index)); } } public long get(int index) { long result = 0; while (index > 0) { result += data[index]; index -= (index & (-index)); } return result; } } public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } public static long pow(long a, long b, long MOD) { if (b == 0) { return 1; } if (b == 1) { return a; } long val = pow(a, b / 2, MOD); if (b % 2 == 0) { return val * val % MOD; } else { return val * (val * a % MOD) % MOD; } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() throws FileNotFoundException { // System.setOut(new PrintStream(new BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt")))); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
Java
["5 1 2 5 5 2", "4 4 2 6 4 2"]
1 second
["5\nAAAAA\nBBBBB\nBBBBB\nCCCCC\nCCCCC", "6\nBBBBBB\nBBBBBB\nAAAACC\nAAAACC\nAAAACC\nAAAACC"]
null
Java 7
standard input
[ "geometry", "constructive algorithms", "bitmasks", "math", "implementation", "brute force" ]
2befe5da2df57d23934601cbe4d4f151
The first line of the input contains six positive integers x1, y1, x2, y2, x3, y3 (1 ≤ x1, y1, x2, y2, x3, y3 ≤ 100), where xi and yi determine the length and width of the logo of the i-th company respectively.
1,700
If it is impossible to place all the three logos on a square shield, print a single integer "-1" (without the quotes). If it is possible, print in the first line the length of a side of square n, where you can place all the three logos. Each of the next n lines should contain n uppercase English letters "A", "B" or "C". The sets of the same letters should form solid rectangles, provided that: the sizes of the rectangle composed from letters "A" should be equal to the sizes of the logo of the first company, the sizes of the rectangle composed from letters "B" should be equal to the sizes of the logo of the second company, the sizes of the rectangle composed from letters "C" should be equal to the sizes of the logo of the third company, Note that the logos of the companies can be rotated for printing on the billboard. The billboard mustn't have any empty space. If a square billboard can be filled with the logos in multiple ways, you are allowed to print any of them. See the samples to better understand the statement.
standard output
PASSED
60d38eb949493f4d81b586573ed7dece
train_002.jsonl
1443430800
Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area. Advertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no empty space left. When you put a logo on the billboard, you should rotate it so that the sides were parallel to the sides of the billboard.Your task is to determine if it is possible to put the logos of all the three companies on some square billboard without breaking any of the described rules.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; public class P581D { public static void print_n(int count, char c) { for(int i = 0; i < count; i++) System.out.print(c); } public static void print_n_lines(int dim, char c, int n) { for (int i = 0; i < n; i++) { print_n(dim, c); System.out.println(); } } // at least one rectangle must take up a whole side // if two rectangles take up a whole slide it's all rows public static boolean valid_case_1(int h1, int w1, int h2, int w2, int h3, int w3, char a, char b, char c) { // square must be length of the longer side int dim = Math.max(h1, w1); int other1 = dim == h1 ? w1 : h1; int lower_height = 0; int width_left = 0; boolean success = false; if ((h2 == h3) && (dim - h2 == other1) && (w2 + w3 == dim)) { lower_height = h2; width_left = w2; success = true; } if ((w2 == w3) && (dim - w2 == other1) && (h2 + h3 == dim)) { lower_height = w2; width_left = h2; success = true; } if ((h2 == w3) && (dim - h2 == other1) && (w2 + h3 == dim)) { lower_height = h2; width_left = w2; success = true; } if ((h3 == w2) && (dim - h3 == other1) && (w3 + h2 == dim)) { lower_height = h3; width_left = h2; success = true; } if (success) { System.out.println(dim); print_n_lines(dim, a, other1); for (int i = 0; i < lower_height; i++) { print_n(width_left, b); print_n(dim - width_left, c); System.out.println(); } } return success; } public static boolean valid_case_2(int h1, int w1, int h2, int w2, int h3, int w3) { // square must be length of the longer side int dim = Math.max(h1, w1); int other1, other2, other3; int main1, main2, main3; if (h1 == dim) { main1 = h1; other1 = w1; } else { main1 = w1; other1 = h1; } if (h2 == dim) { main2 = h2; other2 = w2; } else { main2 = w2; other2 = h2; } if (h3 == dim) { main3 = h3; other3 = w3; } else { main3 = w3; other3 = h3; } if (!((dim == other1 + other2 + other3) && (main1 == dim) && (main2 == dim) && (main3 == dim))) return false; System.out.println(dim); print_n_lines(dim, 'A', other1); print_n_lines(dim, 'B', other2); print_n_lines(dim, 'C', other3); return true; } public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] dims_str = br.readLine().split(" "); int h1 = Integer.parseInt(dims_str[0]); int w1 = Integer.parseInt(dims_str[1]); int h2 = Integer.parseInt(dims_str[2]); int w2 = Integer.parseInt(dims_str[3]); int h3 = Integer.parseInt(dims_str[4]); int w3 = Integer.parseInt(dims_str[5]); if(valid_case_1(h1, w1, h2, w2, h3, w3, 'A', 'B', 'C')) System.exit(0); if(valid_case_1(h2, w2, h1, w1, h3, w3, 'B', 'A', 'C')) System.exit(0); if(valid_case_1(h3, w3, h1, w1, h2, w2, 'C', 'A', 'B')) System.exit(0); if(valid_case_2(h1, w1, h2, w2, h3, w3)) System.exit(0); System.out.println(-1); System.exit(0); } }
Java
["5 1 2 5 5 2", "4 4 2 6 4 2"]
1 second
["5\nAAAAA\nBBBBB\nBBBBB\nCCCCC\nCCCCC", "6\nBBBBBB\nBBBBBB\nAAAACC\nAAAACC\nAAAACC\nAAAACC"]
null
Java 7
standard input
[ "geometry", "constructive algorithms", "bitmasks", "math", "implementation", "brute force" ]
2befe5da2df57d23934601cbe4d4f151
The first line of the input contains six positive integers x1, y1, x2, y2, x3, y3 (1 ≤ x1, y1, x2, y2, x3, y3 ≤ 100), where xi and yi determine the length and width of the logo of the i-th company respectively.
1,700
If it is impossible to place all the three logos on a square shield, print a single integer "-1" (without the quotes). If it is possible, print in the first line the length of a side of square n, where you can place all the three logos. Each of the next n lines should contain n uppercase English letters "A", "B" or "C". The sets of the same letters should form solid rectangles, provided that: the sizes of the rectangle composed from letters "A" should be equal to the sizes of the logo of the first company, the sizes of the rectangle composed from letters "B" should be equal to the sizes of the logo of the second company, the sizes of the rectangle composed from letters "C" should be equal to the sizes of the logo of the third company, Note that the logos of the companies can be rotated for printing on the billboard. The billboard mustn't have any empty space. If a square billboard can be filled with the logos in multiple ways, you are allowed to print any of them. See the samples to better understand the statement.
standard output