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
869195903902bef0673bca2a3e403b16
train_002.jsonl
1580308500
You are given two integers $$$a$$$ and $$$m$$$. Calculate the number of integers $$$x$$$ such that $$$0 \le x < m$$$ and $$$\gcd(a, m) = \gcd(a + x, m)$$$.Note: $$$\gcd(a, b)$$$ is the greatest common divisor of $$$a$$$ and $$$b$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Jeel Vaishnav */ 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); DSameGCDs solver = new DSameGCDs(); solver.solve(1, in, out); out.close(); } static class DSameGCDs { long phi(long n) { // Initialize result as n double result = n; // Consider all prime factors of n and for // every prime factor p, multiply result // with (1 - 1/p) for (long p = 2; p * p <= n; ++p) { // Check if p is a prime factor. if (n % p == 0) { // If yes, then update n and result while (n % p == 0) n /= p; result *= (1.0 - (1.0 / (double) p)); } } // If n has a prime factor greater than sqrt(n) // (There can be at-most one such prime factor) if (n > 1) result *= (1.0 - (1.0 / (double) n)); return (long) result; } long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } public void solve(int testNumber, InputReader sc, PrintWriter out) { int t = sc.nextInt(); for (int x = 0; x < t; ++x) { long a = sc.nextLong(); long m = sc.nextLong(); m /= gcd(a, m); out.println(phi(m)); } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["3\n4 9\n5 10\n42 9999999967"]
2 seconds
["6\n1\n9999999966"]
NoteIn the first test case appropriate $$$x$$$-s are $$$[0, 1, 3, 4, 6, 7]$$$.In the second test case the only appropriate $$$x$$$ is $$$0$$$.
Java 8
standard input
[ "number theory", "math" ]
adcd813d4c45337bbd8bb0abfa2f0e00
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 50$$$) — the number of test cases. Next $$$T$$$ lines contain test cases — one per line. Each line contains two integers $$$a$$$ and $$$m$$$ ($$$1 \le a &lt; m \le 10^{10}$$$).
1,800
Print $$$T$$$ integers — one per test case. For each test case print the number of appropriate $$$x$$$-s.
standard output
PASSED
e5a215f09dc3f6b78b3e896efaedf949
train_002.jsonl
1580308500
You are given two integers $$$a$$$ and $$$m$$$. Calculate the number of integers $$$x$$$ such that $$$0 \le x &lt; m$$$ and $$$\gcd(a, m) = \gcd(a + x, m)$$$.Note: $$$\gcd(a, b)$$$ is the greatest common divisor of $$$a$$$ and $$$b$$$.
256 megabytes
import java.util.*; public class d { static boolean debug = false; public static void main(String[] args) { Scanner in = new Scanner(System.in); int numT = in.nextInt(); for(int t=0; t<numT; t++) { long a = in.nextLong(); long m = in.nextLong(); long gcd = gcd(a, m); if(debug) System.out.printf("GCD = %d\n", gcd); ArrayList<Long> mFactors = factor(m); ArrayList<Long> gcdFactors = factor(gcd); if(debug) { System.out.println("gcd"); for(int i=0; i<gcdFactors.size(); i++) { System.out.printf("%d ", gcdFactors.get(i)); } System.out.println(); } ArrayList<Long> multiplesToIgnore = new ArrayList(); HashSet<Long> hs = new HashSet<>(); int mFactorsInd = 0; for(int i=0; i<gcdFactors.size(); i++) { if(mFactorsInd >= mFactors.size()) break; long cur = gcdFactors.get(i); long mFactorsCur = mFactors.get(mFactorsInd); if(mFactorsCur == cur) { mFactorsInd++; } else { // else we skip the lower one. if(mFactorsCur < cur) { // Since we don't include it, we add it to the list if(!hs.contains(mFactorsCur)) { multiplesToIgnore.add(mFactorsCur); // only add unique hs.add(mFactorsCur); } mFactorsInd++; i--; continue; } else { // iterate through gcd list continue; } } } // Now we add any other ones we ignored for(int i=mFactorsInd; i<mFactors.size(); i++) { if(!hs.contains(mFactors.get(i))) { multiplesToIgnore.add(mFactors.get(i)); hs.add(mFactors.get(i)); } } if(debug) { System.out.println("FactorsToIgnore"); for(int i=0; i<multiplesToIgnore.size(); i++) { System.out.printf("%d ", multiplesToIgnore.get(i)); } System.out.println(); } // We add every gcd-th value long ans = m/gcd; // Now we calculate the number of things to ignore. for(int bit=1 ; bit<(1<<multiplesToIgnore.size()); bit++) { int numOn = 0; long mult = 1; for(int i=0; i<multiplesToIgnore.size(); i++) { if((bit & (1<<i)) != 0) { numOn++; mult *= multiplesToIgnore.get(i); } } if(numOn%2 == 1) { ans -= (m/gcd)/mult; } else { ans += (m/gcd)/mult; } } System.out.println(ans); } } static ArrayList<Long> factor(long n) { ArrayList<Long> ans = new ArrayList<Long>(); for(long x=2; x*x <= n; x++) { while(n%x == 0) { n/=x; ans.add(x); } } if(n != 1) ans.add(n); return ans; } static long gcd(long a, long b) { return (b == 0) ? a : gcd(b, a%b); } } /* 3 4 9 5 10 42 9999999967 6 1 9999999966 0 is always a-o-k 5 15 2 GCD = 1 GCD = 5 GCD = 1 Every multiple of the gcd? until a point? What if co-prime? All co-prime pairs? So divide out the factors disjoint? 5 60 5 10 15 20 25 30 35 40 45 50 55 5 vs 2 2 3 5 ignore everything with mult 3 or 2, but then overcount ignoring 6s no 10 no 20 no 30 no 40 no 50 no 15 no 30 no 45 5 25 35 55 4 9 4 is coprime with 9 5 is coprime 6 is not coprime (mult of 3) 7 is 8 is coprime with 9 9 is not 10 is 11 is 12 is not (mult 3) 2 2 vs 3 3 So gcd = 1 So we care about every 1th number But we subtract out all numbers that have factors other than the num */
Java
["3\n4 9\n5 10\n42 9999999967"]
2 seconds
["6\n1\n9999999966"]
NoteIn the first test case appropriate $$$x$$$-s are $$$[0, 1, 3, 4, 6, 7]$$$.In the second test case the only appropriate $$$x$$$ is $$$0$$$.
Java 8
standard input
[ "number theory", "math" ]
adcd813d4c45337bbd8bb0abfa2f0e00
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 50$$$) — the number of test cases. Next $$$T$$$ lines contain test cases — one per line. Each line contains two integers $$$a$$$ and $$$m$$$ ($$$1 \le a &lt; m \le 10^{10}$$$).
1,800
Print $$$T$$$ integers — one per test case. For each test case print the number of appropriate $$$x$$$-s.
standard output
PASSED
a6fa6a21f7b8ebc8ebffe77807f773df
train_002.jsonl
1580308500
You are given two integers $$$a$$$ and $$$m$$$. Calculate the number of integers $$$x$$$ such that $$$0 \le x &lt; m$$$ and $$$\gcd(a, m) = \gcd(a + x, m)$$$.Note: $$$\gcd(a, b)$$$ is the greatest common divisor of $$$a$$$ and $$$b$$$.
256 megabytes
//package educational.round81; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class D { InputStream is; PrintWriter out; String INPUT = ""; void solve() { for(int T = ni();T > 0;T--){ long A = nl(), M = nl(); long g = gcd(A, M); long[] ds = new long[10000]; int p = 0; for(long i = 1;i*i <= M;i++){ if(M % i == 0){ ds[p++] = i; if(i*i < M)ds[p++] = M/i; } } ds = Arrays.copyOf(ds, p); Arrays.sort(ds); long[] dp = new long[p]; for(int i = p-1;i >= 0;i--){ dp[i] = M/ds[i]; for(int j = i+1;j < p;j++){ if(ds[j] % ds[i] == 0){ dp[i] -= dp[j]; } } if(ds[i] == g){ out.println(dp[i]); break; } } } } public static int[] sieveEratosthenes(int n) { if (n <= 32) { int[] primes = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31 }; for (int i = 0; i < primes.length; i++) { if (n < primes[i]) { return Arrays.copyOf(primes, i); } } return primes; } int u = n + 32; double lu = Math.log(u); int[] ret = new int[(int) (u / lu + u / lu / lu * 1.5)]; ret[0] = 2; int pos = 1; int[] isnp = new int[(n + 1) / 32 / 2 + 1]; int sup = (n + 1) / 32 / 2 + 1; int[] tprimes = { 3, 5, 7, 11, 13, 17, 19, 23, 29, 31 }; for (int tp : tprimes) { ret[pos++] = tp; int[] ptn = new int[tp]; for (int i = (tp - 3) / 2; i < tp << 5; i += tp) ptn[i >> 5] |= 1 << (i & 31); for (int j = 0; j < sup; j += tp) { for (int i = 0; i < tp && i + j < sup; i++) { isnp[j + i] |= ptn[i]; } } } // 3,5,7 // 2x+3=n int[] magic = { 0, 1, 23, 2, 29, 24, 19, 3, 30, 27, 25, 11, 20, 8, 4, 13, 31, 22, 28, 18, 26, 10, 7, 12, 21, 17, 9, 6, 16, 5, 15, 14 }; int h = n / 2; for (int i = 0; i < sup; i++) { for (int j = ~isnp[i]; j != 0; j &= j - 1) { int pp = i << 5 | magic[(j & -j) * 0x076be629 >>> 27]; int p = 2 * pp + 3; if (p > n) break; ret[pos++] = p; if ((long) p * p > n) continue; for (int q = (p * p - 3) / 2; q <= h; q += p) isnp[q >> 5] |= 1 << q; } } return Arrays.copyOf(ret, pos); } public static long gcd(long a, long b) { while (b > 0) { long c = a; a = b; b = c % b; } return a; } 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 D().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["3\n4 9\n5 10\n42 9999999967"]
2 seconds
["6\n1\n9999999966"]
NoteIn the first test case appropriate $$$x$$$-s are $$$[0, 1, 3, 4, 6, 7]$$$.In the second test case the only appropriate $$$x$$$ is $$$0$$$.
Java 8
standard input
[ "number theory", "math" ]
adcd813d4c45337bbd8bb0abfa2f0e00
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 50$$$) — the number of test cases. Next $$$T$$$ lines contain test cases — one per line. Each line contains two integers $$$a$$$ and $$$m$$$ ($$$1 \le a &lt; m \le 10^{10}$$$).
1,800
Print $$$T$$$ integers — one per test case. For each test case print the number of appropriate $$$x$$$-s.
standard output
PASSED
96a3af074bb1515ab946d2d431cfddec
train_002.jsonl
1580308500
You are given two integers $$$a$$$ and $$$m$$$. Calculate the number of integers $$$x$$$ such that $$$0 \le x &lt; m$$$ and $$$\gcd(a, m) = \gcd(a + x, m)$$$.Note: $$$\gcd(a, b)$$$ is the greatest common divisor of $$$a$$$ and $$$b$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Sparsh Sanchorawala */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { long gcd(long a, long b) { if (b == 0) return a; return (gcd(b, a % b)); } public void solve(int testNumber, InputReader s, PrintWriter w) { int t = s.nextInt(); while (t-- > 0) { long a = s.nextLong(), m = s.nextLong(); long k = gcd(a, m); ArrayList<Long> l = new ArrayList<>(); ArrayList<Long> l2 = new ArrayList<>(); for (long i = 1; i * i <= m; i++) { if (m % i != 0) continue; if (i % k == 0) { l.add(i); } if (i != m / i && (m / i) % k == 0) l2.add((m / i)); } for (int i = l2.size() - 1; i >= 0; i--) l.add(l2.get(i)); int n = l.size(); long[] val = new long[n]; for (int i = 0; i < n; i++) { long x = l.get(i); val[i] = (m + a - 1) / x - (a - 1) / x; } for (int i = n - 1; i >= 0; i--) { for (int j = i + 1; j < n; j++) { if (l.get(j) % l.get(i) == 0) val[i] -= val[j]; } } w.println(val[0]); } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["3\n4 9\n5 10\n42 9999999967"]
2 seconds
["6\n1\n9999999966"]
NoteIn the first test case appropriate $$$x$$$-s are $$$[0, 1, 3, 4, 6, 7]$$$.In the second test case the only appropriate $$$x$$$ is $$$0$$$.
Java 8
standard input
[ "number theory", "math" ]
adcd813d4c45337bbd8bb0abfa2f0e00
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 50$$$) — the number of test cases. Next $$$T$$$ lines contain test cases — one per line. Each line contains two integers $$$a$$$ and $$$m$$$ ($$$1 \le a &lt; m \le 10^{10}$$$).
1,800
Print $$$T$$$ integers — one per test case. For each test case print the number of appropriate $$$x$$$-s.
standard output
PASSED
41dea25ce96d96fb7d7c8f5fa15e76a8
train_002.jsonl
1580308500
You are given two integers $$$a$$$ and $$$m$$$. Calculate the number of integers $$$x$$$ such that $$$0 \le x &lt; m$$$ and $$$\gcd(a, m) = \gcd(a + x, m)$$$.Note: $$$\gcd(a, b)$$$ is the greatest common divisor of $$$a$$$ and $$$b$$$.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.StringTokenizer; public class EducationalRound81D { public static void solve() { int t = s.nextInt(); while(t-->0) { long a = s.nextLong(); long m = s.nextLong(); long y = gcd(a,m); HashMap<Long,Integer> first = pf(y); HashMap<Long,Integer> second = pf(m); ArrayList<Long> number = new ArrayList<Long>(); for(Long x:second.keySet()) { int val = second.get(x); if(!first.containsKey(x)) { number.add(x); }else { if(val>first.get(x)) { number.add(x); } } } long ans = Recur(number, 0, new LinkedList<Long>(), a+m-1, y); ans = (a+m-1)/y - ans; long tempans = Recur(number, 0, new LinkedList<Long>(), a-1, y); tempans = (a-1)/y - tempans; ans -= tempans; out.println(ans); } } public static long Recur(ArrayList<Long> number,int pos,LinkedList<Long> selected,long range,long start) { int n = number.size(); if(pos==n) { if(selected.size()==0) { return 0; } long curr = 1; for(Long i : selected) { curr*=i; } start *= curr; if(selected.size()%2==1) { return range/start; }else { return -range/start; } } long ans = 0; ans+= Recur(number,pos+1,selected,range,start); selected.add(number.get(pos)); ans+= Recur(number,pos+1,selected,range,start); selected.removeLast(); return ans; } public static HashMap<Long,Integer> pf(long n){ HashMap<Long,Integer> ans = new HashMap<>(); for(long i = 2;i*i<=n;i++) { int count = 0; while(n%i==0) { n/=i; count++; } if(count!=0) { ans.put(i, count); } } if(n!=1) { ans.put(n, 1); } return ans; } public static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } public static void main(String[] args) { out = new PrintWriter(new BufferedOutputStream(System.out)); s = new FastReader(); solve(); out.close(); } public static FastReader s; public static PrintWriter out; public static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (Exception e) { e.printStackTrace(); } return str; } } }
Java
["3\n4 9\n5 10\n42 9999999967"]
2 seconds
["6\n1\n9999999966"]
NoteIn the first test case appropriate $$$x$$$-s are $$$[0, 1, 3, 4, 6, 7]$$$.In the second test case the only appropriate $$$x$$$ is $$$0$$$.
Java 8
standard input
[ "number theory", "math" ]
adcd813d4c45337bbd8bb0abfa2f0e00
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 50$$$) — the number of test cases. Next $$$T$$$ lines contain test cases — one per line. Each line contains two integers $$$a$$$ and $$$m$$$ ($$$1 \le a &lt; m \le 10^{10}$$$).
1,800
Print $$$T$$$ integers — one per test case. For each test case print the number of appropriate $$$x$$$-s.
standard output
PASSED
1fe8d47c1b231aa31432dace9ffcd585
train_002.jsonl
1580308500
You are given two integers $$$a$$$ and $$$m$$$. Calculate the number of integers $$$x$$$ such that $$$0 \le x &lt; m$$$ and $$$\gcd(a, m) = \gcd(a + x, m)$$$.Note: $$$\gcd(a, b)$$$ is the greatest common divisor of $$$a$$$ and $$$b$$$.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.StringTokenizer; public class EducationalRound81D { public static void solve() { int t = s.nextInt(); while(t-->0) { long a = s.nextLong(); long m = s.nextLong(); long y = gcd(a,m); m/=y; out.println(phi(m)); // HashMap<Long,Integer> first = pf(y); // HashMap<Long,Integer> second = pf(m); // ArrayList<Long> number = new ArrayList<Long>(); // for(Long x:second.keySet()) { // int val = second.get(x); // if(!first.containsKey(x)) { // number.add(x); // }else { // if(val>first.get(x)) { // number.add(x); // } // } // } // long ans = Recur(number, 0, new LinkedList<Long>(), a+m-1, y); // ans = (a+m-1)/y - ans; // long tempans = Recur(number, 0, new LinkedList<Long>(), a-1, y); // tempans = (a-1)/y - tempans; // ans -= tempans; // out.println(ans); } } public static long phi(long number) { long result = number; for(long i = 2;i*i <= number; i++) { if(number%i==0) { while(number%i==0) { number/=i; } result -= result / i; } } if(number > 1) { result -= result/number; } return result; } public static long Recur(ArrayList<Long> number,int pos,LinkedList<Long> selected,long range,long start) { int n = number.size(); if(pos==n) { if(selected.size()==0) { return 0; } long curr = 1; for(Long i : selected) { curr*=i; } start *= curr; if(selected.size()%2==1) { return range/start; }else { return -range/start; } } long ans = 0; ans+= Recur(number,pos+1,selected,range,start); selected.add(number.get(pos)); ans+= Recur(number,pos+1,selected,range,start); selected.removeLast(); return ans; } public static HashMap<Long,Integer> pf(long n){ HashMap<Long,Integer> ans = new HashMap<>(); for(long i = 2;i*i<=n;i++) { int count = 0; while(n%i==0) { n/=i; count++; } if(count!=0) { ans.put(i, count); } } if(n!=1) { ans.put(n, 1); } return ans; } public static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } public static void main(String[] args) { out = new PrintWriter(new BufferedOutputStream(System.out)); s = new FastReader(); solve(); out.close(); } public static FastReader s; public static PrintWriter out; public static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (Exception e) { e.printStackTrace(); } return str; } } }
Java
["3\n4 9\n5 10\n42 9999999967"]
2 seconds
["6\n1\n9999999966"]
NoteIn the first test case appropriate $$$x$$$-s are $$$[0, 1, 3, 4, 6, 7]$$$.In the second test case the only appropriate $$$x$$$ is $$$0$$$.
Java 8
standard input
[ "number theory", "math" ]
adcd813d4c45337bbd8bb0abfa2f0e00
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 50$$$) — the number of test cases. Next $$$T$$$ lines contain test cases — one per line. Each line contains two integers $$$a$$$ and $$$m$$$ ($$$1 \le a &lt; m \le 10^{10}$$$).
1,800
Print $$$T$$$ integers — one per test case. For each test case print the number of appropriate $$$x$$$-s.
standard output
PASSED
d8bb87bd4a411844f412163d1ed3a71a
train_002.jsonl
1580308500
You are given two integers $$$a$$$ and $$$m$$$. Calculate the number of integers $$$x$$$ such that $$$0 \le x &lt; m$$$ and $$$\gcd(a, m) = \gcd(a + x, m)$$$.Note: $$$\gcd(a, b)$$$ is the greatest common divisor of $$$a$$$ and $$$b$$$.
256 megabytes
import java.io.*; import java.util.*; //import java.math.*; //import java.awt.Point; public class Main { //static final long MOD = 998244353L; //static final long INF = -1000000000000000007L; static final long MOD = 1000000007L; //static final int INF = 1000000007; public static void main(String[] args) { FastScanner sc = new FastScanner(); PrintWriter pw = new PrintWriter(System.out); int Q = sc.ni(); for (int q = 0; q < Q; q++) { long A = sc.nl(); long M = sc.nl(); long G = gcd(A,M); HashMap<Long,Integer> Gfactor = new HashMap<Long,Integer>(); long Gtemp = G; for (long i = 2; i*i <= G; i++) { int pow = 0; while (Gtemp % i == 0) { Gtemp /= i; pow++; } if (pow > 0) { Gfactor.put(i,pow); } } if (Gtemp > 1) { Gfactor.put(Gtemp,1); } HashMap<Long,Integer> Mfactor = new HashMap<Long,Integer>(); long Mtemp = M; for (long i = 2; i*i <= M; i++) { int pow = 0; while (Mtemp % i == 0) { Mtemp /= i; pow++; } if (pow > 0) { Mfactor.put(i,pow); } } if (Mtemp > 1) { Mfactor.put(Mtemp,1); } long div = 1; ArrayList<Long> noDiv = new ArrayList<Long>(); for (long divisor: Mfactor.keySet()) { int powM = Mfactor.get(divisor); int powG = Gfactor.getOrDefault(divisor, 0); if (powM == powG) { div *= ((long)Math.pow(divisor,powM)); } else { div *= ((long)Math.pow(divisor,powG)); noDiv.add(divisor); } } long ans = 0; for (int i = 0; i < (1<<noDiv.size()); i++) { long D = 1; for (int j = 0; j < noDiv.size(); j++) { if ((i&(1<<j)) > 0) { D *= noDiv.get(j); } } if (((double)D)*div > 20000000000.0) { //no change continue; } D *= div; long cnt = (A+M-1)/D-(A-1)/D; if (Integer.bitCount(i) % 2 == 0) { ans += cnt; } else { ans -= cnt; } } //pw.println(div); //pw.println(noDiv); pw.println(ans); } pw.close(); } public static long dist(long[] p1, long[] p2) { return (Math.abs(p2[0]-p1[0])+Math.abs(p2[1]-p1[1])); } //Find the GCD of two numbers public static long gcd(long a, long b) { if (a < b) return gcd(b,a); if (b == 0) return a; else return gcd(b,a%b); } //Fast exponentiation (x^y mod m) public static long power(long x, long y, long m) { long ans = 1; x %= m; while (y > 0) { if(y % 2 == 1) ans = (ans * x) % m; y /= 2; x = (x * x) % m; } return ans; } public static int[][] shuffle(int[][] array) { Random rgen = new Random(); for (int i = 0; i < array.length; i++) { int randomPosition = rgen.nextInt(array.length); int[] temp = array[i]; array[i] = array[randomPosition]; array[randomPosition] = temp; } return array; } public static int[][] sort(int[][] array) { //Sort an array (immune to quicksort TLE) Arrays.sort(array, new Comparator<int[]>() { @Override public int compare(int[] arr1, int[] arr2) { return arr1[0]-arr2[0]; //ascending order } }); return array; } public static long[][] sort(long[][] array) { //Sort an array (immune to quicksort TLE) Random rgen = new Random(); for (int i = 0; i < array.length; i++) { int randomPosition = rgen.nextInt(array.length); long[] temp = array[i]; array[i] = array[randomPosition]; array[randomPosition] = temp; } Arrays.sort(array, new Comparator<long[]>() { @Override public int compare(long[] arr1, long[] arr2) { //return 0; if (arr1[0] < arr2[0]) { return -1; } else if (arr1[0] > arr2[0]) { return 1; } else { return 0; } } }); return array; } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int ni() { return Integer.parseInt(next()); } long nl() { return Long.parseLong(next()); } double nd() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n4 9\n5 10\n42 9999999967"]
2 seconds
["6\n1\n9999999966"]
NoteIn the first test case appropriate $$$x$$$-s are $$$[0, 1, 3, 4, 6, 7]$$$.In the second test case the only appropriate $$$x$$$ is $$$0$$$.
Java 8
standard input
[ "number theory", "math" ]
adcd813d4c45337bbd8bb0abfa2f0e00
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 50$$$) — the number of test cases. Next $$$T$$$ lines contain test cases — one per line. Each line contains two integers $$$a$$$ and $$$m$$$ ($$$1 \le a &lt; m \le 10^{10}$$$).
1,800
Print $$$T$$$ integers — one per test case. For each test case print the number of appropriate $$$x$$$-s.
standard output
PASSED
68b3e9320b23c6b63d58c5f4ac26ed7e
train_002.jsonl
1580308500
You are given two integers $$$a$$$ and $$$m$$$. Calculate the number of integers $$$x$$$ such that $$$0 \le x &lt; m$$$ and $$$\gcd(a, m) = \gcd(a + x, m)$$$.Note: $$$\gcd(a, b)$$$ is the greatest common divisor of $$$a$$$ and $$$b$$$.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; import java.util.Stack; public class ROUGH{ public static class FastReader { BufferedReader br; StringTokenizer root; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (root == null || !root.hasMoreTokens()) { try { root = new StringTokenizer(br.readLine()); } catch (Exception r) { r.printStackTrace(); } } return root.nextToken(); } int nextInt() { return Integer.parseInt(next()); } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (Exception r) { r.printStackTrace(); } return str; } } public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out)); static int mod = (int) (1e9+7); static long cf = 998244353; static final int N = (int) 1e3+10; public static List<Integer>[] edges; public static int[][] parent; public static int col = 20; public static int[] Bit; public static long[] fact,inv; public static int[] prime; public static Map<Integer, Integer> map; static char ch = 'z'; static FastReader sc = new FastReader(); public static void main(String[] args) { // Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-->0) { long a = sc.nextLong(); long b = sc.nextLong(); long gcd = gcd(a,b); a/=gcd; b/=gcd; out.println(phi(b)); } out.close(); } static long phi(long n) { long result = n; for (long p = 2; p * p <= n; ++p) { if (n % p == 0) { while (n % p == 0) n /= p; result -= result / p; } } if (n > 1) result -= result / n; return result; } static long gcd(long a,long b) { if(b == 0) return a; return gcd(b,a%b); } }
Java
["3\n4 9\n5 10\n42 9999999967"]
2 seconds
["6\n1\n9999999966"]
NoteIn the first test case appropriate $$$x$$$-s are $$$[0, 1, 3, 4, 6, 7]$$$.In the second test case the only appropriate $$$x$$$ is $$$0$$$.
Java 8
standard input
[ "number theory", "math" ]
adcd813d4c45337bbd8bb0abfa2f0e00
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 50$$$) — the number of test cases. Next $$$T$$$ lines contain test cases — one per line. Each line contains two integers $$$a$$$ and $$$m$$$ ($$$1 \le a &lt; m \le 10^{10}$$$).
1,800
Print $$$T$$$ integers — one per test case. For each test case print the number of appropriate $$$x$$$-s.
standard output
PASSED
805efc243755ed4bb3039021cbef0036
train_002.jsonl
1580308500
You are given two integers $$$a$$$ and $$$m$$$. Calculate the number of integers $$$x$$$ such that $$$0 \le x &lt; m$$$ and $$$\gcd(a, m) = \gcd(a + x, m)$$$.Note: $$$\gcd(a, b)$$$ is the greatest common divisor of $$$a$$$ and $$$b$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main { static Parser parser = new Parser(); public static void main(String[] args) throws IOException { int T = parser.parseInt(); for(int i = 0; i < T; i++){ long a = parser.parseLong(); long m = parser.parseLong(); System.out.println(phi(m / gcd(a, m))); } } public static long phi(long n){ long d = 2; long ans = n; while(d * d <= n){ if(n % d == 0){ while(n % d == 0){ n /= d; } ans -= ans / d; } d += 1; } if(n > 1){ ans -= ans / n; } return ans; } public static long gcd(long a, long b){ return b > 0 ? gcd(b, a % b) : a; } } class Parser { private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); private static final Iterator<String> stringIterator = br.lines().iterator(); private static final Deque<String> inputs = new ArrayDeque<>(); void fill() throws IOException { if(inputs.isEmpty()){ if(!stringIterator.hasNext()) throw new IOException(); inputs.addAll(Arrays.asList(stringIterator.next().split(" "))); } } Integer parseInt() throws IOException { fill(); if(!inputs.isEmpty()) { return Integer.parseInt(inputs.pollFirst()); } throw new IOException(); } Long parseLong() throws IOException { fill(); if(!inputs.isEmpty()) { return Long.parseLong(inputs.pollFirst()); } throw new IOException(); } Double parseDouble() throws IOException { fill(); if(!inputs.isEmpty()) { return Double.parseDouble(inputs.pollFirst()); } throw new IOException(); } String parseString() throws IOException { fill(); return inputs.pollFirst(); } }
Java
["3\n4 9\n5 10\n42 9999999967"]
2 seconds
["6\n1\n9999999966"]
NoteIn the first test case appropriate $$$x$$$-s are $$$[0, 1, 3, 4, 6, 7]$$$.In the second test case the only appropriate $$$x$$$ is $$$0$$$.
Java 8
standard input
[ "number theory", "math" ]
adcd813d4c45337bbd8bb0abfa2f0e00
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 50$$$) — the number of test cases. Next $$$T$$$ lines contain test cases — one per line. Each line contains two integers $$$a$$$ and $$$m$$$ ($$$1 \le a &lt; m \le 10^{10}$$$).
1,800
Print $$$T$$$ integers — one per test case. For each test case print the number of appropriate $$$x$$$-s.
standard output
PASSED
963fc8da7b13af823f8fd5a12adeaab0
train_002.jsonl
1580308500
You are given two integers $$$a$$$ and $$$m$$$. Calculate the number of integers $$$x$$$ such that $$$0 \le x &lt; m$$$ and $$$\gcd(a, m) = \gcd(a + x, m)$$$.Note: $$$\gcd(a, b)$$$ is the greatest common divisor of $$$a$$$ and $$$b$$$.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class Main { private static final Integer[] PRIMES = primesTo(100000); public static void solveCase(FastIO io, int testCase) { long N = io.nextLong(); long M = io.nextLong(); long g = gcd(N, M); long b = M / g; Long[] factors = new HashSet<>(primeFactors(b)).toArray(new Long[0]); // System.out.format("b = %d\n", b); // System.out.println(Arrays.toString(factors)); long total = 0; for (int m = 1; m < (1 << factors.length); ++m) { long p = 1; for (int i = 0; i < factors.length; ++i) { if (((m >> i) & 1) == 1) { p *= factors[i]; } } if (Integer.bitCount(m) % 2 == 1) { total += b / p; } else { total -= b / p; } } io.println(b - total); } private static ArrayList<Long> primeFactors(long n) { return primeFactors(n, PRIMES); } private static ArrayList<Long> primeFactors(long n, Integer[] primes) { ArrayList<Long> factors = new ArrayList<>(); long r = n; for (long p : PRIMES) { if (p > n / p) { break; } while (r % p == 0) { factors.add(p); r /= p; } } if (r > 1) { factors.add(r); } return factors; } /** * Computes the GCD (greatest common denominator) between two numbers. */ public static long gcd(long a, long b) { return BigInteger.valueOf(a).gcd(BigInteger.valueOf(b)).longValue(); } /** * Computes all the primes up to the specified number. */ public static Integer[] primesTo(int n) { ArrayList<Integer> primes = new ArrayList<Integer>(); boolean[] prime = new boolean[n + 1]; for (int i = 0; i < prime.length; i++) prime[i] = true; prime[0] = false; prime[1] = false; for (int i = 2; i < prime.length; i++) { if (prime[i]) { primes.add(i); if ((long) i * i <= n) { for (int j = i * i; j < prime.length; j += i) { prime[j] = false; } } } } return primes.toArray(new Integer[0]); } public static void solve(FastIO io) { int T = io.nextInt(); for (int t = 0; t < T; ++t) { solveCase(io, t); } } public static class FastIO { private InputStream reader; private PrintWriter writer; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastIO(InputStream r, OutputStream w) { reader = r; writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w))); } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = reader.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } // TODO: read this byte-by-byte like the other read functions. public double nextDouble() { return Double.parseDouble(nextString()); } public int[] nextIntArray(int n) { return nextIntArray(n, 0); } public int[] nextIntArray(int n, int off) { int[] arr = new int[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextInt(); } return arr; } public long[] nextLongArray(int n) { return nextLongArray(n, 0); } public long[] nextLongArray(int n, int off) { long[] arr = new long[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void printArray(int[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printArray(long[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printlnArray(int[] arr) { printArray(arr); writer.println(); } public void printlnArray(long[] arr) { printArray(arr); writer.println(); } public void printf(String format, Object... args) { print(String.format(format, args)); } public void flush() { writer.flush(); } } public static void main(String[] args) { FastIO io = new FastIO(System.in, System.out); solve(io); io.flush(); } }
Java
["3\n4 9\n5 10\n42 9999999967"]
2 seconds
["6\n1\n9999999966"]
NoteIn the first test case appropriate $$$x$$$-s are $$$[0, 1, 3, 4, 6, 7]$$$.In the second test case the only appropriate $$$x$$$ is $$$0$$$.
Java 8
standard input
[ "number theory", "math" ]
adcd813d4c45337bbd8bb0abfa2f0e00
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 50$$$) — the number of test cases. Next $$$T$$$ lines contain test cases — one per line. Each line contains two integers $$$a$$$ and $$$m$$$ ($$$1 \le a &lt; m \le 10^{10}$$$).
1,800
Print $$$T$$$ integers — one per test case. For each test case print the number of appropriate $$$x$$$-s.
standard output
PASSED
7049dacc8014ed88450cb3730c5f6b2d
train_002.jsonl
1580308500
You are given two integers $$$a$$$ and $$$m$$$. Calculate the number of integers $$$x$$$ such that $$$0 \le x &lt; m$$$ and $$$\gcd(a, m) = \gcd(a + x, m)$$$.Note: $$$\gcd(a, b)$$$ is the greatest common divisor of $$$a$$$ and $$$b$$$.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class Main { private static final Integer[] PRIMES = primesTo(100000); public static void solveCase(FastIO io, int testCase) { long N = io.nextLong(); long M = io.nextLong(); long g = gcd(N, M); long a = N / g; long b = M / g; HashSet<Long> primeSet = new HashSet<>(); for (long p : PRIMES) { if (b % p == 0) { primeSet.add(p); primeSet.addAll(primeFactors(b / p)); } } primeSet.remove(1L); long rem = b; for (long p : primeSet) { while (rem % p == 0) { rem /= p; } } primeSet.add(rem); primeSet.remove(1L); Long[] factors = primeSet.toArray(new Long[0]); // System.out.format("g = %d, a = %d, b = %d\n", g, a, b); // System.out.println(Arrays.toString(factors)); long total = 0; for (int m = 1; m < (1 << factors.length); ++m) { long p = 1; for (int i = 0; i < factors.length; ++i) { if (((m >> i) & 1) == 1) { p *= factors[i]; } } if (Integer.bitCount(m) % 2 == 1) { total += b / p; } else { total -= b / p; } } io.println(b - total); } private static ArrayList<Long> primeFactors(long n) { ArrayList<Long> factors = new ArrayList<>(); for (long p : PRIMES) { if (n % p == 0) { factors.add(p); } } if (factors.isEmpty()) { factors.add(n); } return factors; } /** * Computes the GCD (greatest common denominator) between two numbers. */ public static long gcd(long a, long b) { return BigInteger.valueOf(a).gcd(BigInteger.valueOf(b)).longValue(); } /** * Computes all the primes up to the specified number. */ public static Integer[] primesTo(int n) { ArrayList<Integer> primes = new ArrayList<Integer>(); boolean[] prime = new boolean[n + 1]; for (int i = 0; i < prime.length; i++) prime[i] = true; prime[0] = false; prime[1] = false; for (int i = 2; i < prime.length; i++) { if (prime[i]) { primes.add(i); if ((long) i * i <= n) { for (int j = i * i; j < prime.length; j += i) { prime[j] = false; } } } } return primes.toArray(new Integer[0]); } public static void solve(FastIO io) { int T = io.nextInt(); for (int t = 0; t < T; ++t) { solveCase(io, t); } } public static class FastIO { private InputStream reader; private PrintWriter writer; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastIO(InputStream r, OutputStream w) { reader = r; writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w))); } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = reader.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } // TODO: read this byte-by-byte like the other read functions. public double nextDouble() { return Double.parseDouble(nextString()); } public int[] nextIntArray(int n) { return nextIntArray(n, 0); } public int[] nextIntArray(int n, int off) { int[] arr = new int[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextInt(); } return arr; } public long[] nextLongArray(int n) { return nextLongArray(n, 0); } public long[] nextLongArray(int n, int off) { long[] arr = new long[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void printArray(int[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printArray(long[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printlnArray(int[] arr) { printArray(arr); writer.println(); } public void printlnArray(long[] arr) { printArray(arr); writer.println(); } public void printf(String format, Object... args) { print(String.format(format, args)); } public void flush() { writer.flush(); } } public static void main(String[] args) { FastIO io = new FastIO(System.in, System.out); solve(io); io.flush(); } }
Java
["3\n4 9\n5 10\n42 9999999967"]
2 seconds
["6\n1\n9999999966"]
NoteIn the first test case appropriate $$$x$$$-s are $$$[0, 1, 3, 4, 6, 7]$$$.In the second test case the only appropriate $$$x$$$ is $$$0$$$.
Java 8
standard input
[ "number theory", "math" ]
adcd813d4c45337bbd8bb0abfa2f0e00
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 50$$$) — the number of test cases. Next $$$T$$$ lines contain test cases — one per line. Each line contains two integers $$$a$$$ and $$$m$$$ ($$$1 \le a &lt; m \le 10^{10}$$$).
1,800
Print $$$T$$$ integers — one per test case. For each test case print the number of appropriate $$$x$$$-s.
standard output
PASSED
f17cf9ca57f84ce10a496ddda808478b
train_002.jsonl
1580308500
You are given two integers $$$a$$$ and $$$m$$$. Calculate the number of integers $$$x$$$ such that $$$0 \le x &lt; m$$$ and $$$\gcd(a, m) = \gcd(a + x, m)$$$.Note: $$$\gcd(a, b)$$$ is the greatest common divisor of $$$a$$$ and $$$b$$$.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class Main { private static final Integer[] PRIMES = primesTo(100000); public static void solveCase(FastIO io, int testCase) { long N = io.nextLong(); long M = io.nextLong(); long g = gcd(N, M); long b = M / g; Long[] factors = new HashSet<>(primeFactors(b, PRIMES)).toArray(new Long[0]); long total = 0; for (int m = 1; m < (1 << factors.length); ++m) { long p = 1; for (int i = 0; i < factors.length; ++i) { if (((m >> i) & 1) == 1) { p *= factors[i]; } } if (Integer.bitCount(m) % 2 == 1) { total += b / p; } else { total -= b / p; } } io.println(b - total); } /* * Computes the prime factors of a number. * Returned list is in increasing order. * The imput list of primes must be go up to at least sqrt(n). */ private static ArrayList<Long> primeFactors(long n, Integer[] primes) { ArrayList<Long> factors = new ArrayList<>(); long r = n; for (long p : PRIMES) { if (p > n / p) { break; } while (r % p == 0) { factors.add(p); r /= p; } } if (r > 1) { factors.add(r); } return factors; } /** * Computes all the primes up to the specified number. */ public static Integer[] primesTo(int n) { ArrayList<Integer> primes = new ArrayList<Integer>(); boolean[] prime = new boolean[n + 1]; for (int i = 0; i < prime.length; i++) prime[i] = true; prime[0] = false; prime[1] = false; for (int i = 2; i < prime.length; i++) { if (prime[i]) { primes.add(i); if ((long) i * i <= n) { for (int j = i * i; j < prime.length; j += i) { prime[j] = false; } } } } return primes.toArray(new Integer[0]); } /** * Computes the GCD (greatest common denominator) between two numbers. */ public static long gcd(long a, long b) { return BigInteger.valueOf(a).gcd(BigInteger.valueOf(b)).longValue(); } public static void solve(FastIO io) { int T = io.nextInt(); for (int t = 0; t < T; ++t) { solveCase(io, t); } } public static class FastIO { private InputStream reader; private PrintWriter writer; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastIO(InputStream r, OutputStream w) { reader = r; writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w))); } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = reader.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } // TODO: read this byte-by-byte like the other read functions. public double nextDouble() { return Double.parseDouble(nextString()); } public int[] nextIntArray(int n) { return nextIntArray(n, 0); } public int[] nextIntArray(int n, int off) { int[] arr = new int[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextInt(); } return arr; } public long[] nextLongArray(int n) { return nextLongArray(n, 0); } public long[] nextLongArray(int n, int off) { long[] arr = new long[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void printArray(int[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printArray(long[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printlnArray(int[] arr) { printArray(arr); writer.println(); } public void printlnArray(long[] arr) { printArray(arr); writer.println(); } public void printf(String format, Object... args) { print(String.format(format, args)); } public void flush() { writer.flush(); } } public static void main(String[] args) { FastIO io = new FastIO(System.in, System.out); solve(io); io.flush(); } }
Java
["3\n4 9\n5 10\n42 9999999967"]
2 seconds
["6\n1\n9999999966"]
NoteIn the first test case appropriate $$$x$$$-s are $$$[0, 1, 3, 4, 6, 7]$$$.In the second test case the only appropriate $$$x$$$ is $$$0$$$.
Java 8
standard input
[ "number theory", "math" ]
adcd813d4c45337bbd8bb0abfa2f0e00
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 50$$$) — the number of test cases. Next $$$T$$$ lines contain test cases — one per line. Each line contains two integers $$$a$$$ and $$$m$$$ ($$$1 \le a &lt; m \le 10^{10}$$$).
1,800
Print $$$T$$$ integers — one per test case. For each test case print the number of appropriate $$$x$$$-s.
standard output
PASSED
8686b9f741bce02d2d7a51e38de18950
train_002.jsonl
1580308500
You are given two integers $$$a$$$ and $$$m$$$. Calculate the number of integers $$$x$$$ such that $$$0 \le x &lt; m$$$ and $$$\gcd(a, m) = \gcd(a + x, m)$$$.Note: $$$\gcd(a, b)$$$ is the greatest common divisor of $$$a$$$ and $$$b$$$.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class Main { private static final Integer[] PRIMES = primesTo(100000); public static void solveCase(FastIO io, int testCase) { long N = io.nextLong(); long M = io.nextLong(); long g = gcd(N, M); long a = N / g; long b = M / g; HashSet<Long> primeSet = new HashSet<>(); for (long p : PRIMES) { if (b % p == 0) { primeSet.add(p); } } primeSet.remove(1L); long rem = b; for (long p : primeSet) { while (rem % p == 0) { rem /= p; } } primeSet.add(rem); primeSet.remove(1L); Long[] factors = primeSet.toArray(new Long[0]); long total = 0; for (int m = 1; m < (1 << factors.length); ++m) { long p = 1; for (int i = 0; i < factors.length; ++i) { if (((m >> i) & 1) == 1) { p *= factors[i]; } } if (Integer.bitCount(m) % 2 == 1) { total += b / p; } else { total -= b / p; } } io.println(b - total); } private static ArrayList<Long> primeFactors(long n) { ArrayList<Long> factors = new ArrayList<>(); for (long p : PRIMES) { if (n % p == 0) { factors.add(p); } } if (factors.isEmpty()) { factors.add(n); } return factors; } /** * Computes the GCD (greatest common denominator) between two numbers. */ public static long gcd(long a, long b) { return BigInteger.valueOf(a).gcd(BigInteger.valueOf(b)).longValue(); } /** * Computes all the primes up to the specified number. */ public static Integer[] primesTo(int n) { ArrayList<Integer> primes = new ArrayList<Integer>(); boolean[] prime = new boolean[n + 1]; for (int i = 0; i < prime.length; i++) prime[i] = true; prime[0] = false; prime[1] = false; for (int i = 2; i < prime.length; i++) { if (prime[i]) { primes.add(i); if ((long) i * i <= n) { for (int j = i * i; j < prime.length; j += i) { prime[j] = false; } } } } return primes.toArray(new Integer[0]); } public static void solve(FastIO io) { int T = io.nextInt(); for (int t = 0; t < T; ++t) { solveCase(io, t); } } public static class FastIO { private InputStream reader; private PrintWriter writer; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastIO(InputStream r, OutputStream w) { reader = r; writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w))); } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = reader.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } // TODO: read this byte-by-byte like the other read functions. public double nextDouble() { return Double.parseDouble(nextString()); } public int[] nextIntArray(int n) { return nextIntArray(n, 0); } public int[] nextIntArray(int n, int off) { int[] arr = new int[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextInt(); } return arr; } public long[] nextLongArray(int n) { return nextLongArray(n, 0); } public long[] nextLongArray(int n, int off) { long[] arr = new long[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void printArray(int[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printArray(long[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printlnArray(int[] arr) { printArray(arr); writer.println(); } public void printlnArray(long[] arr) { printArray(arr); writer.println(); } public void printf(String format, Object... args) { print(String.format(format, args)); } public void flush() { writer.flush(); } } public static void main(String[] args) { FastIO io = new FastIO(System.in, System.out); solve(io); io.flush(); } }
Java
["3\n4 9\n5 10\n42 9999999967"]
2 seconds
["6\n1\n9999999966"]
NoteIn the first test case appropriate $$$x$$$-s are $$$[0, 1, 3, 4, 6, 7]$$$.In the second test case the only appropriate $$$x$$$ is $$$0$$$.
Java 8
standard input
[ "number theory", "math" ]
adcd813d4c45337bbd8bb0abfa2f0e00
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 50$$$) — the number of test cases. Next $$$T$$$ lines contain test cases — one per line. Each line contains two integers $$$a$$$ and $$$m$$$ ($$$1 \le a &lt; m \le 10^{10}$$$).
1,800
Print $$$T$$$ integers — one per test case. For each test case print the number of appropriate $$$x$$$-s.
standard output
PASSED
18425c4df77def37807e0d11fd0bcdf7
train_002.jsonl
1580308500
You are given two integers $$$a$$$ and $$$m$$$. Calculate the number of integers $$$x$$$ such that $$$0 \le x &lt; m$$$ and $$$\gcd(a, m) = \gcd(a + x, m)$$$.Note: $$$\gcd(a, b)$$$ is the greatest common divisor of $$$a$$$ and $$$b$$$.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class Main { private static final Integer[] PRIMES = primesTo(100000); public static void solveCase(FastIO io, int testCase) { long N = io.nextLong(); long M = io.nextLong(); long g = gcd(N, M); long a = N / g; long b = M / g; HashSet<Long> primeSet = new HashSet<>(); for (long p : PRIMES) { if (b % p == 0) { primeSet.add(p); primeSet.addAll(primeFactors(b / p)); } } primeSet.remove(1L); long rem = b; for (long p : primeSet) { while (rem % p == 0) { rem /= p; } } primeSet.add(rem); primeSet.remove(1L); Long[] factors = primeSet.toArray(new Long[0]); long total = 0; for (int m = 1; m < (1 << factors.length); ++m) { long p = 1; for (int i = 0; i < factors.length; ++i) { if (((m >> i) & 1) == 1) { p *= factors[i]; } } if (Integer.bitCount(m) % 2 == 1) { total += b / p; } else { total -= b / p; } } io.println(b - total); } private static ArrayList<Long> primeFactors(long n) { ArrayList<Long> factors = new ArrayList<>(); for (long p : PRIMES) { if (n % p == 0) { factors.add(p); } } if (factors.isEmpty()) { factors.add(n); } return factors; } /** * Computes the GCD (greatest common denominator) between two numbers. */ public static long gcd(long a, long b) { return BigInteger.valueOf(a).gcd(BigInteger.valueOf(b)).longValue(); } /** * Computes all the primes up to the specified number. */ public static Integer[] primesTo(int n) { ArrayList<Integer> primes = new ArrayList<Integer>(); boolean[] prime = new boolean[n + 1]; for (int i = 0; i < prime.length; i++) prime[i] = true; prime[0] = false; prime[1] = false; for (int i = 2; i < prime.length; i++) { if (prime[i]) { primes.add(i); if ((long) i * i <= n) { for (int j = i * i; j < prime.length; j += i) { prime[j] = false; } } } } return primes.toArray(new Integer[0]); } public static void solve(FastIO io) { int T = io.nextInt(); for (int t = 0; t < T; ++t) { solveCase(io, t); } } public static class FastIO { private InputStream reader; private PrintWriter writer; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastIO(InputStream r, OutputStream w) { reader = r; writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w))); } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = reader.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } // TODO: read this byte-by-byte like the other read functions. public double nextDouble() { return Double.parseDouble(nextString()); } public int[] nextIntArray(int n) { return nextIntArray(n, 0); } public int[] nextIntArray(int n, int off) { int[] arr = new int[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextInt(); } return arr; } public long[] nextLongArray(int n) { return nextLongArray(n, 0); } public long[] nextLongArray(int n, int off) { long[] arr = new long[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void printArray(int[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printArray(long[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printlnArray(int[] arr) { printArray(arr); writer.println(); } public void printlnArray(long[] arr) { printArray(arr); writer.println(); } public void printf(String format, Object... args) { print(String.format(format, args)); } public void flush() { writer.flush(); } } public static void main(String[] args) { FastIO io = new FastIO(System.in, System.out); solve(io); io.flush(); } }
Java
["3\n4 9\n5 10\n42 9999999967"]
2 seconds
["6\n1\n9999999966"]
NoteIn the first test case appropriate $$$x$$$-s are $$$[0, 1, 3, 4, 6, 7]$$$.In the second test case the only appropriate $$$x$$$ is $$$0$$$.
Java 8
standard input
[ "number theory", "math" ]
adcd813d4c45337bbd8bb0abfa2f0e00
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 50$$$) — the number of test cases. Next $$$T$$$ lines contain test cases — one per line. Each line contains two integers $$$a$$$ and $$$m$$$ ($$$1 \le a &lt; m \le 10^{10}$$$).
1,800
Print $$$T$$$ integers — one per test case. For each test case print the number of appropriate $$$x$$$-s.
standard output
PASSED
5941015e8043b11c8850abc4c8772159
train_002.jsonl
1320858000
Nicholas, a painter is going to paint several new canvases. Nicholas is sure that the canvases will turn out so great that each one will need framing and being hung on the wall. Frames are what Nicholas decided to begin with. Nicholas has n sticks whose lengths equal a1, a2, ... an. Nicholas does not want to break the sticks or glue them together. To make a h × w-sized frame, he needs two sticks whose lengths equal h and two sticks whose lengths equal w. Specifically, to make a square frame (when h = w), he needs four sticks of the same length.Now Nicholas wants to make from the sticks that he has as many frames as possible; to be able to paint as many canvases as possible to fill the frames. Help him in this uneasy task. Note that it is not necessary to use all the sticks Nicholas has.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args){ Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] map = new int[101]; for(int i = 0; i<n;i++){ int x = in.nextInt(); map[x]++; } int count = 0; int pair =0; for(int i=1; i<=100; i++){ if (map[i]>=4) { count+=map[i]/4; map[i]=map[i]%4; pair+=map[i]/2; } else if (map[i]==1) map[i]=0; else if (map[i]==3 || map[i]==2) pair++; } count+=pair/2; System.out.println(count); } }
Java
["5\n2 4 3 2 3", "13\n2 2 4 4 4 4 6 6 6 7 7 9 9", "4\n3 3 3 5"]
1 second
["1", "3", "0"]
null
Java 7
standard input
[ "implementation" ]
f9b56b3fddcd5db0d0671714df3f8646
The first line contains an integer n (1 ≤ n ≤ 100) — the number of sticks. The second line contains n space-separated integers. The i-th integer equals the length of the i-th stick ai (1 ≤ ai ≤ 100).
1,000
Print the single number — the maximum number of frames Nicholas can make for his future canvases.
standard output
PASSED
018eda1d1f6456b4b47be97e43c838a1
train_002.jsonl
1320858000
Nicholas, a painter is going to paint several new canvases. Nicholas is sure that the canvases will turn out so great that each one will need framing and being hung on the wall. Frames are what Nicholas decided to begin with. Nicholas has n sticks whose lengths equal a1, a2, ... an. Nicholas does not want to break the sticks or glue them together. To make a h × w-sized frame, he needs two sticks whose lengths equal h and two sticks whose lengths equal w. Specifically, to make a square frame (when h = w), he needs four sticks of the same length.Now Nicholas wants to make from the sticks that he has as many frames as possible; to be able to paint as many canvases as possible to fill the frames. Help him in this uneasy task. Note that it is not necessary to use all the sticks Nicholas has.
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { Integer n = in.nextInt(); int sum = 0; Integer[] a = new Integer[101]; Arrays.fill(a, 0); for(int i = 1; i <= n; i++) a[in.nextInt()]++; for(int i = 1; i <= 100; i++ ) if(a[i]%2 == 0)sum += a[i]/2; else { sum += (a[i]-1)/2; } out.println(sum/2); } } class InputReader { public BufferedReader reader; public 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 Integer nextInt() { return Integer.parseInt(next()); } public Long nextLong() { return Long.parseLong(next()); } public Double nextDouble() { return Double.parseDouble(next()); } public Float nextFloat() { return Float.parseFloat(next()); } public BigInteger nextBigInteger() { return new BigInteger(next()); } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } public Integer[] nextIntegerArray(int n) { Integer[] a = new Integer[n]; for(Integer i = 0; i < n; i++) a[i] = nextInt(); return a; } public Long[] nextLongArray(int n) { Long[] a = new Long[n]; for(Integer i = 0; i < n; i++) a[i] = nextLong(); return a; } public String[] nextStringArray(int n){ String[] s = new String[n]; for(Integer i = 0; i < n; i++) s[i] = next(); return s; } public String[] nextLineStringArray(int n){ String[] s = new String[n]; for(Integer i = 0; i < n; i++) s[i] = next(); return s; } }
Java
["5\n2 4 3 2 3", "13\n2 2 4 4 4 4 6 6 6 7 7 9 9", "4\n3 3 3 5"]
1 second
["1", "3", "0"]
null
Java 7
standard input
[ "implementation" ]
f9b56b3fddcd5db0d0671714df3f8646
The first line contains an integer n (1 ≤ n ≤ 100) — the number of sticks. The second line contains n space-separated integers. The i-th integer equals the length of the i-th stick ai (1 ≤ ai ≤ 100).
1,000
Print the single number — the maximum number of frames Nicholas can make for his future canvases.
standard output
PASSED
2a4beaff9b78bb7924c9ade8d78514b2
train_002.jsonl
1320858000
Nicholas, a painter is going to paint several new canvases. Nicholas is sure that the canvases will turn out so great that each one will need framing and being hung on the wall. Frames are what Nicholas decided to begin with. Nicholas has n sticks whose lengths equal a1, a2, ... an. Nicholas does not want to break the sticks or glue them together. To make a h × w-sized frame, he needs two sticks whose lengths equal h and two sticks whose lengths equal w. Specifically, to make a square frame (when h = w), he needs four sticks of the same length.Now Nicholas wants to make from the sticks that he has as many frames as possible; to be able to paint as many canvases as possible to fill the frames. Help him in this uneasy task. Note that it is not necessary to use all the sticks Nicholas has.
256 megabytes
import java.util.Scanner; public class B_Canvas_Frames { public static void main(String[] args){ Scanner input=new Scanner(System.in); int n=input.nextInt(); int[][] sticks=new int[100][2]; int i,number; for(i=0;i<100;i++){ sticks[i][0]=i+1; sticks[i][1]=0; } for(i=0;i<n;i++){ number=input.nextInt(); sticks[number-1][1]++; } int count=0; for(i=0;i<100;i++){ if(sticks[i][1]==2)count=count+2; else if(sticks[i][1]>2 && sticks[i][1]%2==0)count=count+sticks[i][1]; else if(sticks[i][1]>2 && sticks[i][1]%2!=0)count=count+sticks[i][1]-1; } System.out.println(count/4); } }
Java
["5\n2 4 3 2 3", "13\n2 2 4 4 4 4 6 6 6 7 7 9 9", "4\n3 3 3 5"]
1 second
["1", "3", "0"]
null
Java 7
standard input
[ "implementation" ]
f9b56b3fddcd5db0d0671714df3f8646
The first line contains an integer n (1 ≤ n ≤ 100) — the number of sticks. The second line contains n space-separated integers. The i-th integer equals the length of the i-th stick ai (1 ≤ ai ≤ 100).
1,000
Print the single number — the maximum number of frames Nicholas can make for his future canvases.
standard output
PASSED
428726ab33c0f56849433ef3deccb5d3
train_002.jsonl
1320858000
Nicholas, a painter is going to paint several new canvases. Nicholas is sure that the canvases will turn out so great that each one will need framing and being hung on the wall. Frames are what Nicholas decided to begin with. Nicholas has n sticks whose lengths equal a1, a2, ... an. Nicholas does not want to break the sticks or glue them together. To make a h × w-sized frame, he needs two sticks whose lengths equal h and two sticks whose lengths equal w. Specifically, to make a square frame (when h = w), he needs four sticks of the same length.Now Nicholas wants to make from the sticks that he has as many frames as possible; to be able to paint as many canvases as possible to fill the frames. Help him in this uneasy task. Note that it is not necessary to use all the sticks Nicholas has.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class CanvasFrames { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); //READ---------------------------------------------------- int n = sc.nextInt(); int[] t = new int[101]; for (int i = 0; i < n; i++) t[sc.nextInt()]++; //SOLVE---------------------------------------------------- long res = 0; for (int i = 0; i <= 100; i++) res += t[i]/2; System.out.println(res/2); //CLOSE---------------------------------------------------- sc.close(); } }
Java
["5\n2 4 3 2 3", "13\n2 2 4 4 4 4 6 6 6 7 7 9 9", "4\n3 3 3 5"]
1 second
["1", "3", "0"]
null
Java 7
standard input
[ "implementation" ]
f9b56b3fddcd5db0d0671714df3f8646
The first line contains an integer n (1 ≤ n ≤ 100) — the number of sticks. The second line contains n space-separated integers. The i-th integer equals the length of the i-th stick ai (1 ≤ ai ≤ 100).
1,000
Print the single number — the maximum number of frames Nicholas can make for his future canvases.
standard output
PASSED
082f95c4fd339e4b1f664565b30447af
train_002.jsonl
1320858000
Nicholas, a painter is going to paint several new canvases. Nicholas is sure that the canvases will turn out so great that each one will need framing and being hung on the wall. Frames are what Nicholas decided to begin with. Nicholas has n sticks whose lengths equal a1, a2, ... an. Nicholas does not want to break the sticks or glue them together. To make a h × w-sized frame, he needs two sticks whose lengths equal h and two sticks whose lengths equal w. Specifically, to make a square frame (when h = w), he needs four sticks of the same length.Now Nicholas wants to make from the sticks that he has as many frames as possible; to be able to paint as many canvases as possible to fill the frames. Help him in this uneasy task. Note that it is not necessary to use all the sticks Nicholas has.
256 megabytes
import java.util.Scanner; import java.util.HashMap; import java.util.Map.Entry; public class CanvasFrames { public static void main(String []args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); HashMap<Integer,Integer> sticks = new HashMap<Integer,Integer>(); while(n-- > 0) { int tmp = s.nextInt(); if(!sticks.containsKey(tmp)) sticks.put(tmp, 1); else { for(Entry<Integer,Integer> e : sticks.entrySet()) { if(e.getKey() == tmp) e.setValue(e.getValue() + 1); } } } int pairs = 0; for(Entry<Integer,Integer> e : sticks.entrySet()) { pairs += e.getValue() / 2; } System.out.println(pairs / 2); } }
Java
["5\n2 4 3 2 3", "13\n2 2 4 4 4 4 6 6 6 7 7 9 9", "4\n3 3 3 5"]
1 second
["1", "3", "0"]
null
Java 7
standard input
[ "implementation" ]
f9b56b3fddcd5db0d0671714df3f8646
The first line contains an integer n (1 ≤ n ≤ 100) — the number of sticks. The second line contains n space-separated integers. The i-th integer equals the length of the i-th stick ai (1 ≤ ai ≤ 100).
1,000
Print the single number — the maximum number of frames Nicholas can make for his future canvases.
standard output
PASSED
1cf04bd0966a96a4dac38ea36e7e9c48
train_002.jsonl
1320858000
Nicholas, a painter is going to paint several new canvases. Nicholas is sure that the canvases will turn out so great that each one will need framing and being hung on the wall. Frames are what Nicholas decided to begin with. Nicholas has n sticks whose lengths equal a1, a2, ... an. Nicholas does not want to break the sticks or glue them together. To make a h × w-sized frame, he needs two sticks whose lengths equal h and two sticks whose lengths equal w. Specifically, to make a square frame (when h = w), he needs four sticks of the same length.Now Nicholas wants to make from the sticks that he has as many frames as possible; to be able to paint as many canvases as possible to fill the frames. Help him in this uneasy task. Note that it is not necessary to use all the sticks Nicholas has.
256 megabytes
import java.util.*; public class canvas { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] a = new int[100]; for (int i = 0; i < 100; i++) a[i] = 0; for (int i = 0; i < n; i++) { int x = in.nextInt(); a[x-1]++; } for (int i = 0; i < 100; i++) a[i] /= 2; int sum = 0; for (int i = 0; i < 100; i++) sum += a[i]; System.out.println(sum/2); } }
Java
["5\n2 4 3 2 3", "13\n2 2 4 4 4 4 6 6 6 7 7 9 9", "4\n3 3 3 5"]
1 second
["1", "3", "0"]
null
Java 7
standard input
[ "implementation" ]
f9b56b3fddcd5db0d0671714df3f8646
The first line contains an integer n (1 ≤ n ≤ 100) — the number of sticks. The second line contains n space-separated integers. The i-th integer equals the length of the i-th stick ai (1 ≤ ai ≤ 100).
1,000
Print the single number — the maximum number of frames Nicholas can make for his future canvases.
standard output
PASSED
2d060d6999498650f97ef87a41d8db08
train_002.jsonl
1320858000
Nicholas, a painter is going to paint several new canvases. Nicholas is sure that the canvases will turn out so great that each one will need framing and being hung on the wall. Frames are what Nicholas decided to begin with. Nicholas has n sticks whose lengths equal a1, a2, ... an. Nicholas does not want to break the sticks or glue them together. To make a h × w-sized frame, he needs two sticks whose lengths equal h and two sticks whose lengths equal w. Specifically, to make a square frame (when h = w), he needs four sticks of the same length.Now Nicholas wants to make from the sticks that he has as many frames as possible; to be able to paint as many canvases as possible to fill the frames. Help him in this uneasy task. Note that it is not necessary to use all the sticks Nicholas has.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; public class Haha{ public static void main(String[] args) throws IOException{ BufferedReader s = new BufferedReader(new InputStreamReader(System.in)); PrintWriter ww = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int size = Integer.parseInt(s.readLine()); int max = 110; int[] arr = new int[max]; int res=0,cnt=0; String[] str = s.readLine().split(" "); for(int i=0;i<size;i++){ arr[Integer.parseInt(str[i])]++; } for(int i=0;i<max;i++){ if(arr[i]>=4){ int re = arr[i]/4; res += re; cnt += (arr[i]-(re*4))/2; } else if(arr[i]>=2){ cnt += arr[i]/2; } } ww.println(cnt/2+res); ww.close(); } }
Java
["5\n2 4 3 2 3", "13\n2 2 4 4 4 4 6 6 6 7 7 9 9", "4\n3 3 3 5"]
1 second
["1", "3", "0"]
null
Java 7
standard input
[ "implementation" ]
f9b56b3fddcd5db0d0671714df3f8646
The first line contains an integer n (1 ≤ n ≤ 100) — the number of sticks. The second line contains n space-separated integers. The i-th integer equals the length of the i-th stick ai (1 ≤ ai ≤ 100).
1,000
Print the single number — the maximum number of frames Nicholas can make for his future canvases.
standard output
PASSED
036c4ed58d586c6a5ff64ba6f746cb71
train_002.jsonl
1320858000
Nicholas, a painter is going to paint several new canvases. Nicholas is sure that the canvases will turn out so great that each one will need framing and being hung on the wall. Frames are what Nicholas decided to begin with. Nicholas has n sticks whose lengths equal a1, a2, ... an. Nicholas does not want to break the sticks or glue them together. To make a h × w-sized frame, he needs two sticks whose lengths equal h and two sticks whose lengths equal w. Specifically, to make a square frame (when h = w), he needs four sticks of the same length.Now Nicholas wants to make from the sticks that he has as many frames as possible; to be able to paint as many canvases as possible to fill the frames. Help him in this uneasy task. Note that it is not necessary to use all the sticks Nicholas has.
256 megabytes
import java.io.BufferedInputStream; import java.util.Collections.*; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.InputMismatchException; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.Vector; import java.util.Map.Entry; import java.util.Queue; import java.util.Scanner; import java.util.TreeMap; import java.util.TreeSet; import java.math.*; import java.util.*; public class Main { public static void main(String[]args) { Scanner scanner=new Scanner(new BufferedInputStream(System.in)); int n=scanner.nextInt(); int a[]=new int [101]; for (int i=0;i<n;i++){ int x=scanner.nextInt(); a[x]++; } int total=0; for (int i=100;i>=0;i--){ if (a[i]>=2){ while (a[i]>=4){ total++;a[i]-=4; } if (a[i]<2) continue; for (int j=i-1;j>=0;j--){ if (a[j]>=2){ a[i]-=2;a[j]-=2; total++; } if (a[i]<2) break; } } } System.out.println(total); } }
Java
["5\n2 4 3 2 3", "13\n2 2 4 4 4 4 6 6 6 7 7 9 9", "4\n3 3 3 5"]
1 second
["1", "3", "0"]
null
Java 7
standard input
[ "implementation" ]
f9b56b3fddcd5db0d0671714df3f8646
The first line contains an integer n (1 ≤ n ≤ 100) — the number of sticks. The second line contains n space-separated integers. The i-th integer equals the length of the i-th stick ai (1 ≤ ai ≤ 100).
1,000
Print the single number — the maximum number of frames Nicholas can make for his future canvases.
standard output
PASSED
af0b294c98e76c62a468a049c91a765c
train_002.jsonl
1320858000
Nicholas, a painter is going to paint several new canvases. Nicholas is sure that the canvases will turn out so great that each one will need framing and being hung on the wall. Frames are what Nicholas decided to begin with. Nicholas has n sticks whose lengths equal a1, a2, ... an. Nicholas does not want to break the sticks or glue them together. To make a h × w-sized frame, he needs two sticks whose lengths equal h and two sticks whose lengths equal w. Specifically, to make a square frame (when h = w), he needs four sticks of the same length.Now Nicholas wants to make from the sticks that he has as many frames as possible; to be able to paint as many canvases as possible to fill the frames. Help him in this uneasy task. Note that it is not necessary to use all the sticks Nicholas has.
256 megabytes
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 Main { static BufferedReader reader; static StringTokenizer tokenizer; static PrintWriter writer; 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()); } static boolean eof = false; static String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } public static void main(String[] args) throws IOException { tokenizer = null; reader = new BufferedReader(new InputStreamReader(System.in)); writer = new PrintWriter(System.out); banana(); reader.close(); writer.close(); } static void banana() throws IOException { int n = nextInt(); int a[] = new int[n]; for (int i = 0; i < n; ++i) a[i] = nextInt(); Arrays.sort(a); int counter = 0; for (int i = 0; i + 1 < n; ++i) { if (a[i] == a[i + 1]) { ++counter; ++i; } } System.out.println(counter / 2); } }
Java
["5\n2 4 3 2 3", "13\n2 2 4 4 4 4 6 6 6 7 7 9 9", "4\n3 3 3 5"]
1 second
["1", "3", "0"]
null
Java 7
standard input
[ "implementation" ]
f9b56b3fddcd5db0d0671714df3f8646
The first line contains an integer n (1 ≤ n ≤ 100) — the number of sticks. The second line contains n space-separated integers. The i-th integer equals the length of the i-th stick ai (1 ≤ ai ≤ 100).
1,000
Print the single number — the maximum number of frames Nicholas can make for his future canvases.
standard output
PASSED
2946a323cc8ae0ddf191cae7ef0cb2eb
train_002.jsonl
1532617500
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
256 megabytes
import java.util.Scanner; public class Main { static final double EPSILON = 1e-6; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int[] a = readArray(sc, n); int[] b = readArray(sc, n); System.out.println(solve(a, b, m)); sc.close(); } static int[] readArray(Scanner sc, int size) { int[] result = new int[size]; for (int i = 0; i < result.length; i++) { result[i] = sc.nextInt(); } return result; } static double solve(int[] a, int[] b, int m) { double result = -1; double lower = 0; double upper = 1_000_000_001; while (Math.abs(upper - lower) > EPSILON) { double middle = (lower + upper) / 2; if (check(a, b, m, middle)) { result = middle; upper = middle; } else { lower = middle; } } return result; } static boolean check(int[] a, int[] b, int m, double fuel) { int n = a.length; for (int i = 0; i < n; i++) { double needed = (m + fuel) / a[i]; if (fuel < needed) { return false; } fuel -= needed; needed = (m + fuel) / b[(i + 1) % n]; if (fuel < needed) { return false; } fuel -= needed; } return true; } }
Java
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
1 second
["10.0000000000", "-1", "85.4800000000"]
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
Java 8
standard input
[ "binary search", "math" ]
d9bd63e03bf51ed87ba73cd15e8ce58d
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
1,500
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
standard output
PASSED
eb32d8b15a54c0272d550d2e1ed31234
train_002.jsonl
1532617500
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
256 megabytes
import java.util.*; public class Study{ public static double help(int n,int m,int up[],int down[]) { double pywt=m; int i=0; while(i+1<n) { if(up[i]-1<=0 || down[i+1]-1<=0|| up[n-1]-1<=0||down[0]-1<=0) return -1; pywt=pywt*up[i]/(up[i]-1); pywt=pywt*down[i+1]/(down[i+1]-1); i++; } pywt=pywt*up[n-1]/(up[n-1]-1); pywt=pywt*down[0]/(down[0]-1); return pywt; } public static void main(String args[]) { Scanner in=new Scanner(System.in); int n=in.nextInt(); int m=in.nextInt(); int up[]=new int[n]; for(int i=0;i<n;i++) up[i]=in.nextInt(); int down[]=new int[n]; for(int i=0;i<n;i++) down[i]=in.nextInt(); double wt=help(n,m,up,down); if(wt==-1) System.out.println(-1); else System.out.format("%.10f",wt-m); } }
Java
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
1 second
["10.0000000000", "-1", "85.4800000000"]
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
Java 8
standard input
[ "binary search", "math" ]
d9bd63e03bf51ed87ba73cd15e8ce58d
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
1,500
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
standard output
PASSED
c704d72ca84ace5c7270f84e0d9fd053
train_002.jsonl
1532617500
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
256 megabytes
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class Main{ static InputStream is; static PrintWriter out; static String INPUT = ""; private static byte[] inbuf = new byte[1024]; static int lenbuf = 0, ptrbuf = 0; public static 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 static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private static int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } public static double readDouble() { return Double.parseDouble(readString()); } public static char readChar() { return (char) skip(); } public static String readString() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public static char[] readCharArray(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); } public static int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = readInt(); return a; } public static int readInt() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } public static long readLong() { 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(); } } public static void main(String[] args) throws IOException { is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); solve(); out.flush(); } private static void solve() { int n = readInt(); int m = readInt(); int[] arrayA = readArray(n); int[] arrayB = readArray(n); double ans = binarySearch(1, 1000000001, 6, "left", arrayA, arrayB, n, m); if (ans < 0) System.out.println(-1); else System.out.println(ans); } static double binarySearch(double left, double right, int precision, String toMove, int[] arrayA, int[] arrayB, int n, int m) { double ans = -1; while (left <= right) { double mid = Double.parseDouble(String.format("%." + precision + "f", left + (right - left) / 2)); // System.out.printf("%f\n", mid); double unitDist = (double) 1 / (double) Math.pow(10, precision); if (solve(mid, arrayA, arrayB, n, m)) { ans = mid; if (toMove.equalsIgnoreCase("left")) { right = mid - unitDist; } else { left = mid + unitDist; } } else { if (toMove.equalsIgnoreCase("left")) { left = mid + unitDist; } else { right = mid - unitDist; } } } return ans; } static boolean solve(double x, int[] arrayA, int[] arrayB, int n, int m) { double weight = m + x; double petrol = x; for (int i = 0; i < n; i++) { double takeOffUsage = weight / (double) arrayA[i]; petrol -= takeOffUsage; weight -= takeOffUsage; if (petrol < 0) return false; double landingUsage = weight / (double) arrayB[(i + 1) % n]; petrol -= landingUsage; weight -= landingUsage; if (petrol < 0) return false; } return true; } }
Java
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
1 second
["10.0000000000", "-1", "85.4800000000"]
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
Java 8
standard input
[ "binary search", "math" ]
d9bd63e03bf51ed87ba73cd15e8ce58d
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
1,500
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
standard output
PASSED
fe7e0fbadb028d724ecd23f63a16c890
train_002.jsonl
1532617500
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc =new Scanner(System.in); int n=sc.nextInt(); int m=sc.nextInt(); ArrayList<Integer> arra=new ArrayList<Integer>(); ArrayList<Integer> arrb=new ArrayList<Integer>(); boolean cond=true; for(int i=0;i<n;i++) { int a=sc.nextInt(); // System.out.println(a); arra.add(a); if(a==1) cond=false; } for(int i=0;i<n;i++) { int a=sc.nextInt(); // System.out.println(a); arrb.add(a); if(a==1) cond=false; } if(cond||m==0){ double extra=m; int f=arrb.get(0); double fuel=extra/(f-1); extra+=fuel; for(int i=n-1;i>0;i--) { f=arra.get(i); fuel=extra/(f-1); extra+=fuel; f=arrb.get(i); fuel=extra/(f-1); extra+=fuel; } f=arra.get(0); fuel=extra/(f-1); extra+=fuel; System.out.println(extra-m); } else System.out.println(-1); /*for(int i=0;i<n;i++) { System.out.print(arra.get(i)+" "); System.out.println(arrb.get(i)); }*/ } }
Java
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
1 second
["10.0000000000", "-1", "85.4800000000"]
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
Java 8
standard input
[ "binary search", "math" ]
d9bd63e03bf51ed87ba73cd15e8ce58d
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
1,500
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
standard output
PASSED
0389be8159134f242794f875f791e783
train_002.jsonl
1532617500
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n; n=sc.nextInt(); int m; m=sc.nextInt(); double start=m;//有效重量 for(int i=0;i<2*n;i++) { int br=sc.nextInt();// if(br==1){ System.out.println(-1); return; } double currenttemp=start/(double)(br-1); start=start+currenttemp; } System.out.println(start-m); } }
Java
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
1 second
["10.0000000000", "-1", "85.4800000000"]
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
Java 8
standard input
[ "binary search", "math" ]
d9bd63e03bf51ed87ba73cd15e8ce58d
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
1,500
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
standard output
PASSED
baa7d03e2d77d4a4bde5cda7ebf499f7
train_002.jsonl
1532617500
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
256 megabytes
import java.util.*; public class ProblemA { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); int M = sc.nextInt(); int[] takeOffCosts = new int[N+1]; int[] landingCosts = new int[N+1]; for(int i = 1; i <= N; i++) { takeOffCosts[i] = sc.nextInt(); } for(int i = 1; i <= N; i++) { landingCosts[i] = sc.nextInt(); } double weight = M; double additionalWeight = weight / (landingCosts[1]-1); if(additionalWeight <= 0 || Double.POSITIVE_INFINITY <= additionalWeight) { System.out.println(-1); return; } weight += additionalWeight; for(int i = N; i >= 1; i--) { additionalWeight = weight / (takeOffCosts[i]-1); if(additionalWeight <= 0 || Double.POSITIVE_INFINITY <= additionalWeight) { System.out.println(-1); return; } weight += additionalWeight; if(i == 1) { System.out.println(weight-M); return; } additionalWeight = weight / (landingCosts[i]-1); if(additionalWeight <= 0 || Double.POSITIVE_INFINITY <= additionalWeight) { System.out.println(-1); return; } weight += additionalWeight; } } }
Java
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
1 second
["10.0000000000", "-1", "85.4800000000"]
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
Java 8
standard input
[ "binary search", "math" ]
d9bd63e03bf51ed87ba73cd15e8ce58d
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
1,500
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
standard output
PASSED
935795ff272a0aa84c408c18b32c8c3b
train_002.jsonl
1532617500
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
256 megabytes
import java.io.File; import java.util.Scanner; import java.util.StringTokenizer; public class p013 { public static void main(String args[]) throws Exception { // StringTokenizer stok = new StringTokenizer(new Scanner(new File("C:/Users/Arunkumar/Downloads/input.txt")).useDelimiter("\\A").next()); StringTokenizer stok = new StringTokenizer(new Scanner(System.in).useDelimiter("\\A").next()); StringBuilder sb = new StringBuilder(); int n = Integer.parseInt(stok.nextToken()); long m = Long.parseLong(stok.nextToken()); long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = Long.parseLong(stok.nextToken()); } long[] b = new long[n]; for (int i = 0; i < n; i++) { b[i] = Long.parseLong(stok.nextToken()); } double del = 1e-6; if(!doStuff(a,b,m,1e9)) { System.out.println("-1"); } else { double lo=0.0,hi=1e9; while((hi-lo)>del) { double md = (hi+lo)/2; if(doStuff(a,b,m,md)) hi=md; else lo=md; } System.out.println((hi+lo)/2); } } private static boolean doStuff(long[] a, long[] b, long m, double f) { int n = a.length; for(int i=0;i<n;i++) { f -= (m+f)/a[i]; if(f<0-1e-7) return false; f -= (m+f)/b[(i+1)%n]; if(f<0-1e-7) return false; } return true; } }
Java
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
1 second
["10.0000000000", "-1", "85.4800000000"]
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
Java 8
standard input
[ "binary search", "math" ]
d9bd63e03bf51ed87ba73cd15e8ce58d
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
1,500
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
standard output
PASSED
0bd4276811924b51b4011c044cbe562e
train_002.jsonl
1532617500
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
256 megabytes
//package contests.CF1010; import java.io.*; import java.util.StringTokenizer; public class A { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); int m = sc.nextInt(); int[] a = new int[n]; int[] b = new int[n]; for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); } for (int i = 0; i < n; i++) { b[i] = sc.nextInt(); } double lo = 0; double hi = 1e10; for (int i = 0; i < 60; i++) { double mid = lo + (hi-lo)/2; if(canDo(mid, a, b, m)) hi = mid; else lo = mid; } if(lo > 1e9+eps) pw.println(-1); else pw.println(lo); pw.flush(); pw.close(); } static double eps = 1e-9; static boolean canDo(double fuel, int[] a, int[]b, int wt){ double curWt = fuel + wt; int n = a.length; for (int i = 0; i < n - 1; i++) { double consumed = curWt / a[i]; if(consumed > fuel+eps) return false; fuel -= consumed; curWt = wt + fuel; consumed = curWt/b[i+1]; if(consumed > fuel+eps) return false; fuel -= consumed; curWt = wt + fuel; } double consumed = curWt / a[n-1]; if(consumed > fuel+eps) return false; fuel -= consumed; curWt = wt + fuel; consumed = curWt/b[0]; if(consumed > fuel+eps) return false; fuel -= consumed; curWt = wt + fuel; return true; } static int[][] packU(int n, int[] from, int[] to) { int[][] g = new int[n][]; int[] p = new int[n]; for (int f : from) p[f]++; for (int t : to) p[t]++; for (int i = 0; i < n; i++) g[i] = new int[p[i]]; for (int i = 0; i < from.length; i++) { g[from[i]][--p[from[i]]] = to[i]; g[to[i]][--p[to[i]]] = from[i]; } return g; } static int[][] packD(int n, int[] from, int[] to) { int[][] g = new int[n][]; int[] p = new int[n]; for (int f : from) if(f != -1) p[f]++; for (int i = 0; i < n; i++) g[i] = new int[p[i]]; for (int i = 0; i < from.length; i++) if(from[i] != -1) {g[from[i]][--p[from[i]]] = to[i];} return g; } static void shuffle(int[] a) { int n = a.length; for(int i = 0; i < n; i++) { int r = i + (int)(Math.random() * (n - i)); int tmp = a[i]; a[i] = a[r]; a[r] = tmp; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public Scanner(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(s)));} public String next() throws IOException {while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());return st.nextToken();} public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public boolean ready() throws IOException {return br.ready();} } }
Java
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
1 second
["10.0000000000", "-1", "85.4800000000"]
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
Java 8
standard input
[ "binary search", "math" ]
d9bd63e03bf51ed87ba73cd15e8ce58d
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
1,500
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
standard output
PASSED
947a01e5904faa175c883c37557fda8a
train_002.jsonl
1532617500
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; import java.util.stream.*; @SuppressWarnings("unchecked") public class P1010A { final static double EPS = 1e-6; int n; double m, a [], b []; double calc(double t, double ab) { return (t - (m + t) / ab); } double calc(double t) { for (int i = 0; i < (n - 1); i++) { t = calc(t, a[i]); t = calc(t, b[i + 1]); } t = calc(t, a[n - 1]); t = calc(t, b[0]); return t; } public void run() throws Exception { n = nextInt(); m = nextDouble(); a = readDouble(n); b = readDouble(n); double tl = 0, th = 2e9; while ((th - tl) >= EPS) { double tm = (th + tl) / 2.0; double tr = calc(tm); if (tr > 0) { th = tm; } else { tl = tm; } } println((tl > 1e9) ? -1 : (th + tl) / 2); } public static void main(String... args) throws Exception { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedOutputStream(System.out)); new P1010A().run(); br.close(); pw.close(); System.err.println("\n[Time : " + (System.currentTimeMillis() - startTime) + " ms]"); } static long startTime = System.currentTimeMillis(); static BufferedReader br; static PrintWriter pw; StringTokenizer stok; String nextToken() throws IOException { while (stok == null || !stok.hasMoreTokens()) { String s = br.readLine(); if (s == null) { return null; } stok = new StringTokenizer(s); } return stok.nextToken(); } void print(byte b) { print("" + b); } void print(int i) { print("" + i); } void print(long l) { print("" + l); } void print(double d) { print("" + d); } void print(char c) { print("" + c); } void print(Object o) { if (o instanceof int[]) { print(Arrays.toString((int [])o)); } else if (o instanceof long[]) { print(Arrays.toString((long [])o)); } else if (o instanceof char[]) { print(Arrays.toString((char [])o)); } else if (o instanceof byte[]) { print(Arrays.toString((byte [])o)); } else if (o instanceof short[]) { print(Arrays.toString((short [])o)); } else if (o instanceof boolean[]) { print(Arrays.toString((boolean [])o)); } else if (o instanceof float[]) { print(Arrays.toString((float [])o)); } else if (o instanceof double[]) { print(Arrays.toString((double [])o)); } else if (o instanceof Object[]) { print(Arrays.toString((Object [])o)); } else { print("" + o); } } void print(String s) { pw.print(s); } void println() { println(""); } void println(byte b) { println("" + b); } void println(int i) { println("" + i); } void println(long l) { println("" + l); } void println(double d) { println("" + d); } void println(char c) { println("" + c); } void println(Object o) { print(o); println(); } void println(String s) { pw.println(s); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } char nextChar() throws IOException { return (char) (br.read()); } String next() throws IOException { return nextToken(); } String nextLine() throws IOException { return br.readLine(); } int [] readInt(int size) throws IOException { int [] array = new int [size]; for (int i = 0; i < size; i++) { array[i] = nextInt(); } return array; } long [] readLong(int size) throws IOException { long [] array = new long [size]; for (int i = 0; i < size; i++) { array[i] = nextLong(); } return array; } double [] readDouble(int size) throws IOException { double [] array = new double [size]; for (int i = 0; i < size; i++) { array[i] = nextDouble(); } return array; } String [] readLines(int size) throws IOException { String [] array = new String [size]; for (int i = 0; i < size; i++) { array[i] = nextLine(); } return array; } int gcd(int a, int b) { if (a == 0) return Math.abs(b); if (b == 0) return Math.abs(a); a = Math.abs(a); b = Math.abs(b); int az = Integer.numberOfTrailingZeros(a), bz = Integer.numberOfTrailingZeros(b); a >>>= az; b >>>= bz; while (a != b) { if (a > b) { a -= b; a >>>= Integer.numberOfTrailingZeros(a); } else { b -= a; b >>>= Integer.numberOfTrailingZeros(b); } } return (a << Math.min(az, bz)); } long gcd(long a, long b) { if (a == 0) return Math.abs(b); if (b == 0) return Math.abs(a); a = Math.abs(a); b = Math.abs(b); int az = Long.numberOfTrailingZeros(a), bz = Long.numberOfTrailingZeros(b); a >>>= az; b >>>= bz; while (a != b) { if (a > b) { a -= b; a >>>= Long.numberOfTrailingZeros(a); } else { b -= a; b >>>= Long.numberOfTrailingZeros(b); } } return (a << Math.min(az, bz)); } void shuffle(int [] a) { Random r = new Random(); for (int i = a.length - 1; i >= 0; i--) { int j = r.nextInt(a.length); int t = a[i]; a[i] = a[j]; a[j] = t; } } void shuffle(long [] a) { Random r = new Random(); for (int i = a.length - 1; i >= 0; i--) { int j = r.nextInt(a.length); long t = a[i]; a[i] = a[j]; a[j] = t; } } void shuffle(Object [] a) { Random r = new Random(); for (int i = a.length - 1; i >= 0; i--) { int j = r.nextInt(a.length); Object t = a[i]; a[i] = a[j]; a[j] = t; } } }
Java
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
1 second
["10.0000000000", "-1", "85.4800000000"]
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
Java 8
standard input
[ "binary search", "math" ]
d9bd63e03bf51ed87ba73cd15e8ce58d
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
1,500
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
standard output
PASSED
06281cb9ffe611a9f1aff15e0518da2b
train_002.jsonl
1532617500
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
256 megabytes
import java.util.Scanner; public class CF1010A { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int planetsNumber = scanner.nextInt(); double payloadWeight = scanner.nextInt(); double[] lifted = new double[planetsNumber]; double[] landed = new double[planetsNumber]; boolean isPossible = true; for(int i = 0; i < planetsNumber; i++){ lifted[i] = scanner.nextInt(); if (lifted[i] == 1) isPossible = false; } for(int i = 0; i < planetsNumber; i++){ landed[i] = scanner.nextInt(); if (landed[i] ==1) isPossible = false; } if (isPossible) { double fuelWeight = 0; fuelWeight = payloadWeight / (landed[0] - 1); for (int i = planetsNumber - 1; i > 0; i--){ fuelWeight+= (payloadWeight + fuelWeight)/(lifted[i] - 1); fuelWeight+= (payloadWeight + fuelWeight)/(landed[i] - 1); } fuelWeight += (payloadWeight + fuelWeight) / (lifted[0] - 1); System.out.print(fuelWeight); }else System.out.println(-1); } }
Java
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
1 second
["10.0000000000", "-1", "85.4800000000"]
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
Java 8
standard input
[ "binary search", "math" ]
d9bd63e03bf51ed87ba73cd15e8ce58d
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
1,500
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
standard output
PASSED
8fb4ddd3bbc38d7ded7a9bf11c1b11a6
train_002.jsonl
1532617500
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
256 megabytes
import java.util.*; public class rckt { public static void main(String[] args) { Scanner in=new Scanner(System.in); int n; n=in.nextInt(); int m; m=in.nextInt(); int[] toffw=new int[n]; int[] landw=new int[n]; int[] process=new int[2*n]; double start=m; for(int i=0;i<2*n;i++) { int br=in.nextInt(); if(br==1){ System.out.println(-1); return; } double currenttemp=start/(double)(br-1); //System.out.println("currenttemp "+currenttemp); start=start+currenttemp; //System.out.println("start "+start); } System.out.println(start-m); // TODO Auto-generated method stub } }
Java
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
1 second
["10.0000000000", "-1", "85.4800000000"]
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
Java 8
standard input
[ "binary search", "math" ]
d9bd63e03bf51ed87ba73cd15e8ce58d
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
1,500
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
standard output
PASSED
fb6bde19ff222e9f185d8b5c0b45835f
train_002.jsonl
1532617500
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
256 megabytes
import java.util.*; public class rckt { public static void main(String[] args) { Scanner in=new Scanner(System.in); int n; n=in.nextInt(); int m; m=in.nextInt(); //int[] toffw=new int[n]; //int[] landw=new int[n]; //int[] process=new int[2*n]; double start=m; for(int i=0;i<2*n;i++) { int br=in.nextInt(); if(br==1){ System.out.println(-1); return; } double currenttemp=start/(double)(br-1); //System.out.println("currenttemp "+currenttemp); start=start+currenttemp; //System.out.println("start "+start); } System.out.println(start-m); // TODO Auto-generated method stub } }
Java
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
1 second
["10.0000000000", "-1", "85.4800000000"]
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
Java 8
standard input
[ "binary search", "math" ]
d9bd63e03bf51ed87ba73cd15e8ce58d
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
1,500
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
standard output
PASSED
f353a95da4a21bbdeaac63694ca82ec6
train_002.jsonl
1532617500
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
256 megabytes
import java.util.*; public class rckt { public static void main(String[] args) { Scanner in=new Scanner(System.in); int n; n=in.nextInt(); int m; m=in.nextInt(); int[] toffw=new int[n]; int[] landw=new int[n]; int[] process=new int[2*n]; double start=m; for(int i=0;i<2*n;i++) { int br=in.nextInt(); if(br==1){ System.out.println(-1); return; } double currenttemp=start/(double)(br-1); //System.out.println("currenttemp "+currenttemp); start=start+currenttemp; //System.out.println("start "+start); } System.out.println(start-m); // TODO Auto-generated method stub } }
Java
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
1 second
["10.0000000000", "-1", "85.4800000000"]
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
Java 8
standard input
[ "binary search", "math" ]
d9bd63e03bf51ed87ba73cd15e8ce58d
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
1,500
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
standard output
PASSED
3ac5916a7eeb0680c08343f7ca9cb2c5
train_002.jsonl
1532617500
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
256 megabytes
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { public static void main (String[] args) throws java.lang.Exception { int i,j; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); PrintWriter out=new PrintWriter(System.out); int n=Integer.parseInt(br.readLine()); int m=Integer.parseInt(br.readLine());int d=m; int a[]=new int[n]; int b[]=new int[n]; String ss[]=br.readLine().split(" "); String ss1[]=br.readLine().split(" "); double ans=1; for(i=0;i<n;i++) { a[i]=Integer.parseInt(ss[i]); b[i]=Integer.parseInt(ss1[i]); //out.println(a[i]+" "+b[i]); //out.println((a[i]-1)+" "+(b[i]-1)); ans*=(double)(a[i]*b[i])/(double)((a[i]-1)*(b[i]-1)); if(a[i]==1 || b[i]==1) {System.out.println("-1");return ;} } //out.println(ans); out.println(((double)(ans-1.0)*(double)(m))); /*HashMap<Integer,Integer> hm1=new HashMap<Integer,Integer>(); HashMap<Integer,Integer> hm2=new HashMap<Integer,Integer>(); for(j=0;j<n;j++) { int z=a[j]; for(i=2;i<Math.sqrt(z)+1;i++) { while(z%i==0) { z/=i; if(hm1.containsKey(i)) hm1.put(i,hm1.get(i)+1); else hm1.put(i,1);}} if(hm1.containsKey(z) && z!=1)hm1.put(z,hm1.get(z)+1); else if(z!=1)hm1.put(z,1); } for(j=0;j<n;j++) { int z=b[j]; for(i=2;i<Math.sqrt(z)+1;i++) { while(z%i==0) { z/=i; if(hm1.containsKey(i))hm1.put(i,hm1.get(i)+1); else hm1.put(i,1);}} if(hm1.containsKey(z) && z!=1) hm1.put(z,hm1.get(z)+1); else if(z!=1) hm1.put(z,1); } for(i=2;i<Math.sqrt(d)+1;i++) { while(d%i==0) { d/=i; if(hm1.containsKey(i)) hm1.put(i,hm1.get(i)+1); else hm1.put(i,1);}} if(hm1.containsKey(d)&& d!=1)hm1.put(d,hm1.get(d)+1); else if(d!=1)hm1.put(d,1); for(j=0;j<n;j++) { int z=a[j]-1; for(i=2;i<Math.sqrt(z)+1;i++) { while(z%i==0) { z/=i; if(hm2.containsKey(i)) hm2.put(i,hm2.get(i)+1); else hm2.put(i,1);}} if(hm2.containsKey(z) && z!=1)hm2.put(z,hm2.get(z)+1); else if(z!=1)hm2.put(z,1); } for(j=0;j<n;j++) { int z=b[j]-1; for(i=2;i<Math.sqrt(z)+1;i++) { while(z%i==0) { z/=i; if(hm2.containsKey(i))hm2.put(i,hm2.get(i)+1); else hm2.put(i,1);}} if(hm2.containsKey(z) && z!=1) hm2.put(z,hm2.get(z)+1); else if(z!=1) hm2.put(z,1); } for(int z:hm1.keySet()) { if(hm2.containsKey(z)) { int temp=Math.min(hm1.get(z),hm2.get(z)); hm1.put(z,hm1.get(z)-temp); hm2.put(z,hm2.get(z)-temp); } } ArrayList<Integer> arr1=new ArrayList<Integer>(); ArrayList<Integer> arr2=new ArrayList<Integer>(); for(int p:hm1.keySet()) for(i=1;i<=hm1.get(p);i++) arr1.add(p); for(int p:hm2.keySet()) for(i=1;i<=hm2.get(p);i++) arr2.add(p); double temp1=1.0,temp2=1.0; for(i=0;i<Math.max(arr1.size(),arr2.size());i++) { //out.println(temp1+" "+temp2); if(temp1>=Math.pow(10,9) || temp2>=Math.pow(10,9)) {temp1=(double)temp1/temp2;temp2=(double)1.0;} if(i<arr1.size()) temp1*=(double)arr1.get(i); if(i<arr2.size()) temp2*=(double)arr2.get(i); } double ans=temp1/(double)temp2-(double)m; out.println(ans); */out.close(); } }
Java
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
1 second
["10.0000000000", "-1", "85.4800000000"]
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
Java 8
standard input
[ "binary search", "math" ]
d9bd63e03bf51ed87ba73cd15e8ce58d
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
1,500
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
standard output
PASSED
6948adcecac6ec9255994453b5c047b1
train_002.jsonl
1588343700
Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of length $$$k$$$ have the same sum. A subarray of an array is any sequence of consecutive elements.Phoenix currently has an array $$$a$$$ of length $$$n$$$. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautiful. The inserted integers must be between $$$1$$$ and $$$n$$$ inclusive. Integers may be inserted anywhere (even before the first or after the last element), and he is not trying to minimize the number of inserted integers.
256 megabytes
import java.util.*; import java.io.*; public class Task { static BufferedReader s1; static BufferedWriter out; static String read() throws IOException{String line="";while(line.length()==0){line=s1.readLine();continue;}return line;} static int int_v (String s1){return Integer.parseInt(s1);} static long long_v(String s1){return Long.parseLong(s1);} static int[] int_arr() throws IOException{String[] a=read().split(" ");int[] b=new int[a.length];for(int i=0;i<a.length;i++){b[i]=int_v(a[i]);}return b;} static long[] long_arr() throws IOException{String[] a=read().split(" ");long[] b=new long[a.length];for(int i=0;i<a.length;i++){b[i]=long_v(a[i]);}return b;} static void assign(){s1=new BufferedReader(new InputStreamReader(System.in));out=new BufferedWriter(new OutputStreamWriter(System.out));} public static void main(String args[]) throws IOException { assign(); int t=int_v(read()); while(t--!=0){ int[] n1=int_arr(); int n=n1[0],k=n1[1]; int[] a=int_arr(); boolean[] b=new boolean[200]; List<Integer> l=new ArrayList<>(); for(int x:a){ if(!b[x]){l.add(x);b[x]=true;} } if(l.size()>k){out.write("-1\n");} else{ while(l.size()<k){l.add(l.get(0));} out.write(n*l.size()+"\n"); for(int i=1;i<=n;i++){ for(int x:l){out.write(x+" ");} } out.write("\n"); } } out.flush(); } }
Java
["4\n4 2\n1 2 2 1\n4 3\n1 2 2 1\n3 2\n1 2 3\n4 4\n4 3 4 2"]
2 seconds
["5\n1 2 1 2 1\n4\n1 2 2 1\n-1\n7\n4 3 2 1 4 3 2"]
NoteIn the first test case, we can make array $$$a$$$ beautiful by inserting the integer $$$1$$$ at index $$$3$$$ (in between the two existing $$$2$$$s). Now, all subarrays of length $$$k=2$$$ have the same sum $$$3$$$. There exists many other possible solutions, for example: $$$2, 1, 2, 1, 2, 1$$$ $$$1, 2, 1, 2, 1, 2$$$ In the second test case, the array is already beautiful: all subarrays of length $$$k=3$$$ have the same sum $$$5$$$.In the third test case, it can be shown that we cannot insert numbers to make array $$$a$$$ beautiful.In the fourth test case, the array $$$b$$$ shown is beautiful and all subarrays of length $$$k=4$$$ have the same sum $$$10$$$. There exist other solutions also.
Java 8
standard input
[ "data structures", "constructive algorithms", "sortings", "greedy" ]
80d4b2d01215b12ebd89b8ee2d1ac6ed
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 50$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 100$$$). The second line of each test case contains $$$n$$$ space-separated integers ($$$1 \le a_i \le n$$$) — the array that Phoenix currently has. This array may or may not be already beautiful.
1,400
For each test case, if it is impossible to create a beautiful array, print -1. Otherwise, print two lines. The first line should contain the length of the beautiful array $$$m$$$ ($$$n \le m \le 10^4$$$). You don't need to minimize $$$m$$$. The second line should contain $$$m$$$ space-separated integers ($$$1 \le b_i \le n$$$) — a beautiful array that Phoenix can obtain after inserting some, possibly zero, integers into his array $$$a$$$. You may print integers that weren't originally in array $$$a$$$. If there are multiple solutions, print any. It's guaranteed that if we can make array $$$a$$$ beautiful, we can always make it with resulting length no more than $$$10^4$$$.
standard output
PASSED
e665256d183aa588ffac736586a9735a
train_002.jsonl
1588343700
Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of length $$$k$$$ have the same sum. A subarray of an array is any sequence of consecutive elements.Phoenix currently has an array $$$a$$$ of length $$$n$$$. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautiful. The inserted integers must be between $$$1$$$ and $$$n$$$ inclusive. Integers may be inserted anywhere (even before the first or after the last element), and he is not trying to minimize the number of inserted integers.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashSet; import java.util.StringTokenizer; public class Solution { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { FastReader in=new FastReader(); int t = in.nextInt(); StringBuilder st =new StringBuilder(); while(t-->0) { int n = in.nextInt(); int k = in.nextInt(); HashSet <Integer> set = new HashSet<>(); Integer []arr = new Integer[n]; ArrayList<Integer>ar = new ArrayList<>(); for(int i = 0;i<n;i++) { arr[i] = in.nextInt(); if(!set.contains(arr[i])) ar.add(arr[i]); set.add(arr[i]); } if(set.size()>k) { st.append("-1\n"); continue; } while(ar.size()<k) ar.add(1); StringBuilder pat = new StringBuilder(); for(int i:ar) { pat.append(i+" "); } st.append(n*k+"\n"); // System.out.println(pat.toString()); for(int i = 1;i<=n;i++) { st.append(pat); } st.append("\n"); } System.out.println(st.toString()); } private static long find(long pstart, long pend, long div) { long muls = (pstart)/div; if(pstart%div==0)muls--; long mule = (pend)/div; return pend-pstart-(mule-muls)+1; } static long gcd(long a, long b) { if(b==0) return a; return gcd(b,a%b); } }
Java
["4\n4 2\n1 2 2 1\n4 3\n1 2 2 1\n3 2\n1 2 3\n4 4\n4 3 4 2"]
2 seconds
["5\n1 2 1 2 1\n4\n1 2 2 1\n-1\n7\n4 3 2 1 4 3 2"]
NoteIn the first test case, we can make array $$$a$$$ beautiful by inserting the integer $$$1$$$ at index $$$3$$$ (in between the two existing $$$2$$$s). Now, all subarrays of length $$$k=2$$$ have the same sum $$$3$$$. There exists many other possible solutions, for example: $$$2, 1, 2, 1, 2, 1$$$ $$$1, 2, 1, 2, 1, 2$$$ In the second test case, the array is already beautiful: all subarrays of length $$$k=3$$$ have the same sum $$$5$$$.In the third test case, it can be shown that we cannot insert numbers to make array $$$a$$$ beautiful.In the fourth test case, the array $$$b$$$ shown is beautiful and all subarrays of length $$$k=4$$$ have the same sum $$$10$$$. There exist other solutions also.
Java 8
standard input
[ "data structures", "constructive algorithms", "sortings", "greedy" ]
80d4b2d01215b12ebd89b8ee2d1ac6ed
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 50$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 100$$$). The second line of each test case contains $$$n$$$ space-separated integers ($$$1 \le a_i \le n$$$) — the array that Phoenix currently has. This array may or may not be already beautiful.
1,400
For each test case, if it is impossible to create a beautiful array, print -1. Otherwise, print two lines. The first line should contain the length of the beautiful array $$$m$$$ ($$$n \le m \le 10^4$$$). You don't need to minimize $$$m$$$. The second line should contain $$$m$$$ space-separated integers ($$$1 \le b_i \le n$$$) — a beautiful array that Phoenix can obtain after inserting some, possibly zero, integers into his array $$$a$$$. You may print integers that weren't originally in array $$$a$$$. If there are multiple solutions, print any. It's guaranteed that if we can make array $$$a$$$ beautiful, we can always make it with resulting length no more than $$$10^4$$$.
standard output
PASSED
18faad0ff83618aaeb8c45d691e85885
train_002.jsonl
1588343700
Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of length $$$k$$$ have the same sum. A subarray of an array is any sequence of consecutive elements.Phoenix currently has an array $$$a$$$ of length $$$n$$$. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautiful. The inserted integers must be between $$$1$$$ and $$$n$$$ inclusive. Integers may be inserted anywhere (even before the first or after the last element), and he is not trying to minimize the number of inserted integers.
256 megabytes
/* * * @Author Ajudiya_13(Bhargav Girdharbhai Ajudiya) * Dhirubhai Ambani Institute of Information And Communication Technology * */ import java.util.*; import java.io.*; import java.lang.*; public class Code75 { public static void addInMap(HashMap<Integer,Integer> map, int key){ if(map.containsKey(key)) map.put(key, map.get(key) + 1); else map.put(key, 1); } public static void removeFromMap(HashMap<Integer,Integer> map, int key){ int currentValue = map.get(key); currentValue--; if(currentValue==0){ map.remove(key); }else{ map.put(key,currentValue); } } public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter pw = new PrintWriter(System.out); int test_case = in.nextInt(); outer: for(int t=0;t<test_case;t++) { int n = in.nextInt(); int k = in.nextInt(); int[] a = in.nextIntArray(n); HashSet<Integer> set = new HashSet<>(); for(int i=0;i<n;i++) set.add(a[i]); if(set.size()>k){ pw.println(-1); continue outer; } pw.println(n*k); for(int i=0;i<n;i++){ for(int v : set) pw.print(v + " "); for(int j=set.size();j<k;j++) pw.print(a[0] + " "); } pw.println(); } pw.flush(); pw.close(); } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static long mod = 1000000007; public static int d; public static int p; public static int q; public static int[] suffle(int[] a,Random gen) { int n = a.length; for(int i=0;i<n;i++) { int ind = gen.nextInt(n-i)+i; int temp = a[ind]; a[ind] = a[i]; a[i] = temp; } return a; } public static void swap(int a, int b){ int temp = a; a = b; b = temp; } public static HashSet<Integer> primeFactorization(int n) { HashSet<Integer> a =new HashSet<Integer>(); for(int i=2;i*i<=n;i++) { while(n%i==0) { a.add(i); n/=i; } } if(n!=1) a.add(n); return a; } public static void sieve(boolean[] isPrime,int n) { for(int i=1;i<n;i++) isPrime[i] = true; isPrime[0] = false; isPrime[1] = false; for(int i=2;i*i<n;i++) { if(isPrime[i] == true) { for(int j=(2*i);j<n;j+=i) isPrime[j] = false; } } } public static int GCD(int a,int b) { if(b==0) return a; else return GCD(b,a%b); } public static long GCD(long a,long b) { if(b==0) return a; else return GCD(b,a%b); } public static void extendedEuclid(int A,int B) { if(B==0) { d = A; p = 1 ; q = 0; } else { extendedEuclid(B, A%B); int temp = p; p = q; q = temp - (A/B)*q; } } public static long LCM(long a,long b) { return (a*b)/GCD(a,b); } public static int LCM(int a,int b) { return (a*b)/GCD(a,b); } public static int binaryExponentiation(int x,int n) { int result=1; while(n>0) { if(n % 2 ==1) result=result * x; x=x*x; n=n/2; } return result; } public static long binaryExponentiation(long x,long n) { long result=1; while(n>0) { if(n % 2 ==1) result=result * x; x=x*x; n=n/2; } return result; } public static int modularExponentiation(int x,int n,int M) { int result=1; while(n>0) { if(n % 2 ==1) result=(result * x)%M; x=(x*x)%M; n=n/2; } return result; } public static long modularExponentiation(long x,long n,long M) { long result=1; while(n>0) { if(n % 2 ==1) result=(result * x)%M; x=(x*x)%M; n=n/2; } return result; } public static int modInverse(int A,int M) { return modularExponentiation(A,M-2,M); } public static long modInverse(long A,long M) { return modularExponentiation(A,M-2,M); } public static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n%2 == 0 || n%3 == 0) return false; for (int i=5; i*i<=n; i=i+6) { if (n%i == 0 || n%(i+2) == 0) return false; } return true; } static class pair implements Comparable<pair> { Integer x, y; pair(int x,int y) { this.x=x; this.y=y; } public int compareTo(pair o) { int result = x.compareTo(o.x); if(result==0) result = y.compareTo(o.y); return result; } public String toString() { return x+" "+y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair)o; return (Math.abs(p.x-x)==0 && Math.abs(p.y-y)==0); } return false; } public int hashCode() { return new Long(x).hashCode()*31 + new Long(y).hashCode(); } } }
Java
["4\n4 2\n1 2 2 1\n4 3\n1 2 2 1\n3 2\n1 2 3\n4 4\n4 3 4 2"]
2 seconds
["5\n1 2 1 2 1\n4\n1 2 2 1\n-1\n7\n4 3 2 1 4 3 2"]
NoteIn the first test case, we can make array $$$a$$$ beautiful by inserting the integer $$$1$$$ at index $$$3$$$ (in between the two existing $$$2$$$s). Now, all subarrays of length $$$k=2$$$ have the same sum $$$3$$$. There exists many other possible solutions, for example: $$$2, 1, 2, 1, 2, 1$$$ $$$1, 2, 1, 2, 1, 2$$$ In the second test case, the array is already beautiful: all subarrays of length $$$k=3$$$ have the same sum $$$5$$$.In the third test case, it can be shown that we cannot insert numbers to make array $$$a$$$ beautiful.In the fourth test case, the array $$$b$$$ shown is beautiful and all subarrays of length $$$k=4$$$ have the same sum $$$10$$$. There exist other solutions also.
Java 8
standard input
[ "data structures", "constructive algorithms", "sortings", "greedy" ]
80d4b2d01215b12ebd89b8ee2d1ac6ed
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 50$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 100$$$). The second line of each test case contains $$$n$$$ space-separated integers ($$$1 \le a_i \le n$$$) — the array that Phoenix currently has. This array may or may not be already beautiful.
1,400
For each test case, if it is impossible to create a beautiful array, print -1. Otherwise, print two lines. The first line should contain the length of the beautiful array $$$m$$$ ($$$n \le m \le 10^4$$$). You don't need to minimize $$$m$$$. The second line should contain $$$m$$$ space-separated integers ($$$1 \le b_i \le n$$$) — a beautiful array that Phoenix can obtain after inserting some, possibly zero, integers into his array $$$a$$$. You may print integers that weren't originally in array $$$a$$$. If there are multiple solutions, print any. It's guaranteed that if we can make array $$$a$$$ beautiful, we can always make it with resulting length no more than $$$10^4$$$.
standard output
PASSED
cd2626cb290ad9939c5bd35f78f3dec1
train_002.jsonl
1588343700
Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of length $$$k$$$ have the same sum. A subarray of an array is any sequence of consecutive elements.Phoenix currently has an array $$$a$$$ of length $$$n$$$. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautiful. The inserted integers must be between $$$1$$$ and $$$n$$$ inclusive. Integers may be inserted anywhere (even before the first or after the last element), and he is not trying to minimize the number of inserted integers.
256 megabytes
import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays; /** * User :- sudhakar * Date :- 13/06/20 * Time :- 11:16 AM */ public class PhoenixAndBeauty { private static final Reader r = new Reader(); static final int MOD = 1000000007, MAXN = 10000000; static final int MAX_VALUE = Integer.MAX_VALUE; static final int MIN_VALUE = Integer.MIN_VALUE; static int[] spf; /*Inner class for fast input*/ static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public String nextString() throws IOException { byte c = read(); while (Character.isWhitespace(c)) { c = read(); } StringBuilder builder = new StringBuilder(); builder.append((char) c); c = read(); while (!Character.isWhitespace(c)) { builder.append((char) c); c = read(); } return builder.toString(); } public char nextChar() throws IOException { byte c = read(); while (Character.isWhitespace(c)) { c = read(); } return (char) c; } 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; } public int[] nextIntArray(Reader r, int size) throws IOException { int[] arr = new int[size + 1]; for (int i = 1; i <= size; i++) arr[i] = r.nextInt(); return arr; } public long[] nextLongArray(Reader r, int size) throws IOException { long[] arr = new long[size + 1]; for (int i = 1; i <= size; i++) arr[i] = r.nextLong(); return arr; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } private static int ni() throws IOException { return r.nextInt(); } private static long nl() throws IOException { return r.nextLong(); } private static char nc() throws IOException { return r.nextChar(); } private static double nd() throws IOException { return r.nextDouble(); } private static String ns() throws IOException { return r.nextString(); } private static int[] nextIntArr(int size) throws IOException { return r.nextIntArray(r, size); } private static long[] nextLongArr(int size) throws IOException { return r.nextLongArray(r, size); } private static boolean isPrime(int n) { for (int i = 2; i * i <= n; ++i) { if (n % i == 0) { return false; } } return true; } private static boolean isPowerOfTwo(long c) { return (c & (c - 1)) == 0; } public static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static void sieve() { spf = new int[MAXN + 1]; spf[1] = 1; for (int i = 1; i <= MAXN; i += 2) spf[i] = i; for (int i = 2; i <= MAXN; i += 2) spf[i] = 2; for (int i = 3; i * i <= MAXN; i++) { // checking if i is prime if (spf[i] == i) { // marking SPF for all numbers divisible by i for (int j = i * i; j < MAXN; j += i) // marking spf[j] if it is not // previously marked if (spf[j] == j) spf[j] = i; } } } // CODE STARTS HERE public static void main(String[] args) throws IOException { int T = ni(); while (T-- > 0) { int n = ni(); int k = ni(); int[] a = nextIntArr(n); boolean[] marked = new boolean[n + 1]; Arrays.fill(marked, false); int count = 0; int mx = MIN_VALUE; for (int i = 1; i <= n; i++) { if (!marked[a[i]]) { ++count; marked[a[i]] = true; } mx = Math.max(mx, a[i]); } if (count > k) System.out.println(-1); else { StringBuilder builder = new StringBuilder(); for (int i = 1; i <=n ; i++) { if (marked[i]) builder.append(i).append(" "); } int temp = k-count; for (int i = 1; i <=temp ; i++) { builder.append("1").append(" "); } StringBuilder mbuilder = new StringBuilder(); for (int i = 0; i < n; i++) { mbuilder.append(builder.toString()); } System.out.println(k * n); System.out.println(mbuilder.toString()); } } } // SOLUTION ENDS HERE }
Java
["4\n4 2\n1 2 2 1\n4 3\n1 2 2 1\n3 2\n1 2 3\n4 4\n4 3 4 2"]
2 seconds
["5\n1 2 1 2 1\n4\n1 2 2 1\n-1\n7\n4 3 2 1 4 3 2"]
NoteIn the first test case, we can make array $$$a$$$ beautiful by inserting the integer $$$1$$$ at index $$$3$$$ (in between the two existing $$$2$$$s). Now, all subarrays of length $$$k=2$$$ have the same sum $$$3$$$. There exists many other possible solutions, for example: $$$2, 1, 2, 1, 2, 1$$$ $$$1, 2, 1, 2, 1, 2$$$ In the second test case, the array is already beautiful: all subarrays of length $$$k=3$$$ have the same sum $$$5$$$.In the third test case, it can be shown that we cannot insert numbers to make array $$$a$$$ beautiful.In the fourth test case, the array $$$b$$$ shown is beautiful and all subarrays of length $$$k=4$$$ have the same sum $$$10$$$. There exist other solutions also.
Java 8
standard input
[ "data structures", "constructive algorithms", "sortings", "greedy" ]
80d4b2d01215b12ebd89b8ee2d1ac6ed
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 50$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 100$$$). The second line of each test case contains $$$n$$$ space-separated integers ($$$1 \le a_i \le n$$$) — the array that Phoenix currently has. This array may or may not be already beautiful.
1,400
For each test case, if it is impossible to create a beautiful array, print -1. Otherwise, print two lines. The first line should contain the length of the beautiful array $$$m$$$ ($$$n \le m \le 10^4$$$). You don't need to minimize $$$m$$$. The second line should contain $$$m$$$ space-separated integers ($$$1 \le b_i \le n$$$) — a beautiful array that Phoenix can obtain after inserting some, possibly zero, integers into his array $$$a$$$. You may print integers that weren't originally in array $$$a$$$. If there are multiple solutions, print any. It's guaranteed that if we can make array $$$a$$$ beautiful, we can always make it with resulting length no more than $$$10^4$$$.
standard output
PASSED
e4a472c69f5cb3f45d8fcd4ca8f1f7ea
train_002.jsonl
1588343700
Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of length $$$k$$$ have the same sum. A subarray of an array is any sequence of consecutive elements.Phoenix currently has an array $$$a$$$ of length $$$n$$$. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautiful. The inserted integers must be between $$$1$$$ and $$$n$$$ inclusive. Integers may be inserted anywhere (even before the first or after the last element), and he is not trying to minimize the number of inserted integers.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String ars[])throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw=new PrintWriter(System.out); int t=Integer.parseInt(br.readLine()); for(int x=0;x<t;x++) { String str[]=br.readLine().split(" "); TreeSet<Integer> ts=new TreeSet<>(); int n=Integer.parseInt(str[0]); int k=Integer.parseInt(str[1]); int arr[]=new int[n]; str=br.readLine().split(" "); boolean vis[]=new boolean[101]; int u=0; for(int i=0;i<n;i++) { arr[i]=Integer.parseInt(str[i]); if(!vis[arr[i]]) { u++; vis[arr[i]]=true; } ts.add(arr[i]); } if(u>k) pw.println(-1); else { ArrayList<Integer> list=new ArrayList<>(); while(ts.size()>0) list.add(ts.pollFirst()); if(list.size()<k) { int temp=list.size(); for(int i=0;i<k-temp;i++) list.add(list.get(list.size()-1)); } int siz=list.size(); pw.println(n*k); for(int i=0;i<n*k;i++) { pw.print(list.get(i%siz)+" "); } /*TreeSet<Integer> ts1=new TreeSet<>(); ArrayList<Integer> list=new ArrayList<>(); for(int i=0;i<k;i++) { list.add(arr[i]); ts1.add(arr[i]); } if(ts.size()==ts1.size()) { ArrayList<Integer> fin=new ArrayList<>(); for(int i=0;i<n;i++) { for(int j=0;j<list.size();j++) { fin.add(list.get(j)); } } pw.println(fin.size()); for(int i=0;i<fin.size();i++) { pw.print(fin.get(i)+" "); } } else { ArrayList<Integer> fin=new ArrayList<>(); list.clear(); while(ts.size()>0) list.add(ts.pollFirst()); for(int i=0;i<n;i++) { for(int j=0;j<list.size();j++) { fin.add(list.get(j)); } } pw.println(fin.size()); for(int i=0;i<fin.size();i++) { pw.print(fin.get(i)+" "); } }*/ pw.println(); } } pw.flush(); pw.close(); } }
Java
["4\n4 2\n1 2 2 1\n4 3\n1 2 2 1\n3 2\n1 2 3\n4 4\n4 3 4 2"]
2 seconds
["5\n1 2 1 2 1\n4\n1 2 2 1\n-1\n7\n4 3 2 1 4 3 2"]
NoteIn the first test case, we can make array $$$a$$$ beautiful by inserting the integer $$$1$$$ at index $$$3$$$ (in between the two existing $$$2$$$s). Now, all subarrays of length $$$k=2$$$ have the same sum $$$3$$$. There exists many other possible solutions, for example: $$$2, 1, 2, 1, 2, 1$$$ $$$1, 2, 1, 2, 1, 2$$$ In the second test case, the array is already beautiful: all subarrays of length $$$k=3$$$ have the same sum $$$5$$$.In the third test case, it can be shown that we cannot insert numbers to make array $$$a$$$ beautiful.In the fourth test case, the array $$$b$$$ shown is beautiful and all subarrays of length $$$k=4$$$ have the same sum $$$10$$$. There exist other solutions also.
Java 8
standard input
[ "data structures", "constructive algorithms", "sortings", "greedy" ]
80d4b2d01215b12ebd89b8ee2d1ac6ed
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 50$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 100$$$). The second line of each test case contains $$$n$$$ space-separated integers ($$$1 \le a_i \le n$$$) — the array that Phoenix currently has. This array may or may not be already beautiful.
1,400
For each test case, if it is impossible to create a beautiful array, print -1. Otherwise, print two lines. The first line should contain the length of the beautiful array $$$m$$$ ($$$n \le m \le 10^4$$$). You don't need to minimize $$$m$$$. The second line should contain $$$m$$$ space-separated integers ($$$1 \le b_i \le n$$$) — a beautiful array that Phoenix can obtain after inserting some, possibly zero, integers into his array $$$a$$$. You may print integers that weren't originally in array $$$a$$$. If there are multiple solutions, print any. It's guaranteed that if we can make array $$$a$$$ beautiful, we can always make it with resulting length no more than $$$10^4$$$.
standard output
PASSED
3f6148df36f61ede0f8c348781a8621c
train_002.jsonl
1588343700
Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of length $$$k$$$ have the same sum. A subarray of an array is any sequence of consecutive elements.Phoenix currently has an array $$$a$$$ of length $$$n$$$. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautiful. The inserted integers must be between $$$1$$$ and $$$n$$$ inclusive. Integers may be inserted anywhere (even before the first or after the last element), and he is not trying to minimize the number of inserted integers.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class tr1 { static PrintWriter out; static StringBuilder sb; static int n, m, k; static long mod = 998244353; static Boolean[][][] memo; static String s; static HashSet<Integer> nodes; static ArrayList<Integer>[] ad; static boolean[] vis, taken; static int[] occ, ans; static TreeSet<Long> al; static long[] val; static char[] b; public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); out = new PrintWriter(System.out); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int k = sc.nextInt(); int[] a = new int[n]; TreeSet<Integer> hs = new TreeSet<>(); int sum = 0; ArrayList<Integer> ar = new ArrayList<>(); for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); if (!hs.contains(a[i])) ar.add(a[i]); hs.add(a[i]); } if (hs.size() > k) { out.println(-1); continue; } int id = hs.size(); while (id < k) { ar.add(hs.last()); id++; } int l = 0; for (int i = 0; i < n; i++) { while (a[i] != ar.get(l)) { ar.add(ar.get(l)); l++; } ar.add(a[i]); l++; } out.println(ar.size()); for (int kl : ar) out.print(kl + " "); out.println(); } out.flush(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public int[] nextArrInt(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextArrLong(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } }
Java
["4\n4 2\n1 2 2 1\n4 3\n1 2 2 1\n3 2\n1 2 3\n4 4\n4 3 4 2"]
2 seconds
["5\n1 2 1 2 1\n4\n1 2 2 1\n-1\n7\n4 3 2 1 4 3 2"]
NoteIn the first test case, we can make array $$$a$$$ beautiful by inserting the integer $$$1$$$ at index $$$3$$$ (in between the two existing $$$2$$$s). Now, all subarrays of length $$$k=2$$$ have the same sum $$$3$$$. There exists many other possible solutions, for example: $$$2, 1, 2, 1, 2, 1$$$ $$$1, 2, 1, 2, 1, 2$$$ In the second test case, the array is already beautiful: all subarrays of length $$$k=3$$$ have the same sum $$$5$$$.In the third test case, it can be shown that we cannot insert numbers to make array $$$a$$$ beautiful.In the fourth test case, the array $$$b$$$ shown is beautiful and all subarrays of length $$$k=4$$$ have the same sum $$$10$$$. There exist other solutions also.
Java 8
standard input
[ "data structures", "constructive algorithms", "sortings", "greedy" ]
80d4b2d01215b12ebd89b8ee2d1ac6ed
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 50$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 100$$$). The second line of each test case contains $$$n$$$ space-separated integers ($$$1 \le a_i \le n$$$) — the array that Phoenix currently has. This array may or may not be already beautiful.
1,400
For each test case, if it is impossible to create a beautiful array, print -1. Otherwise, print two lines. The first line should contain the length of the beautiful array $$$m$$$ ($$$n \le m \le 10^4$$$). You don't need to minimize $$$m$$$. The second line should contain $$$m$$$ space-separated integers ($$$1 \le b_i \le n$$$) — a beautiful array that Phoenix can obtain after inserting some, possibly zero, integers into his array $$$a$$$. You may print integers that weren't originally in array $$$a$$$. If there are multiple solutions, print any. It's guaranteed that if we can make array $$$a$$$ beautiful, we can always make it with resulting length no more than $$$10^4$$$.
standard output
PASSED
c2aaf9c16fd18129ec84baa81df03c18
train_002.jsonl
1588343700
Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of length $$$k$$$ have the same sum. A subarray of an array is any sequence of consecutive elements.Phoenix currently has an array $$$a$$$ of length $$$n$$$. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautiful. The inserted integers must be between $$$1$$$ and $$$n$$$ inclusive. Integers may be inserted anywhere (even before the first or after the last element), and he is not trying to minimize the number of inserted integers.
256 megabytes
import java.util.*; import java.io.*; public class Drogon { public static void main(String[] args) throws Exception { FastReader sc = new FastReader(); int t=sc.nextInt(); while (t-->0){ int n=sc.nextInt(),k=sc.nextInt(); TreeSet<Integer> s=new TreeSet<>(); for (int i=0;i<n;i++)s.add(sc.nextInt()); if (s.size()>k){ System.out.println(-1); continue; } for (int i=1;i<=n;i++){ if (s.size()==k)break; s.add(i); } StringBuilder sb=new StringBuilder(); for (int i=0;i<n;i++){ for (int j:s){ sb.append(j+" "); } } System.out.println(n*s.size()); System.out.println(sb); } } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
Java
["4\n4 2\n1 2 2 1\n4 3\n1 2 2 1\n3 2\n1 2 3\n4 4\n4 3 4 2"]
2 seconds
["5\n1 2 1 2 1\n4\n1 2 2 1\n-1\n7\n4 3 2 1 4 3 2"]
NoteIn the first test case, we can make array $$$a$$$ beautiful by inserting the integer $$$1$$$ at index $$$3$$$ (in between the two existing $$$2$$$s). Now, all subarrays of length $$$k=2$$$ have the same sum $$$3$$$. There exists many other possible solutions, for example: $$$2, 1, 2, 1, 2, 1$$$ $$$1, 2, 1, 2, 1, 2$$$ In the second test case, the array is already beautiful: all subarrays of length $$$k=3$$$ have the same sum $$$5$$$.In the third test case, it can be shown that we cannot insert numbers to make array $$$a$$$ beautiful.In the fourth test case, the array $$$b$$$ shown is beautiful and all subarrays of length $$$k=4$$$ have the same sum $$$10$$$. There exist other solutions also.
Java 8
standard input
[ "data structures", "constructive algorithms", "sortings", "greedy" ]
80d4b2d01215b12ebd89b8ee2d1ac6ed
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 50$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 100$$$). The second line of each test case contains $$$n$$$ space-separated integers ($$$1 \le a_i \le n$$$) — the array that Phoenix currently has. This array may or may not be already beautiful.
1,400
For each test case, if it is impossible to create a beautiful array, print -1. Otherwise, print two lines. The first line should contain the length of the beautiful array $$$m$$$ ($$$n \le m \le 10^4$$$). You don't need to minimize $$$m$$$. The second line should contain $$$m$$$ space-separated integers ($$$1 \le b_i \le n$$$) — a beautiful array that Phoenix can obtain after inserting some, possibly zero, integers into his array $$$a$$$. You may print integers that weren't originally in array $$$a$$$. If there are multiple solutions, print any. It's guaranteed that if we can make array $$$a$$$ beautiful, we can always make it with resulting length no more than $$$10^4$$$.
standard output
PASSED
44a607cc1459e6fa06dda28225e83657
train_002.jsonl
1588343700
Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of length $$$k$$$ have the same sum. A subarray of an array is any sequence of consecutive elements.Phoenix currently has an array $$$a$$$ of length $$$n$$$. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautiful. The inserted integers must be between $$$1$$$ and $$$n$$$ inclusive. Integers may be inserted anywhere (even before the first or after the last element), and he is not trying to minimize the number of inserted integers.
256 megabytes
import java.io.*; import java.util.*; public class pbe { public static void main (String[] args) { Scanner s = new Scanner(System.in); int t = s.nextInt(); while(t-->0) { int n = s.nextInt(); int k = s.nextInt(); int arr[] = new int[n]; Set<Integer> hs = new HashSet(); for (int i = 0 ; i<n ;i++) { arr[i]= s.nextInt(); hs.add(arr[i]); } if(hs.size()>k) { System.out.println("-1"); continue; } System.out.println(n*k); for (int i = 0 ; i <n;i++) { for (int e : hs) { System.out.print(e+" "); } for (int j =0; j<k-hs.size();j++) { System.out.print("1"+" "); } } System.out.println(""); } } }
Java
["4\n4 2\n1 2 2 1\n4 3\n1 2 2 1\n3 2\n1 2 3\n4 4\n4 3 4 2"]
2 seconds
["5\n1 2 1 2 1\n4\n1 2 2 1\n-1\n7\n4 3 2 1 4 3 2"]
NoteIn the first test case, we can make array $$$a$$$ beautiful by inserting the integer $$$1$$$ at index $$$3$$$ (in between the two existing $$$2$$$s). Now, all subarrays of length $$$k=2$$$ have the same sum $$$3$$$. There exists many other possible solutions, for example: $$$2, 1, 2, 1, 2, 1$$$ $$$1, 2, 1, 2, 1, 2$$$ In the second test case, the array is already beautiful: all subarrays of length $$$k=3$$$ have the same sum $$$5$$$.In the third test case, it can be shown that we cannot insert numbers to make array $$$a$$$ beautiful.In the fourth test case, the array $$$b$$$ shown is beautiful and all subarrays of length $$$k=4$$$ have the same sum $$$10$$$. There exist other solutions also.
Java 8
standard input
[ "data structures", "constructive algorithms", "sortings", "greedy" ]
80d4b2d01215b12ebd89b8ee2d1ac6ed
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 50$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 100$$$). The second line of each test case contains $$$n$$$ space-separated integers ($$$1 \le a_i \le n$$$) — the array that Phoenix currently has. This array may or may not be already beautiful.
1,400
For each test case, if it is impossible to create a beautiful array, print -1. Otherwise, print two lines. The first line should contain the length of the beautiful array $$$m$$$ ($$$n \le m \le 10^4$$$). You don't need to minimize $$$m$$$. The second line should contain $$$m$$$ space-separated integers ($$$1 \le b_i \le n$$$) — a beautiful array that Phoenix can obtain after inserting some, possibly zero, integers into his array $$$a$$$. You may print integers that weren't originally in array $$$a$$$. If there are multiple solutions, print any. It's guaranteed that if we can make array $$$a$$$ beautiful, we can always make it with resulting length no more than $$$10^4$$$.
standard output
PASSED
959011837cfa2f541b8ad0c32322ba37
train_002.jsonl
1588343700
Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of length $$$k$$$ have the same sum. A subarray of an array is any sequence of consecutive elements.Phoenix currently has an array $$$a$$$ of length $$$n$$$. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautiful. The inserted integers must be between $$$1$$$ and $$$n$$$ inclusive. Integers may be inserted anywhere (even before the first or after the last element), and he is not trying to minimize the number of inserted integers.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashSet; import java.util.StringTokenizer; public class question2 { public static void solve() { int t = s.nextInt(); while (t-- > 0) { int n = s.nextInt(); int k = s.nextInt(); int arr[] = new int[n]; HashSet<Integer> set=new HashSet<Integer>(); for (int i = 0; i < n; i++) { arr[i] = s.nextInt(); set.add(arr[i]); } if(k<set.size()) { out.println(-1); }else { out.println(n*k); int l=k-set.size(); for(int j=0;j<n;j++) { for(Integer val:set) { out.print(val+" "); } for(int z=1;z<=l;z++) { out.print(1+" "); } } out.println(); } } } public static void main(String[] args) { out = new PrintWriter(new BufferedOutputStream(System.out)); s = new FastReader(); solve(); out.close(); } public static FastReader s; public static PrintWriter out; public static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (Exception e) { e.printStackTrace(); } return str; } } }
Java
["4\n4 2\n1 2 2 1\n4 3\n1 2 2 1\n3 2\n1 2 3\n4 4\n4 3 4 2"]
2 seconds
["5\n1 2 1 2 1\n4\n1 2 2 1\n-1\n7\n4 3 2 1 4 3 2"]
NoteIn the first test case, we can make array $$$a$$$ beautiful by inserting the integer $$$1$$$ at index $$$3$$$ (in between the two existing $$$2$$$s). Now, all subarrays of length $$$k=2$$$ have the same sum $$$3$$$. There exists many other possible solutions, for example: $$$2, 1, 2, 1, 2, 1$$$ $$$1, 2, 1, 2, 1, 2$$$ In the second test case, the array is already beautiful: all subarrays of length $$$k=3$$$ have the same sum $$$5$$$.In the third test case, it can be shown that we cannot insert numbers to make array $$$a$$$ beautiful.In the fourth test case, the array $$$b$$$ shown is beautiful and all subarrays of length $$$k=4$$$ have the same sum $$$10$$$. There exist other solutions also.
Java 8
standard input
[ "data structures", "constructive algorithms", "sortings", "greedy" ]
80d4b2d01215b12ebd89b8ee2d1ac6ed
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 50$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 100$$$). The second line of each test case contains $$$n$$$ space-separated integers ($$$1 \le a_i \le n$$$) — the array that Phoenix currently has. This array may or may not be already beautiful.
1,400
For each test case, if it is impossible to create a beautiful array, print -1. Otherwise, print two lines. The first line should contain the length of the beautiful array $$$m$$$ ($$$n \le m \le 10^4$$$). You don't need to minimize $$$m$$$. The second line should contain $$$m$$$ space-separated integers ($$$1 \le b_i \le n$$$) — a beautiful array that Phoenix can obtain after inserting some, possibly zero, integers into his array $$$a$$$. You may print integers that weren't originally in array $$$a$$$. If there are multiple solutions, print any. It's guaranteed that if we can make array $$$a$$$ beautiful, we can always make it with resulting length no more than $$$10^4$$$.
standard output
PASSED
1363cac49fd6b819d6d6796148b12b33
train_002.jsonl
1588343700
Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of length $$$k$$$ have the same sum. A subarray of an array is any sequence of consecutive elements.Phoenix currently has an array $$$a$$$ of length $$$n$$$. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautiful. The inserted integers must be between $$$1$$$ and $$$n$$$ inclusive. Integers may be inserted anywhere (even before the first or after the last element), and he is not trying to minimize the number of inserted integers.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashSet; import java.util.StringTokenizer; public class question2 { public static void solve() { int t = s.nextInt(); while (t-- > 0) { int n = s.nextInt(); int k = s.nextInt(); int arr[] = new int[n]; HashSet<Integer> set=new HashSet<Integer>(); for (int i = 0; i < n; i++) { arr[i] = s.nextInt(); set.add(arr[i]); } if(k<set.size()) { out.println(-1); }else { out.println(n*k); int l=k-set.size(); for(int j=0;j<n;j++) { for(Integer val:set) { out.print(val+" "); } for(int z=1;z<=l;z++) { out.print(z+" "); } } out.println(); } } } public static void main(String[] args) { out = new PrintWriter(new BufferedOutputStream(System.out)); s = new FastReader(); solve(); out.close(); } public static FastReader s; public static PrintWriter out; public static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (Exception e) { e.printStackTrace(); } return str; } } }
Java
["4\n4 2\n1 2 2 1\n4 3\n1 2 2 1\n3 2\n1 2 3\n4 4\n4 3 4 2"]
2 seconds
["5\n1 2 1 2 1\n4\n1 2 2 1\n-1\n7\n4 3 2 1 4 3 2"]
NoteIn the first test case, we can make array $$$a$$$ beautiful by inserting the integer $$$1$$$ at index $$$3$$$ (in between the two existing $$$2$$$s). Now, all subarrays of length $$$k=2$$$ have the same sum $$$3$$$. There exists many other possible solutions, for example: $$$2, 1, 2, 1, 2, 1$$$ $$$1, 2, 1, 2, 1, 2$$$ In the second test case, the array is already beautiful: all subarrays of length $$$k=3$$$ have the same sum $$$5$$$.In the third test case, it can be shown that we cannot insert numbers to make array $$$a$$$ beautiful.In the fourth test case, the array $$$b$$$ shown is beautiful and all subarrays of length $$$k=4$$$ have the same sum $$$10$$$. There exist other solutions also.
Java 8
standard input
[ "data structures", "constructive algorithms", "sortings", "greedy" ]
80d4b2d01215b12ebd89b8ee2d1ac6ed
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 50$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 100$$$). The second line of each test case contains $$$n$$$ space-separated integers ($$$1 \le a_i \le n$$$) — the array that Phoenix currently has. This array may or may not be already beautiful.
1,400
For each test case, if it is impossible to create a beautiful array, print -1. Otherwise, print two lines. The first line should contain the length of the beautiful array $$$m$$$ ($$$n \le m \le 10^4$$$). You don't need to minimize $$$m$$$. The second line should contain $$$m$$$ space-separated integers ($$$1 \le b_i \le n$$$) — a beautiful array that Phoenix can obtain after inserting some, possibly zero, integers into his array $$$a$$$. You may print integers that weren't originally in array $$$a$$$. If there are multiple solutions, print any. It's guaranteed that if we can make array $$$a$$$ beautiful, we can always make it with resulting length no more than $$$10^4$$$.
standard output
PASSED
5382c033bd9d34d9ee5568cc15f13972
train_002.jsonl
1588343700
Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of length $$$k$$$ have the same sum. A subarray of an array is any sequence of consecutive elements.Phoenix currently has an array $$$a$$$ of length $$$n$$$. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautiful. The inserted integers must be between $$$1$$$ and $$$n$$$ inclusive. Integers may be inserted anywhere (even before the first or after the last element), and he is not trying to minimize the number of inserted integers.
256 megabytes
import java.util.*; import java.io.*; import java.lang.*; public class Solution { public static void main(String [] args) { Scanner s=new Scanner(System.in); int T=s.nextInt(); while(T-->0) { int N=s.nextInt(); int K=s.nextInt(); int B[]=new int[N]; List<Integer>L=new ArrayList<Integer>(); List<Integer>A=new ArrayList<Integer>(); Set<Integer>S=new TreeSet<Integer>(); for(int i=0;i<N;i++) { B[i]=s.nextInt(); S.add(B[i]); } int n=S.size(); if(n>K) { System.out.println(-1); continue; } A.addAll(S); while(n!=K) { A.add(A.get(0)); n++; } for(int i=0;i<N;i++) { L.addAll(A); } N*=K; System.out.println(N); for(int i=0;i<N;i++) { System.out.print(L.get(i)+" "); } System.out.println(""); } } }
Java
["4\n4 2\n1 2 2 1\n4 3\n1 2 2 1\n3 2\n1 2 3\n4 4\n4 3 4 2"]
2 seconds
["5\n1 2 1 2 1\n4\n1 2 2 1\n-1\n7\n4 3 2 1 4 3 2"]
NoteIn the first test case, we can make array $$$a$$$ beautiful by inserting the integer $$$1$$$ at index $$$3$$$ (in between the two existing $$$2$$$s). Now, all subarrays of length $$$k=2$$$ have the same sum $$$3$$$. There exists many other possible solutions, for example: $$$2, 1, 2, 1, 2, 1$$$ $$$1, 2, 1, 2, 1, 2$$$ In the second test case, the array is already beautiful: all subarrays of length $$$k=3$$$ have the same sum $$$5$$$.In the third test case, it can be shown that we cannot insert numbers to make array $$$a$$$ beautiful.In the fourth test case, the array $$$b$$$ shown is beautiful and all subarrays of length $$$k=4$$$ have the same sum $$$10$$$. There exist other solutions also.
Java 8
standard input
[ "data structures", "constructive algorithms", "sortings", "greedy" ]
80d4b2d01215b12ebd89b8ee2d1ac6ed
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 50$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 100$$$). The second line of each test case contains $$$n$$$ space-separated integers ($$$1 \le a_i \le n$$$) — the array that Phoenix currently has. This array may or may not be already beautiful.
1,400
For each test case, if it is impossible to create a beautiful array, print -1. Otherwise, print two lines. The first line should contain the length of the beautiful array $$$m$$$ ($$$n \le m \le 10^4$$$). You don't need to minimize $$$m$$$. The second line should contain $$$m$$$ space-separated integers ($$$1 \le b_i \le n$$$) — a beautiful array that Phoenix can obtain after inserting some, possibly zero, integers into his array $$$a$$$. You may print integers that weren't originally in array $$$a$$$. If there are multiple solutions, print any. It's guaranteed that if we can make array $$$a$$$ beautiful, we can always make it with resulting length no more than $$$10^4$$$.
standard output
PASSED
47f472e9f9cc5826292abbb46b6340d5
train_002.jsonl
1588343700
Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of length $$$k$$$ have the same sum. A subarray of an array is any sequence of consecutive elements.Phoenix currently has an array $$$a$$$ of length $$$n$$$. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautiful. The inserted integers must be between $$$1$$$ and $$$n$$$ inclusive. Integers may be inserted anywhere (even before the first or after the last element), and he is not trying to minimize the number of inserted integers.
256 megabytes
import java.net.Inet4Address; import java.util.*; import java.io.*; public class Main { static FastReader in=new FastReader(); static long mod=1000000007L; public static void main(String args[]) throws IOException { int t=in.nextInt(); StringBuilder res=new StringBuilder(); loop: while(t-->0) { int n=in.nextInt(); int k=in.nextInt(); int a[]=in.readintarray(n); HashSet<Integer>set=new HashSet<>(); for(int x: a) { set.add(x); } if(set.size()>k) { res.append(-1+"\n"); continue loop; } ArrayList<Integer>list=new ArrayList<>(); for(int x:set) { list.add(x); } while (list.size()<k) { list.add(1); } res.append(n*k+"\n"); while(n-->0) { for(int x: list) { res.append(x+" "); } } //res.append(list.size()+"\n"); res.append("\n"); } print(res); } static < E > void print(E res) { System.out.println(res); } static int gcd(int a,int b) { if(b==0) { return a; } return gcd(b,a%b); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int [] readintarray(int n) { int res [] = new int [n]; for(int i = 0; i<n; i++)res[i] = nextInt(); return res; } long [] readlongarray(int n) { long res [] = new long [n]; for(int i = 0; i<n; i++)res[i] = nextLong(); return res; } } }
Java
["4\n4 2\n1 2 2 1\n4 3\n1 2 2 1\n3 2\n1 2 3\n4 4\n4 3 4 2"]
2 seconds
["5\n1 2 1 2 1\n4\n1 2 2 1\n-1\n7\n4 3 2 1 4 3 2"]
NoteIn the first test case, we can make array $$$a$$$ beautiful by inserting the integer $$$1$$$ at index $$$3$$$ (in between the two existing $$$2$$$s). Now, all subarrays of length $$$k=2$$$ have the same sum $$$3$$$. There exists many other possible solutions, for example: $$$2, 1, 2, 1, 2, 1$$$ $$$1, 2, 1, 2, 1, 2$$$ In the second test case, the array is already beautiful: all subarrays of length $$$k=3$$$ have the same sum $$$5$$$.In the third test case, it can be shown that we cannot insert numbers to make array $$$a$$$ beautiful.In the fourth test case, the array $$$b$$$ shown is beautiful and all subarrays of length $$$k=4$$$ have the same sum $$$10$$$. There exist other solutions also.
Java 8
standard input
[ "data structures", "constructive algorithms", "sortings", "greedy" ]
80d4b2d01215b12ebd89b8ee2d1ac6ed
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 50$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 100$$$). The second line of each test case contains $$$n$$$ space-separated integers ($$$1 \le a_i \le n$$$) — the array that Phoenix currently has. This array may or may not be already beautiful.
1,400
For each test case, if it is impossible to create a beautiful array, print -1. Otherwise, print two lines. The first line should contain the length of the beautiful array $$$m$$$ ($$$n \le m \le 10^4$$$). You don't need to minimize $$$m$$$. The second line should contain $$$m$$$ space-separated integers ($$$1 \le b_i \le n$$$) — a beautiful array that Phoenix can obtain after inserting some, possibly zero, integers into his array $$$a$$$. You may print integers that weren't originally in array $$$a$$$. If there are multiple solutions, print any. It's guaranteed that if we can make array $$$a$$$ beautiful, we can always make it with resulting length no more than $$$10^4$$$.
standard output
PASSED
7fcc47a1d059256d35d7eb120ef760b9
train_002.jsonl
1588343700
Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of length $$$k$$$ have the same sum. A subarray of an array is any sequence of consecutive elements.Phoenix currently has an array $$$a$$$ of length $$$n$$$. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautiful. The inserted integers must be between $$$1$$$ and $$$n$$$ inclusive. Integers may be inserted anywhere (even before the first or after the last element), and he is not trying to minimize the number of inserted integers.
256 megabytes
import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Arrays; import java.util.Scanner; public class B1348 { public static void main(String[] args) throws IOException{ Scanner scanner = new Scanner(System.in); BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out)); int cases = scanner.nextInt(); for(int i = 0; i < cases; i++) { int n = scanner.nextInt(); int sub = scanner.nextInt(); int dif = 0; int[] nums = new int[n]; int[] check = new int[n + 1]; for(int j = 0; j < n; j++) { int temp = scanner.nextInt(); nums[j] = temp; check[temp]++; if(check[temp] == 1) dif++; } if(dif <= sub) { Arrays.sort(nums); long length = (long) n * sub; int[] used = new int[sub]; used[0] = nums[0]; int pos = 1; for(int j = 1; j < n; j++) if(nums[j] != nums[j - 1]) used[pos++] = nums[j]; for(int j = sub - 1; j >= dif ; j--) used[j] = used[dif - 1]; log.write("" + length + "\n"); for(int j = 0; j < length; j++) log.write("" + used[j % sub] + " "); log.write("\n"); } else log.write("-1\n"); } log.flush(); } }
Java
["4\n4 2\n1 2 2 1\n4 3\n1 2 2 1\n3 2\n1 2 3\n4 4\n4 3 4 2"]
2 seconds
["5\n1 2 1 2 1\n4\n1 2 2 1\n-1\n7\n4 3 2 1 4 3 2"]
NoteIn the first test case, we can make array $$$a$$$ beautiful by inserting the integer $$$1$$$ at index $$$3$$$ (in between the two existing $$$2$$$s). Now, all subarrays of length $$$k=2$$$ have the same sum $$$3$$$. There exists many other possible solutions, for example: $$$2, 1, 2, 1, 2, 1$$$ $$$1, 2, 1, 2, 1, 2$$$ In the second test case, the array is already beautiful: all subarrays of length $$$k=3$$$ have the same sum $$$5$$$.In the third test case, it can be shown that we cannot insert numbers to make array $$$a$$$ beautiful.In the fourth test case, the array $$$b$$$ shown is beautiful and all subarrays of length $$$k=4$$$ have the same sum $$$10$$$. There exist other solutions also.
Java 8
standard input
[ "data structures", "constructive algorithms", "sortings", "greedy" ]
80d4b2d01215b12ebd89b8ee2d1ac6ed
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 50$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 100$$$). The second line of each test case contains $$$n$$$ space-separated integers ($$$1 \le a_i \le n$$$) — the array that Phoenix currently has. This array may or may not be already beautiful.
1,400
For each test case, if it is impossible to create a beautiful array, print -1. Otherwise, print two lines. The first line should contain the length of the beautiful array $$$m$$$ ($$$n \le m \le 10^4$$$). You don't need to minimize $$$m$$$. The second line should contain $$$m$$$ space-separated integers ($$$1 \le b_i \le n$$$) — a beautiful array that Phoenix can obtain after inserting some, possibly zero, integers into his array $$$a$$$. You may print integers that weren't originally in array $$$a$$$. If there are multiple solutions, print any. It's guaranteed that if we can make array $$$a$$$ beautiful, we can always make it with resulting length no more than $$$10^4$$$.
standard output
PASSED
adcefa2679ed2326e87d03508e581ccb
train_002.jsonl
1588343700
Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of length $$$k$$$ have the same sum. A subarray of an array is any sequence of consecutive elements.Phoenix currently has an array $$$a$$$ of length $$$n$$$. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautiful. The inserted integers must be between $$$1$$$ and $$$n$$$ inclusive. Integers may be inserted anywhere (even before the first or after the last element), and he is not trying to minimize the number of inserted integers.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; import java.math.*; /** * Author : joney_000[developer.jaswant@gmail.com] * Algorithm : Extended Euclid Algo: find 3 things X, Y, GCD(A, B) Such that X * A + Y * B = GCD(A, B) * Time : O(MAX(A, B)) Space : O(MAX(A, B)) * Platform : Codeforces * Ref : https://www.hackerearth.com/practice/math/number-theory/basic-number-theory-1/tutorial/ */ public class A{ private InputStream inputStream ; private OutputStream outputStream ; private FastReader in ; private PrintWriter out ; private final int BUFFER = 100005; private final long mod = 1000000000+7; private final int INF = Integer.MAX_VALUE; private final long INF_L = Long.MAX_VALUE / 10; public A(){} public A(boolean stdIO)throws FileNotFoundException{ // stdIO = false; if(stdIO){ inputStream = System.in; outputStream = System.out; }else{ inputStream = new FileInputStream("input.txt"); outputStream = new FileOutputStream("output.txt"); } in = new FastReader(inputStream); out = new PrintWriter(outputStream); } int a[] = new int[100005]; int mark[] = new int[101]; void run()throws Exception{ int tests = i(); for(int testId = 1; testId <= tests; testId++){ int n = i(); int m = i(); HashSet<Integer> hs = new HashSet<>(); LinkedList<Integer> res = new LinkedList<>(); for(int i = 1; i <= 100; i++)mark[i] = 0; LinkedList<Integer> rep = new LinkedList<>(); for(int i = 1; i <= n; i++){ a[i] = i(); if(mark[a[i]] == 0)rep.add(a[i]); mark[a[i]] = 1; } int cnt = 0; for(int i = 1; i <= 100; i++){ if(mark[i] == 1)++cnt; } if(cnt > m){ out.write("-1\n"); continue; } for(int i = 1; i <= 100 && rep.size() < m; i++){ if(mark[i] == 0)rep.add(i); } for(int i = 1; i <= n; i++){ // res.add(a[i]); for(int j : rep){ // if(a[i] == j)continue; res.add(j); } } out.write(""+res.size()+"\n"); for(int x: res){ out.write(""+x+" "); } out.write("\n"); } } void clear(){ } long gcd(long a, long b){ if(b == 0)return a; return gcd(b, a % b); } long lcm(long a, long b){ if(a == 0 || b == 0)return 0; return (a * b)/gcd(a, b); } long mulMod(long a, long b, long mod){ if(a == 0 || b == 0)return 0; if(b == 1)return a; long ans = mulMod(a, b/2, mod); ans = (ans * 2) % mod; if(b % 2 == 1)ans = (a + ans)% mod; return ans; } long pow(long a, long b, long mod){ if(b == 0)return 1; if(b == 1)return a; long ans = pow(a, b/2, mod); ans = mulMod(ans, ans, mod); if(ans >= mod)ans %= mod; if(b % 2 == 1)ans = mulMod(a, ans, mod); if(ans >= mod)ans %= mod; return ans; } // 20*20 nCr Pascal Table long[][] ncrTable(){ long ncr[][] = new long[21][21]; for(int i = 0; i <= 20; i++){ ncr[i][0] = ncr[i][i] = 1L; } for(int j = 0; j <= 20; j++){ for(int i = j + 1; i <= 20; i++){ ncr[i][j] = ncr[i-1][j] + ncr[i-1][j-1]; } } return ncr; } int i()throws Exception{ return in.nextInt(); } long l()throws Exception{ return in.nextLong(); } double d()throws Exception{ return in.nextDouble(); } char c()throws Exception{ return in.nextCharacter(); } String s()throws Exception{ return in.nextLine(); } BigInteger bi()throws Exception{ return in.nextBigInteger(); } private void closeResources(){ out.flush(); out.close(); return; } // IMP: roundoff upto 2 digits // double roundOff = Math.round(a * 100.0) / 100.0; // or // System.out.printf("%.2f", val); // print upto 2 digits after decimal // val = ((long)(val * 100.0))/100.0; public static void main(String[] args) throws java.lang.Exception{ A driver = new A(true); driver.run(); driver.closeResources(); } } class FastReader{ private boolean finished = false; private InputStream stream; private byte[] buf = new byte[4 * 1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public FastReader(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 peek(){ if (numChars == -1){ return -1; } if (curChar >= numChars){ curChar = 0; try{ numChars = stream.read (buf); } catch (IOException e){ return -1; } 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==','){ c = read(); } if (c < '0' || c > '9'){ throw new InputMismatchException (); } res *= 10; res += c - '0'; c = read (); } while (!isSpaceChar (c)); return res * sgn; } public long nextLong(){ int c = read (); while (isSpaceChar (c)) c = read (); int sgn = 1; if (c == '-'){ sgn = -1; c = read (); } long res = 0; do{ if (c < '0' || c > '9'){ throw new InputMismatchException (); } res *= 10; res += c - '0'; c = read (); } while (!isSpaceChar (c)); return res * sgn; } public String nextString(){ int c = read (); while (isSpaceChar (c)) c = read (); StringBuilder res = new StringBuilder (); do{ res.appendCodePoint (c); c = read (); } while (!isSpaceChar (c)); return res.toString (); } public boolean isSpaceChar(int c){ if (filter != null){ return filter.isSpaceChar (c); } return isWhitespace (c); } public static boolean isWhitespace(int c){ return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0(){ StringBuilder buf = new StringBuilder (); int c = read (); while (c != '\n' && c != -1){ if (c != '\r'){ buf.appendCodePoint (c); } c = read (); } return buf.toString (); } public String nextLine(){ String s = readLine0 (); while (s.trim ().length () == 0) s = readLine0 (); return s; } public String nextLine(boolean ignoreEmptyLines){ if (ignoreEmptyLines){ return nextLine (); }else{ return readLine0 (); } } public BigInteger nextBigInteger(){ try{ return new BigInteger (nextString ()); } catch (NumberFormatException e){ throw new InputMismatchException (); } } public char nextCharacter(){ int c = read (); while (isSpaceChar (c)) c = read (); return (char) c; } public double nextDouble(){ int c = read (); while (isSpaceChar (c)) c = read (); int sgn = 1; if (c == '-'){ sgn = -1; c = read (); } double res = 0; while (!isSpaceChar (c) && c != '.'){ if (c == 'e' || c == 'E'){ return res * Math.pow (10, nextInt ()); } if (c < '0' || c > '9'){ throw new InputMismatchException (); } res *= 10; res += c - '0'; c = read (); } if (c == '.'){ c = read (); double m = 1; while (!isSpaceChar (c)){ if (c == 'e' || c == 'E'){ return res * Math.pow (10, nextInt ()); } if (c < '0' || c > '9'){ throw new InputMismatchException (); } m /= 10; res += (c - '0') * m; c = read (); } } return res * sgn; } public boolean isExhausted(){ int value; while (isSpaceChar (value = peek ()) && value != -1) read (); return value == -1; } public String next(){ return nextString (); } public SpaceCharFilter getFilter(){ return filter; } public void setFilter(SpaceCharFilter filter){ this.filter = filter; } public interface SpaceCharFilter{ public boolean isSpaceChar(int ch); } } class Pair implements Comparable<Pair>{ public int a; public int b; public Pair(){ this.a = 0; this.b = 0; } public Pair(int a,int b){ this.a = a; this.b = b; } public int compareTo(Pair p){ if(this.a == p.a){ return this.b - p.b; } return this.a - p.a; } @Override public String toString(){ return "a = " + this.a + " b = " + this.b; } }
Java
["4\n4 2\n1 2 2 1\n4 3\n1 2 2 1\n3 2\n1 2 3\n4 4\n4 3 4 2"]
2 seconds
["5\n1 2 1 2 1\n4\n1 2 2 1\n-1\n7\n4 3 2 1 4 3 2"]
NoteIn the first test case, we can make array $$$a$$$ beautiful by inserting the integer $$$1$$$ at index $$$3$$$ (in between the two existing $$$2$$$s). Now, all subarrays of length $$$k=2$$$ have the same sum $$$3$$$. There exists many other possible solutions, for example: $$$2, 1, 2, 1, 2, 1$$$ $$$1, 2, 1, 2, 1, 2$$$ In the second test case, the array is already beautiful: all subarrays of length $$$k=3$$$ have the same sum $$$5$$$.In the third test case, it can be shown that we cannot insert numbers to make array $$$a$$$ beautiful.In the fourth test case, the array $$$b$$$ shown is beautiful and all subarrays of length $$$k=4$$$ have the same sum $$$10$$$. There exist other solutions also.
Java 8
standard input
[ "data structures", "constructive algorithms", "sortings", "greedy" ]
80d4b2d01215b12ebd89b8ee2d1ac6ed
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 50$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 100$$$). The second line of each test case contains $$$n$$$ space-separated integers ($$$1 \le a_i \le n$$$) — the array that Phoenix currently has. This array may or may not be already beautiful.
1,400
For each test case, if it is impossible to create a beautiful array, print -1. Otherwise, print two lines. The first line should contain the length of the beautiful array $$$m$$$ ($$$n \le m \le 10^4$$$). You don't need to minimize $$$m$$$. The second line should contain $$$m$$$ space-separated integers ($$$1 \le b_i \le n$$$) — a beautiful array that Phoenix can obtain after inserting some, possibly zero, integers into his array $$$a$$$. You may print integers that weren't originally in array $$$a$$$. If there are multiple solutions, print any. It's guaranteed that if we can make array $$$a$$$ beautiful, we can always make it with resulting length no more than $$$10^4$$$.
standard output
PASSED
a34fd0a1fa01673d005987079fcece5f
train_002.jsonl
1588343700
Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of length $$$k$$$ have the same sum. A subarray of an array is any sequence of consecutive elements.Phoenix currently has an array $$$a$$$ of length $$$n$$$. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautiful. The inserted integers must be between $$$1$$$ and $$$n$$$ inclusive. Integers may be inserted anywhere (even before the first or after the last element), and he is not trying to minimize the number of inserted integers.
256 megabytes
import java.awt.List; import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; public class b { public static void main(String[] args) { Scanner s=new Scanner(System.in); int t=s.nextInt(); for(int ie=0;ie<t;ie++) { int n=s.nextInt(); int[] arr=new int[n]; int k=s.nextInt(); for(int i=0;i<n;i++) { arr[i]=s.nextInt(); } HashMap<Integer,Integer> map=new HashMap<>(); ArrayList<Integer> list=new ArrayList<>(); for(int i=0;i<n;i++) { if(map.containsKey(arr[i])) { }else { map.put(arr[i], 1); list.add(arr[i]); } } if(list.size()>k) { System.out.println(-1); }else { int c=1; int l=list.size(); for(int i=0;i<k-l;i++) { list.add(c); } //System.out.println(list); System.out.println(10000); int h=0; for(int i=0;i<10000;i++) { if(h>=list.size()) { h=0; } System.out.print(list.get(h)+" "); h++; } System.out.println(); } } } }
Java
["4\n4 2\n1 2 2 1\n4 3\n1 2 2 1\n3 2\n1 2 3\n4 4\n4 3 4 2"]
2 seconds
["5\n1 2 1 2 1\n4\n1 2 2 1\n-1\n7\n4 3 2 1 4 3 2"]
NoteIn the first test case, we can make array $$$a$$$ beautiful by inserting the integer $$$1$$$ at index $$$3$$$ (in between the two existing $$$2$$$s). Now, all subarrays of length $$$k=2$$$ have the same sum $$$3$$$. There exists many other possible solutions, for example: $$$2, 1, 2, 1, 2, 1$$$ $$$1, 2, 1, 2, 1, 2$$$ In the second test case, the array is already beautiful: all subarrays of length $$$k=3$$$ have the same sum $$$5$$$.In the third test case, it can be shown that we cannot insert numbers to make array $$$a$$$ beautiful.In the fourth test case, the array $$$b$$$ shown is beautiful and all subarrays of length $$$k=4$$$ have the same sum $$$10$$$. There exist other solutions also.
Java 8
standard input
[ "data structures", "constructive algorithms", "sortings", "greedy" ]
80d4b2d01215b12ebd89b8ee2d1ac6ed
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 50$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 100$$$). The second line of each test case contains $$$n$$$ space-separated integers ($$$1 \le a_i \le n$$$) — the array that Phoenix currently has. This array may or may not be already beautiful.
1,400
For each test case, if it is impossible to create a beautiful array, print -1. Otherwise, print two lines. The first line should contain the length of the beautiful array $$$m$$$ ($$$n \le m \le 10^4$$$). You don't need to minimize $$$m$$$. The second line should contain $$$m$$$ space-separated integers ($$$1 \le b_i \le n$$$) — a beautiful array that Phoenix can obtain after inserting some, possibly zero, integers into his array $$$a$$$. You may print integers that weren't originally in array $$$a$$$. If there are multiple solutions, print any. It's guaranteed that if we can make array $$$a$$$ beautiful, we can always make it with resulting length no more than $$$10^4$$$.
standard output
PASSED
8424435b6efe2d4eb4c75be905740dcc
train_002.jsonl
1331911800
A string is binary, if it consists only of characters "0" and "1".String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters "1".
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int k = sc.nextInt(); String s = sc.next(); int[] prefix = new int[s.length()]; for(int i = 0; i < s.length(); ++i) { prefix[i] = s.charAt(i) - '0'; if(i > 0) prefix[i] += prefix[i-1]; } long ans = 0; for(int i = 0; i < s.length(); ++i) { int lb = bs(prefix, k, i, true), ub = bs(prefix, k, i, false); if(lb != -1) ans += ub - lb + 1; } out.println(ans); out.flush(); out.close(); } static int bs(int[] prefix, int k, int idx, boolean isLower) { int sub = idx == 0 ? 0 : (prefix[idx - 1]); int lo = idx, hi = prefix.length - 1, ans = -1; while(lo <= hi) { int mid = lo + (hi - lo) / 2; if(prefix[mid] - sub == k) { ans = mid; if(isLower) hi = mid - 1; else lo = mid + 1; } else if(prefix[mid] - sub < k) lo = mid + 1; else hi = mid - 1; } return ans; } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public boolean ready() throws IOException {return br.ready();} public double nextDouble(String x) { 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); } } }
Java
["1\n1010", "2\n01010", "100\n01010"]
2 seconds
["6", "4", "0"]
NoteIn the first sample the sought substrings are: "1", "1", "10", "01", "10", "010".In the second sample the sought substrings are: "101", "0101", "1010", "01010".
Java 8
standard input
[ "dp", "two pointers", "math", "binary search", "brute force", "strings" ]
adc43f273dd9b3f1c58b052a34732a50
The first line contains the single integer k (0 ≤ k ≤ 106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters.
1,600
Print the single number — the number of substrings of the given string, containing exactly k characters "1". Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
21c5bdcc0dd83fbed8b38dbaa08e21aa
train_002.jsonl
1331911800
A string is binary, if it consists only of characters "0" and "1".String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters "1".
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int k = sc.nextInt(); String s = sc.next(); int n = s.length(); int[] prefix = new int[n + 1], count = new int[n + 1]; for(int i = 1; i <= n; ++i) prefix[i] = s.charAt(i-1) - '0' + prefix[i - 1]; long ans = 0; for(int i = 0; i <= n; ++i) { if(prefix[i] >= k) ans += count[prefix[i] - k]; ++count[prefix[i]]; } out.println(ans); out.flush(); out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public boolean ready() throws IOException {return br.ready();} public double nextDouble(String x) { 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); } } }
Java
["1\n1010", "2\n01010", "100\n01010"]
2 seconds
["6", "4", "0"]
NoteIn the first sample the sought substrings are: "1", "1", "10", "01", "10", "010".In the second sample the sought substrings are: "101", "0101", "1010", "01010".
Java 8
standard input
[ "dp", "two pointers", "math", "binary search", "brute force", "strings" ]
adc43f273dd9b3f1c58b052a34732a50
The first line contains the single integer k (0 ≤ k ≤ 106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters.
1,600
Print the single number — the number of substrings of the given string, containing exactly k characters "1". Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
b4613487c47bec37ed4ac68bf82c4ca2
train_002.jsonl
1331911800
A string is binary, if it consists only of characters "0" and "1".String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters "1".
256 megabytes
/** https://codeforces.com/problemset/problem/165/C * idea: two pointer */ import java.util.Scanner; import java.util.ArrayList; public class AnotherProblemString { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int k = sc.nextInt(); String str = sc.next(); char[] charArr = str.toCharArray(); ArrayList<Integer> idxOneArr = new ArrayList<Integer>(); for (int i=0; i < charArr.length; i++) { if (charArr[i] == '1') { idxOneArr.add(i); } } long sum = 0; if (k == 0) { if (idxOneArr.isEmpty()) { int n = str.length(); sum = (long)n*(n+1) / 2; } else { int prev=0; int n = 0; for (int idx : idxOneArr) { n = idx - prev; if ( n > 0) { sum += (long)n * (n+1) / 2; } prev = idx+1; } if (prev <= str.length()) { n = str.length() - prev; sum += (long)n * (n+1) / 2; } } } else { if (k <= idxOneArr.size()) { int startIdx = 0; int idx = 0; int l=0, r=0; for (idx = 0; idx + k < idxOneArr.size(); idx++) { l = idxOneArr.get(idx) - startIdx + 1; startIdx = idxOneArr.get(idx) + 1; r = idxOneArr.get(idx + k) - idxOneArr.get(idx + k - 1); sum += (long)l*r; } if ( idx + k == idxOneArr.size()) { r = str.length() - idxOneArr.get(idx + k - 1); l = idxOneArr.get(idx) - startIdx + 1; sum += (long)l*r; } } } System.out.println(sum); } }
Java
["1\n1010", "2\n01010", "100\n01010"]
2 seconds
["6", "4", "0"]
NoteIn the first sample the sought substrings are: "1", "1", "10", "01", "10", "010".In the second sample the sought substrings are: "101", "0101", "1010", "01010".
Java 8
standard input
[ "dp", "two pointers", "math", "binary search", "brute force", "strings" ]
adc43f273dd9b3f1c58b052a34732a50
The first line contains the single integer k (0 ≤ k ≤ 106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters.
1,600
Print the single number — the number of substrings of the given string, containing exactly k characters "1". Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
d3bb9b5b68657ad4bdd40a83eb5d9570
train_002.jsonl
1331911800
A string is binary, if it consists only of characters "0" and "1".String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters "1".
256 megabytes
import java.util.*; import java.io.*; public class Ana { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int k = sc.nextInt(); String s = sc.next(); int[] cnt = new int[s.length() + 1]; cnt[0] = 1; int sum = 0; long count = 0; if (k == 0) { int prevzero=1; for(int i=0;i<s.length();i++) if(s.charAt(i)=='0') count+=prevzero++; else prevzero=1; } else for (int i = 0; i < s.length(); i++) { sum += s.charAt(i) - '0'; // System.out.println(sum); cnt[sum]++; if (sum - k >= 0) count += cnt[sum - k]; } // out.println(Arrays.toString(cnt)); out.println(count); out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["1\n1010", "2\n01010", "100\n01010"]
2 seconds
["6", "4", "0"]
NoteIn the first sample the sought substrings are: "1", "1", "10", "01", "10", "010".In the second sample the sought substrings are: "101", "0101", "1010", "01010".
Java 8
standard input
[ "dp", "two pointers", "math", "binary search", "brute force", "strings" ]
adc43f273dd9b3f1c58b052a34732a50
The first line contains the single integer k (0 ≤ k ≤ 106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters.
1,600
Print the single number — the number of substrings of the given string, containing exactly k characters "1". Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
05c8c23fd5b15c6d97b67398d8b05aa6
train_002.jsonl
1331911800
A string is binary, if it consists only of characters "0" and "1".String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters "1".
256 megabytes
import java.util.*; import java.io.*; public class Ana { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int k = sc.nextInt(); String s = sc.next(); int[] cnt = new int[s.length() + 1]; cnt[0] = 1; int sum = 0; long count = 0; for (int i = 0; i < s.length(); i++) { sum += s.charAt(i) - '0'; if (sum - k >= 0) count += cnt[sum - k]; cnt[sum]++; } out.println(count); out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["1\n1010", "2\n01010", "100\n01010"]
2 seconds
["6", "4", "0"]
NoteIn the first sample the sought substrings are: "1", "1", "10", "01", "10", "010".In the second sample the sought substrings are: "101", "0101", "1010", "01010".
Java 8
standard input
[ "dp", "two pointers", "math", "binary search", "brute force", "strings" ]
adc43f273dd9b3f1c58b052a34732a50
The first line contains the single integer k (0 ≤ k ≤ 106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters.
1,600
Print the single number — the number of substrings of the given string, containing exactly k characters "1". Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
21bd607cbdff417c314049447a1e1cb0
train_002.jsonl
1331911800
A string is binary, if it consists only of characters "0" and "1".String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters "1".
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Codechef { static PrintWriter out=new PrintWriter(System.out);static FastScanner in = new FastScanner(System.in);static class FastScanner {BufferedReader br;StringTokenizer stok;FastScanner(InputStream is) {br = new BufferedReader(new InputStreamReader(is));} String next() throws IOException {while (stok == null || !stok.hasMoreTokens()) {String s = br.readLine();if (s == null) {return null;} stok = new StringTokenizer(s);}return stok.nextToken();} int ni() throws IOException {return Integer.parseInt(next());}long nl() throws IOException {return Long.parseLong(next());}double nd() throws IOException {return Double.parseDouble(next());}char nc() throws IOException {return (char) (br.read());}String ns() throws IOException {return br.readLine();} int[] nia(int n) throws IOException{int a[] = new int[n];for (int i = 0; i < n; i++)a[i] = ni();return a;}long[] nla(int n) throws IOException {long a[] = new long[n];for (int i = 0; i < n; i++)a[i] = nl();return a;} double[] nda(int n)throws IOException {double a[] = new double[n];for (int i = 0; i < n; i++)a[i] = nd();return a;}int [][] imat(int n,int m) throws IOException{int mat[][]=new int[n][m];for(int i=0;i<n;i++){for(int j=0;j<m;j++)mat[i][j]=ni();}return mat;} } static long mod=Long.MAX_VALUE; public static void main (String[] args) throws java.lang.Exception { int i=0,j=0; HashMap<Integer,Integer> hm=new HashMap<Integer,Integer>(); /* if(hm.containsKey(z)) hm.put(z,hm.get(z)+1); else hm.put(z,1); */ ArrayList<Integer> arr=new ArrayList<Integer>(); HashSet<Integer> set=new HashSet<Integer>(); PriorityQueue<Integer> pq=new PriorityQueue<Integer>(); int k=in.ni(); String s=in.next(); int n=s.length(); int temp[]=new int[n+1]; for(i=1;i<=n;i++) temp[i]=temp[i-1]+s.charAt(i-1)-'0'; /* for(i=0;i<=n;i++) out.print(temp[i]+" "); out.println(" "); */ long ans=0; for(i=0;i<n;i++) { int p=first(temp,i,n,temp[i]+k,n+1); //out.println("searching for"+(temp[i]+k)); int q=last(temp,1,n,temp[i]+k,n+1); if(k==0 && q!=-1) ans+=q-i; else if(p!=-1 && q!=-1) ans+=q-p+1; //out.println("p="+p+" q="+q); } out.println(ans); out.close(); } public static int first(int arr[], int low, int high, int x, int n) { if(high >= low) { int mid = low + (high - low)/2; if( ( mid == 0 || x > arr[mid-1]) && arr[mid] == x) return mid; else if(x > arr[mid]) return first(arr, (mid + 1), high, x, n); else return first(arr, low, (mid -1), x, n); } return -1; } public static int last(int arr[], int low, int high, int x, int n) { if (high >= low) { int mid = low + (high - low)/2; if (( mid == n-1 || x < arr[mid+1]) && arr[mid] == x) return mid; else if (x < arr[mid]) return last(arr, low, (mid -1), x, n); else return last(arr, (mid + 1), high, x, n); } return -1; } }
Java
["1\n1010", "2\n01010", "100\n01010"]
2 seconds
["6", "4", "0"]
NoteIn the first sample the sought substrings are: "1", "1", "10", "01", "10", "010".In the second sample the sought substrings are: "101", "0101", "1010", "01010".
Java 8
standard input
[ "dp", "two pointers", "math", "binary search", "brute force", "strings" ]
adc43f273dd9b3f1c58b052a34732a50
The first line contains the single integer k (0 ≤ k ≤ 106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters.
1,600
Print the single number — the number of substrings of the given string, containing exactly k characters "1". Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
5b6494db1e5476ae696957133ae8b9aa
train_002.jsonl
1331911800
A string is binary, if it consists only of characters "0" and "1".String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters "1".
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; import java.util.HashMap; public class Prac { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int k=sc.nextInt(); String s=sc.next(); int n=s.length(); int i,j=0,ones=0; for(i=0;i<n;i++) if(s.charAt(i)=='1') ones++; long oi[]=new long[ones]; long lz[]=new long[ones]; long rz[]=new long[ones]; long zeroes=0,count=0; for(i=0;i<n;i++){ if(s.charAt(i)=='1'){ oi[j]=i; lz[j]=zeroes; if(j>0) rz[j-1]=zeroes; zeroes=0; j++; } else zeroes++; } if(s.charAt(n-1)=='0'&&j>0) rz[j-1]=zeroes; if(ones==0&&k==0){ System.out.println((zeroes*(zeroes+1))/2); } else if(k==0){ for(i=0;i<ones;i++){ count+=(lz[i]*(lz[i]+1))/2; if(i==ones-1) count+=(rz[i]*(rz[i]+1) )/2; } System.out.println(count); } else{ if(ones<k) System.out.println(0); else{ j=0; for(i=k-1;i<ones;i++){ count+=1+lz[j]+rz[i]+lz[j]*rz[i]; j++; } System.out.println(count); } } } }
Java
["1\n1010", "2\n01010", "100\n01010"]
2 seconds
["6", "4", "0"]
NoteIn the first sample the sought substrings are: "1", "1", "10", "01", "10", "010".In the second sample the sought substrings are: "101", "0101", "1010", "01010".
Java 8
standard input
[ "dp", "two pointers", "math", "binary search", "brute force", "strings" ]
adc43f273dd9b3f1c58b052a34732a50
The first line contains the single integer k (0 ≤ k ≤ 106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters.
1,600
Print the single number — the number of substrings of the given string, containing exactly k characters "1". Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
f502fdb435fcda2d021d80b6a366ab67
train_002.jsonl
1331911800
A string is binary, if it consists only of characters "0" and "1".String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters "1".
256 megabytes
import java.util.*; public class Solution165C{ public static void main(String args[]){ Scanner in=new Scanner(System.in); int k=Integer.parseInt(in.nextLine()); String s=in.nextLine(); int count=0; int n=s.length(); if(k>0){ long[] freq=new long[n+1]; freq[0]=1; for(int i=0;i<n;i++){ if(s.charAt(i)-'0'==1){ count++; } freq[count]++; } // System.out.println(Arrays.toString(freq)); long ret=0; for(int i=k;i<=n;i++){ ret+=freq[i]*freq[i-k]; } System.out.println(ret); }else{ long ret=0; for(int i=0;i<n;i++){ if(s.charAt(i)-'0'==1){ count=0; }else{ count++; } ret+=count; } System.out.println(ret); } } }
Java
["1\n1010", "2\n01010", "100\n01010"]
2 seconds
["6", "4", "0"]
NoteIn the first sample the sought substrings are: "1", "1", "10", "01", "10", "010".In the second sample the sought substrings are: "101", "0101", "1010", "01010".
Java 8
standard input
[ "dp", "two pointers", "math", "binary search", "brute force", "strings" ]
adc43f273dd9b3f1c58b052a34732a50
The first line contains the single integer k (0 ≤ k ≤ 106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters.
1,600
Print the single number — the number of substrings of the given string, containing exactly k characters "1". Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
2611eb302d73df9fcf1364faa4e8eb39
train_002.jsonl
1331911800
A string is binary, if it consists only of characters "0" and "1".String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters "1".
256 megabytes
import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class Flab { public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int k = Integer.parseInt(in.nextLine()); String s = in.nextLine(); int n = s.length(); int[] arr = new int[n]; for (int i = 0; i < arr.length; i++) { arr[i] = Character.getNumericValue(s.charAt(i)); } int[] left = new int[n]; int[] right = new int[n]; int[] ones = new int[n]; long z = arr[0] == 0 ? 1 : 0; long zCur = arr[0] == 0 ? 1 : 0; for (int i = 0; i < right.length; i++) { if(i == 0) { left[i] = arr[i] == 0 ? 1 : 0; ones[i] = arr[i]; } else if(arr[i] == 0) { left[i] = 1 + left[i-1]; ones[i] = ones[i-1]; z += ++zCur; } else { left[i] = 0; ones[i] = 1 + ones[i-1]; zCur = 0; } } if(k == 0) { System.out.println(z); return; } for (int i = n-1; i>=0 ; i--) { if(i == n-1) { right[i] = arr[i] == 0 ? 1 : 0; } else if(arr[i] == 0) { right[i] = 1 + right[i+1]; } else { right[i] = 0; } } long ans = 0; for (int i = 0; i < right.length; i++) { if(arr[i] == 0) { continue; } int pos = i; int cumO = i > 0 ? ones[i-1] : 0; for(int j=30; j>=0; j--) { int shift = (1 << j); if(pos + shift < n && ones[pos + shift] - cumO < k) { pos += shift; } } if(ones[pos] - cumO != k) pos++; if(pos >= n || ones[pos] - cumO < k) { break; } long l = 0; long r = 0; if(i != 0) { l = left[i-1]; } if(pos != n-1) { r = right[pos+1]; } ans += l; ans += r; ans += (l * r); ans++; } System.out.println(ans); } }
Java
["1\n1010", "2\n01010", "100\n01010"]
2 seconds
["6", "4", "0"]
NoteIn the first sample the sought substrings are: "1", "1", "10", "01", "10", "010".In the second sample the sought substrings are: "101", "0101", "1010", "01010".
Java 8
standard input
[ "dp", "two pointers", "math", "binary search", "brute force", "strings" ]
adc43f273dd9b3f1c58b052a34732a50
The first line contains the single integer k (0 ≤ k ≤ 106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters.
1,600
Print the single number — the number of substrings of the given string, containing exactly k characters "1". Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
a8ff17e8e57666d56c12d7c6f00fc1e0
train_002.jsonl
1331911800
A string is binary, if it consists only of characters "0" and "1".String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters "1".
256 megabytes
import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; // some one elses implementation :( public class Plun { static int cannot; static int floors; static long[][] dp; public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = Integer.parseInt(in.nextLine()); char[] arr = in.nextLine().toCharArray(); long sum[] = new long[arr.length+2]; int count = 0; long ans = 0; sum[0] = 1; for(int i=0; i<arr.length; i++) { if(arr[i] == '1') { count++; } if(count >= n) { ans += sum[count - n]; } sum[count]++; } System.out.println(ans); } }
Java
["1\n1010", "2\n01010", "100\n01010"]
2 seconds
["6", "4", "0"]
NoteIn the first sample the sought substrings are: "1", "1", "10", "01", "10", "010".In the second sample the sought substrings are: "101", "0101", "1010", "01010".
Java 8
standard input
[ "dp", "two pointers", "math", "binary search", "brute force", "strings" ]
adc43f273dd9b3f1c58b052a34732a50
The first line contains the single integer k (0 ≤ k ≤ 106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters.
1,600
Print the single number — the number of substrings of the given string, containing exactly k characters "1". Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
55e752ac663750be01be0bf3ff6cf7f2
train_002.jsonl
1331911800
A string is binary, if it consists only of characters "0" and "1".String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters "1".
256 megabytes
import java.util.Scanner; public class AnotherProblemonStrings { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int k = sc.nextInt(); sc.nextLine(); String s = sc.nextLine(); int n = s.length(); int[] a = new int[n + 2]; int ones = 0; // dummy 1 at left most a[ones++] = 0; for (int i = 0; i < n; i++) { if (s.charAt(i) == '1') { a[ones++] = i + 1; } } // dummy 1 at right most a[ones++] = n + 1; long answer = 0; if (k == 0) { for (int i = 1; i < ones; i++) { long l = (a[i] - a[i - 1] - 1); answer += (l + 1) * l / 2; } } else { for (int i = 1; i + k < ones; i++) { long leftZeros = a[i] - a[i - 1] - 1; long rightZeros = a[i + k] - a[i + k - 1] - 1; answer += (leftZeros + 1) * (rightZeros + 1); } } System.out.println(answer); } }
Java
["1\n1010", "2\n01010", "100\n01010"]
2 seconds
["6", "4", "0"]
NoteIn the first sample the sought substrings are: "1", "1", "10", "01", "10", "010".In the second sample the sought substrings are: "101", "0101", "1010", "01010".
Java 8
standard input
[ "dp", "two pointers", "math", "binary search", "brute force", "strings" ]
adc43f273dd9b3f1c58b052a34732a50
The first line contains the single integer k (0 ≤ k ≤ 106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters.
1,600
Print the single number — the number of substrings of the given string, containing exactly k characters "1". Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
b18ae669d896c8b7701e1dd83111b354
train_002.jsonl
1331911800
A string is binary, if it consists only of characters "0" and "1".String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters "1".
256 megabytes
import java.io.*; public class Strings165C { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int k = Integer.parseInt(br.readLine().trim()); char[] cs = br.readLine().toCharArray(); long[] count = new long[1000001]; count[0] = 1; int sum = 0; long ans = 0; for (char c : cs) { sum += c - 48; ++count[sum]; } for (int i = k; i <= sum; ++i) { if (k == 0) ans += (count[i] - 1) * count[i] / 2; else ans += count[i] * count[i - k]; } System.out.println(ans); } }
Java
["1\n1010", "2\n01010", "100\n01010"]
2 seconds
["6", "4", "0"]
NoteIn the first sample the sought substrings are: "1", "1", "10", "01", "10", "010".In the second sample the sought substrings are: "101", "0101", "1010", "01010".
Java 8
standard input
[ "dp", "two pointers", "math", "binary search", "brute force", "strings" ]
adc43f273dd9b3f1c58b052a34732a50
The first line contains the single integer k (0 ≤ k ≤ 106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters.
1,600
Print the single number — the number of substrings of the given string, containing exactly k characters "1". Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
a15ebcd01f5c0e7ff49337568fef05f8
train_002.jsonl
1331911800
A string is binary, if it consists only of characters "0" and "1".String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters "1".
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.StringTokenizer; public class A { public static void main(String[] args) throws NumberFormatException, IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); int k = sc.nextInt(); char[] s = sc.next().toCharArray(); long ans = 0; ArrayList<Integer> a = new ArrayList<>(); a.add(-1); for (int i = 0; i < s.length; i++) { if (s[i] == '1') a.add(i); } a.add(s.length); for (int i = 1; i + k < a.size(); i++) { if (k == 0) ans += 1l*(a.get(i) - a.get(i - 1) - 1)*(a.get(i) - a.get(i - 1))/2; else ans += 1l * (a.get(i) - a.get(i - 1)) * (a.get(i + k) - a.get(i + k - 1)); } out.println(ans); out.flush(); out.close(); } static class Query implements Comparable<Query> { int l, r, ind; public Query(int a, int b, int i) { l = a; r = b; ind = i; } @Override public int compareTo(Query o) { if (l == o.l) return r - o.r; return l - o.l; } } static class Scanner { BufferedReader bf; StringTokenizer st; public Scanner() { bf = new BufferedReader(new InputStreamReader(System.in)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(bf.readLine()); return st.nextToken(); } public int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); } public double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } } }
Java
["1\n1010", "2\n01010", "100\n01010"]
2 seconds
["6", "4", "0"]
NoteIn the first sample the sought substrings are: "1", "1", "10", "01", "10", "010".In the second sample the sought substrings are: "101", "0101", "1010", "01010".
Java 8
standard input
[ "dp", "two pointers", "math", "binary search", "brute force", "strings" ]
adc43f273dd9b3f1c58b052a34732a50
The first line contains the single integer k (0 ≤ k ≤ 106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters.
1,600
Print the single number — the number of substrings of the given string, containing exactly k characters "1". Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
3da8861ac3bee494ced880e02f63cc99
train_002.jsonl
1331911800
A string is binary, if it consists only of characters "0" and "1".String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters "1".
256 megabytes
import java.util.*; import java.io.*; public class a { public static void main(String[] args) throws IOException { new a(); } public a() throws IOException { FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); int k = in.nextInt(); char[] s = in.next().toCharArray(); if(k == 0) { long ret = 0; long cnt = 0; for(int i = 0; i < s.length; i++) { if(s[i] == '0') { cnt++; } else if(i-1 >= 0 && s[i] == '1' && s[i-1] == '0') { ret += (cnt*(cnt+1)/2); cnt = 0; } } if(cnt != 0) ret += (cnt*(cnt+1)/2); out.println(ret); out.close(); return; } ArrayList<Integer> vs = new ArrayList<Integer>(); vs.add(-1); for(int i = 0; i < s.length; i++) { if(s[i] == '1') vs.add(i); } vs.add(s.length); long ret = 0; for(int i = 1; i+k-1 < vs.size()-1; i++) { int r = i+k-1; long op1 = 1; long op2 = 1; if(i != 0) { op1 = vs.get(i)-vs.get(i-1); } if(r+1 < vs.size()) { op2 = vs.get(r+1)-vs.get(r); } ret += op1*op2; } out.println(ret); in.close(); out.close(); } long pow(int base, int exp) { if(exp == 0) return 1; if(exp%2 == 1) return pow(base, exp/2)*base; long ret = pow(base, exp/2); return ret*ret; } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = new StringTokenizer(""); } public String next() throws IOException { while(!st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public void close() throws IOException { br.close(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } } }
Java
["1\n1010", "2\n01010", "100\n01010"]
2 seconds
["6", "4", "0"]
NoteIn the first sample the sought substrings are: "1", "1", "10", "01", "10", "010".In the second sample the sought substrings are: "101", "0101", "1010", "01010".
Java 8
standard input
[ "dp", "two pointers", "math", "binary search", "brute force", "strings" ]
adc43f273dd9b3f1c58b052a34732a50
The first line contains the single integer k (0 ≤ k ≤ 106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters.
1,600
Print the single number — the number of substrings of the given string, containing exactly k characters "1". Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
2b4b026c427e39e298d94aad7db206ba
train_002.jsonl
1331911800
A string is binary, if it consists only of characters "0" and "1".String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters "1".
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.InputMismatchException; import java.util.Iterator; public class Solution1 implements Runnable { static final long MAX = 464897L; static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static void main(String args[]) throws Exception { new Thread(null, new Solution1(),"Solution",1<<26).start(); } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } long MOD = 998244353; ArrayList<Integer> adj[]; ArrayList<Pair> adj2[]; public void run() { //InputReader sc= new InputReader(new FileInputStream("input.txt")); //PrintWriter w= new PrintWriter(new FileWriter("output.txt")); InputReader sc = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int k = sc.nextInt(); String s = sc.next(); long count = 0; ArrayList<Integer> ar = new ArrayList(); for(int i = 0;i < s.length();i++) { if(s.charAt(i) == '1') { ar.add(i); } } if(k == 0) { long temp = 0; long ans = 0; for(int i = 0;i < s.length();i++) { if(s.charAt(i) == '0') { temp++; }else { ans += (temp * (temp+1))/2; temp = 0; } } ans += (temp * (temp + 1))/2; w.println(ans); } else { long ini = 0; for(int i = k-1;i < ar.size();i++) { long one = 1; long two = 1; if(i + 1 < ar.size()) { one = (ar.get(i+1) - ar.get(i)); }else { one = ((s.length()-1) - ar.get(i) + 1); } if(i == k-1) { two = ar.get(i-k+1) - ini+1; }else { two = ar.get(i-k+1) - ini; } ini = ar.get(i-k+1); count += one * two; } w.println(count); } w.close(); } static long power(long a,long b,long mod) { long ans = 1; while(b != 0) { if(b % 2 == 1) { ans = (ans * a); } a = (a * a); b = b/2; } return ans; } class Pair implements Comparable<Pair>{ long a; long b; //int c; Pair(long a,long b){ this.b = b; this.a = a; } public boolean equals(Object o) { Pair p = (Pair)o; return this.a == p.a && this.b == p.b; } public int hashCode(){ return Long.hashCode(a)*27 + Long.hashCode(b)* 31; } public int compareTo(Pair p) { return Long.compare(Math.max(this.a,this.b),Math.max(p.a,p.b)); } } }
Java
["1\n1010", "2\n01010", "100\n01010"]
2 seconds
["6", "4", "0"]
NoteIn the first sample the sought substrings are: "1", "1", "10", "01", "10", "010".In the second sample the sought substrings are: "101", "0101", "1010", "01010".
Java 8
standard input
[ "dp", "two pointers", "math", "binary search", "brute force", "strings" ]
adc43f273dd9b3f1c58b052a34732a50
The first line contains the single integer k (0 ≤ k ≤ 106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters.
1,600
Print the single number — the number of substrings of the given string, containing exactly k characters "1". Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
9f4575b7d94646473614808336850137
train_002.jsonl
1331911800
A string is binary, if it consists only of characters "0" and "1".String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters "1".
256 megabytes
//package C165; /** * * @author Abdulrahman Mobarak */ import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; public class Main { public static void main(String[] args) throws IOException { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, InputReader input, PrintWriter out) throws IOException { int k = input.nextInt(); char[] arr = input.next().toCharArray(); int ar[] = new int[arr.length + 1]; ar[0] = 1; long sum = 0; int count = 0; if (k > arr.length) { out.println(0); return; } for (int i = 0; i < arr.length; i++) { if (arr[i] == '1') { count++; } if (count >= k) { sum += ar[count - k]; } ar[count]++; } out.println(sum); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["1\n1010", "2\n01010", "100\n01010"]
2 seconds
["6", "4", "0"]
NoteIn the first sample the sought substrings are: "1", "1", "10", "01", "10", "010".In the second sample the sought substrings are: "101", "0101", "1010", "01010".
Java 8
standard input
[ "dp", "two pointers", "math", "binary search", "brute force", "strings" ]
adc43f273dd9b3f1c58b052a34732a50
The first line contains the single integer k (0 ≤ k ≤ 106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters.
1,600
Print the single number — the number of substrings of the given string, containing exactly k characters "1". Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
92f0e5aa9383a6901bfcd35155afd0cf
train_002.jsonl
1331911800
A string is binary, if it consists only of characters "0" and "1".String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters "1".
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class cb { InputStream is; PrintWriter out; static long mod=(long)(1e7+9); void solve() { int k=ni(); char ch[]=ns().toCharArray();int n=ch.length; long a[]=new long[n]; for(int i=0;i<n;i++) { if(i==0) { if(ch[i]=='1') a[i]=1; } else a[i]=a[i-1]+(ch[i]-'0'); } long f[]=new long[(int)(a[n-1]+1)]; f[0]=1; for(int i=0;i<n;i++) f[(int)(a[i])]++; long ans=0; for(int i=k;i<a[n-1]+1;i++) { if(k==0) ans+=((f[i]-1)*f[i])/2; else ans+=(f[i]*f[i-k]); } out.println(ans); } static class pair { int k,v; public pair(int k,int v) { this.k=k; this.v=v; } } public static long [][] multiply(long a[][],long b[][]) { long mul[][]=new long[2][2]; for(int i=0;i<2;i++) { for(int j=0;j<2;j++) { mul[i][j]=0; for(int k=0;k<2;k++) mul[i][j]=(mul[i][j]+(a[i][k]*b[k][j]))%mod; } } return mul; } /* Matrix Exponention*/ public static long [][] power(long [][] mat,int n) { long res[][]=new long[2][2]; res[0][0]=1;res[1][1]=1; while(n>0) { if(n%2==1) res=multiply(res,mat); mat=multiply(mat,mat); n/=2; } return res; } //---------- I/O Template ---------- public static void main(String[] args) { new cb().run(); } void run() { is = System.in; out = new PrintWriter(System.out); solve(); out.flush(); } byte input[] = new byte[1024]; int len = 0, ptr = 0; int readByte() { if(ptr >= len) { ptr = 0; try { len = is.read(input); } catch(IOException e) { throw new InputMismatchException(); } if(len <= 0) { return -1; } } return input[ptr++]; } boolean isSpaceChar(int c) { return !( c >= 33 && c <= 126 ); } int skip() { int b = readByte(); while(b != -1 && isSpaceChar(b)) { b = readByte(); } return b; } char nc() { return (char)skip(); } String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!isSpaceChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } String nLine() { int b = skip(); StringBuilder sb = new StringBuilder(); while( !(isSpaceChar(b) && b != ' ') ) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } int ni() { int n = 0, b = readByte(); boolean minus = false; while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); } if(b == '-') { minus = true; b = readByte(); } if(b == -1) { return -1; } //no input while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); } return minus ? -n : n; } long nl() { long n = 0L; int b = readByte(); boolean minus = false; while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); } if(b == '-') { minus = true; b = readByte(); } while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); } return minus ? -n : n; } double nd() { return Double.parseDouble(ns()); } float nf() { return Float.parseFloat(ns()); } int[] na(int n) { int a[] = new int[n]; for(int i = 0; i < n; i++) { a[i] = ni(); } return a; } char[] ns(int n) { char c[] = new char[n]; int i, b = skip(); for(i = 0; i < n; i++) { if(isSpaceChar(b)) { break; } c[i] = (char)b; b = readByte(); } return i == n ? c : Arrays.copyOf(c,i); } }
Java
["1\n1010", "2\n01010", "100\n01010"]
2 seconds
["6", "4", "0"]
NoteIn the first sample the sought substrings are: "1", "1", "10", "01", "10", "010".In the second sample the sought substrings are: "101", "0101", "1010", "01010".
Java 8
standard input
[ "dp", "two pointers", "math", "binary search", "brute force", "strings" ]
adc43f273dd9b3f1c58b052a34732a50
The first line contains the single integer k (0 ≤ k ≤ 106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters.
1,600
Print the single number — the number of substrings of the given string, containing exactly k characters "1". Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
1327e74dde073af91bc2025f47296c51
train_002.jsonl
1331911800
A string is binary, if it consists only of characters "0" and "1".String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters "1".
256 megabytes
import java.util.LinkedList; import java.util.Scanner; public class Main { private static long getResult(LinkedList<Integer> list) { int pos1 = list.pollFirst() , pos2 = list.pollLast(); long value1 = list.peekFirst() - pos1; long value2 = pos2 - list.peekLast(); list.addFirst(pos1); list.addLast(pos2); return value1 * value2; } private static long solve(String input) { int i , length = input.length(); long ans = 0; for (i = 0;i < length;i ++) { long cnt = 0; if (input.charAt(i) == '0') { while (i < length && (input.charAt(i) == '0')) { i ++; cnt ++; } ans += (cnt + 1) * cnt / 2; } } return ans; } public static void main(String[] args) throws Exception { Scanner scan = new Scanner(System.in); long ans = 0; int i , k = scan.nextInt(); String input = scan.next(); if (k == 0) { System.out.println(solve(input)); } else { LinkedList<Integer> list = new LinkedList<>(); list.addLast(- 1); for (i = 0;i < input.length();i ++) { if (input.charAt(i) == '1') { list.addLast(i); } if (list.size() == k + 2) { ans += getResult(list); list.pollFirst(); } } list.add(input.length()); if (list.size() == k + 2) { ans += getResult(list); } System.out.println(ans); } } }
Java
["1\n1010", "2\n01010", "100\n01010"]
2 seconds
["6", "4", "0"]
NoteIn the first sample the sought substrings are: "1", "1", "10", "01", "10", "010".In the second sample the sought substrings are: "101", "0101", "1010", "01010".
Java 8
standard input
[ "dp", "two pointers", "math", "binary search", "brute force", "strings" ]
adc43f273dd9b3f1c58b052a34732a50
The first line contains the single integer k (0 ≤ k ≤ 106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters.
1,600
Print the single number — the number of substrings of the given string, containing exactly k characters "1". Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
d4c1dbaf8e3f1094eebe7765f63f8538
train_002.jsonl
1331911800
A string is binary, if it consists only of characters "0" and "1".String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters "1".
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; public class ANOS { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int k=Integer.parseInt(br.readLine()); String str = br.readLine(); ArrayList<Long> unos = new ArrayList<Long>(); unos.add(-1l); for(int i=0; i<str.length();i++) if(str.charAt(i)=='1') unos.add((long) i); if(unos.size()<=k) System.out.println("0"); else{ long total = 0; unos.add((long) str.length()); if(k==0){ long v1,v2; long dif; v2=unos.get(0); for(int i=1; i<unos.size();i++){ v1=v2; v2=unos.get(i); dif = v2-v1; if(dif != 1) total+=(dif*(dif-1))/2; } } else for(int i=1; i<unos.size()-k;i++){ total+=(unos.get(i)-unos.get(i-1))*(unos.get(i+k)-unos.get(i+k-1)); } System.out.println(total); } } }
Java
["1\n1010", "2\n01010", "100\n01010"]
2 seconds
["6", "4", "0"]
NoteIn the first sample the sought substrings are: "1", "1", "10", "01", "10", "010".In the second sample the sought substrings are: "101", "0101", "1010", "01010".
Java 8
standard input
[ "dp", "two pointers", "math", "binary search", "brute force", "strings" ]
adc43f273dd9b3f1c58b052a34732a50
The first line contains the single integer k (0 ≤ k ≤ 106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters.
1,600
Print the single number — the number of substrings of the given string, containing exactly k characters "1". Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
6b376395ec802230ad56339efe0e9e21
train_002.jsonl
1331911800
A string is binary, if it consists only of characters "0" and "1".String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters "1".
256 megabytes
import java.io.*; import java.util.*; public class Solution { public static void main(String ag[]) { Scanner sc=new Scanner(System.in); int i,j,k; int K=sc.nextInt(); char A[]=sc.next().toCharArray(); int N=A.length; HashMap<Integer,Long> map=new HashMap<>(); int sum=0; long ans=0; for(i=0;i<N;i++) { sum+=Integer.parseInt(A[i]+""); if(sum==K) ans++; if(map.containsKey(sum-K)) ans+=map.get(sum-K); if(!map.containsKey(sum)) map.put(sum,1L); else map.put(sum,map.get(sum)+1); } System.out.println(ans); } }
Java
["1\n1010", "2\n01010", "100\n01010"]
2 seconds
["6", "4", "0"]
NoteIn the first sample the sought substrings are: "1", "1", "10", "01", "10", "010".In the second sample the sought substrings are: "101", "0101", "1010", "01010".
Java 8
standard input
[ "dp", "two pointers", "math", "binary search", "brute force", "strings" ]
adc43f273dd9b3f1c58b052a34732a50
The first line contains the single integer k (0 ≤ k ≤ 106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters.
1,600
Print the single number — the number of substrings of the given string, containing exactly k characters "1". Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
7ae55ae889b9f9a4a80ae11284912076
train_002.jsonl
1331911800
A string is binary, if it consists only of characters "0" and "1".String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters "1".
256 megabytes
import java.util.Scanner; public class AnotherProblemOnStrings { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int k = sc.nextInt(); String s = sc.next(); long ways [] = new long[1000010]; int count =0; long res = 0; ways[0]=1; for (int i = 0; i < s.length(); i++) { if(s.charAt(i) == '1' ) count++; if(count-k>=0) res+=ways[(count-k)]; ways[count]++; } System.out.println(res); } }
Java
["1\n1010", "2\n01010", "100\n01010"]
2 seconds
["6", "4", "0"]
NoteIn the first sample the sought substrings are: "1", "1", "10", "01", "10", "010".In the second sample the sought substrings are: "101", "0101", "1010", "01010".
Java 8
standard input
[ "dp", "two pointers", "math", "binary search", "brute force", "strings" ]
adc43f273dd9b3f1c58b052a34732a50
The first line contains the single integer k (0 ≤ k ≤ 106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters.
1,600
Print the single number — the number of substrings of the given string, containing exactly k characters "1". Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
b4ccc6b4f58e87ff81f9fd54756138f1
train_002.jsonl
1331911800
A string is binary, if it consists only of characters "0" and "1".String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters "1".
256 megabytes
import java.io.InputStream; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.IOException; import java.util.StringTokenizer; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { int k = in.nextInt(); String string = in.next(); int start = 0, end = 0; start = string.indexOf('1'); end = string.indexOf('1'); long res = 0; if (k == 0){ long ans = 0; start = -1;int last = -1; while (start < string.length()){ start = string.indexOf("1",start + 1); if (start == -1)start = string.length(); long g = start - last - 1; last = start; ans += ((g*(g + 1)) / 2); } out.print(ans); return; } int cnt = 1, n = string.length(); while (end != n){ if (cnt == k){ int g = string.indexOf("1",end + 1); int g1 = string.lastIndexOf('1',start - 1); if (g == -1) g = n; res += (1L*(start - g1)*(g - end)); cnt++; end = g; } if (cnt > k){ start = string.indexOf('1',start + 1); cnt--; } if (cnt < k){ cnt++; end = string.indexOf('1',end + 1); if (end == -1)end = n; } } out.print(res+"\n"); } } class InputReader { public BufferedReader reader; public 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
["1\n1010", "2\n01010", "100\n01010"]
2 seconds
["6", "4", "0"]
NoteIn the first sample the sought substrings are: "1", "1", "10", "01", "10", "010".In the second sample the sought substrings are: "101", "0101", "1010", "01010".
Java 8
standard input
[ "dp", "two pointers", "math", "binary search", "brute force", "strings" ]
adc43f273dd9b3f1c58b052a34732a50
The first line contains the single integer k (0 ≤ k ≤ 106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters.
1,600
Print the single number — the number of substrings of the given string, containing exactly k characters "1". Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
bc7fbf2d8e25242ba65107ab02bd2a03
train_002.jsonl
1331911800
A string is binary, if it consists only of characters "0" and "1".String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters "1".
256 megabytes
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.InputMismatchException; public class Strings165C { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int k = ni(); char ch[] = ns().toCharArray(); int n = ch.length; ArrayList<Integer> al = new ArrayList<>(); for(int i = 0 ; i<ch.length ; i++) { if(ch[i] == '1') al.add(i); } long l[] = new long[al.size()]; long r[] = new long[al.size()]; for(int i = 0 ; i<al.size() ; i++) { if(i == 0) l[i] = al.get(i); else l[i] = al.get(i)-al.get(i-1)-1; } for(int i = al.size()-1 ; i>=0 ; i--) { if(i == al.size()-1) r[i] = n-1-al.get(i); else r[i] = al.get(i+1)-al.get(i)-1; } if(k == 0) { if(al.size() == 0) { out.println((n*1l*(n+1))/2); return ; } long sum = 0; for(int i = 0 ; i<al.size(); i++) { sum += (l[i]*(l[i]+1))/2; } if(al.size() != 0) { sum += (r[al.size()-1]*(r[al.size()-1]+1))/2; } out.println(sum); return; } // // for(int i = 0 ; i<al.size() ; i++) out.print(l[i]+" "); // out.println(); // // for(int i = 0 ; i<al.size() ; i++) out.print(r[i]+" "); // out.println(); boolean flag = false; long sum = 0; long prev = 0; for(int i = 0 ; i<al.size() && i+k-1<al.size(); i++) { if(i == 0) { if(i+k-1>=al.size()) { flag = true; break; } else { prev = (l[0]+1)*(r[i+k-1]+1); } sum += prev; } else { long x = 0 , y = 0 , diff = 0; prev = 0; if(i+k-1<al.size()) { prev += (l[i]+1)*(r[i+k-1]+1); } sum += prev; } //out.println(prev); } if(flag) out.println(0); else out.println(sum); } void run() throws Exception { is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new Strings165C().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } void display2D(int a[][]) { for(int i[] : a) { for(int j : i) { out.print(j+" "); } out.println(); } } private static void tr(Object... o) { System.out.println(Arrays.deepToString(o)); } }
Java
["1\n1010", "2\n01010", "100\n01010"]
2 seconds
["6", "4", "0"]
NoteIn the first sample the sought substrings are: "1", "1", "10", "01", "10", "010".In the second sample the sought substrings are: "101", "0101", "1010", "01010".
Java 8
standard input
[ "dp", "two pointers", "math", "binary search", "brute force", "strings" ]
adc43f273dd9b3f1c58b052a34732a50
The first line contains the single integer k (0 ≤ k ≤ 106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters.
1,600
Print the single number — the number of substrings of the given string, containing exactly k characters "1". Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
a386b73c05a3ce2149c5aaced6ac2f4a
train_002.jsonl
1331911800
A string is binary, if it consists only of characters "0" and "1".String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters "1".
256 megabytes
import java.util.*; import java.io.*; import java.lang.Math.*; public class MainA { public static int mod = 20000; public static long[] val; public static long[] arr; static int max = (int) 1e9 + 7; public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); // Reading input from STDIN int k=in.nextInt(); String s=in.nextLine();ArrayList<Integer> arr=new ArrayList();arr.add(-1); for(int i=0;i<s.length();i++) { if(s.charAt(i)=='1')arr.add(i); } if(arr.size()<k+1)out.println(0); else { long ans=0; if(k!=0){ int end=0;int start=0;int k1=1; for(int i=k;i<arr.size();i++) { start=-arr.get(k1-1)+arr.get(k1); if(i==arr.size()-1) { end=s.length()-arr.get(i); } else { end=arr.get(i+1)-arr.get(i); } k1++; ans=ans+(long)end*start; } out.println(ans);} else { long temp=((long)s.length()*(s.length()+1))/2; if(arr.size()==1)out.println(temp); else { arr.add(s.length()); long ans1=0; for(int i=1;i<arr.size();i++) { long n1=arr.get(i)-arr.get(i-1)-1; long te=(n1*(n1+1))/2; ans1=ans1+(te); } out.println(ans1); } } } out.close(); } static void swap(Pairs arr[], int i, int j) { Pairs t = arr[i]; arr[i] = arr[j]; arr[j] = t; } static int partition(Pairs arr[], int l, int h) { long x = arr[h].x; int i = (l - 1); for (int j = l; j <= h - 1; j++) { if (arr[j].x <= x) { i++; // swap arr[i] and arr[j] swap(arr, i, j); } } // swap arr[i+1] and arr[h] swap(arr, i + 1, h); return (i + 1); } // Sorts arr[l..h] using iterative QuickSort static void sort(Pairs arr[], int l, int h) { // create auxiliary stack int stack[] = new int[h - l + 1]; // initialize top of stack int top = -1; // push initial values in the stack stack[++top] = l; stack[++top] = h; // keep popping elements until stack is not empty while (top >= 0) { // pop h and l h = stack[top--]; l = stack[top--]; // set pivot element at it's proper position int p = partition(arr, l, h); // If there are elements on left side of pivot, // then push left side to stack if (p - 1 > l) { stack[++top] = l; stack[++top] = p - 1; } // If there are elements on right side of pivot, // then push right side to stack if (p + 1 < h) { stack[++top] = p + 1; stack[++top] = h; } } } static class Pairs implements Comparable<Pairs> { long x; int y; Pairs(long a, int b) { x = a; y = b; } @Override public int compareTo(Pairs o) { // TODO Auto-generated method stub if (x == o.x) return Integer.compare(y, o.y); else return Long.compare(x, o.x); } } public static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } public static boolean isPal(String s) { for (int i = 0, j = s.length() - 1; i <= j; i++, j--) { if (s.charAt(i) != s.charAt(j)) return false; } return true; } public static String rev(String s) { StringBuilder sb = new StringBuilder(s); sb.reverse(); return sb.toString(); } public static long gcd(long x, long y) { if (y == 0) return x; if (x % y == 0) return y; else return gcd(y, x % y); } public static int gcd(int x, int y) { if (x % y == 0) return y; else return gcd(y, x % y); } public static long gcdExtended(long a, long b, long[] x) { if (a == 0) { x[0] = 0; x[1] = 1; return b; } long[] y = new long[2]; long gcd = gcdExtended(b % a, a, y); x[0] = y[1] - (b / a) * y[0]; x[1] = y[0]; return gcd; } public static int abs(int a, int b) { return (int) Math.abs(a - b); } public static long abs(long a, long b) { return (long) Math.abs(a - b); } public static int max(int a, int b) { if (a > b) return a; else return b; } public static int min(int a, int b) { if (a > b) return b; else return a; } public static long max(long a, long b) { if (a > b) return a; else return b; } public static long min(long a, long b) { if (a > b) return b; else return a; } public static long[][] mul(long a[][], long b[][]) { long c[][] = new long[2][2]; c[0][0] = a[0][0] * b[0][0] + a[0][1] * b[1][0]; c[0][1] = a[0][0] * b[0][1] + a[0][1] * b[1][1]; c[1][0] = a[1][0] * b[0][0] + a[1][1] * b[1][0]; c[1][1] = a[1][0] * b[0][1] + a[1][1] * b[1][1]; return c; } public static long[][] pow(long n[][], long p, long m) { long result[][] = new long[2][2]; result[0][0] = 1; result[0][1] = 0; result[1][0] = 0; result[1][1] = 1; if (p == 0) return result; if (p == 1) return n; while (p != 0) { if (p % 2 == 1) result = mul(result, n); //System.out.println(result[0][0]); for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { if (result[i][j] >= m) result[i][j] %= m; } } p >>= 1; n = mul(n, n); // System.out.println(1+" "+n[0][0]+" "+n[0][1]+" "+n[1][0]+" "+n[1][1]); for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { if (n[i][j] >= m) n[i][j] %= m; } } } return result; } public static long pow(long n, long p) { long result = 1; if (p == 0) return 1; if (p == 1) return n; while (p != 0) { if (p % 2 == 1) result *= n; p >>= 1; n *= n; } return result; } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public long[] nextLongArray(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["1\n1010", "2\n01010", "100\n01010"]
2 seconds
["6", "4", "0"]
NoteIn the first sample the sought substrings are: "1", "1", "10", "01", "10", "010".In the second sample the sought substrings are: "101", "0101", "1010", "01010".
Java 8
standard input
[ "dp", "two pointers", "math", "binary search", "brute force", "strings" ]
adc43f273dd9b3f1c58b052a34732a50
The first line contains the single integer k (0 ≤ k ≤ 106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters.
1,600
Print the single number — the number of substrings of the given string, containing exactly k characters "1". Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
4b0ebd71107cd4d7ac1b9445b1c0e4ec
train_002.jsonl
1331911800
A string is binary, if it consists only of characters "0" and "1".String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters "1".
256 megabytes
/** * Alipay.com Inc. Copyright (c) 2004-2020 All Rights Reserved. */ import java.util.Scanner; /** * Codeforces Round #112 (Div. 2) * http://codeforces.com/contest/165/problem/C * * @author linwanying * @version $Id: AnotherProblemOnStrings.java, v 0.1 2020年02月29日 1:38 PM linwanying Exp $ */ public class AnotherProblemOnStrings { public static void main(String[] args) { new AnotherProblemOnStrings().run(); } private void run() { Scanner scanner = new Scanner(System.in); int k = scanner.nextInt(); String s = scanner.next(); int[] sum = new int[s.length()+1]; for (int i = 1; i < s.length() + 1; ++i) { if (s.charAt(i-1) == '1') { sum[i] = sum[i-1] + 1; } else { sum[i] = sum[i-1]; } } int j,left = 0; int[] cnt = new int[s.length()+1]; long res = 0; if (k != 0) { for (int i = 1; i < s.length()+1; ++i) { if (i != 1 && sum[i] == sum[i-1]) { cnt[i] = cnt[i-1]; } else { for (j = left; j < i && sum[j] <= sum[i]-k; ++j,++left) { if (sum[j] == sum[i]-k) { cnt[i] += 1; } } } res += cnt[i]; } } else { int[] sum0 = new int[s.length()+1]; for (int i = 1; i < s.length()+1; ++i) { if (s.charAt(i-1) == '1') { sum0[i] = 0; } else { sum0[i] = sum0[i-1] + 1; res += sum0[i]; } } } System.out.println(res); } }
Java
["1\n1010", "2\n01010", "100\n01010"]
2 seconds
["6", "4", "0"]
NoteIn the first sample the sought substrings are: "1", "1", "10", "01", "10", "010".In the second sample the sought substrings are: "101", "0101", "1010", "01010".
Java 8
standard input
[ "dp", "two pointers", "math", "binary search", "brute force", "strings" ]
adc43f273dd9b3f1c58b052a34732a50
The first line contains the single integer k (0 ≤ k ≤ 106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters.
1,600
Print the single number — the number of substrings of the given string, containing exactly k characters "1". Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
982850d644a4264b1cbc774548ec3692
train_002.jsonl
1403191800
Andrey needs one more problem to conduct a programming contest. He has n friends who are always willing to help. He can ask some of them to come up with a contest problem. Andrey knows one value for each of his fiends — the probability that this friend will come up with a problem if Andrey asks him.Help Andrey choose people to ask. As he needs only one problem, Andrey is going to be really upset if no one comes up with a problem or if he gets more than one problem from his friends. You need to choose such a set of people that maximizes the chances of Andrey not getting upset.
256 megabytes
import java.util.*; import java.io.*; import java.math.BigDecimal; import java.math.MathContext; 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(); int n=input.scanInt(); float arr[]=new float[n]; for(int i=0;i<n;i++) { arr[i]=(float)input.scanDouble(); } Arrays.sort(arr); BigDecimal ans=new BigDecimal(""+arr[n-1]); BigDecimal mul=BigDecimal.ONE; mul=mul.subtract(ans, MathContext.DECIMAL64); boolean taken[]=new boolean[n]; taken[n-1]=true; for(int i=0;i<n;i++) { BigDecimal tmp=new BigDecimal(""+ans); int indx=-1; for(int j=0;j<n;j++) { if(taken[j]) { continue; } BigDecimal curr=new BigDecimal(""+arr[j]); BigDecimal tmp1=new BigDecimal(""+ans); tmp1=tmp1.multiply(BigDecimal.ONE.subtract(curr, MathContext.DECIMAL64), MathContext.UNLIMITED); tmp1=tmp1.add(mul.multiply(curr, MathContext.DECIMAL64), MathContext.DECIMAL64); if(tmp1.compareTo(tmp)==1) { tmp=new BigDecimal(""+tmp1); indx=j; } } if(tmp.compareTo(ans)==1) { ans=new BigDecimal(""+tmp); taken[indx]=true; BigDecimal curr=new BigDecimal(""+arr[indx]); mul=mul.multiply(BigDecimal.ONE.subtract(curr, MathContext.DECIMAL64), MathContext.DECIMAL64); } } System.out.println(ans); } }
Java
["4\n0.1 0.2 0.3 0.8", "2\n0.1 0.2"]
2 seconds
["0.800000000000", "0.260000000000"]
NoteIn the first sample the best strategy for Andrey is to ask only one of his friends, the most reliable one.In the second sample the best strategy for Andrey is to ask all of his friends to come up with a problem. Then the probability that he will get exactly one problem is 0.1·0.8 + 0.9·0.2 = 0.26.
Java 11
standard input
[ "dp", "greedy", "probabilities", "math", "sortings" ]
b4ac594755951e84001dfd610d420eb5
The first line contains a single integer n (1 ≤ n ≤ 100) — the number of Andrey's friends. The second line contains n real numbers pi (0.0 ≤ pi ≤ 1.0) — the probability that the i-th friend can come up with a problem. The probabilities are given with at most 6 digits after decimal point.
1,800
Print a single real number — the probability that Andrey won't get upset at the optimal choice of friends. The answer will be considered valid if it differs from the correct one by at most 10 - 9.
standard output
PASSED
dccb96737c7311f09a7f0fa27311d455
train_002.jsonl
1403191800
Andrey needs one more problem to conduct a programming contest. He has n friends who are always willing to help. He can ask some of them to come up with a contest problem. Andrey knows one value for each of his fiends — the probability that this friend will come up with a problem if Andrey asks him.Help Andrey choose people to ask. As he needs only one problem, Andrey is going to be really upset if no one comes up with a problem or if he gets more than one problem from his friends. You need to choose such a set of people that maximizes the chances of Andrey not getting upset.
256 megabytes
// Imports import java.util.*; import java.io.*; public class D443 { /** * @param args the command line arguments * @throws IOException, FileNotFoundException */ public static void main(String[] args) throws IOException, FileNotFoundException { // TODO UNCOMMENT WHEN ALGORITHM CORRECT BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); // TODO code application logic here int N = Integer.parseInt(f.readLine()); double[] zeroprob = new double[N + 1]; double[] oneprob = new double[N + 1]; zeroprob[0] = 1.0; Double[] pxmil = new Double[N]; StringTokenizer st = new StringTokenizer(f.readLine()); for(int i = 0; i < N; i++) { pxmil[i] = Double.parseDouble(st.nextToken()); } Arrays.sort(pxmil, (Double o1, Double o2) -> { if(o2 < o1) { return -1; } else if(o2 > o1) { return 1; } return 0; }); for(int i = 1; i <= N; i++) { for(int j = 0; j < i; j++) { if(pxmil[i - 1]*zeroprob[j] + (1.0 - pxmil[i - 1])*oneprob[j] > oneprob[i]) { oneprob[i] = pxmil[i - 1]*zeroprob[j] + (1.0 - pxmil[i - 1])*oneprob[j]; zeroprob[i] = (1.0 - pxmil[i - 1])*zeroprob[j]; } else if(pxmil[i - 1]*zeroprob[j] + (1.0 - pxmil[i - 1])*oneprob[j] == oneprob[i]) { zeroprob[i] = Math.max(zeroprob[i], (1.0 - pxmil[i - 1])*zeroprob[j]); } } } double max = 0; for(int i = 0; i <= N; i++) { max = Math.max(max, oneprob[i]); } System.out.println(max); } }
Java
["4\n0.1 0.2 0.3 0.8", "2\n0.1 0.2"]
2 seconds
["0.800000000000", "0.260000000000"]
NoteIn the first sample the best strategy for Andrey is to ask only one of his friends, the most reliable one.In the second sample the best strategy for Andrey is to ask all of his friends to come up with a problem. Then the probability that he will get exactly one problem is 0.1·0.8 + 0.9·0.2 = 0.26.
Java 11
standard input
[ "dp", "greedy", "probabilities", "math", "sortings" ]
b4ac594755951e84001dfd610d420eb5
The first line contains a single integer n (1 ≤ n ≤ 100) — the number of Andrey's friends. The second line contains n real numbers pi (0.0 ≤ pi ≤ 1.0) — the probability that the i-th friend can come up with a problem. The probabilities are given with at most 6 digits after decimal point.
1,800
Print a single real number — the probability that Andrey won't get upset at the optimal choice of friends. The answer will be considered valid if it differs from the correct one by at most 10 - 9.
standard output
PASSED
257258d4ba8faffed23990e13ac8ede6
train_002.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
import java.io.*; import java.util.*; public class Main { long X; long[] pxor; long[] s; void run() throws Exception{ int N = nextInt(); s = new long[N + 1]; for (int i = 1; i <= N; i++){ s[i] = nextLong(); } pxor = new long[N + 1]; for (int i = 1; i <= N; i++){ pxor[i] = s[i] ^ pxor[i-1]; } X = pxor[N]; Arrays.sort(pxor); int maxl = 0; long maxp = pxor[N]; while (maxp > 0) { maxp = maxp >> 1; maxl++; } long [] trie = new long[N + 1]; long rside = 0; long lside; int t = -1; for (int k = maxl - 1; k >= 0; k--){ for (int i = 0; i <= N; i++){ trie[i] = (pxor[i] >> k); } long K = X >> k; int i = 0; outer: for (i = 0; i <= N; i++){ lside = trie[i] ^ K ^ ((rside << 1) + 1); t = Arrays.binarySearch(trie, lside); if (t >= 0) { rside = (rside << 1) + 1; break; } } if(i == N + 1) rside = (rside << 1 ); } System.out.println(rside); } public static void main(String args[]) throws Exception { new Main().run(); // read rsideom stdin/stdout // new Main("prog.in", "prog.out").run(); // or use file i/o } BufferedReader in; PrintStream out; StringTokenizer st; Main() throws Exception { in = new BufferedReader(new InputStreamReader(System.in)); out = System.out; } Main(String is, String os) throws Exception { in = new BufferedReader(new FileReader(new File(is))); out = new PrintStream(new File(os)); } long nextLong() throws Exception { return Long.parseLong(next()); } int nextInt() throws Exception { return Integer.parseInt(next()); } String next() throws Exception { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } }
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 8
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
3863307db186b8bd56284b3b032c3dc9
train_002.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner in=new Scanner(System.in); int len=(int)Integer.parseInt(in.nextLine()); long[] s=new long[len+1]; String[] value=(String[])in.nextLine().split(" "); for(int i=1;i<=len;i++){ s[i]=Long.parseLong(value[i-1]); } long result=getMax(len,s); System.out.print(result); } public static long getMax(int len,long[] s){ long[] preValue=new long[len+1]; long[] tree=new long[len+1]; long max=0; int deep=0; for(int i=1;i<=len;i++) preValue[i]=s[i]^preValue[i-1]; long val=preValue[len]; Arrays.sort(preValue); long temp=preValue[len]; while(temp>0){ temp=temp>>1; deep++; } for(int k=deep-1;k>=0;k--){ for(int i=0;i<=len;i++) tree[i]=preValue[i]>>k; long keep=val>>k; int i; for(i=0;i<=len;i++){ if(Arrays.binarySearch(tree, tree[i]^keep^((max<<1)+1))>=0){ max=(max<<1)+1; break; } } max=i==len+1?max<<1:max; } return max; } }
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 8
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
531c2706cea7427cc4e77e8fa0704182
train_002.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner in=new Scanner(System.in); int len=(int)Integer.parseInt(in.nextLine()); long[] s=new long[len+1]; String[] value=(String[])in.nextLine().split(" "); for(int i=1;i<=len;i++){ s[i]=Long.parseLong(value[i-1]); } long result=getMax(len,s); System.out.print(result); } public static long getMax(int len,long[] s){ long[] preValue=new long[len+1]; long[] trie=new long[len+1]; long max=0; long left; for(int i=1;i<=len;i++){ preValue[i]=s[i]^preValue[i-1]; } int deep=0; long val=preValue[len]; Arrays.sort(preValue); long temp=preValue[len];; while(temp>0){ temp=temp>>1; deep++; } for(int k=deep-1;k>=0;k--){ for(int i=0;i<=len;i++) trie[i]=preValue[i]>>k; long keep=val>>k; int i; for(i=0;i<=len;i++){ left=trie[i]^keep^((max<<1)+1); int index=Arrays.binarySearch(trie, left); if(index>=0){ max=(max<<1)+1; break; } } if(i==len+1) max=max<<1; } return max; } }
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 8
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
3f0f7654430914542928d80e1f9788e1
train_002.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner in=new Scanner(System.in); int len=(int)Integer.parseInt(in.nextLine()); long[] s=new long[len+1]; long[] pxor=new long[len+1]; String[] value=(String[])in.nextLine().split(" "); for(int i=1;i<=len;i++){ s[i]=Long.parseLong(value[i-1]); } for(int i=1;i<=len;i++) pxor[i]=s[i]^pxor[i-1]; long X=pxor[len]; Arrays.sort(pxor); int maxl=0; long maxp=pxor[len]; while(maxp>0){ maxp=maxp>>1; maxl++; } long[] trie=new long[len+1]; long rside=0; long lside; int t=-1; for(int k=maxl-1;k>=0;k--){ for(int i=0;i<=len;i++) trie[i]=pxor[i]>>k; long K=X>>k; int i=0; for(i=0;i<=len;i++){ lside=trie[i]^K^((rside<<1)+1); t=Arrays.binarySearch(trie, lside); if(t>=0){ rside=(rside<<1)+1; break; } } if(i==len+1) rside=rside<<1; } System.out.print(rside); } }
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 8
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
0fe8bdb79dfd79b87718ac17c5e3a6b7
train_002.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner in=new Scanner(System.in); int len=(int)Integer.parseInt(in.nextLine()); long[] s=new long[len+1]; String[] value=(String[])in.nextLine().split(" "); for(int i=1;i<=len;i++){ s[i]=Long.parseLong(value[i-1]); } long result=getMax(len,s); System.out.print(result); } public static long getMax(int len,long[] s){ long[] preValue=new long[len+1]; for(int i=1;i<=len;i++) preValue[i]=s[i]^preValue[i-1]; long X=preValue[len]; int maxL=0; Arrays.sort(preValue); long maxp=preValue[len]; while(maxp>0){ maxp=maxp>>1; maxL++; } long[] trie=new long[len+1]; long max=0; long left; int t=-1; for(int k=maxL-1;k>=0;k--){ for(int i=0;i<=len;i++) trie[i]=preValue[i]>>k; long K=X>>k; int i=0; for(i=0;i<=len;i++){ left=trie[i]^K^((max<<1)+1); t=Arrays.binarySearch(trie, left); if(t>=0){ max=(max<<1)+1; break; } } if(i==len+1) max=max<<1; } return max; } }
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 8
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
61afb1768f6e6c77134480e9cddd3e05
train_002.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner in=new Scanner(System.in); int len=(int)Integer.parseInt(in.nextLine()); long[] s=new long[len+1]; long[] pxor=new long[len+1]; String[] value=(String[])in.nextLine().split(" "); for(int i=1;i<=len;i++){ s[i]=Long.parseLong(value[i-1]); } for(int i=1;i<=len;i++) pxor[i]=s[i]^pxor[i-1]; long X=pxor[len]; Arrays.sort(pxor); int maxl=0; long maxp=pxor[len]; while(maxp>0){ maxp=maxp>>1; maxl++; } long[] trie=new long[len+1]; long rside=0; long lside; int t=-1; for(int k=maxl-1;k>=0;k--){ for(int i=0;i<=len;i++) trie[i]=pxor[i]>>k; long K=X>>k; int i=0; outer: for(i=0;i<=len;i++){ lside=trie[i]^K^((rside<<1)+1); t=Arrays.binarySearch(trie, lside); if(t>=0){ rside=(rside<<1)+1; break; } } if(i==len+1) rside=rside<<1; } System.out.print(rside); } }
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 8
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
d8b884a00e7eb0b7156cd5d8afbdbb8e
train_002.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
import static java.util.Arrays.* ; import static java.lang.Math.* ; import java.util.*; import java.io.*; public class Main { void main() throws Exception { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int N = sc.nextInt() ; long [] a = new long [N] ; long suffix = 0 ; for(int i = 0 ; i < N ;i++) suffix ^= a[i] = sc.nextLong() ; Trie t = new Trie() ; t.add(0); long max = 0 ; long prefix = 0 ; for(long x : a) { suffix ^= x; prefix ^= x ; t.add(prefix); max = max(max , t.query(suffix) ^ suffix); } out.println(max); out.flush(); out.close(); } class Trie { int [][] nodes = new int [2][61 * (int)(2e5 + 1)]; int id = 1 ; void add(long x) { int curr = 0 ; for(int i = 60 ; i >= 0 ; i--) { int bit =(int)((x >> i) & 1); if(nodes[bit][curr] == 0) nodes[bit][curr] = id++ ; curr = nodes[bit][curr] ; } } long query(long x) // best F(1 , L - 1) { int curr = 0 ; long ans = 0 ; for(int i = 60 ; i >= 0 ;i--) { int bit =(int)((x >> i) & 1); if(nodes[bit ^ 1][curr] != 0) { ans |= ((long)(bit ^ 1)) << i ; curr = nodes[bit ^ 1][curr] ; }else if(nodes[bit][curr] != 0) { ans |= ((long)(bit )) << i ; curr = nodes[bit][curr] ; } else { if(nodes[0][curr] == 0) nodes[0][curr] = id++ ; curr = nodes[0][curr]; } } return ans ; } } class Scanner { BufferedReader br; StringTokenizer st; Scanner(InputStream in) { br = new BufferedReader(new InputStreamReader(System.in)); } String next() throws Exception { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws Exception { return Integer.parseInt(next()); } long nextLong() throws Exception { return Long.parseLong(next()); } double nextDouble() throws Exception { return Double.parseDouble(next());} } public static void main (String [] args) throws Exception {(new Main()).main();} }
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 8
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
ed64dbf6551da4eb50aaa295f0fd1d00
train_002.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
import static java.util.Arrays.* ; import static java.lang.Math.* ; import java.util.*; import java.io.*; public class Main { void main() throws Exception { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int N = sc.nextInt() ; long [] a = new long [N] ; long suffix = 0 ; for(int i = 0 ; i < N ;i++) suffix ^= a[i] = sc.nextLong() ; Trie t = new Trie() ; t.add(0); long max = 0 ; long prefix = 0 ; for(long x : a) { suffix ^= x; prefix ^= x ; t.add(prefix); max = max(max , t.query(suffix) ^ suffix); } out.println(max); out.flush(); out.close(); } class Trie { class Node { Node zero , one ; } Node root = new Node(); void add(long x) { Node curr = root ; for(int i = 60 ; i >= 0 ; i--) { long bit = (x & (1L << i)) ; if(bit == 0) { if(curr.zero == null) curr.zero = new Node() ; curr = curr.zero ; } else { if(curr.one == null) curr.one = new Node() ; curr = curr.one ; } } } long query(long x) // best F(1 , L - 1) { Node curr = root ; long ans = 0 ; for(int i = 60 ; i >= 0 ;i--) { long bit = (x & (1L << i)) ; if(bit == 0) { if(curr.one != null) { curr = curr.one; ans |= 1L << i ; } else if(curr.zero != null){ curr = curr.zero; } else { curr.zero = new Node() ; curr = curr.zero; } } else { if(curr.zero != null) curr = curr.zero ; else if (curr.one != null){ ans |= 1 << i ; curr = curr.one; } else { curr.zero = new Node(); curr = curr.zero; } } } return ans ; } } class Scanner { BufferedReader br; StringTokenizer st; Scanner(InputStream in) { br = new BufferedReader(new InputStreamReader(System.in)); } String next() throws Exception { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws Exception { return Integer.parseInt(next()); } long nextLong() throws Exception { return Long.parseLong(next()); } double nextDouble() throws Exception { return Double.parseDouble(next());} } public static void main (String [] args) throws Exception {(new Main()).main();} }
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 8
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
7b096c6de77e5f656588693ddc3f78b7
train_002.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
import static java.util.Arrays.* ; import static java.lang.Math.* ; import java.util.*; import java.io.*; public class Main { void main() throws Exception { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int N = sc.nextInt() ; long [] a = new long [N] ; long suffix = 0 ; for(int i = 0 ; i < N ;i++) suffix ^= a[i] = sc.nextLong() ; Trie t = new Trie() ; t.add(0); long max = 0 ; long prefix = 0 ; for(long x : a) { suffix ^= x; prefix ^= x ; t.add(prefix); max = max(max , t.query(suffix) ^ suffix); } out.println(max); out.flush(); out.close(); } class Trie { int [][] nodes = new int [2][41 * (int)(2e5 + 1)]; int id = 1 ; void add(long x) { int curr = 0 ; for(int i = 40 ; i >= 0 ; i--) { int bit =(int)((x >> i) & 1); if(nodes[bit][curr] == 0) nodes[bit][curr] = id++ ; curr = nodes[bit][curr] ; } } long query(long x) // best F(1 , L - 1) { int curr = 0 ; long ans = 0 ; for(int i = 40 ; i >= 0 ;i--) { int bit =(int)((x >> i) & 1); if(nodes[bit ^ 1][curr] != 0) { ans |= ((long)(bit ^ 1)) << i ; curr = nodes[bit ^ 1][curr] ; }else if(nodes[bit][curr] != 0) { ans |= ((long)(bit )) << i ; curr = nodes[bit][curr] ; } else { if(nodes[0][curr] == 0) nodes[0][curr] = id++ ; curr = nodes[0][curr]; } } return ans ; } } class Scanner { BufferedReader br; StringTokenizer st; Scanner(InputStream in) { br = new BufferedReader(new InputStreamReader(System.in)); } String next() throws Exception { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws Exception { return Integer.parseInt(next()); } long nextLong() throws Exception { return Long.parseLong(next()); } double nextDouble() throws Exception { return Double.parseDouble(next());} } public static void main (String [] args) throws Exception {(new Main()).main();} }
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 8
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
dbcb258e37865897298b89e30af541bc
train_002.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
import java.io.*; import java.util.*; public class Main{ public static int count = 1; public static void insert(TrieNode[] Nodes, long x){ int k=0; for(int i=40;i >=0; i--){ int id = ((1L<<i)&x) ==0 ?0:1; if(Nodes[k].next[id] == -1){ Nodes[count] = new TrieNode(); Nodes[k].next[id] =count++; } k = Nodes[k].next[id]; } } public static long find(TrieNode[] Nodes, long x){ long res =0L; int k=0; for(int i=40;i >=0; i--){ int id = ((1L<<i)&x) !=0 ?0:1; if(Nodes[k].next[id]==-1) id^=1; res=res*2+id; k = Nodes[k].next[id]; } return res^x; } public static void main(String args[]) throws Exception { TrieNode Nodes[] = new TrieNode[64*100000]; Scanner cin=new Scanner(System.in); while (cin.hasNext()) { int n = cin.nextInt(); if(n<0) return; long suffix=0; long arr[]= new long[n]; for(int i=0; i<n;i++){ arr[i] =cin.nextLong(); suffix ^= arr[i]; } Nodes[0] = new TrieNode(); insert(Nodes,0); long prefix =0; long max = 0; for(int i=0; i<n;i++){ prefix ^= arr[i]; suffix ^= arr[i]; insert(Nodes,prefix); max = Math.max(find(Nodes, suffix),max); } System.out.println(max); } } } class TrieNode { // Initialize your data structure here. public int[] next ; public TrieNode(){ next = new int[2]; next[0]=-1; next[1]=-1; } }
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 8
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
653ac364aaf127afb549d88ed758887c
train_002.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
// package practice.E; import java.io.*; import java.util.Arrays; import java.util.StringTokenizer; public class CF282E { static int trie[][]; static int nxt = 0; static final int MX = 41*100000 + 10; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); long[] arr = new long[n]; long a = 0; long b = 0; for (int i = 0; i < n; i++) { arr[i] = sc.nextLong(); a ^= arr[i]; } trie = new int[2][MX]; hasWord = new boolean[MX]; for (int i = 0; i < 2; i++) Arrays.fill(trie[i], -1); long ans = a; add(getBinary(0)); for (int i = n-1; i >= 0; i--) { b ^= arr[i]; a ^= arr[i]; add(getBinary(b)); ans = Math.max(getMax(getBinary(a)), ans); } pw.print(ans); pw.flush(); pw.close(); } static int[] getBinary(long x){ long wt = 1l<<40; int i = 0; int[] ret = new int[41]; while(x > 0){ if(x >= wt){ x -= wt; ret[i] = 1; } i++; wt >>= 1; } return ret; } static boolean[] hasWord; static void add(int[] b){ int node = 0; hasWord[0] = true; for (int i = 0; i < b.length; i++) { int c = b[i]; if(trie[c][node] == -1) trie[c][node] = ++nxt; node = trie[c][node]; hasWord[node] = true; } } static long getMax(int[] b){ long wt = 1l<<40; int node = 0; long ans = 0; for (int i = 0; i < b.length; i++) { int c = b[i]; int comp = 1-c; if(trie[comp][node] != -1 && hasWord[trie[comp][node]]){ node = trie[comp][node]; ans += wt*1; }else{ node = trie[c][node]; } wt = wt >> 1; } return ans; } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public Scanner(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(s)));} public String next() throws IOException {while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());return st.nextToken();} public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public boolean ready() throws IOException {return br.ready();} } }
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 8
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
15e5d464d7c28840a419fbd53f453460
train_002.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
//package practice.E; import java.io.*; import java.util.Arrays; import java.util.StringTokenizer; public class CF282E { static int trie[][]; static int nxt = 0; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); long[] arr = new long[n]; long a = 0; long b = 0; for (int i = 0; i < n; i++) { arr[i] = sc.nextLong(); a ^= arr[i]; } trie = new int[2][(n+1)*41 + 10]; hasWord = new boolean[(n+1)*41 + 10]; for (int i = 0; i < 2; i++) Arrays.fill(trie[i], -1); long ans = a; add(getBinary(0)); for (int i = n-1; i >= 0; i--) { b ^= arr[i]; a ^= arr[i]; add(getBinary(b)); ans = Math.max(getMax(getBinary(a)), ans); } pw.print(ans); pw.flush(); pw.close(); } static int[] getBinary(long x){ long wt = 1l<<40; int i = 0; int[] ret = new int[41]; while(x > 0){ if(x >= wt){ x -= wt; ret[i] = 1; } i++; wt >>= 1; } return ret; } static boolean[] hasWord; static void add(int[] b){ int node = 0; hasWord[0] = true; for (int i = 0; i < b.length; i++) { int c = b[i]; if(trie[c][node] == -1) trie[c][node] = ++nxt; node = trie[c][node]; hasWord[node] = true; } hasWord[node] = true; } static long getMax(int[] b){ long wt = 1l<<40; int node = 0; long ans = 0; for (int i = 0; i < b.length; i++) { int c = b[i]; int comp = 1-c; if(trie[comp][node] != -1 && hasWord[trie[comp][node]]){ node = trie[comp][node]; ans += wt*1; }else{ node = trie[c][node]; } wt = wt >> 1; } return ans; } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public Scanner(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(s)));} public String next() throws IOException {while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());return st.nextToken();} public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public boolean ready() throws IOException {return br.ready();} } }
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 8
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
2ce1d017498875440b5bf5c9103872ae
train_002.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
import java.io.*; import java.util.StringTokenizer; public class D { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); long[] a = new long[n]; long xor = 0; for(int i = 0; i < n; ++i) xor ^= a[i] = sc.nextLong(); Trie t = new Trie(); t.add(0); long ans = xor, v = 0; for(long b: a) { v ^= b; ans = Math.max(ans, t.get(v ^ xor)); t.add(v); } out.println(ans); out.close(); } static class Node { Node zero, one; } static final int BITS = 40; static class Trie { Node root = new Node(); void add(long v) { Node cur = root; for(int bit = BITS - 1; bit >= 0; --bit) { Node nxt = (v & 1l << bit) == 0 ? cur.zero : cur.one; if (nxt == null) if ((v & 1l << bit) == 0) nxt = cur.zero = new Node(); else nxt = cur.one = new Node(); cur = nxt; } } long get(long v) { return get(root, BITS - 1, v); } long get(Node node, int bit, long v) { if (bit == -1) return 0; if (node.zero == null || node.one == null) return get(node.zero == null ? node.one : node.zero, bit - 1, v) | ((node.zero == null ? 1l : 0l) ^ (v >> bit & 1)) << bit; return get((v & 1l << bit) == 0 ? node.one : node.zero, bit - 1, v) | (1l << bit); } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public boolean ready() throws IOException {return br.ready();} } }
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 8
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
b189ebffd0935e10e7311731f4474642
train_002.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.io.PrintWriter; public class E282 { static class Scanner { BufferedReader br; StringTokenizer tk=new StringTokenizer(""); public Scanner(InputStream is) { br=new BufferedReader(new InputStreamReader(is)); } public int nextInt() throws IOException { if(tk.hasMoreTokens()) return Integer.parseInt(tk.nextToken()); tk=new StringTokenizer(br.readLine()); return nextInt(); } public long nextLong() throws IOException { if(tk.hasMoreTokens()) return Long.parseLong(tk.nextToken()); tk=new StringTokenizer(br.readLine()); return nextLong(); } public String next() throws IOException { if(tk.hasMoreTokens()) return (tk.nextToken()); tk=new StringTokenizer(br.readLine()); return next(); } public String nextLine() throws IOException { tk=new StringTokenizer(""); return br.readLine(); } public double nextDouble() throws IOException { if(tk.hasMoreTokens()) return Double.parseDouble(tk.nextToken()); tk=new StringTokenizer(br.readLine()); return nextDouble(); } public char nextChar() throws IOException { if(tk.hasMoreTokens()) return (tk.nextToken().charAt(0)); tk=new StringTokenizer(br.readLine()); return nextChar(); } public int[] nextIntArray(int n) throws IOException { int a[]=new int[n]; for(int i=0;i<n;i++) a[i]=nextInt(); return a; } public long[] nextLongArray(int n) throws IOException { long a[]=new long[n]; for(int i=0;i<n;i++) a[i]=nextLong(); return a; } public int[] nextIntArrayOneBased(int n) throws IOException { int a[]=new int[n+1]; for(int i=1;i<=n;i++) a[i]=nextInt(); return a; } public long[] nextLongArrayOneBased(int n) throws IOException { long a[]=new long[n+1]; for(int i=1;i<=n;i++) a[i]=nextLong(); return a; } } static class Trie { int N; int left[], right[]; Trie() { N = 1; left = new int[5000000]; right = new int[5000000]; } int createNode() { N++; return N; } void insert(long value) { int node = 1; long mask = 1l << 40; while (mask > 0) { if ((value & mask) > 0) { if (right[node] == 0) { right[node]=createNode(); } node = right[node]; } else { if (left[node] == 0) { left[node]=createNode(); } node = left[node]; } mask >>= 1; } } long maxXor(long value) { long ans = 0; int node = 1; long mask = 1l << 40; while (mask > 0) { if ((mask & value) > 0) { if (left[node] != 0) { ans += mask; node = left[node]; } else if (right[node] != 0) { node = right[node]; } else { break; } } else if (right[node] != 0) { ans += mask; node = right[node]; } else if (left[node] != 0) { node = left[node]; } else { break; } mask>>=1; } return ans; } } public static void main(String args[]) throws IOException { Scanner in=new Scanner(System.in); PrintWriter out=new PrintWriter(System.out); int n=in.nextInt(); Trie t=new Trie(); long a[]=in.nextLongArray(n); long xor=0; for(int i=0;i<n;i++) xor^=a[i]; long ans=xor; t.insert(0); for(int i=n-1;i>=0;i--) { xor^=a[i]; if(i+1!=n) a[i]^=a[i+1]; t.insert(a[i]); ans=Math.max(ans,t.maxXor(xor)); ans=Math.max(ans, a[i]); } out.println(ans); out.close(); } }
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 8
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
021c935cb0529abaaa89ff0c13d17728
train_002.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
import java.io.*; import java.math.*; import java.security.KeyStore.Entry; import java.util.*; public class CODEFORCES { private InputStream is; private PrintWriter out; int next[][] = new int[5000000][2]; int id = 0; void insert(long a) { int now = 0; for (int i = 39; i >= 0; i--) { int c = (int) ((a & (1L << i)) == 0 ? 0 : 1); if (next[now][c] == 0) next[now][c] = ++id; now = next[now][c]; } } long ans(long a) { long nm = 0; int now = 0; for (int i = 39; i >= 0; i--) { int c = ((a & (1L << i)) == 0 ? 0 : 1); int co = 1 ^ c; if (next[now][co] != 0) { now = next[now][co]; nm |= (1L << i); } else now = next[now][c]; } return nm; } void solve() { int n = ni(); long arr[] = new long[n]; long xor = 0; long max = 0; long p[] = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nl(); xor ^= arr[i]; p[i] = xor; } max = xor; insert(0); for (int i = 0; i < n; i++) { insert(p[i]); max = Math.max(max, ans(p[i] ^ xor)); } out.println(max); } void soln() { is = System.in; 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 CODEFORCES().soln(); } // To Get Input // Some Buffer Methods private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char) skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' // ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if (!oj) System.out.println(Arrays.deepToString(o)); } }
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 8
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
2f12b6da65a90941c6acaec2f26d3742
train_002.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
//package wap; import java.util.Scanner; public class Sausage { public static treeNode root = new treeNode(); public static int height = 41; public static void main(String[] args){ // treeNode[] nodes = new treeNode[64*100000]; Scanner scanner= new Scanner(System.in); while(scanner.hasNext()){ int n = scanner.nextInt(); long[] a = new long[n]; int h = 0; long ans = 0, pre = 0, tmp = 0; for(int i=0; i<n; i++){ a[i] = scanner.nextLong(); tmp ^= a[i]; } insert(0); for(int i=0; i<n; i++){ pre ^= a[i]; tmp ^= a[i]; insert(pre); ans = Math.max(query(tmp), ans); } System.out.println(ans); } } public static void insert(long num){ treeNode p = root; for(int i = height; i>=0; i--){ int x = ((1L<<i)&num) !=0 ?0:1; if(x == 1){ if(p.right == null)p.right = new treeNode(); p = p.right; }else{ if(p.left == null)p.left = new treeNode(); p = p.left; } } } public static long query(long num){ treeNode p = root; long res = 0; for(int i=height; i>=0; i--){ int x = ((1L<<i)&num) !=0 ?0:1; if(x == 1){ if(p.left == null){ p = p.right; res = res << 1; }else{ p = p.left; res = (res << 1) + 1; } }else{ if(p.right == null){ p = p.left; res = res << 1; }else{ p = p.right; res = (res<<1)+1; } } } return res; } } /** * ��������� * */ class treeNode { public treeNode left; public treeNode right; public treeNode(){ left = null; right = null; } }
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 8
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
b3da06f4c0b6026da1b9a12fab5e5146
train_002.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
import java.io.*; import java.util.*; //I am fading....... //read the question correctly (is y a vowel? what are the exact constraints?) //look out for SPECIAL CASES (n=1?) and overflow (ll vs int?) //always declare multidimensional arrays as [2][n] not [n][2] //it can lead to upto 2-3x diff in runtime public class Main { static class node { node[]a=new node[16]; int level; node(int lev) { level=lev-4; } void add(long ho) { if(a[(int)((ho>>level)&15)]==null) a[(int)((ho>>level)&15)]=new node(level); if(level>=0) a[(int)((ho>>level)&15)].add(ho); } long find(long ho) { if(level<0) return 0; for(int i=15; i>0; i--) { if(a[(int)((ho>>level)^i)&15]!=null) return (((long)i)<<level)+a[(int)((ho>>level)^i)&15].find(ho); } return a[(int)(ho>>level)&15].find(ho); } } public static void main(String[] args) throws Exception { int n=ni(); long[]a=nla(n); node hola=new node(40); hola.add(0); long xorian=0; long[]prex=new long[n]; prex[0]=a[0]; for(int i=1; i<n; i++) prex[i]=prex[i-1]^a[i]; long ans=0; for(int i=n-1; i>=0; i--) { ans=Math.max(ans, hola.find(prex[i])); xorian^=a[i]; hola.add(xorian); } ans=Math.max(ans, hola.find(0)); pr(ans); System.out.print(output); } /////////////////////////////////////////// /////////////////////////////////////////// ///template from here static class pair { int a, b; pair(){} pair(int c,int d){a=c;b=d;} } static interface combiner { public long combine(long a, long b); } static final int mod=1000000007; static final double eps=1e-9; static final long inf=100000000000000000L; static Reader in=new Reader(); static StringBuilder output=new StringBuilder(); static Random rn=new Random(); static void reverse(int[]a){for(int i=0; i<a.length/2; i++){a[i]^=a[a.length-i-1];a[a.length-i-1]^=a[i];a[i]^=a[a.length-i-1];}} static void sort(int[]a) { int te; for(int i=0; i<a.length; i+=2) { te=rn.nextInt(a.length); if(i!=te) { a[i]^=a[te]; a[te]^=a[i]; a[i]^=a[te]; } } Arrays.sort(a); } static void sort(long[]a) { int te; for(int i=0; i<a.length; i+=2) { te=rn.nextInt(a.length); if(i!=te) { a[i]^=a[te]; a[te]^=a[i]; a[i]^=a[te]; } } Arrays.sort(a); } static void sort(double[]a) { int te; double te1; for(int i=0; i<a.length; i+=2) { te=rn.nextInt(a.length); if(i!=te) { te1=a[te]; a[te]=a[i]; a[i]=te1; } } Arrays.sort(a); } static void sort(int[][]a) { Arrays.sort(a, new Comparator<int[]>() { public int compare(int[]a,int[]b) { if(a[0]>b[0]) return -1; if(b[0]>a[0]) return 1; return 0; } }); } static void sort(pair[]a) { Arrays.sort(a,new Comparator<pair>() { @Override public int compare(pair a,pair b) { if(a.a>b.a) return 1; if(b.a>a.a) return -1; return 0; } }); } static int log2n(long a) { int te=0; while(a>0) { a>>=1; ++te; } return te; } static class vector implements Iterable<Integer> { int a[],size; vector(){a=new int[10];size=0;} vector(int n){a=new int[n];size=0;} public void add(int b){if(++size==a.length)a=Arrays.copyOf(a, 2*size);a[size-1]=b;} public void sort(){Arrays.sort(a, 0, size);} public void sort(int l, int r){Arrays.sort(a, l, r);} @Override public Iterator<Integer> iterator() { Iterator<Integer> hola=new Iterator<Integer>() { int cur=0; @Override public boolean hasNext() { return cur<size; } @Override public Integer next() { return a[cur++]; } }; return hola; } } //output functions//////////////// static void pr(Object a){output.append(a+"\n");} static void pr(){output.append("\n");} static void p(Object a){output.append(a);} static void pra(int[]a){for(int i:a)output.append(i+" ");output.append("\n");} static void pra(long[]a){for(long i:a)output.append(i+" ");output.append("\n");} static void pra(String[]a){for(String i:a)output.append(i+" ");output.append("\n");} static void pra(double[]a){for(double i:a)output.append(i+" ");output.append("\n");} static void sop(Object a){System.out.println(a);} static void flush(){System.out.println(output);output=new StringBuilder();} ////////////////////////////////// //input functions///////////////// static int ni(){return Integer.parseInt(in.next());} static long nl(){return Long.parseLong(in.next());} static String ns(){return in.next();} static double nd(){return Double.parseDouble(in.next());} static int[] nia(int n){int a[]=new int[n];for(int i=0; i<n; i++)a[i]=ni();return a;} static int[] pnia(int n){int a[]=new int[n+1];for(int i=1; i<=n; i++)a[i]=ni();return a;} static long[] nla(int n){long a[]=new long[n];for(int i=0; i<n; i++)a[i]=nl();return a;} static String[] nsa(int n){String a[]=new String[n];for(int i=0; i<n; i++)a[i]=ns();return a;} static double[] nda(int n){double a[]=new double[n];for(int i=0; i<n; i++)a[i]=nd();return a;} ////////////////////////////////// //some utility functions static void exit(){System.out.print(output);System.exit(0);} static int min(int... a){int min=a[0];for(int i:a)min=Math.min(min, i);return min;} static int max(int... a){int max=a[0];for(int i:a)max=Math.max(max, i);return max;} static int gcd(int... a){int gcd=a[0];for(int i:a)gcd=gcd(gcd, i);return gcd;} static long min(long... a){long min=a[0];for(long i:a)min=Math.min(min, i);return min;} static long max(long... a){long max=a[0];for(long i:a)max=Math.max(max, i);return max;} static long gcd(long... a){long gcd=a[0];for(long i:a)gcd=gcd(gcd, i);return gcd;} static String pr(String a, long b){String c="";while(b>0){if(b%2==1)c=c.concat(a);a=a.concat(a);b>>=1;}return c;} static long powm(long a, long b, long m){long an=1;long c=a;while(b>0){if(b%2==1)an=(an*c)%m;c=(c*c)%m;b>>=1;}return an;} static int gcd(int a, int b){if(b==0)return a;return gcd(b, a%b);} static long gcd(long a, long b){if(b==0)return a;return gcd(b, a%b);} static class Reader { public BufferedReader reader; public StringTokenizer tokenizer; public Reader() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } } }
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 8
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
f0c19f564a4a10aefd8a9c7f41b120b9
train_002.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
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 E { public static void main(String[] args) throws NumberFormatException, IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); Trie t = new Trie(40 * 100_000 + 20); long [] pref = new long[n+1]; long maxPref = 0; for (int i = 0; i <= n; ++i) { if(i > 0) { pref[i] = sc.nextLong(); pref[i] ^= pref[i-1]; } maxPref = Math.max(maxPref, pref[i]); t.put(pref[i], 1); } long ans = maxPref; long suf = 0L; for (int i = n; i > 0; --i) { suf ^= pref[i] ^ pref[i-1]; // remove prefix t.put(pref[i], -1); // get max prefix ans = Math.max(ans, t.search(suf)); } out.println(ans); out.close(); } static class Trie { int idx, nodes [][], val [][]; Trie(int n) { nodes = new int[2][n]; Arrays.fill(nodes[0], -1); Arrays.fill(nodes[1], -1); val = new int[2][n]; } void put(long s, int v) // O(n) where n = |s|. Can be implemented recursively { int cur = 0; int c = 0; for(int i = 39; i >= 0; --i) { c = (s & (1L<<i)) == 0?0:1; if(nodes[c][cur] == -1) nodes[c][cur] = ++idx; val[c][cur] += v; cur = nodes[c][cur]; } val[c][cur] += v; } long search(long s) { long ans = 0L; int cur = 0; for(int i = 39; i >= 0; --i) { int c = (s & (1L<<i)) == 0?0:1; ans <<= 1; int nxt = nodes[1-c][cur]; if(nxt == -1 || val[1-c][cur] == 0){ nxt = nodes[c][cur]; } else ++ans; cur = nxt; } return ans; } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } public int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); } public long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } } }
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 8
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
3bdee8481f7df8efd33e0a7eb1a79e8b
train_002.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; /** * Created by wangxiaoyi on 16/5/22. */ public class Main { public static void main(String[] args) throws IOException { BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); String s = input.readLine(); int n = Integer.parseInt(s); s = input.readLine(); String[] ss = s.split(" "); long[] nums = new long[n]; long suffixXor = 0; for (int i = 0; i < n; ++i) { nums[i] = Long.parseLong(ss[i]); suffixXor ^= nums[i]; } System.out.println(getMaxXorWithPrefixAndSuffix(nums, suffixXor)); } /** * * @param nums * @param suffixXor * @return */ public static long getMaxXorWithPrefixAndSuffix(long[] nums, long suffixXor) { long maxXor = suffixXor, prefixXor = 0; int len = nums.length; BinaryLongTrie trie = new BinaryLongTrie(len + 1); trie.insert(0l); for (int i = 0; i < len; ++ i){ prefixXor ^= nums[i]; suffixXor ^= nums[i]; trie.insert(prefixXor); long temp = trie.search(suffixXor); maxXor = Math.max(maxXor, temp ^ suffixXor); } trie.clear(); return maxXor; } static class BinaryLongTrie { private TNode []nodes; private int total; public BinaryLongTrie(int len){ nodes = new TNode[64 * len]; nodes[0] = new TNode(); total = 1; } /** * Node for Trie tree */ class TNode{ int []next; public TNode(){ next = new int[] {-1, -1}; } } /** * @param value */ public void insert(long value) { for (int i = 63, u = 0; i >= 0; i--) { int id = (((1l) << i) & value) != 0 ? 1 : 0; if (nodes[u].next[id] == -1) { nodes[total] = new TNode(); nodes[u].next[id] = total++; } u = nodes[u].next[id]; } } /** * @param key * @return */ public long search(long key) { long res = 0; for (int i = 63, u = 0; i >= 0; i--) { int id = (((1L) << i) & key) == 0 ? 1 : 0; if (nodes[u].next[id] == -1) id ^= 1; res = (res << 1) + (long) id; u = nodes[u].next[id]; } return res; } public void clear(){ nodes = null; } } }
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 8
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
9feb9294f27dd83e3e563fd94439b2c9
train_002.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * Created by wangxiaoyi on 16/5/22. */ public class Main { private static long base[]; public static void main(String[] args) throws IOException { base = new long[64]; for (int i = 0; i < 64; ++ i){ base[i] = (1l << i); } BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); String s = input.readLine(); int n = Integer.parseInt(s); s = input.readLine(); String[] ss = s.split(" "); long[] nums = new long[n]; long suffixXor = 0; for (int i = 0; i < n; ++i) { nums[i] = Long.parseLong(ss[i]); suffixXor ^= nums[i]; } System.out.println(getMaxXorWithPrefixAndSuffix(nums, suffixXor)); } /** * @param nums * @param suffixXor * @return */ public static long getMaxXorWithPrefixAndSuffix(long[] nums, long suffixXor) { long maxXor = suffixXor, prefixXor = 0; int len = nums.length; BinaryLongTrie trie = new BinaryLongTrie(len + 1); trie.insert(0l); for (int i = 0; i < len; ++i) { prefixXor ^= nums[i]; suffixXor ^= nums[i]; trie.insert(prefixXor); long temp = trie.search(suffixXor); maxXor = Math.max(maxXor, temp ^ suffixXor); } trie.clear(); return maxXor; } static class BinaryLongTrie { private TNode[] nodes; private int total; public BinaryLongTrie(int len) { nodes = new TNode[64 * len]; nodes[0] = new TNode(); total = 1; } /** * Node for Trie tree */ class TNode { int[] next; public TNode() { next = new int[]{-1, -1}; } } /** * @param value */ public void insert(long value) { for (int i = 63, u = 0; i >= 0; i--) { int id = (((1l) << i) & value) != 0 ? 1 : 0; if (nodes[u].next[id] == -1) { nodes[total] = new TNode(); nodes[u].next[id] = total++; } u = nodes[u].next[id]; } } /** * @param key * @return */ public long search(long key) { long res = 0; for (int i = 63, u = 0; i >= 0; i--) { int id = (((1L) << i) & key) == 0 ? 1 : 0; if (nodes[u].next[id] == -1) id ^= 1; res = (res << 1) + (long) id; u = nodes[u].next[id]; } return res; } public void clear() { nodes = null; } } }
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 8
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
2b5ab1cbc9c739e394f2a2f85cb4cbda
train_002.jsonl
1546007700
You are given a range of positive integers from $$$l$$$ to $$$r$$$.Find such a pair of integers $$$(x, y)$$$ that $$$l \le x, y \le r$$$, $$$x \ne y$$$ and $$$x$$$ divides $$$y$$$.If there are multiple answers, print any of them.You are also asked to answer $$$T$$$ independent queries.
256 megabytes
import java.io.*; import java.util.*; public class findDiv { public static void main (String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int t = Integer.parseInt(br.readLine()); for(int i=0;i<t;i++) { StringTokenizer st = new StringTokenizer(br.readLine()); int l = Integer.parseInt(st.nextToken()); int r = Integer.parseInt(st.nextToken()); out.println(l+" "+2*l); }//end for i out.close(); }//end main }//end class findDiv
Java
["3\n1 10\n3 14\n1 10"]
2 seconds
["1 7\n3 9\n5 10"]
null
Java 8
standard input
[ "implementation", "greedy", "math" ]
a9cd97046e27d799c894d8514e90a377
The first line contains a single integer $$$T$$$ ($$$1 \le T \le 1000$$$) — the number of queries. Each of the next $$$T$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le 998244353$$$) — inclusive borders of the range. It is guaranteed that testset only includes queries, which have at least one suitable pair.
800
Print $$$T$$$ lines, each line should contain the answer — two integers $$$x$$$ and $$$y$$$ such that $$$l \le x, y \le r$$$, $$$x \ne y$$$ and $$$x$$$ divides $$$y$$$. The answer in the $$$i$$$-th line should correspond to the $$$i$$$-th query from the input. If there are multiple answers, print any of them.
standard output