exec_outcome
stringclasses
1 value
code_uid
stringlengths
32
32
file_name
stringclasses
111 values
prob_desc_created_at
stringlengths
10
10
prob_desc_description
stringlengths
63
3.8k
prob_desc_memory_limit
stringclasses
18 values
source_code
stringlengths
117
65.5k
lang_cluster
stringclasses
1 value
prob_desc_sample_inputs
stringlengths
2
802
prob_desc_time_limit
stringclasses
27 values
prob_desc_sample_outputs
stringlengths
2
796
prob_desc_notes
stringlengths
4
3k
βŒ€
lang
stringclasses
5 values
prob_desc_input_from
stringclasses
3 values
tags
sequencelengths
0
11
src_uid
stringlengths
32
32
prob_desc_input_spec
stringlengths
28
2.37k
βŒ€
difficulty
int64
-1
3.5k
βŒ€
prob_desc_output_spec
stringlengths
17
1.47k
βŒ€
prob_desc_output_to
stringclasses
3 values
hidden_unit_tests
stringclasses
1 value
PASSED
809e22f43d7442dc9a3b263b01590c06
train_000.jsonl
1540740900
Janusz is a businessman. He owns a company "Januszex", which produces games for teenagers. Last hit of Januszex was a cool one-person game "Make it one". The player is given a sequence of $$$n$$$ integers $$$a_i$$$.It is allowed to select any subset of them, and the score is equal to the greatest common divisor of selected elements. The goal is to take as little elements as it is possible, getting the score $$$1$$$. Now Janusz wonders, for given sequence, how much elements should the player choose?
256 megabytes
import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.System.exit; import static java.util.Arrays.fill; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class F { static void solve() throws Exception { int n = scanInt(); int a[] = new int[n]; int max = 0; for (int i = 0; i < n; i++) { a[i] = scanInt(); max = max(max, a[i]); } boolean have[] = new boolean[max + 1]; for (int i = 0; i < n; i++) { have[a[i]] = true; } int mul[] = new int[max + 1]; fill(mul, -1); for (int p = 2; p <= max; p++) { if (mul[p] >= 0) { continue; } mul[p] = p; if (p <= 46340) { for (int i = p * p; i <= max; i += p) { if (mul[i] < 0) { mul[i] = p; } } } } counts = new int[max + 1]; factors = new int[10]; for (int i = 1; i <= max; i++) { if (!have[i]) { continue; } int nFactors = 0; int prev = 0; for (int j = i; j != 1; j /= mul[j]) { if (prev != mul[j]) { prev = factors[nFactors++] = mul[j]; } } go1(nFactors, 1); } int ans = Integer.MAX_VALUE; counts2 = new int[1 << 10]; int counts3[] = new int[1 << 10]; int signum[] = new int[1 << 10]; for (int i = 0; i < signum.length; i++) { signum[i] = (Integer.bitCount(i) & 1) != 0 ? -1 : 1; } for (int i = 1; i <= max; i++) { if (!have[i]) { continue; } int nFactors = 0; int prev = 0; for (int j = i; j != 1; j /= mul[j]) { if (prev != mul[j]) { prev = factors[nFactors++] = mul[j]; } } go2(nFactors, 1, 0); for (int j = 0; j < 1 << nFactors; j++) { int cur = 0; for (int k = j;; k = (k - 1) & j) { cur += signum[k] * counts2[k]; if (k == 0) { break; } } int cval = Integer.MAX_VALUE; if (j == 0) { cval = 0; } else if (cur != 0) { cval = 1; } else { for (int k = (j - 1) & j; k != 0; k = (k - 1) & j) { if (counts3[k] != Integer.MAX_VALUE && counts3[k ^ j] != Integer.MAX_VALUE) { cval = min(cval, counts3[k] + counts3[k ^ j]); } } } counts3[j] = cval; } int v = counts3[(1 << nFactors) - 1]; if (v != Integer.MAX_VALUE) { ans = min(ans, v + 1); } } out.print(ans == Integer.MAX_VALUE ? -1 : ans); } static int counts[], factors[], counts2[]; static void go1(int i, int cur) { if (i == 0) { ++counts[cur]; return; } --i; go1(i, cur); go1(i, cur * factors[i]); } static void go2(int i, int curNum, int curSet) { if (i == 0) { counts2[curSet] = counts[curNum]; return; } --i; go2(i, curNum, curSet); go2(i, curNum * factors[i], curSet | (1 << i)); } static int scanInt() throws IOException { return parseInt(scanString()); } static long scanLong() throws IOException { return parseLong(scanString()); } static String scanString() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } static BufferedReader in; static PrintWriter out; static StringTokenizer tok; public static void main(String[] args) { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); in.close(); out.close(); } catch (Throwable e) { e.printStackTrace(); exit(1); } } }
Java
["3\n10 6 15", "3\n2 4 6", "7\n30 60 21 42 70 15 30"]
3 seconds
["3", "-1", "3"]
NoteIn the first example, selecting a subset of all numbers gives a gcd of $$$1$$$ and for all smaller subsets the gcd is greater than $$$1$$$.In the second example, for all subsets of numbers the gcd is at least $$$2$$$.
Java 8
standard input
[ "dp", "combinatorics", "number theory", "bitmasks", "shortest paths", "math" ]
3baa00206d3bf03ce02a414747e2a633
The first line contains an only integer $$$n$$$ ($$$1 \le n \le 300\,000$$$)Β β€” the number of integers in the sequence. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 300\,000$$$).
2,500
If there is no subset of the given sequence with gcd equal to $$$1$$$, output -1. Otherwise, output exactly one integerΒ β€” the size of the smallest subset with gcd equal to $$$1$$$.
standard output
PASSED
6273b8cd600e83dce2c543cf3a091a99
train_000.jsonl
1540740900
Janusz is a businessman. He owns a company "Januszex", which produces games for teenagers. Last hit of Januszex was a cool one-person game "Make it one". The player is given a sequence of $$$n$$$ integers $$$a_i$$$.It is allowed to select any subset of them, and the score is equal to the greatest common divisor of selected elements. The goal is to take as little elements as it is possible, getting the score $$$1$$$. Now Janusz wonders, for given sequence, how much elements should the player choose?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import java.io.IOException; import java.io.UncheckedIOException; import java.io.Closeable; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27); thread.start(); thread.join(); } static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastInput in = new FastInput(inputStream); FastOutput out = new FastOutput(outputStream); FMakeItOne solver = new FMakeItOne(); solver.solve(1, in, out); out.close(); } } static class FMakeItOne { public void solve(int testNumber, FastInput in, FastOutput out) { int n = in.readInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.readInt(); } GcdLcmProblem problem = new GcdLcmProblem(300000, a); int ans = problem.minimumSizeOfSubsetWhoseGCDDivisibleBy(1); if (ans == GcdLcmProblem.INF) { out.println(-1); } else { out.println(ans); } } } static class GcdLcmProblem { private MultiWayIntegerStack primeFactors; private IntegerList allFactors = new IntegerList(20); private int[] cntOfMultiple; private int m; private int[] seq; public static final int INF = (int) 1e9; private int[] coprime; private MultiWayIntegerDeque indexesOfSeq; private int[] dp; public GcdLcmProblem(int m, int[] seq) { this.m = m; this.seq = seq; primeFactors = Factorization.factorizeRangePrime(m); prepareCntOfMultiple(); coprime = new int[m + 1]; Arrays.fill(coprime, -1); indexesOfSeq = new MultiWayIntegerDeque(m + 1, seq.length); for (int i = 0; i < seq.length; i++) { indexesOfSeq.addLast(seq[i], i); } } private void prepareCntOfMultiple() { cntOfMultiple = new int[m + 1]; for (int x : seq) { cntOfMultiple[x]++; } for (int i = 1; i <= m; i++) { for (int j = i + i; j <= m; j += i) { cntOfMultiple[i] += cntOfMultiple[j]; } } } public int coprime(int x) { if (coprime[x] == -1) { factorize(x); coprime[x] = ie(cntOfMultiple, allFactors.size() - 1, 1, 0); } return coprime[x]; } public int minimumSizeOfSubsetWhoseGCDDivisibleBy(int x) { if (dp == null) { dp = new int[m + 1]; Arrays.fill(dp, INF); for (int e : seq) { dp[e] = 1; } for (int i = m; i >= 1; i--) { for (int j = i + i; j <= m; j += i) { if (coprime(j / i) > 0) { dp[i] = Math.min(dp[i], dp[j] + 1); } } } } return dp[x]; } private void factorize(int x) { allFactors.clear(); allFactors.addAll(primeFactors.iterator(x)); } private int ie(int[] cnts, int i, int divisor, int numberOfFactors) { if (i < 0) { int ans = cnts[divisor]; if ((numberOfFactors & 1) == 1) { ans = -ans; } return ans; } return ie(cnts, i - 1, divisor, numberOfFactors) + ie(cnts, i - 1, divisor * allFactors.get(i), numberOfFactors + 1); } } static class FastInput { private final InputStream is; private byte[] buf = new byte[1 << 13]; private int bufLen; private int bufOffset; private int next; public FastInput(InputStream is) { this.is = is; } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { bufLen = -1; } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public int readInt() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } int val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } } static class FastOutput implements AutoCloseable, Closeable { private StringBuilder cache = new StringBuilder(10 << 20); private final Writer os; public FastOutput(Writer os) { this.os = os; } public FastOutput(OutputStream os) { this(new OutputStreamWriter(os)); } public FastOutput println(int c) { cache.append(c); println(); return this; } public FastOutput println() { cache.append(System.lineSeparator()); return this; } public FastOutput flush() { try { os.append(cache); os.flush(); cache.setLength(0); } catch (IOException e) { throw new UncheckedIOException(e); } return this; } public void close() { flush(); try { os.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } public String toString() { return cache.toString(); } } static class Factorization { public static MultiWayIntegerStack factorizeRangePrime(int n) { int size = 0; for (int i = 1; i <= n; i++) { size += n / i; } MultiWayIntegerStack stack = new MultiWayIntegerStack(n + 1, size); boolean[] isComp = new boolean[n + 1]; for (int i = 2; i <= n; i++) { if (isComp[i]) { continue; } for (int j = i; j <= n; j += i) { isComp[j] = true; stack.addLast(j, i); } } return stack; } } static interface IntegerIterator { boolean hasNext(); int next(); } static class SequenceUtils { public static boolean equal(int[] a, int al, int ar, int[] b, int bl, int br) { if ((ar - al) != (br - bl)) { return false; } for (int i = al, j = bl; i <= ar; i++, j++) { if (a[i] != b[j]) { return false; } } return true; } } static class MultiWayIntegerDeque { private int[] values; private int[] next; private int[] prev; private int[] heads; private int[] tails; private int alloc; private int queueNum; public IntegerIterator iterator(final int queue) { return new IntegerIterator() { int ele = heads[queue]; public boolean hasNext() { return ele != 0; } public int next() { int ans = values[ele]; ele = next[ele]; return ans; } }; } private void doubleCapacity() { int newSize = Math.max(next.length + 10, next.length * 2); next = Arrays.copyOf(next, newSize); prev = Arrays.copyOf(prev, newSize); values = Arrays.copyOf(values, newSize); } public void alloc() { alloc++; if (alloc >= next.length) { doubleCapacity(); } next[alloc] = 0; } public MultiWayIntegerDeque(int qNum, int totalCapacity) { values = new int[totalCapacity + 1]; next = new int[totalCapacity + 1]; prev = new int[totalCapacity + 1]; heads = new int[qNum]; tails = new int[qNum]; queueNum = qNum; } public void addLast(int qId, int x) { alloc(); values[alloc] = x; if (heads[qId] == 0) { heads[qId] = tails[qId] = alloc; return; } next[tails[qId]] = alloc; prev[alloc] = tails[qId]; tails[qId] = alloc; } public String toString() { StringBuilder builder = new StringBuilder(); for (int i = 0; i < queueNum; i++) { builder.append(i).append(": "); for (IntegerIterator iterator = iterator(i); iterator.hasNext(); ) { builder.append(iterator.next()).append(","); } if (builder.charAt(builder.length() - 1) == ',') { builder.setLength(builder.length() - 1); } builder.append('\n'); } return builder.toString(); } } static class IntegerList implements Cloneable { private int size; private int cap; private int[] data; private static final int[] EMPTY = new int[0]; public IntegerList(int cap) { this.cap = cap; if (cap == 0) { data = EMPTY; } else { data = new int[cap]; } } public IntegerList(IntegerList list) { this.size = list.size; this.cap = list.cap; this.data = Arrays.copyOf(list.data, size); } public void addAll(IntegerIterator iterator) { while (iterator.hasNext()) { add(iterator.next()); } } public IntegerList() { this(0); } public void ensureSpace(int req) { if (req > cap) { while (cap < req) { cap = Math.max(cap + 10, 2 * cap); } data = Arrays.copyOf(data, cap); } } private void checkRange(int i) { if (i < 0 || i >= size) { throw new ArrayIndexOutOfBoundsException("index " + i + " out of range"); } } public int get(int i) { checkRange(i); return data[i]; } public void add(int x) { ensureSpace(size + 1); data[size++] = x; } public void addAll(int[] x, int offset, int len) { ensureSpace(size + len); System.arraycopy(x, offset, data, size, len); size += len; } public void addAll(IntegerList list) { addAll(list.data, 0, list.size); } public int size() { return size; } public int[] toArray() { return Arrays.copyOf(data, size); } public void clear() { size = 0; } public String toString() { return Arrays.toString(toArray()); } public boolean equals(Object obj) { if (!(obj instanceof IntegerList)) { return false; } IntegerList other = (IntegerList) obj; return SequenceUtils.equal(data, 0, size - 1, other.data, 0, other.size - 1); } public int hashCode() { int h = 1; for (int i = 0; i < size; i++) { h = h * 31 + Integer.hashCode(data[i]); } return h; } public IntegerList clone() { IntegerList ans = new IntegerList(); ans.addAll(this); return ans; } } static class MultiWayIntegerStack { private int[] values; private int[] next; private int[] heads; private int alloc; private int stackNum; public IntegerIterator iterator(final int queue) { return new IntegerIterator() { int ele = heads[queue]; public boolean hasNext() { return ele != 0; } public int next() { int ans = values[ele]; ele = next[ele]; return ans; } }; } private void doubleCapacity() { int newSize = Math.max(next.length + 10, next.length * 2); next = Arrays.copyOf(next, newSize); values = Arrays.copyOf(values, newSize); } public void alloc() { alloc++; if (alloc >= next.length) { doubleCapacity(); } next[alloc] = 0; } public MultiWayIntegerStack(int qNum, int totalCapacity) { values = new int[totalCapacity + 1]; next = new int[totalCapacity + 1]; heads = new int[qNum]; stackNum = qNum; } public void addLast(int qId, int x) { alloc(); values[alloc] = x; next[alloc] = heads[qId]; heads[qId] = alloc; } public String toString() { StringBuilder builder = new StringBuilder(); for (int i = 0; i < stackNum; i++) { builder.append(i).append(": "); for (IntegerIterator iterator = iterator(i); iterator.hasNext(); ) { builder.append(iterator.next()).append(","); } if (builder.charAt(builder.length() - 1) == ',') { builder.setLength(builder.length() - 1); } builder.append('\n'); } return builder.toString(); } } }
Java
["3\n10 6 15", "3\n2 4 6", "7\n30 60 21 42 70 15 30"]
3 seconds
["3", "-1", "3"]
NoteIn the first example, selecting a subset of all numbers gives a gcd of $$$1$$$ and for all smaller subsets the gcd is greater than $$$1$$$.In the second example, for all subsets of numbers the gcd is at least $$$2$$$.
Java 8
standard input
[ "dp", "combinatorics", "number theory", "bitmasks", "shortest paths", "math" ]
3baa00206d3bf03ce02a414747e2a633
The first line contains an only integer $$$n$$$ ($$$1 \le n \le 300\,000$$$)Β β€” the number of integers in the sequence. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 300\,000$$$).
2,500
If there is no subset of the given sequence with gcd equal to $$$1$$$, output -1. Otherwise, output exactly one integerΒ β€” the size of the smallest subset with gcd equal to $$$1$$$.
standard output
PASSED
7194aba9d2ee6b56b797160b12d12a8b
train_000.jsonl
1540740900
Janusz is a businessman. He owns a company "Januszex", which produces games for teenagers. Last hit of Januszex was a cool one-person game "Make it one". The player is given a sequence of $$$n$$$ integers $$$a_i$$$.It is allowed to select any subset of them, and the score is equal to the greatest common divisor of selected elements. The goal is to take as little elements as it is possible, getting the score $$$1$$$. Now Janusz wonders, for given sequence, how much elements should the player choose?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import java.io.IOException; import java.io.UncheckedIOException; import java.io.Closeable; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27); thread.start(); thread.join(); } static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastInput in = new FastInput(inputStream); FastOutput out = new FastOutput(outputStream); FMakeItOne solver = new FMakeItOne(); solver.solve(1, in, out); out.close(); } } static class FMakeItOne { public void solve(int testNumber, FastInput in, FastOutput out) { int n = in.readInt(); int limit = 300000; int[] cnts = new int[limit + 1]; for (int i = 0; i < n; i++) { cnts[in.readInt()]++; } if (cnts[1] > 0) { out.println(1); return; } MultiWayIntegerStack allPrimeFactors = new MultiWayIntegerStack(limit + 1, limit * 7); boolean[] isComp = new boolean[limit + 1]; for (int i = 2; i <= limit; i++) { if (isComp[i]) { continue; } for (int j = i; j <= limit; j += i) { isComp[j] = true; allPrimeFactors.addLast(j, i); } } int[] hasGcdGreaterThan1 = new int[limit + 1]; int[] multiples = new int[limit + 1]; for (int i = 1; i <= limit; i++) { for (int j = i; j <= limit; j += i) { multiples[i] += cnts[j]; } } IntegerList allFactors = new IntegerList(10); for (int i = 1; i <= limit; i++) { allFactors.clear(); for (IntegerIterator iterator = allPrimeFactors.iterator(i); iterator.hasNext(); ) { allFactors.add(iterator.next()); } hasGcdGreaterThan1[i] = dfs(multiples, allFactors.getData(), 1, 0, allFactors.size() - 1); } int[] dp = new int[limit + 1]; Arrays.fill(dp, (int) 1e8); for (int i = limit; i >= 1; i--) { if (cnts[i] > 0) { dp[i] = Math.min(dp[i], 1); } for (int j = 2; j * i <= limit; j++) { if (hasGcdGreaterThan1[j] == n) { continue; } dp[i] = Math.min(dp[i], dp[j * i] + 1); } } if (dp[1] == (int) 1e8) { out.println(-1); return; } out.println(dp[1]); } public int dfs(int[] multiples, int[] allFactors, int prod, int factors, int i) { if (i == -1) { if (factors == 0) { return 0; } int ans = multiples[prod]; if (factors % 2 == 0) { ans = -ans; } return ans; } return dfs(multiples, allFactors, prod * allFactors[i], factors + 1, i - 1) + dfs(multiples, allFactors, prod, factors, i - 1); } } static class IntegerList implements Cloneable { private int size; private int cap; private int[] data; private static final int[] EMPTY = new int[0]; public int[] getData() { return data; } public IntegerList(int cap) { this.cap = cap; if (cap == 0) { data = EMPTY; } else { data = new int[cap]; } } public IntegerList(IntegerList list) { this.size = list.size; this.cap = list.cap; this.data = Arrays.copyOf(list.data, size); } public IntegerList() { this(0); } public void ensureSpace(int req) { if (req > cap) { while (cap < req) { cap = Math.max(cap + 10, 2 * cap); } data = Arrays.copyOf(data, cap); } } public void add(int x) { ensureSpace(size + 1); data[size++] = x; } public void addAll(int[] x, int offset, int len) { ensureSpace(size + len); System.arraycopy(x, offset, data, size, len); size += len; } public void addAll(IntegerList list) { addAll(list.data, 0, list.size); } public int size() { return size; } public int[] toArray() { return Arrays.copyOf(data, size); } public void clear() { size = 0; } public String toString() { return Arrays.toString(toArray()); } public boolean equals(Object obj) { if (!(obj instanceof IntegerList)) { return false; } IntegerList other = (IntegerList) obj; return SequenceUtils.equal(data, 0, size - 1, other.data, 0, other.size - 1); } public int hashCode() { int h = 1; for (int i = 0; i < size; i++) { h = h * 31 + Integer.hashCode(data[i]); } return h; } public IntegerList clone() { IntegerList ans = new IntegerList(); ans.addAll(this); return ans; } } static class MultiWayIntegerStack { private int[] values; private int[] next; private int[] heads; private int alloc; private int stackNum; public IntegerIterator iterator(final int queue) { return new IntegerIterator() { int ele = heads[queue]; public boolean hasNext() { return ele != 0; } public int next() { int ans = values[ele]; ele = next[ele]; return ans; } }; } private void doubleCapacity() { int newSize = Math.max(next.length + 10, next.length * 2); next = Arrays.copyOf(next, newSize); values = Arrays.copyOf(values, newSize); } public void alloc() { alloc++; if (alloc >= next.length) { doubleCapacity(); } next[alloc] = 0; } public MultiWayIntegerStack(int qNum, int totalCapacity) { values = new int[totalCapacity + 1]; next = new int[totalCapacity + 1]; heads = new int[qNum]; stackNum = qNum; } public void addLast(int qId, int x) { alloc(); values[alloc] = x; next[alloc] = heads[qId]; heads[qId] = alloc; } public String toString() { StringBuilder builder = new StringBuilder(); for (int i = 0; i < stackNum; i++) { builder.append(i).append(": "); for (IntegerIterator iterator = iterator(i); iterator.hasNext(); ) { builder.append(iterator.next()).append(","); } if (builder.charAt(builder.length() - 1) == ',') { builder.setLength(builder.length() - 1); } builder.append('\n'); } return builder.toString(); } } static class FastInput { private final InputStream is; private byte[] buf = new byte[1 << 13]; private int bufLen; private int bufOffset; private int next; public FastInput(InputStream is) { this.is = is; } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { bufLen = -1; } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public int readInt() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } int val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } } static class SequenceUtils { public static boolean equal(int[] a, int al, int ar, int[] b, int bl, int br) { if ((ar - al) != (br - bl)) { return false; } for (int i = al, j = bl; i <= ar; i++, j++) { if (a[i] != b[j]) { return false; } } return true; } } static interface IntegerIterator { boolean hasNext(); int next(); } static class FastOutput implements AutoCloseable, Closeable { private StringBuilder cache = new StringBuilder(10 << 20); private final Writer os; public FastOutput(Writer os) { this.os = os; } public FastOutput(OutputStream os) { this(new OutputStreamWriter(os)); } public FastOutput println(int c) { cache.append(c).append('\n'); return this; } public FastOutput flush() { try { os.append(cache); os.flush(); cache.setLength(0); } catch (IOException e) { throw new UncheckedIOException(e); } return this; } public void close() { flush(); try { os.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } public String toString() { return cache.toString(); } } }
Java
["3\n10 6 15", "3\n2 4 6", "7\n30 60 21 42 70 15 30"]
3 seconds
["3", "-1", "3"]
NoteIn the first example, selecting a subset of all numbers gives a gcd of $$$1$$$ and for all smaller subsets the gcd is greater than $$$1$$$.In the second example, for all subsets of numbers the gcd is at least $$$2$$$.
Java 8
standard input
[ "dp", "combinatorics", "number theory", "bitmasks", "shortest paths", "math" ]
3baa00206d3bf03ce02a414747e2a633
The first line contains an only integer $$$n$$$ ($$$1 \le n \le 300\,000$$$)Β β€” the number of integers in the sequence. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 300\,000$$$).
2,500
If there is no subset of the given sequence with gcd equal to $$$1$$$, output -1. Otherwise, output exactly one integerΒ β€” the size of the smallest subset with gcd equal to $$$1$$$.
standard output
PASSED
9de43b67cc465d569284aa253cd1be4f
train_000.jsonl
1540740900
Janusz is a businessman. He owns a company "Januszex", which produces games for teenagers. Last hit of Januszex was a cool one-person game "Make it one". The player is given a sequence of $$$n$$$ integers $$$a_i$$$.It is allowed to select any subset of them, and the score is equal to the greatest common divisor of selected elements. The goal is to take as little elements as it is possible, getting the score $$$1$$$. Now Janusz wonders, for given sequence, how much elements should the player choose?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.IOException; import java.io.InputStreamReader; import java.io.FileNotFoundException; import java.util.ArrayList; import java.security.SecureRandom; import java.util.List; import java.util.StringTokenizer; import java.math.BigInteger; import java.io.BufferedReader; import java.io.FileReader; 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; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskF solver = new TaskF(); solver.solve(1, in, out); out.close(); } static class TaskF { int MAX = 300_000; int MAX_ANS = 20; int MOD = 0; public void solve(int testNumber, FastScanner in, PrintWriter out) { int n = in.nextInt(); int[] a = in.nextIntArray(n); int[] count = new int[MAX + 1]; for (int i : a) { count[i] = 1; } MOD = BigInteger.probablePrime(30, new SecureRandom()).intValue(); List<Integer> primes = NumberTheory.primes(MAX + 1); int[] t = new int[MAX + 1]; for (int i = 1; i <= MAX; i++) { for (int j = i; j <= MAX; j += i) { t[i] += count[j]; } } int[] mobius = new int[MAX + 1]; mobius[1] = 1; for (int i = 1; i <= MAX; i++) { for (int j = i + i; j <= MAX; j += i) { mobius[j] -= mobius[i]; } } int gcd = 0; for (int i : a) { gcd = MathUtils.gcd(gcd, i); } if (gcd != 1) { out.println(-1); return; } int[] clone = t.clone(); for (int ans = 1; ans <= MAX_ANS; ans++) { int inverse1 = 0; for (int i = 1; i <= MAX; i++) { inverse1 += mobius[i] * t[i]; if (inverse1 < 0) { inverse1 += MOD; } if (inverse1 >= MOD) { inverse1 -= MOD; } } if (inverse1 != 0) { out.println(ans); return; } for (int i = 1; i <= MAX; i++) { t[i] = (int) (1L * t[i] * clone[i] % MOD); } } throw new AssertionError(); } } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); } public FastScanner(String fileName) { try { br = new BufferedReader(new FileReader(fileName)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public int nextInt() { return Integer.parseInt(next()); } public String next() { while (st == null || !st.hasMoreElements()) { String line = null; try { line = br.readLine(); } catch (IOException e) { } st = new StringTokenizer(line); } return st.nextToken(); } public int[] nextIntArray(int n) { int[] ret = new int[n]; for (int i = 0; i < n; i++) { ret[i] = nextInt(); } return ret; } } static class NumberTheory { public static List<Integer> primes(int max) { boolean[] isPrime = new boolean[max + 1]; Arrays.fill(isPrime, true); List<Integer> ans = new ArrayList<>(); for (int i = 2; i <= max; i++) { if (isPrime[i]) { ans.add(i); for (int j = 2 * i; j <= max; j += i) { isPrime[j] = false; } } } return ans; } } static class MathUtils { public static int gcd(int a, int b) { int t; while (a != 0) { t = b % a; b = a; a = t; } return b; } } }
Java
["3\n10 6 15", "3\n2 4 6", "7\n30 60 21 42 70 15 30"]
3 seconds
["3", "-1", "3"]
NoteIn the first example, selecting a subset of all numbers gives a gcd of $$$1$$$ and for all smaller subsets the gcd is greater than $$$1$$$.In the second example, for all subsets of numbers the gcd is at least $$$2$$$.
Java 8
standard input
[ "dp", "combinatorics", "number theory", "bitmasks", "shortest paths", "math" ]
3baa00206d3bf03ce02a414747e2a633
The first line contains an only integer $$$n$$$ ($$$1 \le n \le 300\,000$$$)Β β€” the number of integers in the sequence. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 300\,000$$$).
2,500
If there is no subset of the given sequence with gcd equal to $$$1$$$, output -1. Otherwise, output exactly one integerΒ β€” the size of the smallest subset with gcd equal to $$$1$$$.
standard output
PASSED
40a88f95fce9c92b8b90fa3211ca0575
train_000.jsonl
1540740900
Janusz is a businessman. He owns a company "Januszex", which produces games for teenagers. Last hit of Januszex was a cool one-person game "Make it one". The player is given a sequence of $$$n$$$ integers $$$a_i$$$.It is allowed to select any subset of them, and the score is equal to the greatest common divisor of selected elements. The goal is to take as little elements as it is possible, getting the score $$$1$$$. Now Janusz wonders, for given sequence, how much elements should the player choose?
256 megabytes
//package com.company; import java.io.*; import java.util.*; public class Main { static long TIME_START, TIME_END; public static class Task { int N = 300001; public class Factor { int[] factors; List<Integer> primes; List<Integer>[] allDivisors; int[] mapToOnlyFactor; int[] mapToIndex; int[] toGetFactorCount; int M; public void reduceActiveSetSize(Set<Integer> activeNumbers) { List<Integer> toRemove = new ArrayList<>(); for (int active : activeNumbers) { int cost = getCount(active); int ha = mapToIndex[active]; boolean remove = false; if (active != 1 && cost >= toGetFactorCount[0] - 1) { remove = true; } else { for (int l : allDivisors[ha]) { int hl = mapToIndex[l]; if (toGetFactorCount[hl] <= cost) { remove = true; break; } } } if (remove) toRemove.add(active); } activeNumbers.removeAll(toRemove); } public boolean updateToGetFactor(int x, int cost) { int hx = mapToIndex[x]; if (toGetFactorCount[hx] <= cost) return false; toGetFactorCount[hx] = cost; if (x != 1 && cost >= toGetFactorCount[0] - 1) return false; for (int l : allDivisors[hx]) { int hl = mapToIndex[l]; if (toGetFactorCount[hl] <= cost) return false; } return true; } public int getCount(int x) { int hx = mapToIndex[x]; return toGetFactorCount[hx]; } public Factor() { factors = new int[N]; primes = new ArrayList<>(); for (int i = 2; i < N; i++) { if (factors[i] == 0) { factors[i] = i; primes.add(i); } for (int j : primes) { int y = i * j; if (y >= N) break; factors[y] = j; if (i % j == 0) break; } } Map<Integer, Integer> onlyFactors = new HashMap<>(); mapToOnlyFactor = new int[N]; for (int i = 1; i < N; i++) { mapToOnlyFactor[i] = getOnlyFactor(i); if (!onlyFactors.containsKey(mapToOnlyFactor[i])) onlyFactors.put(mapToOnlyFactor[i], M++); } mapToIndex = new int[N]; for (int i = 1; i < N; i++) { mapToIndex[i] = onlyFactors.get(mapToOnlyFactor[i]); } allDivisors = new List[M]; for (Map.Entry<Integer, Integer> numberAndIdx: onlyFactors.entrySet()) { allDivisors[numberAndIdx.getValue()] = getAllDivisors(numberAndIdx.getKey()); } toGetFactorCount = new int[M]; int inf = Integer.MAX_VALUE / 2; Arrays.fill(toGetFactorCount, inf); } public List<Integer> getAllDivisors(int x) { List<Integer> primeDivisors = new ArrayList<>(); while (x != 1) { int v = factors[x]; primeDivisors.add(v); while (x % v == 0) x /= v; } int n = primeDivisors.size(); List<Integer> allDivisors = new ArrayList<>(); for (int i = 1; i < (1 << n) - 1; i++) { int y = 1; for (int j = 0; j < n; j++) { if ((i & (1 << j)) != 0) y *= primeDivisors.get(j); } allDivisors.add(y); } return allDivisors; } public int getOnlyFactor(int x) { int y = 1; while (x != 1) { int v = factors[x]; y *= v; while (x % v == 0) x /= v; } return y; } } public int gcd(int a, int b) { while (b != 0) { a = a % b; int t = b; b = a; a = t; } return a; } public void solve(Scanner sc, PrintWriter pw) throws IOException { Factor f = new Factor(); int[] allNumbers = new int[N]; int n = sc.nextInt(); for (int i = 0; i < n; i++) { int a = sc.nextInt(); allNumbers[a] = 1; } List<Integer> numbers = new ArrayList<>(); for (int i = 0; i < N; i++) { if (allNumbers[i] == 1) { numbers.add(i); } } Collections.shuffle(numbers); int maximumSubsetSize = 7; Set<Integer> activeNumbers = new HashSet<>(); int fresh = 0; for (int number : numbers) { f.updateToGetFactor(number, 1); List<Integer> pendingAdd = new ArrayList<>(); pendingAdd.add(number); for (int active : activeNumbers) { int gcd = gcd(active, number); int cost = f.getCount(active) + 1; if (cost > maximumSubsetSize || f.updateToGetFactor(gcd, cost)) { pendingAdd.add(gcd); } } activeNumbers.addAll(pendingAdd); if (activeNumbers.size() > 50) { if (activeNumbers.size() > 500 || fresh == 0) { fresh = 10; f.reduceActiveSetSize(activeNumbers); } else { fresh--; } } } pw.println(f.getCount(1) > maximumSubsetSize ? -1 : f.getCount(1)); } } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); // Scanner sc = new Scanner(new FileInputStream("Test.in")); PrintWriter pw = new PrintWriter(System.out); // PrintWriter pw = new PrintWriter(new FileOutputStream("Test.in")); // PrintWriter pw = new PrintWriter(new FileOutputStream("Test.out")); // int n = 300000; // int sy = 2 * 3 * 5 * 7 * 11; // pw.println(n); // Random rnd = new Random(); // for (int i = 0; i < n - 11; i++) { // pw.println(rnd.nextInt(n / sy - 1) * sy + sy); // } // pw.println(2 * 3 * 5 * 7); // pw.println(2 * 3 * 5 * 11); // pw.println(2 * 3 * 7 * 11); // pw.println(2 * 5 * 7 * 11); // pw.println(3 * 5 * 7 * 11); // // pw.println(3 * 5 * 7 * 11 * 13); // pw.println(3 * 5 * 7 * 11 * 17); // pw.println(3 * 5 * 7 * 11 * 19); // pw.println(3 * 5 * 7 * 11 * 23); // pw.println(3 * 5 * 7 * 11 * 29); // // pw.println(3 * 5 * 7); // // pw.close(); Runtime runtime = Runtime.getRuntime(); long usedMemoryBefore = runtime.totalMemory() - runtime.freeMemory(); TIME_START = System.currentTimeMillis(); Task t = new Task(); t.solve(sc, pw); TIME_END = System.currentTimeMillis(); long usedMemoryAfter = runtime.totalMemory() - runtime.freeMemory(); pw.close(); System.out.println("Memory increased:" + (usedMemoryAfter - usedMemoryBefore) / 1000000); System.out.println("Time used: " + (TIME_END - TIME_START) + "."); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader s) throws FileNotFoundException { br = new BufferedReader(s); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["3\n10 6 15", "3\n2 4 6", "7\n30 60 21 42 70 15 30"]
3 seconds
["3", "-1", "3"]
NoteIn the first example, selecting a subset of all numbers gives a gcd of $$$1$$$ and for all smaller subsets the gcd is greater than $$$1$$$.In the second example, for all subsets of numbers the gcd is at least $$$2$$$.
Java 8
standard input
[ "dp", "combinatorics", "number theory", "bitmasks", "shortest paths", "math" ]
3baa00206d3bf03ce02a414747e2a633
The first line contains an only integer $$$n$$$ ($$$1 \le n \le 300\,000$$$)Β β€” the number of integers in the sequence. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 300\,000$$$).
2,500
If there is no subset of the given sequence with gcd equal to $$$1$$$, output -1. Otherwise, output exactly one integerΒ β€” the size of the smallest subset with gcd equal to $$$1$$$.
standard output
PASSED
368de4d3913800438eecca500658c34e
train_000.jsonl
1540740900
Janusz is a businessman. He owns a company "Januszex", which produces games for teenagers. Last hit of Januszex was a cool one-person game "Make it one". The player is given a sequence of $$$n$$$ integers $$$a_i$$$.It is allowed to select any subset of them, and the score is equal to the greatest common divisor of selected elements. The goal is to take as little elements as it is possible, getting the score $$$1$$$. Now Janusz wonders, for given sequence, how much elements should the player choose?
256 megabytes
/** * BaZ :D */ import java.util.*; import java.io.*; import static java.lang.Math.*; public class Main { static Reader scan; static PrintWriter pw; static long MOD = 1_000_000_007, temp; static long fact[] = new long[1000001]; static long invfact[] = new long[1000001]; static long inv[] = new long[1000001]; public static void main(String[] args) { new Thread(null,null,"BaZ",1<<25) { public void run() { try { solve(); } catch(Exception e) { e.printStackTrace(); System.exit(1); } } }.start(); } static void solve() throws IOException { scan = new Reader(); pw = new PrintWriter(System.out,true); StringBuilder sb = new StringBuilder(); fact[0] = fact[1] = inv[1] = invfact[0] = invfact[1] = 1; long q; int r; for(int i=2;i<=1000000;++i) { q = MOD/i; r = (int)MOD%i; inv[i] = (-(q*inv[r])%MOD+MOD)%MOD; fact[i] = (fact[i-1]*i)%MOD; invfact[i] = (invfact[i-1]*inv[i])%MOD; } int freq[] = new int[300001]; int n = ni(); for(int i=0;i<n;++i) { ++freq[ni()]; } int nmul[] = new int[300001]; for(int i=1;i<=300000;++i) { for(int j=i;j<=300000;j+=i) { nmul[i]+=freq[j]; } } long dp[] = new long[300001]; boolean foo = false; for(int sz=1;sz<=10;++sz) { for(int i=300000;i>0;--i) { dp[i] = nCr(nmul[i], sz); for(int k=2*i;k<=300000;k+=i) { dp[i] = (dp[i] - dp[k] + MOD)%MOD; } } if(dp[1]>0) { pl(sz); foo = true; break; } else { for(int i=1;i<=300000;++i) { dp[i] = 0; } } } if(!foo) { pl(-1); } pw.flush(); pw.close(); } static long nCr(int n, int r) { if(r<0 || r>n) { return 0; } temp = fact[n]; temp*=invfact[r]; temp%=MOD; temp*=invfact[n-r]; temp%=MOD; return temp; } static int ni() throws IOException { return scan.nextInt(); } static long nl() throws IOException { return scan.nextLong(); } static double nd() throws IOException { return scan.nextDouble(); } static void pl() { pw.println(); } static void p(Object o) { pw.print(o+" "); } static void pl(Object o) { pw.println(o); } static void psb(StringBuilder sb) { pw.print(sb); } static void pa(String arrayName, Object arr[]) { pl(arrayName+" : "); for(Object o : arr) p(o); pl(); } static void pa(String arrayName, int arr[]) { pl(arrayName+" : "); for(int o : arr) p(o); pl(); } static void pa(String arrayName, long arr[]) { pl(arrayName+" : "); for(long o : arr) p(o); pl(); } static void pa(String arrayName, double arr[]) { pl(arrayName+" : "); for(double o : arr) p(o); pl(); } static void pa(String arrayName, char arr[]) { pl(arrayName+" : "); for(char o : arr) p(o); pl(); } static void pa(String listName, List list) { pl(listName+" : "); for(Object o : list) p(o); pl(); } static void pa(String arrayName, Object[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(Object o : arr[i]) p(o); pl(); } } static void pa(String arrayName, int[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(int o : arr[i]) p(o); pl(); } } static void pa(String arrayName, long[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(long o : arr[i]) p(o); pl(); } } static void pa(String arrayName, char[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(char o : arr[i]) p(o); pl(); } } static void pa(String arrayName, double[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(double o : arr[i]) p(o); pl(); } } 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]; int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') while ((c = read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10); if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } }
Java
["3\n10 6 15", "3\n2 4 6", "7\n30 60 21 42 70 15 30"]
3 seconds
["3", "-1", "3"]
NoteIn the first example, selecting a subset of all numbers gives a gcd of $$$1$$$ and for all smaller subsets the gcd is greater than $$$1$$$.In the second example, for all subsets of numbers the gcd is at least $$$2$$$.
Java 8
standard input
[ "dp", "combinatorics", "number theory", "bitmasks", "shortest paths", "math" ]
3baa00206d3bf03ce02a414747e2a633
The first line contains an only integer $$$n$$$ ($$$1 \le n \le 300\,000$$$)Β β€” the number of integers in the sequence. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 300\,000$$$).
2,500
If there is no subset of the given sequence with gcd equal to $$$1$$$, output -1. Otherwise, output exactly one integerΒ β€” the size of the smallest subset with gcd equal to $$$1$$$.
standard output
PASSED
1f9afe2fec674192d6b3262b604cb3d1
train_000.jsonl
1540740900
Janusz is a businessman. He owns a company "Januszex", which produces games for teenagers. Last hit of Januszex was a cool one-person game "Make it one". The player is given a sequence of $$$n$$$ integers $$$a_i$$$.It is allowed to select any subset of them, and the score is equal to the greatest common divisor of selected elements. The goal is to take as little elements as it is possible, getting the score $$$1$$$. Now Janusz wonders, for given sequence, how much elements should the player choose?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashSet; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.LinkedHashSet; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author prakharjain */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); _1043F solver = new _1043F(); solver.solve(1, in, out); out.close(); } static class _1043F { int max = 0; int mod = 1000000007; int[][] nCr(int n, int r, int mod) { int[][] ncr = new int[n + 1][r + 1]; ncr[0][0] = 1; for (int i = 1; i <= n; i++) { ncr[i][0] = 1; } for (int i = 1; i <= n; i++) { for (int j = 1; j <= r; j++) { ncr[i][j] = ncr[i - 1][j - 1] + ncr[i - 1][j]; ncr[i][j] %= mod; } } return ncr; } public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int[] a = new int[n]; in.readArray(a, n, 0); LinkedHashSet<Integer> lhs = new LinkedHashSet<>(); for (int val : a) { lhs.add(val); max = Math.max(max, val); } n = lhs.size(); //int[] mobius = mobius(max); int[][] ncr = nCr(max, 7, mod); long[][] dp = new long[8][max + 1]; for (int i = max; i >= 1; i--) { int num = 0; for (int j = 1; j * i <= max; j++) { if (lhs.contains(j * i)) { num++; } } for (int j = 1; j <= 7; j++) { dp[j][i] = ncr[num][j]; for (int k = 2; k * i <= max; k++) { dp[j][i] -= dp[j][i * k]; dp[j][i] %= mod; } } } for (int j = 1; j <= 7; j++) { if (dp[j][1] != 0) { out.println(j); return; } } out.println(-1); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void println(int i) { writer.println(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public void readArray(int[] a, int n, int offset) { for (int i = 0; i < n; i++) { a[i] = nextInt() - offset; } } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["3\n10 6 15", "3\n2 4 6", "7\n30 60 21 42 70 15 30"]
3 seconds
["3", "-1", "3"]
NoteIn the first example, selecting a subset of all numbers gives a gcd of $$$1$$$ and for all smaller subsets the gcd is greater than $$$1$$$.In the second example, for all subsets of numbers the gcd is at least $$$2$$$.
Java 8
standard input
[ "dp", "combinatorics", "number theory", "bitmasks", "shortest paths", "math" ]
3baa00206d3bf03ce02a414747e2a633
The first line contains an only integer $$$n$$$ ($$$1 \le n \le 300\,000$$$)Β β€” the number of integers in the sequence. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 300\,000$$$).
2,500
If there is no subset of the given sequence with gcd equal to $$$1$$$, output -1. Otherwise, output exactly one integerΒ β€” the size of the smallest subset with gcd equal to $$$1$$$.
standard output
PASSED
6dc8f3708279b1a2915f9ca1c4851c27
train_000.jsonl
1540740900
Janusz is a businessman. He owns a company "Januszex", which produces games for teenagers. Last hit of Januszex was a cool one-person game "Make it one". The player is given a sequence of $$$n$$$ integers $$$a_i$$$.It is allowed to select any subset of them, and the score is equal to the greatest common divisor of selected elements. The goal is to take as little elements as it is possible, getting the score $$$1$$$. Now Janusz wonders, for given sequence, how much elements should the player choose?
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.lang.*; import static java.lang.Math.*; public class Main implements Runnable { 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 Main(),"Main",1<<26).start(); } void solve2(int level, int val, int termParity, int ind) { if(level == pList.size()) { if(val == 1) return; if(termParity == 1) dp[ind] += cnt[val]; else dp[ind] -= cnt[val]; return; } solve2(level + 1, val, termParity, ind); solve2(level + 1, val * pList.get(level), termParity ^ 1, ind); } void solve3(int level, int val1, int val2, int ind) { if(level == pList.size()) { if(val2 == 1) return; if(dp2[val1] != -1 && dp[val2] != n) { if(dp2[ind] == -1) dp2[ind] = dp2[val1] + 1; else dp2[ind] = min(dp2[ind], dp2[val1] + 1); } return; } solve3(level + 1, val1, val2, ind); solve3(level + 1, val1 * pList.get(level), val2 / pList.get(level), ind); } void solve(int level, int val) { if(level == pList.size()) { cnt[val]++; return; } solve(level + 1, val); solve(level + 1, val * pList.get(level)); } ArrayList<Integer> pList = new ArrayList<>(); int cnt[] = new int[300001]; int sieve[] = new int[300001]; int dp[] = new int[300001]; int dp2[] = new int[300001]; int n; public void run() { InputReader sc = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); n = sc.nextInt(); int a[] = new int[n]; for(int i = 0; i < n; ++i) a[i] = sc.nextInt(); for(int i = 2; i <= 300000; ++i) { if(sieve[i] == 0) { for(int j = i; j <= 300000; j += i) sieve[j] = i; } } for(int i = 0; i < n; ++i) { pList.clear(); int temp = a[i]; while(temp != 1) { int curP = sieve[temp]; pList.add(curP); while(temp % curP == 0) temp /= curP; } solve(0, 1); } for(int i = 1; i <= 300000; ++i) { pList.clear(); int temp = i; while(temp != 1) { int curP = sieve[temp]; pList.add(curP); while(temp % curP == 0) temp /= curP; } solve2(0, 1, 0, i); //if(i <= 10) //System.out.println(i + " " + dp[i] + " " + cnt[i]); } dp2 = new int[300001]; Arrays.fill(dp2, -1); dp2[1] = 0; for(int i = 2; i <= 300000; ++i) { pList.clear(); int temp = i; while(temp != 1) { int curP = sieve[temp]; pList.add(curP); while(temp % curP == 0) temp /= curP; } int fullVal = 1; for(int j : pList) fullVal *= j; solve3(0, 1, fullVal, i); } int ans = -1; for(int i = 0; i < n; ++i) { if(dp2[a[i]] != -1) { if(ans == -1) ans = dp2[a[i]] + 1; else ans = min(ans, dp2[a[i]] + 1); } } w.print(ans); w.close(); } }
Java
["3\n10 6 15", "3\n2 4 6", "7\n30 60 21 42 70 15 30"]
3 seconds
["3", "-1", "3"]
NoteIn the first example, selecting a subset of all numbers gives a gcd of $$$1$$$ and for all smaller subsets the gcd is greater than $$$1$$$.In the second example, for all subsets of numbers the gcd is at least $$$2$$$.
Java 8
standard input
[ "dp", "combinatorics", "number theory", "bitmasks", "shortest paths", "math" ]
3baa00206d3bf03ce02a414747e2a633
The first line contains an only integer $$$n$$$ ($$$1 \le n \le 300\,000$$$)Β β€” the number of integers in the sequence. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 300\,000$$$).
2,500
If there is no subset of the given sequence with gcd equal to $$$1$$$, output -1. Otherwise, output exactly one integerΒ β€” the size of the smallest subset with gcd equal to $$$1$$$.
standard output
PASSED
34cadfc1e1e85625ad7bd8640e76406c
train_000.jsonl
1540740900
Janusz is a businessman. He owns a company "Januszex", which produces games for teenagers. Last hit of Januszex was a cool one-person game "Make it one". The player is given a sequence of $$$n$$$ integers $$$a_i$$$.It is allowed to select any subset of them, and the score is equal to the greatest common divisor of selected elements. The goal is to take as little elements as it is possible, getting the score $$$1$$$. Now Janusz wonders, for given sequence, how much elements should the player choose?
256 megabytes
//package round519; 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 F { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(); int[] a = na(n); int g = 0; for(int v : a)g = gcd(g, v); if(g > 1){ out.println(-1); return; } int Q = 300001; long[] f = new long[Q]; for(int v : a)f[v] = 1; int[] lpf = enumLowestPrimeFactors(Q+3); int[] mob = enumMobiusByLPF(Q+2, lpf); for(int i = 1;i < Q;i++){ for(int j = 2*i;j < Q;j+=i){ f[i] += f[j]; } } for(int d = 1;;d++){ long val = 0; for(int i = 1;i < Q;i++){ long v = 1; for(int j = 0;j < d;j++){ v = v * (f[i]-j) / (j+1); } val += mob[i] * v; } if(val != 0){ out.println(d); return; } } } public static int[] enumMobiusByLPF(int n, int[] lpf) { int[] mob = new int[n+1]; mob[1] = 1; for(int i = 2;i <= n;i++){ int j = i/lpf[i]; if(lpf[j] == lpf[i]){ // mob[i] = 0; }else{ mob[i] = -mob[j]; } } return mob; } public static int[] enumLowestPrimeFactors(int n) { int tot = 0; int[] lpf = new int[n + 1]; int u = n + 32; double lu = Math.log(u); int[] primes = new int[(int) (u / lu + u / lu / lu * 1.5)]; for (int i = 2; i <= n; i++) lpf[i] = i; for (int p = 2; p <= n; p++) { if (lpf[p] == p) primes[tot++] = p; int tmp; for (int i = 0; i < tot && primes[i] <= lpf[p] && (tmp = primes[i] * p) <= n; i++) { lpf[tmp] = primes[i]; } } return lpf; } public static int gcd(int a, int b) { while (b > 0) { int 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 F().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\n10 6 15", "3\n2 4 6", "7\n30 60 21 42 70 15 30"]
3 seconds
["3", "-1", "3"]
NoteIn the first example, selecting a subset of all numbers gives a gcd of $$$1$$$ and for all smaller subsets the gcd is greater than $$$1$$$.In the second example, for all subsets of numbers the gcd is at least $$$2$$$.
Java 8
standard input
[ "dp", "combinatorics", "number theory", "bitmasks", "shortest paths", "math" ]
3baa00206d3bf03ce02a414747e2a633
The first line contains an only integer $$$n$$$ ($$$1 \le n \le 300\,000$$$)Β β€” the number of integers in the sequence. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 300\,000$$$).
2,500
If there is no subset of the given sequence with gcd equal to $$$1$$$, output -1. Otherwise, output exactly one integerΒ β€” the size of the smallest subset with gcd equal to $$$1$$$.
standard output
PASSED
f8083a7927b48331f77991094331cacc
train_000.jsonl
1540740900
Janusz is a businessman. He owns a company "Januszex", which produces games for teenagers. Last hit of Januszex was a cool one-person game "Make it one". The player is given a sequence of $$$n$$$ integers $$$a_i$$$.It is allowed to select any subset of them, and the score is equal to the greatest common divisor of selected elements. The goal is to take as little elements as it is possible, getting the score $$$1$$$. Now Janusz wonders, for given sequence, how much elements should the player choose?
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class A { public static void main (String[] args) { new A(); } Random rand = new Random(); int MOD = BigInteger.valueOf(1000000000 + rand.nextInt(100000000)).nextProbablePrime().intValue(); int MAX = 300300; int[] fact, invFact; A() { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); System.err.println(""); build(); int n = fs.nextInt(), g = 0; int[] a = new int[n]; int[] freq = new int[MAX]; for(int i = 0; i < n; i++) { a[i] = fs.nextInt(); g = gcd(g, a[i]); if(a[i] == 1) { System.out.println(1); return; } freq[a[i]]++; } if(g != 1) { System.out.println(-1); return; } int[] cnts = new int[MAX]; for(int i = 1; i < MAX; i++) { for(int j = i; j < MAX; j += i) cnts[i] += freq[j]; } int[] ways = new int[MAX]; for(int moves = 2; moves <= 7; moves++) { for(int gcd = MAX-1; gcd >= 1; gcd--) { if(cnts[gcd] < moves) { ways[gcd] = 0; continue; } ways[gcd] = nChooseK(cnts[gcd], moves); int cur = 2*gcd; while(cur < MAX) { ways[gcd] = sub(ways[gcd], ways[cur]); cur += gcd; } } if(ways[1] != 0) { System.out.println(moves); return; } } out.close(); } int nChooseK(int n, int k) { return mult(fact[n], mult(invFact[k], invFact[n-k])); } int gcd(int a, int b) { if(b == 0) return a; return gcd(b, a % b); } void build() { fact = new int[MAX]; fact[0] = fact[1] = 1; for(int i = 2; i < MAX; i++) { fact[i] = mult(i, fact[i-1]); } int[] invs = new int[MAX]; invs[0] = invs[1] = 1; for (int i = 2; i < invs.length; i++) { invs[i] = mult(MOD - MOD / i, invs[MOD % i]); } invFact = new int[MAX]; invFact[0] = invs[0]; invFact[1] = invs[1]; for(int i = 2; i < MAX; i++) { invFact[i] = mult(invFact[i-1], invs[i]); } } int mult(long a, long b) { return (int)(a*b % MOD); } int sub(int a, int b) { a -= b; if(a < 0) a += MOD; return a; } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(){ br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(""); } String next() { if(st.hasMoreTokens()) return st.nextToken(); try { st = new StringTokenizer(br.readLine()); } catch (Exception e) {} return next(); } int nextInt() { return Integer.parseInt(next()); } } }
Java
["3\n10 6 15", "3\n2 4 6", "7\n30 60 21 42 70 15 30"]
3 seconds
["3", "-1", "3"]
NoteIn the first example, selecting a subset of all numbers gives a gcd of $$$1$$$ and for all smaller subsets the gcd is greater than $$$1$$$.In the second example, for all subsets of numbers the gcd is at least $$$2$$$.
Java 8
standard input
[ "dp", "combinatorics", "number theory", "bitmasks", "shortest paths", "math" ]
3baa00206d3bf03ce02a414747e2a633
The first line contains an only integer $$$n$$$ ($$$1 \le n \le 300\,000$$$)Β β€” the number of integers in the sequence. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 300\,000$$$).
2,500
If there is no subset of the given sequence with gcd equal to $$$1$$$, output -1. Otherwise, output exactly one integerΒ β€” the size of the smallest subset with gcd equal to $$$1$$$.
standard output
PASSED
457a68cb14105fb271b686b023b76273
train_000.jsonl
1540740900
Janusz is a businessman. He owns a company "Januszex", which produces games for teenagers. Last hit of Januszex was a cool one-person game "Make it one". The player is given a sequence of $$$n$$$ integers $$$a_i$$$.It is allowed to select any subset of them, and the score is equal to the greatest common divisor of selected elements. The goal is to take as little elements as it is possible, getting the score $$$1$$$. Now Janusz wonders, for given sequence, how much elements should the player choose?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author lewin */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); FMakeItOne solver = new FMakeItOne(); solver.solve(1, in, out); out.close(); } static class FMakeItOne { int maxn = 300010; public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int[] arr = in.readIntArray(n); int gcd = arr[0]; for (int i = 1; i < n; i++) { gcd = Utils.gcd(arr[i], gcd); } if (gcd != 1) { out.println(-1); return; } arr = AUtils.unique(arr); n = arr.length; long[] count = new long[maxn]; for (int x : arr) count[x]++; if (count[1] > 0) { out.println(1); return; } for (int i = 1; i < maxn; i++) { for (int j = i + i; j < maxn; j += i) { count[i] += count[j]; } } long[] r = Arrays.copyOf(count, maxn); int ans = 1; while (true) { for (int j = 1; j < maxn; j++) { r[j] = r[j] * count[j]; } long[] tmp = Arrays.copyOf(r, maxn); for (int i = maxn - 1; i >= 1; i--) { for (int j = i + i; j < maxn; j += i) { tmp[i] -= tmp[j]; } } ans++; if (tmp[1] != 0) break; } out.println(ans); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void println(int i) { writer.println(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1 << 20]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int[] readIntArray(int tokens) { int[] ret = new int[tokens]; for (int i = 0; i < tokens; i++) { ret[i] = nextInt(); } return ret; } public int read() { if (this.numChars == -1) { throw new InputMismatchException(); } else { if (this.curChar >= this.numChars) { this.curChar = 0; try { this.numChars = this.stream.read(this.buf); } catch (IOException var2) { throw new InputMismatchException(); } if (this.numChars <= 0) { return -1; } } return this.buf[this.curChar++]; } } public int nextInt() { int c; for (c = this.read(); isSpaceChar(c); c = this.read()) { ; } byte sgn = 1; if (c == 45) { sgn = -1; c = this.read(); } int res = 0; while (c >= 48 && c <= 57) { res *= 10; res += c - 48; c = this.read(); if (isSpaceChar(c)) { return res * sgn; } } throw new InputMismatchException(); } public static boolean isSpaceChar(int c) { return c == 32 || c == 10 || c == 13 || c == 9 || c == -1; } } static class AUtils { public static void sort(int[] arr) { for (int i = 1; i < arr.length; i++) { int j = (int) (Math.random() * (i + 1)); if (i != j) { int t = arr[i]; arr[i] = arr[j]; arr[j] = t; } } Arrays.sort(arr); } public static int[] unique(int[] a) { a = a.clone(); sort(a); int sz = 1; for (int i = 1; i < a.length; i++) { if (a[i] != a[sz - 1]) { a[sz++] = a[i]; } } return Arrays.copyOf(a, sz); } } static class Utils { public static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } } }
Java
["3\n10 6 15", "3\n2 4 6", "7\n30 60 21 42 70 15 30"]
3 seconds
["3", "-1", "3"]
NoteIn the first example, selecting a subset of all numbers gives a gcd of $$$1$$$ and for all smaller subsets the gcd is greater than $$$1$$$.In the second example, for all subsets of numbers the gcd is at least $$$2$$$.
Java 8
standard input
[ "dp", "combinatorics", "number theory", "bitmasks", "shortest paths", "math" ]
3baa00206d3bf03ce02a414747e2a633
The first line contains an only integer $$$n$$$ ($$$1 \le n \le 300\,000$$$)Β β€” the number of integers in the sequence. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 300\,000$$$).
2,500
If there is no subset of the given sequence with gcd equal to $$$1$$$, output -1. Otherwise, output exactly one integerΒ β€” the size of the smallest subset with gcd equal to $$$1$$$.
standard output
PASSED
aca48f99fc4a536d6ae96c8907876790
train_000.jsonl
1540740900
Janusz is a businessman. He owns a company "Januszex", which produces games for teenagers. Last hit of Januszex was a cool one-person game "Make it one". The player is given a sequence of $$$n$$$ integers $$$a_i$$$.It is allowed to select any subset of them, and the score is equal to the greatest common divisor of selected elements. The goal is to take as little elements as it is possible, getting the score $$$1$$$. Now Janusz wonders, for given sequence, how much elements should the player choose?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.FilterInputStream; import java.io.BufferedInputStream; import java.io.InputStream; /** * @author khokharnikunj8 */ public class Main { public static void main(String[] args) { new Thread(null, new Runnable() { public void run() { new Main().solve(); } }, "1", 1 << 26).start(); } void solve() { InputStream inputStream = System.in; OutputStream outputStream = System.out; ScanReader in = new ScanReader(inputStream); PrintWriter out = new PrintWriter(outputStream); FMakeItOne solver = new FMakeItOne(); solver.solve(1, in, out); out.close(); } static class FMakeItOne { long mod = 1000000009; long[] fact; long findIt(long n, long r) { if (r > n) return 0; return (fact[(int) n] * CodeHash.modInverse((fact[(int) (n - r)] * fact[(int) r]) % mod, mod)) % mod; } public void solve(int testNumber, ScanReader in, PrintWriter out) { fact = new long[300005]; fact[0] = 1; for (int i = 1; i < 300005; i++) fact[i] = (fact[i - 1] * i) % mod; long[][] dp = new long[8][300005]; int n = in.scanInt(); int[] ar = new int[n]; int[] cnt = new int[300005]; long gcd = ar[0] = in.scanInt(); cnt[ar[0]]++; for (int i = 1; i < n; i++) { ar[i] = in.scanInt(); gcd = CodeHash.gcd(gcd, ar[i]); cnt[ar[i]]++; } if (gcd != 1) { out.println(-1); return; } for (int i = 1; i <= 300000; i++) for (int j = 2 * i; j <= 300000; j += i) cnt[i] += cnt[j]; for (int i = 1; i < 8; i++) { for (int j = 300000; j >= 1; j--) { dp[i][j] = findIt(cnt[j], i) % mod; for (int k = 2 * j; k <= 300000; k += j) dp[i][j] = (mod - dp[i][k] + dp[i][j]) % mod; } if (dp[i][1] != 0) { out.println(i); return; } } throw new RuntimeException("NONONO"); } } static class CodeHash { public static long[] euclidExtended(long a, long b) { if (b == 0) { long ar[] = new long[]{1, 0}; return ar; } long ar[] = euclidExtended(b, a % b); long temp = ar[0]; ar[0] = ar[1]; ar[1] = temp - (a / b) * ar[1]; return ar; } public static long modInverse(long a, long m) { long ar[] = euclidExtended(a, m); return ((ar[0] % m) + m) % m; } public static long gcd(long a, long b) { if (b == 0) return a; else return gcd(b, a % b); } } static class ScanReader { private byte[] buf = new byte[4 * 1024]; private int index; private BufferedInputStream in; private int total; public ScanReader(InputStream inputStream) { in = new BufferedInputStream(inputStream); } private int scan() { if (index >= total) { index = 0; try { total = in.read(buf); } catch (Exception e) { e.printStackTrace(); } if (total <= 0) return -1; } return buf[index++]; } public int scanInt() { int integer = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { integer *= 10; integer += n - '0'; n = scan(); } } return neg * integer; } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; else return false; } } }
Java
["3\n10 6 15", "3\n2 4 6", "7\n30 60 21 42 70 15 30"]
3 seconds
["3", "-1", "3"]
NoteIn the first example, selecting a subset of all numbers gives a gcd of $$$1$$$ and for all smaller subsets the gcd is greater than $$$1$$$.In the second example, for all subsets of numbers the gcd is at least $$$2$$$.
Java 8
standard input
[ "dp", "combinatorics", "number theory", "bitmasks", "shortest paths", "math" ]
3baa00206d3bf03ce02a414747e2a633
The first line contains an only integer $$$n$$$ ($$$1 \le n \le 300\,000$$$)Β β€” the number of integers in the sequence. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 300\,000$$$).
2,500
If there is no subset of the given sequence with gcd equal to $$$1$$$, output -1. Otherwise, output exactly one integerΒ β€” the size of the smallest subset with gcd equal to $$$1$$$.
standard output
PASSED
411c392e97db0926560b793910b92c0b
train_000.jsonl
1540740900
Janusz is a businessman. He owns a company "Januszex", which produces games for teenagers. Last hit of Januszex was a cool one-person game "Make it one". The player is given a sequence of $$$n$$$ integers $$$a_i$$$.It is allowed to select any subset of them, and the score is equal to the greatest common divisor of selected elements. The goal is to take as little elements as it is possible, getting the score $$$1$$$. Now Janusz wonders, for given sequence, how much elements should the player choose?
256 megabytes
//package que_a; import java.io.*; import java.util.*; import java.math.*; public class utkarsh { InputStream is; PrintWriter out; long mod = (long) (1e9 + 7), inf = (long) (3e18); void solve() { int n = ni(); int a[] = na(n); int gcd = a[0]; for(int x : a) gcd = gcd(gcd, x); if(gcd > 1) { out.println(-1); return; } int z = 300300; int spf[] = new int[z]; for(int i = 0; i < z; i++) spf[i] = i; for(int i = 2; i*i < z; i++) { if(spf[i] != i) continue; for(int j = i*i; j < z; j += i) { if(spf[j] == j) spf[j] = i; } } ArrayList <Integer> d[] = new ArrayList[n]; int h[] = new int[z]; for(int i = 0; i < n; i++) { d[i] = new ArrayList<>(); int x = a[i]; h[x] = 1; while(x > 1) { d[i].add(spf[x]); int u = spf[x]; while(spf[x] == u) x /= spf[x]; } } for(int i = 1; i < z; i++) { for(int j = i+i; j < z; j += i) { h[i] += h[j]; // count of multiples of i present in the array } } int ans = 7; for(int i = 0; i < n; i++) { int sz = d[i].size(); int dp[] = new int[1 << sz]; for(int k = 0; k < (1 << sz); k++) { int u = 1; for(int j = 0; j < sz; j++) { if(((k >> j) & 1) == 1) u *= d[i].get(j); } dp[k] = h[u]; } for(int j = 0; j < sz; j++) { for(int k = 0; k < (1 << sz); k++) { if(((k >> j) & 1) == 1) dp[k ^ (1 << j)] -= dp[k]; } } for(int j = 0; j < sz; j++) { for(int k = 0; k < (1 << sz); k++) { if(((k >> j) & 1) == 1) dp[k] += dp[k ^ (1 << j)]; } } int ap[] = new int[1 << sz]; ap[0] = 1; for(int k = 1; k < (1 << sz); k++) { ap[k] = n+1; int u = k; while(u > 0) { if(dp[(1 << sz) - 1 - u] > 0) ap[k] = Math.min(ap[k], ap[k - u] + 1); u = (u - 1) & k; } } ans = Math.min(ans, ap[(1 << sz) - 1]); } out.println(ans); } int gcd(int a, int b) { if(b == 0) return a; return gcd(b, a%b); } long mp(long b, long e) { long r = 1; while(e > 0) { if((e&1) == 1) r = (r * b) % mod; b = (b * b) % mod; e >>= 1; } return r; } //---------- I/O Template ---------- public static void main(String[] args) { new utkarsh().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
["3\n10 6 15", "3\n2 4 6", "7\n30 60 21 42 70 15 30"]
3 seconds
["3", "-1", "3"]
NoteIn the first example, selecting a subset of all numbers gives a gcd of $$$1$$$ and for all smaller subsets the gcd is greater than $$$1$$$.In the second example, for all subsets of numbers the gcd is at least $$$2$$$.
Java 8
standard input
[ "dp", "combinatorics", "number theory", "bitmasks", "shortest paths", "math" ]
3baa00206d3bf03ce02a414747e2a633
The first line contains an only integer $$$n$$$ ($$$1 \le n \le 300\,000$$$)Β β€” the number of integers in the sequence. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 300\,000$$$).
2,500
If there is no subset of the given sequence with gcd equal to $$$1$$$, output -1. Otherwise, output exactly one integerΒ β€” the size of the smallest subset with gcd equal to $$$1$$$.
standard output
PASSED
09085302c5da533209da4defb95ae4e0
train_000.jsonl
1540740900
Janusz is a businessman. He owns a company "Januszex", which produces games for teenagers. Last hit of Januszex was a cool one-person game "Make it one". The player is given a sequence of $$$n$$$ integers $$$a_i$$$.It is allowed to select any subset of them, and the score is equal to the greatest common divisor of selected elements. The goal is to take as little elements as it is possible, getting the score $$$1$$$. Now Janusz wonders, for given sequence, how much elements should the player choose?
256 megabytes
import java.lang.*; import java.math.*; import java.util.*; import java.io.*; public class Main { void solve() { int n=ni(); HashSet<Integer>hs=new HashSet<>(); for(int i=1;i<=n;i++){ int a=ni(); int num=1; for(int j=2;j*j<=a;j++){ if(a%j==0){ while(a%j==0){ a/=j; } num*=j; } } num*=a; hs.add(num); } int cnt[]=new int[MX+1]; for(int u : hs) { cnt[u] = 1; // pw.println(u); } for(int i=1;i<=MX;i++){ for(int j=2*i;j<=MX;j+=i) cnt[i]+=cnt[j]; } // for(int i=1;i<=MX;i++) if(cnt[i]>0) pw.println(i+" "+cnt[i]); long dp[]=new long[MX+1]; precompute(); for(int i=1;i<=7;i++){ Arrays.fill(dp,0); for(int j=MX;j>=1;j--){ //if(cnt[j]>MX) System.out.println(j+" "+cnt[j]); dp[j]=ncr(cnt[j],i); for(int k=2;k*j<=MX;k++){ dp[j]=sub(dp[j],dp[k*j]); } } if(dp[1]>0){ pw.println(i); return; } } pw.println("-1"); } long fact[]; long inv[]; int MX=300000; long ncr(int n,int r){ if(r>n) return 0; long ans=fact[n]; ans=mul(ans,inv[r]); ans=mul(ans,inv[n-r]); return ans; } void precompute(){ fact=new long[MX+1]; inv=new long[MX+1]; fact[0]=1; for(int i=1;i<=MX;i++) fact[i]=(fact[i-1]*i)%M; inv[MX]=modInverse(fact[MX],M); for(int i=MX-1;i>=0;i--){ inv[i]=mul(inv[i+1],i+1); } } long add(long x,long y){ x+=y; if(x>=M) x-=M; return x; } long sub(long x,long y){ x-=y; if(x<0) x+=M; return x; } long mul(long x,long y){ x*=y; if(x>=M) x%=M; return x; } long modpow(long a, long b) { long r=1; while(b>0) { if((b&1)>0) r=mul(r,a); a=mul(a,a); b>>=1; } return r; } long modInverse(long A, long M) { return modpow(A,M-2); } long M= (long)1e9+7; InputStream is; PrintWriter pw; String INPUT = ""; void run() throws Exception { is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); pw = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); pw.flush(); if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new Main().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(INPUT.length() > 0)System.out.println(Arrays.deepToString(o)); } }
Java
["3\n10 6 15", "3\n2 4 6", "7\n30 60 21 42 70 15 30"]
3 seconds
["3", "-1", "3"]
NoteIn the first example, selecting a subset of all numbers gives a gcd of $$$1$$$ and for all smaller subsets the gcd is greater than $$$1$$$.In the second example, for all subsets of numbers the gcd is at least $$$2$$$.
Java 8
standard input
[ "dp", "combinatorics", "number theory", "bitmasks", "shortest paths", "math" ]
3baa00206d3bf03ce02a414747e2a633
The first line contains an only integer $$$n$$$ ($$$1 \le n \le 300\,000$$$)Β β€” the number of integers in the sequence. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 300\,000$$$).
2,500
If there is no subset of the given sequence with gcd equal to $$$1$$$, output -1. Otherwise, output exactly one integerΒ β€” the size of the smallest subset with gcd equal to $$$1$$$.
standard output
PASSED
4901c3a8cbc837be2d00611ae622b539
train_000.jsonl
1540740900
Janusz is a businessman. He owns a company "Januszex", which produces games for teenagers. Last hit of Januszex was a cool one-person game "Make it one". The player is given a sequence of $$$n$$$ integers $$$a_i$$$.It is allowed to select any subset of them, and the score is equal to the greatest common divisor of selected elements. The goal is to take as little elements as it is possible, getting the score $$$1$$$. Now Janusz wonders, for given sequence, how much elements should the player choose?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskF solver = new TaskF(); solver.solve(1, in, out); out.close(); } static class TaskF { int MAX_DIVISORS = 6; int INF = (int) 1e9; public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int[] a = new int[n]; int maxa = 1; for (int i = 0; i < n; ++i) { a[i] = in.nextInt(); maxa = Math.max(maxa, a[i]); } int[] divisor = new int[maxa + 1]; for (int i = 2; i <= maxa; ++i) if (divisor[i] == 0) { divisor[i] = i; for (int j = 2 * i; j <= maxa; j += i) if (divisor[j] == 0) divisor[j] = i; } for (int i = 0; i < n; ++i) { int q = a[i]; int p = 1; while (q > 1) { int d = divisor[q]; while (q % d == 0) { q /= d; } p *= d; } a[i] = p; } int[] count = new int[maxa + 1]; for (int x : a) ++count[x]; for (int d = 2; d <= maxa; ++d) if (divisor[d] == d) { for (int i = d; i <= maxa; i += d) count[i / d] += count[i]; } int[] curDivisors = new int[MAX_DIVISORS]; int[] curProd = new int[1 << MAX_DIVISORS]; int[] curCount = new int[1 << MAX_DIVISORS]; int[] minOps = new int[1 << MAX_DIVISORS]; int res = INF; for (int first = 0; first < n; ++first) { int f = a[first]; int k = 0; while (f > 1) { curDivisors[k++] = divisor[f]; f /= divisor[f]; } for (int set = 0; set < (1 << k); ++set) { int prod = 1; if (set > 0) { int tz = Integer.numberOfTrailingZeros(set); prod = curProd[set ^ (1 << tz)] * curDivisors[tz]; } curProd[set] = prod; curCount[set] = count[prod]; } for (int bit = 0; bit < k; ++bit) { for (int i = 0; i < (1 << k); ++i) { if ((i & (1 << bit)) == 0) { curCount[i] -= curCount[i ^ (1 << bit)]; } } } Arrays.fill(minOps, INF); for (int i = 0; i < (1 << k); ++i) { if (curCount[i] > 0) minOps[(1 << k) - 1 - i] = 1; } for (int bit = 0; bit < k; ++bit) { for (int i = 0; i < (1 << k); ++i) { if ((i & (1 << bit)) == 0) { if (minOps[i ^ (1 << bit)] == 1) minOps[i] = 1; } } } minOps[0] = 0; for (int i = 1; i < (1 << k); ++i) { for (int j = (i - 1) & i; j > 0; j = (j - 1) & i) { minOps[i] = Math.min(minOps[i], minOps[j] + minOps[i ^ j]); } } res = Math.min(res, 1 + minOps[(1 << k) - 1]); } if (res >= INF) { out.println(-1); } else { out.println(res); } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["3\n10 6 15", "3\n2 4 6", "7\n30 60 21 42 70 15 30"]
3 seconds
["3", "-1", "3"]
NoteIn the first example, selecting a subset of all numbers gives a gcd of $$$1$$$ and for all smaller subsets the gcd is greater than $$$1$$$.In the second example, for all subsets of numbers the gcd is at least $$$2$$$.
Java 8
standard input
[ "dp", "combinatorics", "number theory", "bitmasks", "shortest paths", "math" ]
3baa00206d3bf03ce02a414747e2a633
The first line contains an only integer $$$n$$$ ($$$1 \le n \le 300\,000$$$)Β β€” the number of integers in the sequence. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 300\,000$$$).
2,500
If there is no subset of the given sequence with gcd equal to $$$1$$$, output -1. Otherwise, output exactly one integerΒ β€” the size of the smallest subset with gcd equal to $$$1$$$.
standard output
PASSED
f30c1a3d211a17086b7a46cf3d5317bf
train_000.jsonl
1277823600
Bob got a job as a system administrator in X corporation. His first task was to connect n servers with the help of m two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of servers should have at most one direct connection. Y corporation, a business rival of X corporation, made Bob an offer that he couldn't refuse: Bob was asked to connect the servers in such a way, that when server with index v fails, the transmission of data between some other two servers becomes impossible, i.e. the system stops being connected. Help Bob connect the servers.
256 megabytes
import java.util.*; import java.io.*; public class Main { // static LinkedList<Integer> adj[]; // static boolean cats[]; // static boolean visited[]; public static void main(String[] args) { FastScanner sc = new FastScanner(); long n = sc.nextLong(); long m = sc.nextLong(); long v = sc.nextLong(); ArrayList<pair> vector = new ArrayList<pair>(); long lim = ((n - 2) * (n - 3) / 2) + n - 1; if(m < (n - 1) || m > lim) System.out.println("-1"); else { for(int i = 1; i <= n; i++) { if(i != v) { vector.add(new pair(i, v)); } } m -= (n - 1); int start = 1; if(start == v) start++; for(int i = 1; i <= n && m > 0; i++) { if(i == start || i == v) continue; for(int j = i + 1; j <= n && m > 0; j++) { if(j == start || j == v) continue; vector.add(new pair(i, j)); m--; } } // while(m > 0) // { // vector.add(new pair(x, y)); // m--; // y++; // if(y == v) // y++; // if(y > n) // { // if((x + 1) == v) // x += 2; // else // { // x++; // y = x + 1; // } // } // // } for(int i = 0; i < vector.size(); i++) System.out.println(vector.get(i).first + " " + vector.get(i).second); // for(int i = 1; i <= m; i++) // { // if(i == v) // continue; // // } } } public static class pair { long first; long second; public pair(long f, long s) { first = f; second = s; } } // public static void addEdge(int a, int b) // { // adj[a].add(b); // adj[b].add(a); // } // public static int dfs(int pos, int count, int lim) // { // if(cats[pos]) // count++; // else // count = 0; // if(count > lim || visited[pos]) // return 0; // visited[pos] = true; // if(pos > 1 && adj[pos].size() == 1) //if leaf // return 1; // int ans = 0; // for(int i = 0; i < adj[pos].size(); i++) // ans += dfs(adj[pos].get(i), count, lim); // return ans; // // } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["5 6 3", "6 100 1"]
1 second
["1 2\n2 3\n3 4\n4 5\n1 3\n3 5", "-1"]
null
Java 8
standard input
[ "graphs" ]
959709bfe7b26a4b9f2e7430350650a9
The first input line contains 3 space-separated integer numbers n, m, v (3 ≀ n ≀ 105, 0 ≀ m ≀ 105, 1 ≀ v ≀ n), n β€” amount of servers, m β€” amount of direct connections, v β€” index of the server that fails and leads to the failure of the whole system.
1,700
If it is impossible to connect the servers in the required way, output -1. Otherwise output m lines with 2 numbers each β€” description of all the direct connections in the system. Each direct connection is described by two numbers β€” indexes of two servers, linked by this direct connection. The servers are numbered from 1. If the answer is not unique, output any.
standard output
PASSED
5ec6f2e851fa7024a99b96f7332e40c7
train_000.jsonl
1277823600
Bob got a job as a system administrator in X corporation. His first task was to connect n servers with the help of m two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of servers should have at most one direct connection. Y corporation, a business rival of X corporation, made Bob an offer that he couldn't refuse: Bob was asked to connect the servers in such a way, that when server with index v fails, the transmission of data between some other two servers becomes impossible, i.e. the system stops being connected. Help Bob connect the servers.
256 megabytes
import java.util.*; import java.io.*; public class Main { // static LinkedList<Integer> adj[]; // static boolean cats[]; // static boolean visited[]; public static void main(String[] args) { FastScanner sc = new FastScanner(); long n = sc.nextLong(); long m = sc.nextLong(); long v = sc.nextLong(); ArrayList<pair> vector = new ArrayList<pair>(); long lim = ((n - 2) * (n - 3) / 2) + n - 1; if(m < (n - 1) || m > lim) System.out.println("-1"); else { for(int i = 1; i <= n; i++) { if(i != v) { vector.add(new pair(i, v)); } } m -= (n - 1); int start = 1; if(start == v) start++; int x = 1; int y = x + 1; while(m > 0) { if(x == start || x == v) { x++; y = x + 1; continue; } if(y == start || y == v) { y++; if(y > n) { x++; y = x + 1; } continue; } vector.add(new pair(x, y)); y++; m--; if(y > n) { x++; y = x + 1; } } // for(int i = 1; i <= n && m > 0; i++) // { // if(i == start || i == v) // continue; // for(int j = i + 1; j <= n && m > 0; j++) // { // if(j == start || j == v) // continue; // vector.add(new pair(i, j)); // m--; // } // } // while(m > 0) // { // vector.add(new pair(x, y)); // m--; // y++; // if(y == v) // y++; // if(y > n) // { // if((x + 1) == v) // x += 2; // else // { // x++; // y = x + 1; // } // } // // } for(int i = 0; i < vector.size(); i++) System.out.println(vector.get(i).first + " " + vector.get(i).second); // for(int i = 1; i <= m; i++) // { // if(i == v) // continue; // // } } } public static class pair { long first; long second; public pair(long f, long s) { first = f; second = s; } } // public static void addEdge(int a, int b) // { // adj[a].add(b); // adj[b].add(a); // } // public static int dfs(int pos, int count, int lim) // { // if(cats[pos]) // count++; // else // count = 0; // if(count > lim || visited[pos]) // return 0; // visited[pos] = true; // if(pos > 1 && adj[pos].size() == 1) //if leaf // return 1; // int ans = 0; // for(int i = 0; i < adj[pos].size(); i++) // ans += dfs(adj[pos].get(i), count, lim); // return ans; // // } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["5 6 3", "6 100 1"]
1 second
["1 2\n2 3\n3 4\n4 5\n1 3\n3 5", "-1"]
null
Java 8
standard input
[ "graphs" ]
959709bfe7b26a4b9f2e7430350650a9
The first input line contains 3 space-separated integer numbers n, m, v (3 ≀ n ≀ 105, 0 ≀ m ≀ 105, 1 ≀ v ≀ n), n β€” amount of servers, m β€” amount of direct connections, v β€” index of the server that fails and leads to the failure of the whole system.
1,700
If it is impossible to connect the servers in the required way, output -1. Otherwise output m lines with 2 numbers each β€” description of all the direct connections in the system. Each direct connection is described by two numbers β€” indexes of two servers, linked by this direct connection. The servers are numbered from 1. If the answer is not unique, output any.
standard output
PASSED
51297ece827c06da9285b0194881bbde
train_000.jsonl
1277823600
Bob got a job as a system administrator in X corporation. His first task was to connect n servers with the help of m two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of servers should have at most one direct connection. Y corporation, a business rival of X corporation, made Bob an offer that he couldn't refuse: Bob was asked to connect the servers in such a way, that when server with index v fails, the transmission of data between some other two servers becomes impossible, i.e. the system stops being connected. Help Bob connect the servers.
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 system{ public static void main (String[]args) throws IOException{ PrintWriter out=new PrintWriter(System.out); Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int edges=sc.nextInt(); int ind=sc.nextInt()-1; int max=(((n-1)*(n-2))/2)+1; int x; if(ind==0) x=1; else{ if(ind==n-1) x=0; else x=ind+1; } if(edges>max || edges<n-1) out.println(-1); else{ int c=0; for(int i=1;i<=n ;i++){ if(i==(ind+1)) continue; out.println(i+" "+(ind+1)); c++; } for(int i=0;i<n;i++){ for(int j=i+1;j<n && c<edges;j++){ if(i==ind || j==x || i==x || j==ind) continue; out.println((i+1)+" "+(j+1)); c++; } } } out.flush(); } 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
["5 6 3", "6 100 1"]
1 second
["1 2\n2 3\n3 4\n4 5\n1 3\n3 5", "-1"]
null
Java 8
standard input
[ "graphs" ]
959709bfe7b26a4b9f2e7430350650a9
The first input line contains 3 space-separated integer numbers n, m, v (3 ≀ n ≀ 105, 0 ≀ m ≀ 105, 1 ≀ v ≀ n), n β€” amount of servers, m β€” amount of direct connections, v β€” index of the server that fails and leads to the failure of the whole system.
1,700
If it is impossible to connect the servers in the required way, output -1. Otherwise output m lines with 2 numbers each β€” description of all the direct connections in the system. Each direct connection is described by two numbers β€” indexes of two servers, linked by this direct connection. The servers are numbered from 1. If the answer is not unique, output any.
standard output
PASSED
277f550027c2928392c0a184fc281592
train_000.jsonl
1277823600
Bob got a job as a system administrator in X corporation. His first task was to connect n servers with the help of m two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of servers should have at most one direct connection. Y corporation, a business rival of X corporation, made Bob an offer that he couldn't refuse: Bob was asked to connect the servers in such a way, that when server with index v fails, the transmission of data between some other two servers becomes impossible, i.e. the system stops being connected. Help Bob connect the servers.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; import java.util.Iterator; import java.util.TreeSet; /** * 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(); } static class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(), m = in.nextInt(), v = in.nextInt(); int minConnections = n - 1; int maxConnections = 1 + (n - 2) + ((n - 2) * (n - 2 - 1) / 2); TreeSet<Integer> nodes = new TreeSet(); Object[] nodesArray; int singleNode; String connections = ""; if (m < minConnections || m > maxConnections) { System.out.println("-1"); } else { // Add all vertices to TreeSet for (int i = 1; i <= n; i++) { nodes.add(i); } // Now remove node v nodes.remove(v); // Setup singleNode on "Left" and also remove from TreeSet singleNode = nodes.first(); nodes.remove(singleNode); // Make minimal connections // (1) Connect "Left" node and v out.println(singleNode + " " + v); // Connect v with "first" node on right out.println(v + " " + nodes.first()); // Connect nodes on "right" to each other nodesArray = nodes.toArray(); for (int i = 0; i < nodesArray.length - 1; i++) { out.println(nodesArray[i] + " " + nodesArray[i + 1]); } // Reduce m by number of connections made. m = m - 2 - (n - 2 - 1); // IF m > 0, start adding connections between v and nodes on "right" if (m > 0) { nodesArray = nodes.toArray(); for (int i = 1; i < nodesArray.length; i++) { out.println(v + " " + nodesArray[i]); m--; if (m == 0) { break; } } } // IF m is still > 0, add connections between nodes on right if (m > 0) { nodesArray = nodes.toArray(); for (int i = 0; i < nodesArray.length; i++) { if (m == 0) { break; } for (int j = 0; j < nodesArray.length; j++) { if (j >= i + 2) { out.println(nodesArray[i] + " " + nodesArray[j]); m--; if (m == 0) { break; } } } } } } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["5 6 3", "6 100 1"]
1 second
["1 2\n2 3\n3 4\n4 5\n1 3\n3 5", "-1"]
null
Java 8
standard input
[ "graphs" ]
959709bfe7b26a4b9f2e7430350650a9
The first input line contains 3 space-separated integer numbers n, m, v (3 ≀ n ≀ 105, 0 ≀ m ≀ 105, 1 ≀ v ≀ n), n β€” amount of servers, m β€” amount of direct connections, v β€” index of the server that fails and leads to the failure of the whole system.
1,700
If it is impossible to connect the servers in the required way, output -1. Otherwise output m lines with 2 numbers each β€” description of all the direct connections in the system. Each direct connection is described by two numbers β€” indexes of two servers, linked by this direct connection. The servers are numbered from 1. If the answer is not unique, output any.
standard output
PASSED
525854291f3ea1033fdb300639306790
train_000.jsonl
1277823600
Bob got a job as a system administrator in X corporation. His first task was to connect n servers with the help of m two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of servers should have at most one direct connection. Y corporation, a business rival of X corporation, made Bob an offer that he couldn't refuse: Bob was asked to connect the servers in such a way, that when server with index v fails, the transmission of data between some other two servers becomes impossible, i.e. the system stops being connected. Help Bob connect the servers.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Scanner; /** * Built using CHelper plug-in Actual solution is at the top */ public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int v = sc.nextInt(); int max = (n - 1) + (((n - 2) * (n - 3)) / 2); ArrayList<Integer> al = new ArrayList(); int min = n - 1; for (int i = 1; i <= n; i++) { if (i != v) { al.add(i); } } if (!(m <= max && m >= min)) { System.out.print(-1); } else { int a = al.remove(0); System.out.println(v + " " + a); for (int i = 0; i < al.size(); i++) { System.out.println(v + " " + al.get(i)); } int counter = min; while (counter != m) { int b = al.remove(0); for (int i = 0; i < al.size(); i++) { System.out.println(b + " " + al.get(i)); counter++; if (counter == m) { break; } } } } } }
Java
["5 6 3", "6 100 1"]
1 second
["1 2\n2 3\n3 4\n4 5\n1 3\n3 5", "-1"]
null
Java 8
standard input
[ "graphs" ]
959709bfe7b26a4b9f2e7430350650a9
The first input line contains 3 space-separated integer numbers n, m, v (3 ≀ n ≀ 105, 0 ≀ m ≀ 105, 1 ≀ v ≀ n), n β€” amount of servers, m β€” amount of direct connections, v β€” index of the server that fails and leads to the failure of the whole system.
1,700
If it is impossible to connect the servers in the required way, output -1. Otherwise output m lines with 2 numbers each β€” description of all the direct connections in the system. Each direct connection is described by two numbers β€” indexes of two servers, linked by this direct connection. The servers are numbered from 1. If the answer is not unique, output any.
standard output
PASSED
e5018af40dddaae0ab9173ade504a557
train_000.jsonl
1277823600
Bob got a job as a system administrator in X corporation. His first task was to connect n servers with the help of m two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of servers should have at most one direct connection. Y corporation, a business rival of X corporation, made Bob an offer that he couldn't refuse: Bob was asked to connect the servers in such a way, that when server with index v fails, the transmission of data between some other two servers becomes impossible, i.e. the system stops being connected. Help Bob connect the servers.
256 megabytes
import java.io.*; import java.util.*; public class CF22C { static int swap(int x, int a, int b) { if (x == a) return b; if (x == b) return a; return x; } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int v = sc.nextInt(); long max = (long) (n - 1) * (n - 2) / 2 + 1; if (m < n - 1 || m > max) { System.out.println("-1"); return; } PrintWriter pw = new PrintWriter(System.out); for (int i = 1; i < n; i++) pw.format("%d %d\n", swap(i, v, 2), swap(i + 1, v, 2)); m -= n - 1; if (m == 0) { pw.close(); return; } for (int i = 2; i <= n; i++) for (int j = i + 2; j <= n; j++) { pw.format("%d %d\n", swap(i, v, 2), swap(j, v, 2)); m--; if (m == 0) { pw.close(); return; } } } }
Java
["5 6 3", "6 100 1"]
1 second
["1 2\n2 3\n3 4\n4 5\n1 3\n3 5", "-1"]
null
Java 8
standard input
[ "graphs" ]
959709bfe7b26a4b9f2e7430350650a9
The first input line contains 3 space-separated integer numbers n, m, v (3 ≀ n ≀ 105, 0 ≀ m ≀ 105, 1 ≀ v ≀ n), n β€” amount of servers, m β€” amount of direct connections, v β€” index of the server that fails and leads to the failure of the whole system.
1,700
If it is impossible to connect the servers in the required way, output -1. Otherwise output m lines with 2 numbers each β€” description of all the direct connections in the system. Each direct connection is described by two numbers β€” indexes of two servers, linked by this direct connection. The servers are numbered from 1. If the answer is not unique, output any.
standard output
PASSED
4d82e7f7bdc3c1bd24dab7a960a40dcf
train_000.jsonl
1277823600
Bob got a job as a system administrator in X corporation. His first task was to connect n servers with the help of m two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of servers should have at most one direct connection. Y corporation, a business rival of X corporation, made Bob an offer that he couldn't refuse: Bob was asked to connect the servers in such a way, that when server with index v fails, the transmission of data between some other two servers becomes impossible, i.e. the system stops being connected. Help Bob connect the servers.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Stack; import java.util.StringTokenizer; public class Main { private static MyScanner sc; private static PrintWriter out; public static void main(String[] args) { sc = new MyScanner(); out = new PrintWriter(System.out); int n = sc.nextInt(); int m = sc.nextInt(); int v = sc.nextInt() - 1; long maxPossible = ((n - 2) * (n - 3) / 2) + n - 1; if(maxPossible < m || m < (n - 1)) { out.println(-1); } else { solve(n, m, v); } out.close(); } private static boolean solve(int n, int m, int v) { int need = m; int random = -1; boolean selected = false; for(int i = 0; i < n; i++) { if(need == 0) return true; if(i != v) { out.println((v + 1) + " " + (i + 1)); need--; } if(!selected && i != v) { random = i; selected = true; } } for(int i = 0; i < n; i++) { for(int j = i + 1; j < n; j++) { if(i != random && j != random && i != v && j != v) { if(need == 0) return true; out.println((i + 1) + " " + (j + 1)); need--; } } } return true; } private static int max(int a, int b) { if(a > b) return a; else return b; } private static int min(int a, int b) { if(a < b) return a; else return b; } private static int abs(int a, int b) { return (int) Math.abs(a - b); } public static int modexp(int a, int b, int n) { if (b == 0) return 1; long t = modexp(a, b/2, n); long c = (t * t) % n; if (b % 2 == 1) c = (c * a) % n; return (int) c; } public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5 6 3", "6 100 1"]
1 second
["1 2\n2 3\n3 4\n4 5\n1 3\n3 5", "-1"]
null
Java 8
standard input
[ "graphs" ]
959709bfe7b26a4b9f2e7430350650a9
The first input line contains 3 space-separated integer numbers n, m, v (3 ≀ n ≀ 105, 0 ≀ m ≀ 105, 1 ≀ v ≀ n), n β€” amount of servers, m β€” amount of direct connections, v β€” index of the server that fails and leads to the failure of the whole system.
1,700
If it is impossible to connect the servers in the required way, output -1. Otherwise output m lines with 2 numbers each β€” description of all the direct connections in the system. Each direct connection is described by two numbers β€” indexes of two servers, linked by this direct connection. The servers are numbered from 1. If the answer is not unique, output any.
standard output
PASSED
74464dab8fba4572492c06a6cb6b31ba
train_000.jsonl
1277823600
Bob got a job as a system administrator in X corporation. His first task was to connect n servers with the help of m two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of servers should have at most one direct connection. Y corporation, a business rival of X corporation, made Bob an offer that he couldn't refuse: Bob was asked to connect the servers in such a way, that when server with index v fails, the transmission of data between some other two servers becomes impossible, i.e. the system stops being connected. Help Bob connect the servers.
256 megabytes
import java.io.*; import java.util.*; public class Main { static PrintWriter out; static InputReader in; static InputStream inputs; public static void main(String[] args) { inputs = System.in; in = new InputReader(inputs); out = new PrintWriter(new BufferedOutputStream(System.out),true); //Jaber's Code XD int n = in.nextInt(), m= in.nextInt(),v = in.nextInt() , maxConnections = ((n-1)*(n-2)/2+1); if (m > maxConnections || m<(n-1)) { System.out.println("-1"); }else { //---------------- int[] array = new int[n+1];// i used an array :P for (int i = 1; i <= n; i++) { array[i] = i; } //---------------- array[v] = 1;// So ? array[1] = v;// what did i do ? do you know ? //---------------- for (int i = 2; i <= n; i++) { // we used 1 so we start from 2 // if (i != v) // i guess no need for that... out.println(array[i] + " " + array[1]);// see why did i use an array ? } m -= n-1;// what did i do ? don't ask me something starnge is it ? for (int i = 3; i <= n && m > 0; i++) { // we started from 2 (prevuisely)?.. so lets start from 3 (what is the point of this o = 0 ? // if (i != v) // again i don't think this is a good idea for (int j = i + 1; j <= n && m > 0; j++) { // if (j != i && j != v) why man ? :P // { out.println(array[i] + " " + array[j]); // o++; ?? :D //its m--; m--;// why ? find it your self // } } } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["5 6 3", "6 100 1"]
1 second
["1 2\n2 3\n3 4\n4 5\n1 3\n3 5", "-1"]
null
Java 8
standard input
[ "graphs" ]
959709bfe7b26a4b9f2e7430350650a9
The first input line contains 3 space-separated integer numbers n, m, v (3 ≀ n ≀ 105, 0 ≀ m ≀ 105, 1 ≀ v ≀ n), n β€” amount of servers, m β€” amount of direct connections, v β€” index of the server that fails and leads to the failure of the whole system.
1,700
If it is impossible to connect the servers in the required way, output -1. Otherwise output m lines with 2 numbers each β€” description of all the direct connections in the system. Each direct connection is described by two numbers β€” indexes of two servers, linked by this direct connection. The servers are numbered from 1. If the answer is not unique, output any.
standard output
PASSED
12f48b89f1b41ceacdc0f4a5a235ecc2
train_000.jsonl
1277823600
Bob got a job as a system administrator in X corporation. His first task was to connect n servers with the help of m two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of servers should have at most one direct connection. Y corporation, a business rival of X corporation, made Bob an offer that he couldn't refuse: Bob was asked to connect the servers in such a way, that when server with index v fails, the transmission of data between some other two servers becomes impossible, i.e. the system stops being connected. Help Bob connect the servers.
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashSet; import java.util.Random; import java.util.StringTokenizer; public class P { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int N = sc.nextInt(), M = sc.nextInt(), V = sc.nextInt(); if ((1l * (N - 1) * (N - 2)) / 2 < (M - 1) || M < N - 1) out.println(-1); else { int[] nodes = new int[N]; for (int i = 0; i < N; i++) nodes[i] = i + 1; nodes[N - 2] = V; nodes[V - 1] = N - 1; for (int i = 0; i < N - 1; i++) out.println(nodes[i] + " " + nodes[i + 1]); int used = N - 1; LOOP: for (int i = 0; i < N - 1; i++) for (int j = i + 2; j < N - 1; j++) { if (used == M) break LOOP; out.println(nodes[i] + " " + nodes[j]); used++; } } out.flush(); out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String f) throws FileNotFoundException { br = new BufferedReader(new FileReader(f)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException { return br.ready(); } 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 int[] nextIntArray1(int n) throws IOException { int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextInt(); return a; } public int[] shuffle(int[] a, int n) { int[] b = new int[n]; for (int i = 0; i < n; i++) b[i] = a[i]; Random r = new Random(); for (int i = 0; i < n; i++) { int j = i + r.nextInt(n - i); int t = b[i]; b[i] = b[j]; b[j] = t; } return b; } public int[] nextIntArraySorted(int n) throws IOException { int[] a = nextIntArray(n); a = shuffle(a, n); Arrays.sort(a); 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 long[] nextLongArray1(int n) throws IOException { long[] a = new long[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextLong(); return a; } public long[] nextLongArraySorted(int n) throws IOException { long[] a = nextLongArray(n); Random r = new Random(); for (int i = 0; i < n; i++) { int j = i + r.nextInt(n - i); long t = a[i]; a[i] = a[j]; a[j] = t; } Arrays.sort(a); return a; } } }
Java
["5 6 3", "6 100 1"]
1 second
["1 2\n2 3\n3 4\n4 5\n1 3\n3 5", "-1"]
null
Java 8
standard input
[ "graphs" ]
959709bfe7b26a4b9f2e7430350650a9
The first input line contains 3 space-separated integer numbers n, m, v (3 ≀ n ≀ 105, 0 ≀ m ≀ 105, 1 ≀ v ≀ n), n β€” amount of servers, m β€” amount of direct connections, v β€” index of the server that fails and leads to the failure of the whole system.
1,700
If it is impossible to connect the servers in the required way, output -1. Otherwise output m lines with 2 numbers each β€” description of all the direct connections in the system. Each direct connection is described by two numbers β€” indexes of two servers, linked by this direct connection. The servers are numbered from 1. If the answer is not unique, output any.
standard output
PASSED
68ba5c40bf87911eb7f3eb9d58a5c7b4
train_000.jsonl
1277823600
Bob got a job as a system administrator in X corporation. His first task was to connect n servers with the help of m two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of servers should have at most one direct connection. Y corporation, a business rival of X corporation, made Bob an offer that he couldn't refuse: Bob was asked to connect the servers in such a way, that when server with index v fails, the transmission of data between some other two servers becomes impossible, i.e. the system stops being connected. Help Bob connect the servers.
256 megabytes
import java.io.*; import java.util.*; public class A { public static void main(String[] args)throws Throwable { MyScanner sc=new MyScanner(); PrintWriter pw=new PrintWriter(System.out); int n=sc.nextInt(); int m=sc.nextInt(); int v=sc.nextInt()-1; long max=1+(1L*(n-2)*(n-1))/2; if(max<m || m<n-1){ pw.println(-1); pw.flush(); return; } int other=0; if(v==0) other++; pw.println((v+1)+" "+(other+1)); m--; for(int i=0;i<n && m>0;i++){ if(i==other) continue; for(int j=i+1;j<n && m>0;j++){ if(j==other) continue; pw.println((i+1)+" "+(j+1)); m--; } } pw.flush(); pw.close(); } 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 MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() {br = new BufferedReader(new InputStreamReader(System.in));} String next() {while (st == null || !st.hasMoreElements()) { try {st = new StringTokenizer(br.readLine());} catch (IOException e) {e.printStackTrace();}} return st.nextToken();} int nextInt() {return Integer.parseInt(next());} long nextLong() {return Long.parseLong(next());} double nextDouble() {return Double.parseDouble(next());} String nextLine(){String str = ""; try {str = br.readLine();} catch (IOException e) {e.printStackTrace();} return str;} } }
Java
["5 6 3", "6 100 1"]
1 second
["1 2\n2 3\n3 4\n4 5\n1 3\n3 5", "-1"]
null
Java 8
standard input
[ "graphs" ]
959709bfe7b26a4b9f2e7430350650a9
The first input line contains 3 space-separated integer numbers n, m, v (3 ≀ n ≀ 105, 0 ≀ m ≀ 105, 1 ≀ v ≀ n), n β€” amount of servers, m β€” amount of direct connections, v β€” index of the server that fails and leads to the failure of the whole system.
1,700
If it is impossible to connect the servers in the required way, output -1. Otherwise output m lines with 2 numbers each β€” description of all the direct connections in the system. Each direct connection is described by two numbers β€” indexes of two servers, linked by this direct connection. The servers are numbered from 1. If the answer is not unique, output any.
standard output
PASSED
3432f9046b67a246da2a4995b3d1b1f2
train_000.jsonl
1277823600
Bob got a job as a system administrator in X corporation. His first task was to connect n servers with the help of m two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of servers should have at most one direct connection. Y corporation, a business rival of X corporation, made Bob an offer that he couldn't refuse: Bob was asked to connect the servers in such a way, that when server with index v fails, the transmission of data between some other two servers becomes impossible, i.e. the system stops being connected. Help Bob connect the servers.
256 megabytes
// Name: Ibraheem Cazalas // Date: import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { input.init(System.in); int n = input.nextInt(), m = input.nextInt(), v = input.nextInt(); if (m < (n - 1) || m > ((n-1)+(n-3)*(n-3+1)/2)) { System.out.println("-1"); } else { for (int i = 1; i <= n; i++) { if (i == v) { continue; } System.out.println(v + " " + i); m--; } if (v == n) { for (int i = 2; i < n; i++) { if (i == v) { continue; } for (int j = i + 1; j < n; j++) { if (m == 0) { System.out.close(); java.lang.System.exit(0); } if (j == v) { continue; } System.out.println(i + " " + j); m--; } } } else { for (int i = 1; i < n; i++) { if (i == v) { continue; } for (int j = i + 1; j < n; j++) { if (m == 0) { System.out.close(); java.lang.System.exit(0); } if (j == v) { continue; } System.out.println(i + " " + j); m--; } } } } System.out.close(); } } class input { static BufferedReader reader; static StringTokenizer tokenizer; /** * call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader(new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } /** * get next word */ static String next() throws IOException { while (!tokenizer.hasMoreTokens()) { //TODO add check for eof if necessary tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } } class System { static PrintWriter out = new PrintWriter(java.lang.System.out); static InputStream in = java.lang.System.in; }
Java
["5 6 3", "6 100 1"]
1 second
["1 2\n2 3\n3 4\n4 5\n1 3\n3 5", "-1"]
null
Java 8
standard input
[ "graphs" ]
959709bfe7b26a4b9f2e7430350650a9
The first input line contains 3 space-separated integer numbers n, m, v (3 ≀ n ≀ 105, 0 ≀ m ≀ 105, 1 ≀ v ≀ n), n β€” amount of servers, m β€” amount of direct connections, v β€” index of the server that fails and leads to the failure of the whole system.
1,700
If it is impossible to connect the servers in the required way, output -1. Otherwise output m lines with 2 numbers each β€” description of all the direct connections in the system. Each direct connection is described by two numbers β€” indexes of two servers, linked by this direct connection. The servers are numbered from 1. If the answer is not unique, output any.
standard output
PASSED
e7ffacb15b53d0a6b5be155aa1822d49
train_000.jsonl
1277823600
Bob got a job as a system administrator in X corporation. His first task was to connect n servers with the help of m two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of servers should have at most one direct connection. Y corporation, a business rival of X corporation, made Bob an offer that he couldn't refuse: Bob was asked to connect the servers in such a way, that when server with index v fails, the transmission of data between some other two servers becomes impossible, i.e. the system stops being connected. Help Bob connect the servers.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { InputStream inputStream = System.in; // InputStream inputStream = new FileInputStream("sum.in"); OutputStream outputStream = System.out; // OutputStream outputStream = new FileOutputStream("sum.out"); // Path path = Paths.get(URI.create("file:///foo/bar/Main.java")); // System.out.print(path.getName(200)); // Path p = Paths.get("/foo/bar/Main.java"); // for (Path e : p) { // System.out.println(e); // } InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Answer solver = new Answer(); solver.solve(in, out); out.close(); } } class Answer { private final int INF = (int) (1e9 + 7); private final int MOD = (int) (1e9 + 7); private final int MOD1 = (int) (1e6 + 3); private final long INF_LONG = (long) (1e18 + 1); private final double EPS = 1e-9; public void solve(InputReader in, PrintWriter out) throws IOException { int n = in.nextInt(); int m = in.nextInt(); int v = in.nextInt(); if (m < n - 1 || 1L * n * n - 3 * n + 4 < 2 * m) { out.print("-1"); return; } for (int i = 1; i <= n; i++) { if (i != v) { out.println(v + " " + i); } } m -= n - 1; if (m == 0) { return; } List<Integer> a = new ArrayList<>(); int x = 1; while (x <= n && a.size() != n - 2) { if (v != x) { a.add(x); } x++; } for (int i = 0; i < a.size(); i++) { for (int j = i + 1; j < a.size(); j++) { out.println(a.get(i) + " " + a.get(j)); m--; if (m == 0) { return; } } } } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; 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()); } public int[] nextArrayInt(int count) { int[] a = new int[count]; for (int i = 0; i < count; i++) { a[i] = nextInt(); } return a; } public long[] nextArrayLong(int count) { long[] a = new long[count]; for (int i = 0; i < count; i++) { a[i] = nextLong(); } return a; } }
Java
["5 6 3", "6 100 1"]
1 second
["1 2\n2 3\n3 4\n4 5\n1 3\n3 5", "-1"]
null
Java 8
standard input
[ "graphs" ]
959709bfe7b26a4b9f2e7430350650a9
The first input line contains 3 space-separated integer numbers n, m, v (3 ≀ n ≀ 105, 0 ≀ m ≀ 105, 1 ≀ v ≀ n), n β€” amount of servers, m β€” amount of direct connections, v β€” index of the server that fails and leads to the failure of the whole system.
1,700
If it is impossible to connect the servers in the required way, output -1. Otherwise output m lines with 2 numbers each β€” description of all the direct connections in the system. Each direct connection is described by two numbers β€” indexes of two servers, linked by this direct connection. The servers are numbered from 1. If the answer is not unique, output any.
standard output
PASSED
aea1859b0cc3058499730c4c0c31c1b9
train_000.jsonl
1277823600
Bob got a job as a system administrator in X corporation. His first task was to connect n servers with the help of m two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of servers should have at most one direct connection. Y corporation, a business rival of X corporation, made Bob an offer that he couldn't refuse: Bob was asked to connect the servers in such a way, that when server with index v fails, the transmission of data between some other two servers becomes impossible, i.e. the system stops being connected. Help Bob connect the servers.
256 megabytes
import java.io.*; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; public class Graph { static Scanner sc = new Scanner(System.in); static PrintWriter pw = new PrintWriter(System.out), pw2 = new PrintWriter(System.out); public static void main(String[] args) throws IOException { int n = sc.nextInt(), m = sc.nextInt(), mm = m*2, k = sc.nextInt(); if ((n - 1) * (n - 2) / 2 + 1 < m || n - 1 > m) System.out.println(-1); else { graph g = new graph(n); for(int i=1;i<=n;i++){ if(i==k)continue; g.addEdge(k,i); mm--; } for (int i = 1; i <= n & mm >= 0; i++) { if(i==k)continue; for (int j = i + 1; j <= n & mm >= 0; j++) { if(j==k)continue; g.addEdge(i, j); mm--; } } g.BFS(k, m); } } public static <E> void print2D(E[][] arr) { for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) { pw2.println(arr[i][j]); } } pw2.flush(); } public static int digitSum(String s) { int toReturn = 0; for (int i = 0; i < s.length(); i++) toReturn += Integer.parseInt(s.charAt(i) + " "); return toReturn; } public static boolean isPrime(long n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (long i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } public static long pow(long a, long pow) { return pow == 0 ? 1 : pow % 2 == 0 ? pow(a * a, pow >> 1) : a * pow(a, pow >> 1); } public static long sumNum(long a) { return a * (a + 1) / 2; } public static int gcd(int n1, int n2) { return n2 == 0 ? n1 : gcd(n2, n1 % n2); } public static long factorial(long a) { return a == 0 || a == 1 ? 1 : a * factorial(a - 1); } public static Double[] solveQuadratic(double a, double b, double c) { double result = (b * b) - 4.0 * a * c; double r1; if (result > 0.0) { r1 = ((double) (-b) + Math.pow(result, 0.5)) / (2.0 * a); double r2 = ((double) (-b) - Math.pow(result, 0.5)) / (2.0 * a); return new Double[]{r1, r2}; } else if (result == 0.0) { r1 = (double) (-b) / (2.0 * a); return new Double[]{r1, r1}; } else { return new Double[]{null, null}; } } public static BigDecimal[] solveQuadraticBigDicimal(double aa, double bb, double cc) { BigDecimal a = BigDecimal.valueOf(aa), b = BigDecimal.valueOf(bb), c = BigDecimal.valueOf(cc); BigDecimal result = (b.multiply(b)).multiply(BigDecimal.valueOf(4).multiply(a.multiply(c))); BigDecimal r1; if (result.compareTo(BigDecimal.ZERO) > 0) { r1 = (b.negate().add(bigSqrt(result)).divide(a.multiply(BigDecimal.valueOf(2)))); BigDecimal r2 = (b.negate().subtract(bigSqrt(result)).divide(a.multiply(BigDecimal.valueOf(2)))); return new BigDecimal[]{r1, r2}; } else if (result.compareTo(BigDecimal.ZERO) == 0) { r1 = b.negate().divide(a.multiply(BigDecimal.valueOf(2))); return new BigDecimal[]{r1, r1}; } else { return new BigDecimal[]{null, null}; } } private static BigDecimal sqrtNewtonRaphson(BigDecimal c, BigDecimal xn, BigDecimal precision) { BigDecimal fx = xn.pow(2).add(c.negate()); BigDecimal fpx = xn.multiply(new BigDecimal(2)); BigDecimal xn1 = fx.divide(fpx, 2 * BigDecimal.valueOf(16).intValue(), RoundingMode.HALF_DOWN); xn1 = xn.add(xn1.negate()); BigDecimal currentSquare = xn1.pow(2); BigDecimal currentPrecision = currentSquare.subtract(c); currentPrecision = currentPrecision.abs(); if (currentPrecision.compareTo(precision) <= -1) { return xn1; } return sqrtNewtonRaphson(c, xn1, precision); } public static BigDecimal bigSqrt(BigDecimal c) { return sqrtNewtonRaphson(c, new BigDecimal(1), new BigDecimal(1).divide(BigDecimal.valueOf(10).pow(16))); } static class graph { int V; ArrayList<Integer> list[]; boolean[] vis; public graph(int V) { this.V = V; vis = new boolean[V + 1]; list = new ArrayList[V + 1]; for (int i = 0; i < V + 1; i++) list[i] = new ArrayList<>(); } public void addEdge(int v1, int v2) { this.list[v1].add(v2); this.list[v2].add(v1); } public void BFS(int n, int m) { Queue<Integer> q = new LinkedList<>(); q.add(n); while (!q.isEmpty()) { int a = q.poll(); vis[a] = true; for (int x : list[a]) { if (!vis[x]) { System.out.println(a + " " + x); if (--m == 0) return; q.add(x); } } vis[list[a].get(list[a].size() - 1)] = true; } } } static class pair<E1, E2> implements Comparable<pair> { E1 x; E2 y; pair(E1 x, E2 y) { this.x = x; this.y = y; } @Override public int compareTo(pair o) { return x.equals(o.x) ? (Integer) y - (Integer) o.y : (Integer) x - (Integer) o.x; } @Override public String toString() { return x + " " + y; } public double pointDis(pair p1) { return Math.sqrt(((Integer) y - (Integer) p1.y) * ((Integer) y - (Integer) p1.y) + ((Integer) x - (Integer) p1.x) * ((Integer) x - (Integer) p1.x)); } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(FileReader r) { br = new BufferedReader(r); } public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["5 6 3", "6 100 1"]
1 second
["1 2\n2 3\n3 4\n4 5\n1 3\n3 5", "-1"]
null
Java 8
standard input
[ "graphs" ]
959709bfe7b26a4b9f2e7430350650a9
The first input line contains 3 space-separated integer numbers n, m, v (3 ≀ n ≀ 105, 0 ≀ m ≀ 105, 1 ≀ v ≀ n), n β€” amount of servers, m β€” amount of direct connections, v β€” index of the server that fails and leads to the failure of the whole system.
1,700
If it is impossible to connect the servers in the required way, output -1. Otherwise output m lines with 2 numbers each β€” description of all the direct connections in the system. Each direct connection is described by two numbers β€” indexes of two servers, linked by this direct connection. The servers are numbered from 1. If the answer is not unique, output any.
standard output
PASSED
3605a6fce21cdc0392e075b6e855dc01
train_000.jsonl
1277823600
Bob got a job as a system administrator in X corporation. His first task was to connect n servers with the help of m two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of servers should have at most one direct connection. Y corporation, a business rival of X corporation, made Bob an offer that he couldn't refuse: Bob was asked to connect the servers in such a way, that when server with index v fails, the transmission of data between some other two servers becomes impossible, i.e. the system stops being connected. Help Bob connect the servers.
256 megabytes
import java.io.*; public class SystemAdministrator { public static void main(String args[]) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); //BufferedReader reader = new BufferedReader(new FileReader("servers")); StringBuilder sb=new StringBuilder(); String [] input = reader.readLine().split(" "); int n=Integer.parseInt(input[0]); int m=Integer.parseInt(input[1]); int v=Integer.parseInt(input[2]); long bound=(long)(n-1)*(n-2)/2+1; if(m>=n-1&&m<=bound) { for(int i=1; i<=n; i++) { if(i!=v) { sb.append(i+" "+v+"\n"); } } m-=n-1; for(int i=1; m>0; i++) { if(i!=v) { for(int j=1; j<i&&m>0; j++) { if(j!=v) { sb.append(j+" "+i+"\n"); m--; } } } } System.out.println(sb); } else { System.out.println("-1"); } } }
Java
["5 6 3", "6 100 1"]
1 second
["1 2\n2 3\n3 4\n4 5\n1 3\n3 5", "-1"]
null
Java 8
standard input
[ "graphs" ]
959709bfe7b26a4b9f2e7430350650a9
The first input line contains 3 space-separated integer numbers n, m, v (3 ≀ n ≀ 105, 0 ≀ m ≀ 105, 1 ≀ v ≀ n), n β€” amount of servers, m β€” amount of direct connections, v β€” index of the server that fails and leads to the failure of the whole system.
1,700
If it is impossible to connect the servers in the required way, output -1. Otherwise output m lines with 2 numbers each β€” description of all the direct connections in the system. Each direct connection is described by two numbers β€” indexes of two servers, linked by this direct connection. The servers are numbered from 1. If the answer is not unique, output any.
standard output
PASSED
c902b74c9e388c95b3decc9dc0b764b1
train_000.jsonl
1277823600
Bob got a job as a system administrator in X corporation. His first task was to connect n servers with the help of m two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of servers should have at most one direct connection. Y corporation, a business rival of X corporation, made Bob an offer that he couldn't refuse: Bob was asked to connect the servers in such a way, that when server with index v fails, the transmission of data between some other two servers becomes impossible, i.e. the system stops being connected. Help Bob connect the servers.
256 megabytes
import java.util.ArrayList; import java.util.Scanner; public class Problem3 { public static void main (String [] args){ Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int m = scan.nextInt(); int v = scan.nextInt(); if(m<n-1 || m>(n-1)*(n-2)/2 + 1){ System.out.println("-1"); } else{ ArrayList<Link> links = new ArrayList<Link>(); int counter = 0; int isolator = n; if(v == isolator) isolator = 1; for(int i = 1; i<=n; i++){ if(counter == m) break; if(i != v){ links.add(new Link(i,v)); counter ++; } } for(int i = 1; i<=n; i++){ if( i != v && i != isolator){ for(int j = i+1; j<=n; j++){ if(counter == m) break; if( j != v && j != isolator){ links.add(new Link(i,j)); counter++; } } } } //System.out.println(links.size()); for(int i = 0; i<links.size(); i++){ System.out.println(links.get(i)); } } } public static class Link{ int start; int end; public Link(int s, int e){ start = s; end = e; } @Override public String toString(){ return ("" + start + " " + end ); } } }
Java
["5 6 3", "6 100 1"]
1 second
["1 2\n2 3\n3 4\n4 5\n1 3\n3 5", "-1"]
null
Java 8
standard input
[ "graphs" ]
959709bfe7b26a4b9f2e7430350650a9
The first input line contains 3 space-separated integer numbers n, m, v (3 ≀ n ≀ 105, 0 ≀ m ≀ 105, 1 ≀ v ≀ n), n β€” amount of servers, m β€” amount of direct connections, v β€” index of the server that fails and leads to the failure of the whole system.
1,700
If it is impossible to connect the servers in the required way, output -1. Otherwise output m lines with 2 numbers each β€” description of all the direct connections in the system. Each direct connection is described by two numbers β€” indexes of two servers, linked by this direct connection. The servers are numbered from 1. If the answer is not unique, output any.
standard output
PASSED
f8fe8503ba6868793f4129c73ac2eb3e
train_000.jsonl
1277823600
Bob got a job as a system administrator in X corporation. His first task was to connect n servers with the help of m two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of servers should have at most one direct connection. Y corporation, a business rival of X corporation, made Bob an offer that he couldn't refuse: Bob was asked to connect the servers in such a way, that when server with index v fails, the transmission of data between some other two servers becomes impossible, i.e. the system stops being connected. Help Bob connect the servers.
256 megabytes
import java.io.PrintWriter; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = scan.nextInt(); int m = scan.nextInt(); int v = scan.nextInt(); int maxM = 1 + (n - 1) * (n - 2) / 2; if (m > maxM || m < n - 1) { out.println(-1); } else { //print connections printGraph(n, m, v, out); } out.close(); } private static void printGraph(int n, int m, int v, PrintWriter out) { int count = 1; int start, end; if (v != 1) { start = 2; end = n; out.println("1 " + v); } else { start = 1; end = n - 1; out.println(n + " " + v); } for (int i = start; i <= end; i++) { for (int j = i + 1; j <= end; j++) { out.println(i + " " + j); count++; if (count == m) { return; } } } } }
Java
["5 6 3", "6 100 1"]
1 second
["1 2\n2 3\n3 4\n4 5\n1 3\n3 5", "-1"]
null
Java 8
standard input
[ "graphs" ]
959709bfe7b26a4b9f2e7430350650a9
The first input line contains 3 space-separated integer numbers n, m, v (3 ≀ n ≀ 105, 0 ≀ m ≀ 105, 1 ≀ v ≀ n), n β€” amount of servers, m β€” amount of direct connections, v β€” index of the server that fails and leads to the failure of the whole system.
1,700
If it is impossible to connect the servers in the required way, output -1. Otherwise output m lines with 2 numbers each β€” description of all the direct connections in the system. Each direct connection is described by two numbers β€” indexes of two servers, linked by this direct connection. The servers are numbered from 1. If the answer is not unique, output any.
standard output
PASSED
3bceb768df50ea5411d731ccba6b8f2b
train_000.jsonl
1277823600
Bob got a job as a system administrator in X corporation. His first task was to connect n servers with the help of m two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of servers should have at most one direct connection. Y corporation, a business rival of X corporation, made Bob an offer that he couldn't refuse: Bob was asked to connect the servers in such a way, that when server with index v fails, the transmission of data between some other two servers becomes impossible, i.e. the system stops being connected. Help Bob connect the servers.
256 megabytes
import java.util.*; import java.io.*; // im so sorry public class C22 { public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int n = in.nextInt(); int m = in.nextInt(); int v = in.nextInt(); int link = m; int isolate = 0; if( m < n-1 || m > (((n-1)*(n-2))/2)+1 ) { pw.println(-1); } else { for( int i = 1; i <= n; i++ ) { if( i != v ) { pw.println( v + " " + i ); link--; } } if( v != n ) isolate = n; else isolate = n-1; for( int i = 1; i <= n; i++ ) { if( link == 0 ) break; for( int j = i+1; j <= n; j++ ) { if( link == 0 ) break; if( i != isolate && j != isolate && i != v && j != v ) { pw.println( i + " " + j ); link--; } } } } pw.flush(); pw.close(); } }
Java
["5 6 3", "6 100 1"]
1 second
["1 2\n2 3\n3 4\n4 5\n1 3\n3 5", "-1"]
null
Java 8
standard input
[ "graphs" ]
959709bfe7b26a4b9f2e7430350650a9
The first input line contains 3 space-separated integer numbers n, m, v (3 ≀ n ≀ 105, 0 ≀ m ≀ 105, 1 ≀ v ≀ n), n β€” amount of servers, m β€” amount of direct connections, v β€” index of the server that fails and leads to the failure of the whole system.
1,700
If it is impossible to connect the servers in the required way, output -1. Otherwise output m lines with 2 numbers each β€” description of all the direct connections in the system. Each direct connection is described by two numbers β€” indexes of two servers, linked by this direct connection. The servers are numbered from 1. If the answer is not unique, output any.
standard output
PASSED
c7369988aebca8a3cb2f12d8303d800e
train_000.jsonl
1277823600
Bob got a job as a system administrator in X corporation. His first task was to connect n servers with the help of m two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of servers should have at most one direct connection. Y corporation, a business rival of X corporation, made Bob an offer that he couldn't refuse: Bob was asked to connect the servers in such a way, that when server with index v fails, the transmission of data between some other two servers becomes impossible, i.e. the system stops being connected. Help Bob connect the servers.
256 megabytes
import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; public class Main { public final static int OO = Integer.MAX_VALUE; private static Reader r; public static void main(String[] args)throws Exception { r = new Reader(); r.readLine(); int n = r.readInt(0); int m = r.readInt(1); int v = r.readInt(2); int tempM = m; StringBuilder ans = new StringBuilder(); for(int i=1;i<=n;++i) { if(i==v) continue; if(m==0) break; ans.append(i); ans.append(" "); ans.append(v); ans.append("\n"); --m; } int ignore = v==1?2:1; for(int i=1;i<=n;++i) { if(i==v || i==ignore) continue; for(int j=i+1;j<=n;++j) { if(m==0) break; if(j==v || j==ignore) continue; ans.append(i); ans.append(" "); ans.append(j); ans.append("\n"); --m; } } System.out.print(m!=0 || tempM<n-1?-1:ans.toString().trim()); r.close(); } private static void dfs(int v, boolean []flag, List<List<Integer>> graph) { flag[v] = true; for (int u:graph.get(v)) { if (!flag[u]) { dfs(u, flag, graph); } } } private static int bfs(List<List<Integer>> graph, int v) { Queue<Integer> queue = new LinkedList<>(); queue.add(v); boolean flag[] = new boolean[graph.size()]; while (!queue.isEmpty()) { v = queue.poll(); flag[v] = true; for (int u:graph.get(v)) if (!flag[u]) { queue.add(u); } } return v; } private static int longestPathInTree(List<List<Integer>> graph, int v) { v = bfs(graph,v); Queue<Pair> level = new LinkedList<>(); boolean []isV = new boolean[graph.size()]; Pair p = new Pair(v, 0); level.add(p); while (!level.isEmpty()) { p = level.poll(); isV[p.f] = true; v = p.f; for (int u:graph.get(v)) if (!isV[u]) { level.add(new Pair(u, p.s + 1)); } } return p.s; } } class Pair implements Comparable<Pair> { int f,s; public Pair() {} public Pair(int f, int s) { this.f = f; this.s = s; } @Override public String toString() { return f + " " + s; } @Override public int compareTo(Pair o) { if (f == o.f) return s - o.s; return f - o.f; } } class Reader { private BufferedReader reader; private String line[]; public Reader() { reader = new BufferedReader(new InputStreamReader(System.in)); } public String[] getLine() { return line; } public void readLine() throws IOException { line = reader.readLine().split(" "); } public List<Integer> getIntegersList() { List<Integer> res = new ArrayList<>(); for (String str:line) res.add(Integer.parseInt(str)); return res; } public int readInt(int pos)throws IOException { return Integer.parseInt(line[pos]); } public double readDouble(int pos)throws IOException { return Double.parseDouble(line[pos]); } public long readLong(int pos)throws IOException { return Long.parseLong(line[pos]); } public String readString(int pos)throws IOException { return line[pos]; } public void close()throws IOException { reader.close(); } } class Vertix implements Comparable<Vertix> { int to,w; public Vertix(int to, int w) { this.to = to; this.w = w; } @Override public int compareTo(Vertix p1) { return w - p1.w; } } class Dijkstra { boolean isDirected; int n; List<List<Vertix>> adjList; int distance[]; int parent[]; boolean visited[]; Dijkstra(int n, boolean isDirected) { this.isDirected = isDirected; this.n = n; adjList = new ArrayList<>(); distance = new int[n + 1]; parent = new int[n + 1]; visited = new boolean[n + 1]; for (int i=0;i <= n;++i) { adjList.add(new ArrayList<Vertix>()); distance[i] = Main.OO; parent[i] = -1; } } void addEdge(int fr, int to, int w) { adjList.get(fr).add(new Vertix(to, w)); if (!isDirected) adjList.get(to).add(new Vertix(fr, w)); } Stack<Integer> getShortestPath(int src, int dis) { PriorityQueue<Vertix> queue = new PriorityQueue<>(); distance[src] = 0; queue.add(new Vertix(src, 0)); while (!queue.isEmpty()) { Vertix v = queue.poll(); int to = v.to; if (visited[to]) continue; if (to == dis) { Stack<Integer> res = new Stack<>(); res.add(dis); for (int c=parent[dis];c != src;c = parent[c]) res.add(c); res.add(src); return res; } visited[to] = true; for (Vertix vv:adjList.get(to)) { if (!visited[vv.to] && distance[vv.to] > distance[to] + vv.w) { distance[vv.to] = distance[to] + vv.w; parent[vv.to] = to; queue.add(new Vertix(vv.to, distance[vv.to])); } } } return null; } }
Java
["5 6 3", "6 100 1"]
1 second
["1 2\n2 3\n3 4\n4 5\n1 3\n3 5", "-1"]
null
Java 8
standard input
[ "graphs" ]
959709bfe7b26a4b9f2e7430350650a9
The first input line contains 3 space-separated integer numbers n, m, v (3 ≀ n ≀ 105, 0 ≀ m ≀ 105, 1 ≀ v ≀ n), n β€” amount of servers, m β€” amount of direct connections, v β€” index of the server that fails and leads to the failure of the whole system.
1,700
If it is impossible to connect the servers in the required way, output -1. Otherwise output m lines with 2 numbers each β€” description of all the direct connections in the system. Each direct connection is described by two numbers β€” indexes of two servers, linked by this direct connection. The servers are numbered from 1. If the answer is not unique, output any.
standard output
PASSED
dc614d5f46e5fbadc7076239e23f0f97
train_000.jsonl
1277823600
Bob got a job as a system administrator in X corporation. His first task was to connect n servers with the help of m two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of servers should have at most one direct connection. Y corporation, a business rival of X corporation, made Bob an offer that he couldn't refuse: Bob was asked to connect the servers in such a way, that when server with index v fails, the transmission of data between some other two servers becomes impossible, i.e. the system stops being connected. Help Bob connect the servers.
256 megabytes
import java.io.*; import java.util.*; /** * BEGIN NO SAD * Blessed are those who suffer for doing what is right. * The kingdom of heaven belongs to them. * (Matthew 5:10-12) * @author Tran Anh Tai * @template for CP codes * END NO SAD */ public class ProbC { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(in, out); out.close(); } // main solver static class Task{ public void solve(InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); int v = in.nextInt(); if (m < n - 1 || m >= (long)(n - 2) * (n - 3) / 2 + (n - 1) + 1){ out.println("-1"); } else{ ArrayList<Pair> pairs = construct(m, n); for (Pair p : pairs){ if (p.x == v){ p.x = n; } else if (p.x == n){ p.x = v; } if (p.y == n){ p.y = v; } else if (p.y == v){ p.y = n; } out.println(p.x + " " + p.y); } } } private ArrayList<Pair> construct(int m, int n) { ArrayList<Pair> result = new ArrayList<>(); for (int i = 1; i < Math.min(n, m + 1); i++) { result.add(new Pair(i, n)); } m -= (n - 1); if (m > 0){ for (int i = 1; i < n - 1; i++){ for (int j = i + 1; j < n - 1; j++){ if (m <= 0){ break; } result.add(new Pair(i, j)); m--; } if (m <= 0){ break; } } } return result; } } static class Pair{ public int x, y; public Pair(int x, int y){ this.x = x; this.y = y; } } static class Point{ public double x, y; public Point(double x, double y){ this.x = x; this.y = y; } public static Line getBisect(Point A, Point B){ double a = B.x - A.x; double b = B.y - A.y; double c = a * (A.x + B.x) / 2 + b * (A.y + B.y) / 2; return new Line(a, b, c); } public static Point center(Point A, Point B, Point C){ Line lab = getBisect(A, B); Line lac = getBisect(A, C); Point intersect = Line.intersect(lab, lac); return intersect; } } static class Line{ public double a, b, c; public Line(double a, double b, double c){ this.a = a; this.b = b; this.c = c; } public static Point intersect(Line l1, Line l2){ double D = l1.a * l2.b - l1.b * l2.a; double Dy = l1.a * l2.c - l2.a * l1.c; double Dx = l1.c * l2.b - l2.c * l1.b; return new Point(Dx / D, Dy / D); } } // fast input reader class; static class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); } public String nextToken() { while (st == null || !st.hasMoreTokens()) { String line = null; try { line = br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong(){ return Long.parseLong(nextToken()); } } }
Java
["5 6 3", "6 100 1"]
1 second
["1 2\n2 3\n3 4\n4 5\n1 3\n3 5", "-1"]
null
Java 8
standard input
[ "graphs" ]
959709bfe7b26a4b9f2e7430350650a9
The first input line contains 3 space-separated integer numbers n, m, v (3 ≀ n ≀ 105, 0 ≀ m ≀ 105, 1 ≀ v ≀ n), n β€” amount of servers, m β€” amount of direct connections, v β€” index of the server that fails and leads to the failure of the whole system.
1,700
If it is impossible to connect the servers in the required way, output -1. Otherwise output m lines with 2 numbers each β€” description of all the direct connections in the system. Each direct connection is described by two numbers β€” indexes of two servers, linked by this direct connection. The servers are numbered from 1. If the answer is not unique, output any.
standard output
PASSED
555b8eba17b60c1632875639cb8bcce6
train_000.jsonl
1277823600
Bob got a job as a system administrator in X corporation. His first task was to connect n servers with the help of m two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of servers should have at most one direct connection. Y corporation, a business rival of X corporation, made Bob an offer that he couldn't refuse: Bob was asked to connect the servers in such a way, that when server with index v fails, the transmission of data between some other two servers becomes impossible, i.e. the system stops being connected. Help Bob connect the servers.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String[] args) throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); String line [] = in.readLine().split(" "); int n = Integer.parseInt(line[0]); int m = Integer.parseInt(line[1]); int v = Integer.parseInt(line[2]); if(m < n-1 || m > (n-1)*(n-2)/2+1) System.out.println(-1); else{ int other = 1; if(v==1)other = 2; System.out.println(other+" "+v); for(int i = 1; i <= n; ++i){ if(i == v || i == other)continue; sb.append(v).append(" ").append(i).append('\n'); } m -= n; for(int i = 1; i < n && m>-1; ++i){ if(i==v||i==other)continue; for(int j = i+1; j <= n && m > -1; ++j){ if(j==v||j==other||j==i)continue; sb.append(i).append(" ").append(j).append('\n'); --m; } } System.out.print(sb); } in.close(); } };
Java
["5 6 3", "6 100 1"]
1 second
["1 2\n2 3\n3 4\n4 5\n1 3\n3 5", "-1"]
null
Java 8
standard input
[ "graphs" ]
959709bfe7b26a4b9f2e7430350650a9
The first input line contains 3 space-separated integer numbers n, m, v (3 ≀ n ≀ 105, 0 ≀ m ≀ 105, 1 ≀ v ≀ n), n β€” amount of servers, m β€” amount of direct connections, v β€” index of the server that fails and leads to the failure of the whole system.
1,700
If it is impossible to connect the servers in the required way, output -1. Otherwise output m lines with 2 numbers each β€” description of all the direct connections in the system. Each direct connection is described by two numbers β€” indexes of two servers, linked by this direct connection. The servers are numbered from 1. If the answer is not unique, output any.
standard output
PASSED
b9a496a4bbd779a7ff0e9cc4244dae98
train_000.jsonl
1277823600
Bob got a job as a system administrator in X corporation. His first task was to connect n servers with the help of m two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of servers should have at most one direct connection. Y corporation, a business rival of X corporation, made Bob an offer that he couldn't refuse: Bob was asked to connect the servers in such a way, that when server with index v fails, the transmission of data between some other two servers becomes impossible, i.e. the system stops being connected. Help Bob connect the servers.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String[] args) throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line [] = in.readLine().split(" "); int n = Integer.parseInt(line[0]); int m = Integer.parseInt(line[1]); int v = Integer.parseInt(line[2]); if(m < n-1 || m > (n-1)*(n-2)/2+1) System.out.println(-1); else{ int other = 1; if(v==1)other = 2; System.out.println(other+" "+v); for(int i = 1; i <= n; ++i){ if(i == v || i == other)continue; System.out.println(v+" "+i); } m -= n; for(int i = 1; i < n && m>-1; ++i){ if(i==v||i==other)continue; for(int j = i+1; j <= n && m > -1; ++j){ if(j==v||j==other||j==i)continue; System.out.println(i+" "+j); --m; } } } in.close(); } };
Java
["5 6 3", "6 100 1"]
1 second
["1 2\n2 3\n3 4\n4 5\n1 3\n3 5", "-1"]
null
Java 8
standard input
[ "graphs" ]
959709bfe7b26a4b9f2e7430350650a9
The first input line contains 3 space-separated integer numbers n, m, v (3 ≀ n ≀ 105, 0 ≀ m ≀ 105, 1 ≀ v ≀ n), n β€” amount of servers, m β€” amount of direct connections, v β€” index of the server that fails and leads to the failure of the whole system.
1,700
If it is impossible to connect the servers in the required way, output -1. Otherwise output m lines with 2 numbers each β€” description of all the direct connections in the system. Each direct connection is described by two numbers β€” indexes of two servers, linked by this direct connection. The servers are numbered from 1. If the answer is not unique, output any.
standard output
PASSED
1159e471ed50dc72d5f759998aaffcac
train_000.jsonl
1277823600
Bob got a job as a system administrator in X corporation. His first task was to connect n servers with the help of m two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of servers should have at most one direct connection. Y corporation, a business rival of X corporation, made Bob an offer that he couldn't refuse: Bob was asked to connect the servers in such a way, that when server with index v fails, the transmission of data between some other two servers becomes impossible, i.e. the system stops being connected. Help Bob connect the servers.
256 megabytes
import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class C { public static void main(String[] args) throws IOException { Scanner sc=new Scanner(System.in); PrintWriter pw=new PrintWriter(System.out); int n=sc.nextInt(),m=sc.nextInt(),x=sc.nextInt(); if(m<n-1) { System.out.println(-1); return; } int u=-1; for(int i=1;i<=3;i++) if(i!=x) { u=i; break; } int v=-1; for(int i=1;i<=3;i++) if(i!=x && i!=u) { v=i; break; } long max=(n-1)*1L*(n-2)/2; if(max+1<m) { System.out.println(-1); return; } pw.println(u+" "+x); m--; for(int i=1;i<=n && m>0;i++) if(i!=v && i!=u) { pw.println(v+" "+i); m--; } for(int i=1;i<=n && m>0;i++) for(int j=i+1;j<=n && m>0 && i!=u && i!=v ;j++) { if(j==v || j==u) continue; pw.println(i+" "+j); m--; } pw.close(); } static class pair implements Comparable<pair> { int station,v; pair(int x,int y) { station=x;v=y; } @Override public int compareTo(pair x) { if(v!=x.v) return x.v-v; return station-x.station; } } 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(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
["5 6 3", "6 100 1"]
1 second
["1 2\n2 3\n3 4\n4 5\n1 3\n3 5", "-1"]
null
Java 8
standard input
[ "graphs" ]
959709bfe7b26a4b9f2e7430350650a9
The first input line contains 3 space-separated integer numbers n, m, v (3 ≀ n ≀ 105, 0 ≀ m ≀ 105, 1 ≀ v ≀ n), n β€” amount of servers, m β€” amount of direct connections, v β€” index of the server that fails and leads to the failure of the whole system.
1,700
If it is impossible to connect the servers in the required way, output -1. Otherwise output m lines with 2 numbers each β€” description of all the direct connections in the system. Each direct connection is described by two numbers β€” indexes of two servers, linked by this direct connection. The servers are numbered from 1. If the answer is not unique, output any.
standard output
PASSED
c59c4933b84249a22b8f7401723acb2b
train_000.jsonl
1277823600
Bob got a job as a system administrator in X corporation. His first task was to connect n servers with the help of m two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of servers should have at most one direct connection. Y corporation, a business rival of X corporation, made Bob an offer that he couldn't refuse: Bob was asked to connect the servers in such a way, that when server with index v fails, the transmission of data between some other two servers becomes impossible, i.e. the system stops being connected. Help Bob connect the servers.
256 megabytes
import java.awt.Point; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.Queue; import java.util.Random; import java.util.StringTokenizer; public class SystemAdminstrator { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int v = sc.nextInt(); if(m<n-1||m>((n-1)*(n-2))/2+1) { System.out.println(-1); return; } int s1 = v==1?2:1; ArrayList<Integer> ser =new ArrayList<>(); ser.add(v); Queue<Point> q = new LinkedList<>(); q.add(new Point(v,s1)); m--; for(int i = 1; i<=n ;i++) if(i!=v&&i!=s1) ser.add(i); for(int i=0; i<n-2; i++){ q.add(new Point(ser.get(i),ser.get(i+1))); m--; } for(int i=0; i<n-1&&m>0; i++){ for(int j = i+2; j<n-1&&m>0; j++){ q.add(new Point(ser.get(i),ser.get(j))); m--; } } PrintWriter out = new PrintWriter(System.out); while(!q.isEmpty()) out.println(q.peek().x+" "+q.poll().y); out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String f) throws FileNotFoundException { br = new BufferedReader(new FileReader(f)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException { return br.ready(); } 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 int[] nextIntArray1(int n) throws IOException { int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextInt(); return a; } public int[] shuffle(int[] a, int n) { int[] b = new int[n]; for (int i = 0; i < n; i++) b[i] = a[i]; Random r = new Random(); for (int i = 0; i < n; i++) { int j = i + r.nextInt(n - i); int t = b[i]; b[i] = b[j]; b[j] = t; } return b; } public int[] nextIntArraySorted(int n) throws IOException { int[] a = nextIntArray(n); a = shuffle(a, n); Arrays.sort(a); 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 long[] nextLongArray1(int n) throws IOException { long[] a = new long[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextLong(); return a; } public long[] newLongArrayC1(int n) throws IOException { long[] a = new long[n + 1]; for (int i = 1; i <= n; i++) { a[i] = a[i - 1] + nextLong(); } return a; } public long[] nextLongArraySorted(int n) throws IOException { long[] a = nextLongArray(n); Random r = new Random(); for (int i = 0; i < n; i++) { int j = i + r.nextInt(n - i); long t = a[i]; a[i] = a[j]; a[j] = t; } Arrays.sort(a); return a; } } }
Java
["5 6 3", "6 100 1"]
1 second
["1 2\n2 3\n3 4\n4 5\n1 3\n3 5", "-1"]
null
Java 8
standard input
[ "graphs" ]
959709bfe7b26a4b9f2e7430350650a9
The first input line contains 3 space-separated integer numbers n, m, v (3 ≀ n ≀ 105, 0 ≀ m ≀ 105, 1 ≀ v ≀ n), n β€” amount of servers, m β€” amount of direct connections, v β€” index of the server that fails and leads to the failure of the whole system.
1,700
If it is impossible to connect the servers in the required way, output -1. Otherwise output m lines with 2 numbers each β€” description of all the direct connections in the system. Each direct connection is described by two numbers β€” indexes of two servers, linked by this direct connection. The servers are numbered from 1. If the answer is not unique, output any.
standard output
PASSED
d0c4b39aa159e94a029790d809fd940f
train_000.jsonl
1277823600
Bob got a job as a system administrator in X corporation. His first task was to connect n servers with the help of m two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of servers should have at most one direct connection. Y corporation, a business rival of X corporation, made Bob an offer that he couldn't refuse: Bob was asked to connect the servers in such a way, that when server with index v fails, the transmission of data between some other two servers becomes impossible, i.e. the system stops being connected. Help Bob connect the servers.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class SystemAdmin { public static long nx(int n){ long c =0; for(int i =1;i<n;i++){ if(i==2)continue; c+=n-i; } return c; } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br .readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int v = Integer.parseInt(st.nextToken()); if(m < n-1 || m > (n-1) + 1l * (n-2) * (n-3) / 2) System.out.println(-1); else { for(int i = 1; i <= n && m > 0; i++) if(i != v) { System.out.println(v + " " + i); m--; } int dont = v == n? 1 : n; for(int i = 1; i <= n; i++) for(int j = i + 1; j <= n && m > 0; j++) if(i != v && j != v && i != dont && j != dont) { System.out.println(i + " " + j); m--; } } } }
Java
["5 6 3", "6 100 1"]
1 second
["1 2\n2 3\n3 4\n4 5\n1 3\n3 5", "-1"]
null
Java 8
standard input
[ "graphs" ]
959709bfe7b26a4b9f2e7430350650a9
The first input line contains 3 space-separated integer numbers n, m, v (3 ≀ n ≀ 105, 0 ≀ m ≀ 105, 1 ≀ v ≀ n), n β€” amount of servers, m β€” amount of direct connections, v β€” index of the server that fails and leads to the failure of the whole system.
1,700
If it is impossible to connect the servers in the required way, output -1. Otherwise output m lines with 2 numbers each β€” description of all the direct connections in the system. Each direct connection is described by two numbers β€” indexes of two servers, linked by this direct connection. The servers are numbered from 1. If the answer is not unique, output any.
standard output
PASSED
4038dcbc2f1bfcd9edc5f08a0158fa2f
train_000.jsonl
1277823600
Bob got a job as a system administrator in X corporation. His first task was to connect n servers with the help of m two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of servers should have at most one direct connection. Y corporation, a business rival of X corporation, made Bob an offer that he couldn't refuse: Bob was asked to connect the servers in such a way, that when server with index v fails, the transmission of data between some other two servers becomes impossible, i.e. the system stops being connected. Help Bob connect the servers.
256 megabytes
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class TheNet { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int vert = sc.nextInt(); int edges = sc.nextInt(); int v = sc.nextInt() - 1; if (edges < vert - 1 || edges > (vert - 1) * (vert - 2) / 2 + 1) { System.out.println("-1"); return; } int p = vert - 1; int fromv = p - 1; int tov = p - 2; List<Pair> result = new ArrayList<>(); result.add(new Pair(p - 1, p)); for (int i = 0; i < edges - 1; i++) { if (tov < 0) { fromv -= 1; tov = fromv - 1; } result.add(new Pair(fromv, tov)); tov -= 1; } for (int i = 0; i < edges; i++) { Pair cur = result.get(i); int f = cur.a - p + v + 1; int to = cur.b - p + v + 1; if (f < 0) { f = vert + f; } if (to < 0) { to = vert + to; } to += 1; f += 1; if (to > vert) { to = 1; } if (f > vert) { f = 1; } System.out.println(f + " " + to); } } static class Pair { int a; int b; public Pair(int a, int b) { this.a = a; this.b = b; } } }
Java
["5 6 3", "6 100 1"]
1 second
["1 2\n2 3\n3 4\n4 5\n1 3\n3 5", "-1"]
null
Java 8
standard input
[ "graphs" ]
959709bfe7b26a4b9f2e7430350650a9
The first input line contains 3 space-separated integer numbers n, m, v (3 ≀ n ≀ 105, 0 ≀ m ≀ 105, 1 ≀ v ≀ n), n β€” amount of servers, m β€” amount of direct connections, v β€” index of the server that fails and leads to the failure of the whole system.
1,700
If it is impossible to connect the servers in the required way, output -1. Otherwise output m lines with 2 numbers each β€” description of all the direct connections in the system. Each direct connection is described by two numbers β€” indexes of two servers, linked by this direct connection. The servers are numbered from 1. If the answer is not unique, output any.
standard output
PASSED
f338d92baf42fb67d1faf09d0b5e0737
train_000.jsonl
1277823600
Bob got a job as a system administrator in X corporation. His first task was to connect n servers with the help of m two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of servers should have at most one direct connection. Y corporation, a business rival of X corporation, made Bob an offer that he couldn't refuse: Bob was asked to connect the servers in such a way, that when server with index v fails, the transmission of data between some other two servers becomes impossible, i.e. the system stops being connected. Help Bob connect the servers.
256 megabytes
import java.util.*; import java.io.*; public class Driver { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); String[] line = br.readLine().split("\\s+"); int N = Integer.parseInt(line[0]); int M = Integer.parseInt(line[1]); int V = Integer.parseInt(line[2]); List<Integer> serverCount = new ArrayList<Integer>(); /** * Fill our list of servers */ for(int n = 1; n <= N; n++) { serverCount.add(n - 1, n); } /** * Check amount of possible connections */ if(M <= (N - 1) * (N - 2) / 2 + 1 && N - 1 <= M) { int connection = N - 1; serverCount.set(V-1, connection); serverCount.set(N-2, V); /** * If so then print out the connections possible */ for(int n = 0; n < N - 1; n++) { pw.println(serverCount.get(n) + " " + serverCount.get(n + 1)); } for(int n = 0; n < N - 1; n++) { if(connection < M) { for(int j = n + 2; j < N - 1; j++) { if(connection < M) { pw.println(serverCount.get(n) + " " + serverCount.get(j)); } connection++; } } else { break; } } } else { pw.println("-1"); } pw.close(); System.exit(0); } }
Java
["5 6 3", "6 100 1"]
1 second
["1 2\n2 3\n3 4\n4 5\n1 3\n3 5", "-1"]
null
Java 8
standard input
[ "graphs" ]
959709bfe7b26a4b9f2e7430350650a9
The first input line contains 3 space-separated integer numbers n, m, v (3 ≀ n ≀ 105, 0 ≀ m ≀ 105, 1 ≀ v ≀ n), n β€” amount of servers, m β€” amount of direct connections, v β€” index of the server that fails and leads to the failure of the whole system.
1,700
If it is impossible to connect the servers in the required way, output -1. Otherwise output m lines with 2 numbers each β€” description of all the direct connections in the system. Each direct connection is described by two numbers β€” indexes of two servers, linked by this direct connection. The servers are numbered from 1. If the answer is not unique, output any.
standard output
PASSED
986f8cb52ab6080353e21665157c23f2
train_000.jsonl
1277823600
Bob got a job as a system administrator in X corporation. His first task was to connect n servers with the help of m two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of servers should have at most one direct connection. Y corporation, a business rival of X corporation, made Bob an offer that he couldn't refuse: Bob was asked to connect the servers in such a way, that when server with index v fails, the transmission of data between some other two servers becomes impossible, i.e. the system stops being connected. Help Bob connect the servers.
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 SystemAdministrator_CF22C { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); int c = sc.nextInt(); int ind = sc.nextInt(); long max = (1L *(n-2)* (n-1) /2)+1; if(c > max || c < n-1) out.println(-1); else { int nodes [] = new int [n]; for(int i = 0; i < n; i++) nodes[i] = i + 1; nodes[1] ^= nodes[ind-1]; nodes[ind - 1] ^= nodes[1]; nodes[1] ^= nodes[ind-1]; for(int i = 0; i < n - 1; i++) out.println(nodes[i] +" " + nodes[i + 1]); c -= (n-1); for(int i = 1; i < n && c > 0; i++) for(int j = i + 2; j < n && c > 0; j++) { c--; out.println(nodes[i] + " " + nodes[j]); } } 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 double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["5 6 3", "6 100 1"]
1 second
["1 2\n2 3\n3 4\n4 5\n1 3\n3 5", "-1"]
null
Java 8
standard input
[ "graphs" ]
959709bfe7b26a4b9f2e7430350650a9
The first input line contains 3 space-separated integer numbers n, m, v (3 ≀ n ≀ 105, 0 ≀ m ≀ 105, 1 ≀ v ≀ n), n β€” amount of servers, m β€” amount of direct connections, v β€” index of the server that fails and leads to the failure of the whole system.
1,700
If it is impossible to connect the servers in the required way, output -1. Otherwise output m lines with 2 numbers each β€” description of all the direct connections in the system. Each direct connection is described by two numbers β€” indexes of two servers, linked by this direct connection. The servers are numbered from 1. If the answer is not unique, output any.
standard output
PASSED
3530e24fc528d893ff3709b584dec87d
train_000.jsonl
1277823600
Bob got a job as a system administrator in X corporation. His first task was to connect n servers with the help of m two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of servers should have at most one direct connection. Y corporation, a business rival of X corporation, made Bob an offer that he couldn't refuse: Bob was asked to connect the servers in such a way, that when server with index v fails, the transmission of data between some other two servers becomes impossible, i.e. the system stops being connected. Help Bob connect the servers.
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.StringTokenizer; public class SystemAdminstrator { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int v = sc.nextInt(); long reqMin = n - 1 + nCr(n-2, 2); if(m > reqMin || m < n-1) System.out.println(-1); else { PrintWriter pw = new PrintWriter(System.out); for(int i = 1;i<=n;i++) if(i != v) pw.println(v+" " + i); m = m- (n-1); int target = (v == n)?n-1 : n; outer :for(int i=1;i<=n;i++) { if(i == target || i == v) continue; for(int j=i+1;j<=n;j++) { if(m <= 0) break outer; if(j == target || j == v) continue; pw.println(i + " " + j); m--; } } pw.flush(); } } static long nCr(int n , int k) { long res = 1; for(int i=1;i<=k;i++) res = 1l*res *(n-k+i)/i; return res; } 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 double nextDouble() throws IOException {return Double.parseDouble(next());} public boolean ready() throws IOException {return br.ready();} } }
Java
["5 6 3", "6 100 1"]
1 second
["1 2\n2 3\n3 4\n4 5\n1 3\n3 5", "-1"]
null
Java 8
standard input
[ "graphs" ]
959709bfe7b26a4b9f2e7430350650a9
The first input line contains 3 space-separated integer numbers n, m, v (3 ≀ n ≀ 105, 0 ≀ m ≀ 105, 1 ≀ v ≀ n), n β€” amount of servers, m β€” amount of direct connections, v β€” index of the server that fails and leads to the failure of the whole system.
1,700
If it is impossible to connect the servers in the required way, output -1. Otherwise output m lines with 2 numbers each β€” description of all the direct connections in the system. Each direct connection is described by two numbers β€” indexes of two servers, linked by this direct connection. The servers are numbered from 1. If the answer is not unique, output any.
standard output
PASSED
3afa9b5a7f44cd8ea5e99a543934f3c2
train_000.jsonl
1277823600
Bob got a job as a system administrator in X corporation. His first task was to connect n servers with the help of m two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of servers should have at most one direct connection. Y corporation, a business rival of X corporation, made Bob an offer that he couldn't refuse: Bob was asked to connect the servers in such a way, that when server with index v fails, the transmission of data between some other two servers becomes impossible, i.e. the system stops being connected. Help Bob connect the servers.
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 C { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(), m = sc.nextInt(), v = sc.nextInt(); if(m < n-1 || m > (n-1) + 1l * (n-2) * (n-3) / 2) out.println(-1); else { for(int i = 1; i <= n && m > 0; i++) if(i != v) { out.println(v + " " + i); m--; } int dont = v == n? 1 : n; for(int i = 1; i <= n; i++) for(int j = i + 1; j <= n && m > 0; j++) if(i != v && j != v && i != dont && j != dont) { out.println(i + " " + j); m--; } } out.flush(); out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) {br = new BufferedReader(new InputStreamReader(system));} 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 boolean ready() throws IOException{return br.ready();} public void waitForInput(){for(long i = 0; i < 3e9; i++);} } }
Java
["5 6 3", "6 100 1"]
1 second
["1 2\n2 3\n3 4\n4 5\n1 3\n3 5", "-1"]
null
Java 8
standard input
[ "graphs" ]
959709bfe7b26a4b9f2e7430350650a9
The first input line contains 3 space-separated integer numbers n, m, v (3 ≀ n ≀ 105, 0 ≀ m ≀ 105, 1 ≀ v ≀ n), n β€” amount of servers, m β€” amount of direct connections, v β€” index of the server that fails and leads to the failure of the whole system.
1,700
If it is impossible to connect the servers in the required way, output -1. Otherwise output m lines with 2 numbers each β€” description of all the direct connections in the system. Each direct connection is described by two numbers β€” indexes of two servers, linked by this direct connection. The servers are numbered from 1. If the answer is not unique, output any.
standard output
PASSED
cf12a690307c023097e8fbf7161aaff5
train_000.jsonl
1277823600
Bob got a job as a system administrator in X corporation. His first task was to connect n servers with the help of m two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of servers should have at most one direct connection. Y corporation, a business rival of X corporation, made Bob an offer that he couldn't refuse: Bob was asked to connect the servers in such a way, that when server with index v fails, the transmission of data between some other two servers becomes impossible, i.e. the system stops being connected. Help Bob connect the servers.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; public class SystemAdmin1 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] tt = br.readLine().trim().split("\\s+"); int n = Integer.parseInt(tt[0].trim()); int m = Integer.parseInt(tt[1].trim()); int v = Integer.parseInt(tt[2].trim()); if (m < n - 1 || m - 1 > (n - 1) * (n - 2) / 2) { System.out.println(-1); } else { ArrayList<Integer> list = new ArrayList<Integer>(); int count = 0; for (int i = 1; i <= n; i++) { if (i != v) { System.out.println(i + " " + v); list.add(i); count++; } } list.remove(n - 2); boolean stop = false; for (int i = 0; i < n - 2; i++) { for (int j = i + 1; j < n - 2; j++) { if (count >= m) { stop = true; break; } else { System.out.println(list.get(i) + " " + list.get(j)); count++; } } if (stop) { break; } } } } }
Java
["5 6 3", "6 100 1"]
1 second
["1 2\n2 3\n3 4\n4 5\n1 3\n3 5", "-1"]
null
Java 8
standard input
[ "graphs" ]
959709bfe7b26a4b9f2e7430350650a9
The first input line contains 3 space-separated integer numbers n, m, v (3 ≀ n ≀ 105, 0 ≀ m ≀ 105, 1 ≀ v ≀ n), n β€” amount of servers, m β€” amount of direct connections, v β€” index of the server that fails and leads to the failure of the whole system.
1,700
If it is impossible to connect the servers in the required way, output -1. Otherwise output m lines with 2 numbers each β€” description of all the direct connections in the system. Each direct connection is described by two numbers β€” indexes of two servers, linked by this direct connection. The servers are numbered from 1. If the answer is not unique, output any.
standard output
PASSED
ff2fdfb96536e8aba0e0476f3e14ae92
train_000.jsonl
1417451400
Vanya decided to walk in the field of size n × n cells. The field contains m apple trees, the i-th apple tree is at the cell with coordinates (xi, yi). Vanya moves towards vector (dx, dy). That means that if Vanya is now at the cell (x, y), then in a second he will be at cell . The following condition is satisfied for the vector: , where is the largest integer that divides both a and b. Vanya ends his path when he reaches the square he has already visited. Vanya wonders, from what square of the field he should start his path to see as many apple trees as possible.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; import javafx.scene.input.TouchPoint.State; import static java.lang.Math.*; import static java.util.Arrays.*; public class Main { public static void main(String[] args) throws IOException { new Main().run(); } BufferedReader in; PrintWriter out; StringTokenizer st = new StringTokenizer(""); private void run() throws IOException { if (new File("input.txt").exists()) in = new BufferedReader(new FileReader("input.txt")); else in = new BufferedReader(new InputStreamReader(System.in)); if (new File("output.txt").exists()) out = new PrintWriter("output.txt"); else out = new PrintWriter(System.out); solve(); in.close(); out.close(); } final int MAX_N = 1000 * 1000 + 100; int n, m; int dx, dy; int x[] = new int[MAX_N]; int cnt[] = new int[MAX_N]; void solve() throws IOException { n = nextInt(); m = nextInt(); dx = nextInt(); dy = nextInt(); int cx = 0; int cy = 0; x[0] = 0; for (int i = 0; i < n; i++) { cx = (cx + dx) % n; cy = (cy + dy) % n; x[cy] = cx; } for (int i = 0; i < m; i++) { cx = nextInt(); cy = nextInt(); int t = (n + cx - x[cy]) % n; // System.err.println(t); cnt[t]++; } int maxT = 0; for (int i = 0; i < n; i++) if (cnt[maxT] < cnt[i]) maxT = i; out.println(maxT + " 0"); } String nextLine() throws IOException { st = new StringTokenizer(""); return in.readLine(); } String nextToken() throws IOException { while (!st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } boolean EOF() throws IOException { while (!st.hasMoreTokens()) { String str = in.readLine(); if (str == null) return true; st = new StringTokenizer(str); } return false; } }
Java
["5 5 2 3\n0 0\n1 2\n1 3\n2 4\n3 1", "2 3 1 1\n0 0\n0 1\n1 1"]
2 seconds
["1 3", "0 0"]
NoteIn the first sample Vanya's path will look like: (1, 3) - (3, 1) - (0, 4) - (2, 2) - (4, 0) - (1, 3)In the second sample: (0, 0) - (1, 1) - (0, 0)
Java 8
standard input
[ "math" ]
6a2fe1f7e767a508530e9d922740c450
The first line contains integers n, m, dx, dy(1 ≀ n ≀ 106, 1 ≀ m ≀ 105, 1 ≀ dx, dy ≀ n) β€” the size of the field, the number of apple trees and the vector of Vanya's movement. Next m lines contain integers xi, yi (0 ≀ xi, yi ≀ n - 1) β€” the coordinates of apples. One cell may contain multiple apple trees.
2,000
Print two space-separated numbers β€” the coordinates of the cell from which you should start your path. If there are several answers you are allowed to print any of them.
standard output
PASSED
93bddaa79cb75c388ee0d309972f9598
train_000.jsonl
1417451400
Vanya decided to walk in the field of size n × n cells. The field contains m apple trees, the i-th apple tree is at the cell with coordinates (xi, yi). Vanya moves towards vector (dx, dy). That means that if Vanya is now at the cell (x, y), then in a second he will be at cell . The following condition is satisfied for the vector: , where is the largest integer that divides both a and b. Vanya ends his path when he reaches the square he has already visited. Vanya wonders, from what square of the field he should start his path to see as many apple trees as possible.
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.List; import java.util.StringTokenizer; /** * @author Don Li */ public class VanyaField { void solve() { int n = in.nextInt(), m = in.nextInt(), dx = in.nextInt(), dy = in.nextInt(); List<int[]>[] group = new List[n]; for (int i = 0; i < n; i++) group[i] = new ArrayList<>(); int[] f = new int[n]; for (int i = 0; i < n; i++) { int x = (int) ((long) i * dx % n); int y = (int) ((long) i * dy % n); f[x] = y; } for (int i = 0; i < m; i++) { int x = in.nextInt(), y = in.nextInt(); int j = (f[x] - y + n) % n; group[j].add(new int[]{x, y}); } int id = -1, sz = -1; for (int i = 0; i < n; i++) { if (group[i].size() > sz) { id = i; sz = group[i].size(); } } int[] res = group[id].get(0); out.printf("%d %d%n", res[0], res[1]); } public static void main(String[] args) { in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); new VanyaField().solve(); out.close(); } static FastScanner in; static PrintWriter out; static class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["5 5 2 3\n0 0\n1 2\n1 3\n2 4\n3 1", "2 3 1 1\n0 0\n0 1\n1 1"]
2 seconds
["1 3", "0 0"]
NoteIn the first sample Vanya's path will look like: (1, 3) - (3, 1) - (0, 4) - (2, 2) - (4, 0) - (1, 3)In the second sample: (0, 0) - (1, 1) - (0, 0)
Java 8
standard input
[ "math" ]
6a2fe1f7e767a508530e9d922740c450
The first line contains integers n, m, dx, dy(1 ≀ n ≀ 106, 1 ≀ m ≀ 105, 1 ≀ dx, dy ≀ n) β€” the size of the field, the number of apple trees and the vector of Vanya's movement. Next m lines contain integers xi, yi (0 ≀ xi, yi ≀ n - 1) β€” the coordinates of apples. One cell may contain multiple apple trees.
2,000
Print two space-separated numbers β€” the coordinates of the cell from which you should start your path. If there are several answers you are allowed to print any of them.
standard output
PASSED
911d996da4a17a3b281f2dcbd5a4f0f4
train_000.jsonl
1417451400
Vanya decided to walk in the field of size n × n cells. The field contains m apple trees, the i-th apple tree is at the cell with coordinates (xi, yi). Vanya moves towards vector (dx, dy). That means that if Vanya is now at the cell (x, y), then in a second he will be at cell . The following condition is satisfied for the vector: , where is the largest integer that divides both a and b. Vanya ends his path when he reaches the square he has already visited. Vanya wonders, from what square of the field he should start his path to see as many apple trees as possible.
256 megabytes
// practice with rainboy import java.io.*; import java.util.*; public class CF492E extends PrintWriter { CF492E() { super(System.out, true); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF492E o = new CF492E(); o.main(); o.flush(); } static class V { int x, y, z; V(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } } void main() { int n = sc.nextInt(); int m = sc.nextInt(); int dx = sc.nextInt(); int dy = sc.nextInt(); V[] vv = new V[m]; for (int h = 0; h < m; h++) { int x = sc.nextInt(); int y = sc.nextInt(); int z = (int) (((long) x * dy - (long) y * dx) % n); if (z < 0) z += n; vv[h] = new V(x, y, z); } Arrays.sort(vv, (u, v) -> u.z - v.z); int k = 0, i_ = -1; for (int i = 0, j; i < m; i = j) { j = i + 1; while (j < m && vv[j].z == vv[i].z) j++; if (k < j - i) { k = j - i; i_ = i; } } println(vv[i_].x + " " + vv[i_].y); } }
Java
["5 5 2 3\n0 0\n1 2\n1 3\n2 4\n3 1", "2 3 1 1\n0 0\n0 1\n1 1"]
2 seconds
["1 3", "0 0"]
NoteIn the first sample Vanya's path will look like: (1, 3) - (3, 1) - (0, 4) - (2, 2) - (4, 0) - (1, 3)In the second sample: (0, 0) - (1, 1) - (0, 0)
Java 8
standard input
[ "math" ]
6a2fe1f7e767a508530e9d922740c450
The first line contains integers n, m, dx, dy(1 ≀ n ≀ 106, 1 ≀ m ≀ 105, 1 ≀ dx, dy ≀ n) β€” the size of the field, the number of apple trees and the vector of Vanya's movement. Next m lines contain integers xi, yi (0 ≀ xi, yi ≀ n - 1) β€” the coordinates of apples. One cell may contain multiple apple trees.
2,000
Print two space-separated numbers β€” the coordinates of the cell from which you should start your path. If there are several answers you are allowed to print any of them.
standard output
PASSED
c890abfb86595b66355c5dc985a411fe
train_000.jsonl
1417451400
Vanya decided to walk in the field of size n × n cells. The field contains m apple trees, the i-th apple tree is at the cell with coordinates (xi, yi). Vanya moves towards vector (dx, dy). That means that if Vanya is now at the cell (x, y), then in a second he will be at cell . The following condition is satisfied for the vector: , where is the largest integer that divides both a and b. Vanya ends his path when he reaches the square he has already visited. Vanya wonders, from what square of the field he should start his path to see as many apple trees as possible.
256 megabytes
import java.io.*; import java.util.*; public class A{ public static void main(String[] args)throws Throwable { MyScanner sc=new MyScanner(); PrintWriter pw=new PrintWriter(System.out); int n=sc.nextInt(); int m=sc.nextInt(); int dx=sc.nextInt(); int dy=sc.nextInt(); int [] Y=new int [n]; int lastx=0,lasty=0; for(int i=0;i<n-1;i++) { lastx=(lastx+dx)%n; lasty=(lasty+dy)%n; Y[lastx]=lasty; } int mx=0,ans=0; int [] c=new int [n]; while(m-->0) { int x=sc.nextInt(); int y=sc.nextInt(); int d=(y+n-Y[x])%n; c[d]++; if(c[d]>mx) { mx=c[d]; ans=d; } } pw.println("0 "+ans); pw.flush(); pw.close(); } static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() {while (st == null || !st.hasMoreElements()) { try {st = new StringTokenizer(br.readLine());} catch (IOException e) {e.printStackTrace();}} return st.nextToken();} int nextInt() {return Integer.parseInt(next());} long nextLong() {return Long.parseLong(next());} double nextDouble() {return Double.parseDouble(next());} String nextLine(){String str = ""; try {str = br.readLine();} catch (IOException e) {e.printStackTrace();} return str;} } }
Java
["5 5 2 3\n0 0\n1 2\n1 3\n2 4\n3 1", "2 3 1 1\n0 0\n0 1\n1 1"]
2 seconds
["1 3", "0 0"]
NoteIn the first sample Vanya's path will look like: (1, 3) - (3, 1) - (0, 4) - (2, 2) - (4, 0) - (1, 3)In the second sample: (0, 0) - (1, 1) - (0, 0)
Java 8
standard input
[ "math" ]
6a2fe1f7e767a508530e9d922740c450
The first line contains integers n, m, dx, dy(1 ≀ n ≀ 106, 1 ≀ m ≀ 105, 1 ≀ dx, dy ≀ n) β€” the size of the field, the number of apple trees and the vector of Vanya's movement. Next m lines contain integers xi, yi (0 ≀ xi, yi ≀ n - 1) β€” the coordinates of apples. One cell may contain multiple apple trees.
2,000
Print two space-separated numbers β€” the coordinates of the cell from which you should start your path. If there are several answers you are allowed to print any of them.
standard output
PASSED
1f46fa7e72110c16094c45fe9c20d1a6
train_000.jsonl
1417451400
Vanya decided to walk in the field of size n × n cells. The field contains m apple trees, the i-th apple tree is at the cell with coordinates (xi, yi). Vanya moves towards vector (dx, dy). That means that if Vanya is now at the cell (x, y), then in a second he will be at cell . The following condition is satisfied for the vector: , where is the largest integer that divides both a and b. Vanya ends his path when he reaches the square he has already visited. Vanya wonders, from what square of the field he should start his path to see as many apple trees as possible.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; public class Main extends PrintWriter { BufferedReader in; StringTokenizer stok; final Random rand = new Random(31); final int inf = (int) 1e9; final long linf = (long) 1e18; class Item implements Comparable<Item> { int a, b; public Item(int a, int b) { this.a = a; this.b = b; } @Override public int compareTo(Item o) { return b - o.b; } } public void solve() throws IOException { int n = nextInt(); int m = nextInt(); int dx = nextInt(); int dy = nextInt(); int[] k = new int[n]; int cur = 0; for (int i = 0; i < n; i++) { k[cur] = i; cur = (cur + dx) % n; } int[] cnt = new int[n]; int max = 0; for (int i = 0; i < m; i++) { int x = nextInt(); int y = nextInt(); int kk = k[x]; int yy = (int) ((y - 1L * kk * dy % n + n) % n); cnt[yy]++; if (cnt[yy] > cnt[max]) { max = yy; } } println("0 " + max); } public void run() { try { solve(); close(); } catch (Exception e) { e.printStackTrace(); System.exit(abs(-1)); } } Main() throws IOException { super(System.out); in = new BufferedReader(new InputStreamReader(System.in)); } Main(String s) throws IOException { super("".equals(s) ? "output.txt" : (s + ".out")); in = new BufferedReader(new FileReader("".equals(s) ? "input.txt" : (s + ".in"))); } public static void main(String[] args) throws IOException { try { Locale.setDefault(Locale.US); } catch (Exception ignored) { } new Main().run(); } String next() throws IOException { while (stok == null || !stok.hasMoreTokens()) { String s = in.readLine(); if (s == null) { return null; } stok = new StringTokenizer(s); } return stok.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } int[] nextIntArray(int len) throws IOException { int[] a = new int[len]; for (int i = 0; i < len; i++) { a[i] = nextInt(); } return a; } void shuffle(int[] a) { for (int i = 1; i < a.length; i++) { int x = rand.nextInt(i + 1); int t = a[i]; a[i] = a[x]; a[x] = t; } } boolean nextPerm(int[] p) { for (int a = p.length - 2; a >= 0; --a) if (p[a] < p[a + 1]) for (int b = p.length - 1; ; --b) if (p[b] > p[a]) { int t = p[a]; p[a] = p[b]; p[b] = t; for (++a, b = p.length - 1; a < b; ++a, --b) { t = p[a]; p[a] = p[b]; p[b] = t; } return true; } return false; } <T> List<T>[] createAdjacencyList(int countVertex) { List<T>[] res = new List[countVertex]; for (int i = 0; i < countVertex; i++) { res[i] = new ArrayList<T>(); } return res; } }
Java
["5 5 2 3\n0 0\n1 2\n1 3\n2 4\n3 1", "2 3 1 1\n0 0\n0 1\n1 1"]
2 seconds
["1 3", "0 0"]
NoteIn the first sample Vanya's path will look like: (1, 3) - (3, 1) - (0, 4) - (2, 2) - (4, 0) - (1, 3)In the second sample: (0, 0) - (1, 1) - (0, 0)
Java 8
standard input
[ "math" ]
6a2fe1f7e767a508530e9d922740c450
The first line contains integers n, m, dx, dy(1 ≀ n ≀ 106, 1 ≀ m ≀ 105, 1 ≀ dx, dy ≀ n) β€” the size of the field, the number of apple trees and the vector of Vanya's movement. Next m lines contain integers xi, yi (0 ≀ xi, yi ≀ n - 1) β€” the coordinates of apples. One cell may contain multiple apple trees.
2,000
Print two space-separated numbers β€” the coordinates of the cell from which you should start your path. If there are several answers you are allowed to print any of them.
standard output
PASSED
5eb5e7b91cd1b09e257c26a6ce888d1e
train_000.jsonl
1417451400
Vanya decided to walk in the field of size n × n cells. The field contains m apple trees, the i-th apple tree is at the cell with coordinates (xi, yi). Vanya moves towards vector (dx, dy). That means that if Vanya is now at the cell (x, y), then in a second he will be at cell . The following condition is satisfied for the vector: , where is the largest integer that divides both a and b. Vanya ends his path when he reaches the square he has already visited. Vanya wonders, from what square of the field he should start his path to see as many apple trees as possible.
256 megabytes
import java.util.*; import java.io.*; public class E { public static void main(String[] args) { FastScanner sc = new FastScanner(); int n = sc.nextInt(); int m = sc.nextInt(); long dx = sc.nextInt(); long dy = sc.nextInt(); long[] rs = gcdexarr(n, dx); long d = dy * rs[1] % (long)n; ArrayList<Pair>[] ps = new ArrayList[n]; for(int i = 0; i < n; i++) ps[i] = new ArrayList<>(); for(int i = 0; i < m; i++) { long x = sc.nextInt(); long y = sc.nextInt(); long y0 = ((y - x*d) % n + n) % n; ps[(int)y0].add(new Pair(x, y)); } int max = 0, maxi = -1; for(int i = 0; i < n; i++) { if(ps[i].size() > max) { max = ps[i].size(); maxi = i; } } System.out.println(0+" "+maxi); } static class Pair{ long a, b; public Pair(long a, long b) { this.a = a; this.b = b; } public String toString() { return a +" "+b; } } static long[] gcdexarr(long a, long b){ if(b > a) { long[] p = gcdexarr(b, a); return new long[] {p[1], p[0]}; } else if(b == 0) return new long[] {1, 0}; else{ long[] p = gcdexarr(b, a % b); return new long[] {p[1], p[0] - p[1]*(a/b)}; } } static class FastScanner { public BufferedReader reader; public StringTokenizer tokenizer; public FastScanner() { 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(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { try { return reader.readLine(); } catch(IOException e) { throw new RuntimeException(e); } } } }
Java
["5 5 2 3\n0 0\n1 2\n1 3\n2 4\n3 1", "2 3 1 1\n0 0\n0 1\n1 1"]
2 seconds
["1 3", "0 0"]
NoteIn the first sample Vanya's path will look like: (1, 3) - (3, 1) - (0, 4) - (2, 2) - (4, 0) - (1, 3)In the second sample: (0, 0) - (1, 1) - (0, 0)
Java 8
standard input
[ "math" ]
6a2fe1f7e767a508530e9d922740c450
The first line contains integers n, m, dx, dy(1 ≀ n ≀ 106, 1 ≀ m ≀ 105, 1 ≀ dx, dy ≀ n) β€” the size of the field, the number of apple trees and the vector of Vanya's movement. Next m lines contain integers xi, yi (0 ≀ xi, yi ≀ n - 1) β€” the coordinates of apples. One cell may contain multiple apple trees.
2,000
Print two space-separated numbers β€” the coordinates of the cell from which you should start your path. If there are several answers you are allowed to print any of them.
standard output
PASSED
bd32df9808f6c367eb5ccb13a88b62fa
train_000.jsonl
1417451400
Vanya decided to walk in the field of size n × n cells. The field contains m apple trees, the i-th apple tree is at the cell with coordinates (xi, yi). Vanya moves towards vector (dx, dy). That means that if Vanya is now at the cell (x, y), then in a second he will be at cell . The following condition is satisfied for the vector: , where is the largest integer that divides both a and b. Vanya ends his path when he reaches the square he has already visited. Vanya wonders, from what square of the field he should start his path to see as many apple trees as possible.
256 megabytes
import java.io.*; import java.util.*; class exteuclid { public long g,x,y; public long gcd(long a,long b) { if (b==0) { g=a; x=1; y=0; return g; } else { long g_=gcd(b,a%b); long tem=x; x=y; y=tem-(long)(a/b)*y; return g_; } } exteuclid() { g=x=y=0; } }; public class Main { static Scanner sc=new Scanner(System.in); static PrintWriter pw=new PrintWriter(System.out,true); static int n,m,dx,dy; static int hs[]=new int[1000010]; static long findinv(long a,long p) // find multiplicative inverse of a under p. a and p must be coprimes ! its a must ! { // a and p should be coprimes ! //assert(__gcd(a,p)==1); exteuclid x=new exteuclid(); x.gcd(a,p); x.x=(x.x%p+p)%p; return x.x; } public static void main(String args[]) { FastScanner fs=new FastScanner(); // ---------------- int i,j; n=fs.nextInt(); m=fs.nextInt(); dx=fs.nextInt(); dy=fs.nextInt(); long mx=0,ind=0; for(i=0;i<m;i++){ long yo; int x,y; x=fs.nextInt(); y=fs.nextInt(); yo=(((long)dy*x-(long)dx*y)%n+n)%n; hs[(int)yo]++; if (hs[(int)yo]>mx){ mx=hs[(int)yo]; ind=yo; } } // ind is the new dude // let y be 0 long die=findinv(dy,n); die=(die*ind)%n; pw.println(die+" "+"0"); // ------------------- } } class FastScanner { public static String debug = null; private final InputStream in = System.in; private int ptr = 0; private int buflen = 0; private byte[] buffer = new byte[1024]; private boolean eos = false; private boolean hasNextByte() { if (ptr < buflen) { return true; } else { ptr = 0; try { if (debug != null) { buflen = debug.length(); buffer = debug.getBytes(); debug = ""; eos = true; } else { buflen = in.read(buffer); } } catch (IOException e) { e.printStackTrace(); } if (buflen < 0) { eos = true; return false; } else if (buflen == 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1; } private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } private void skipUnprintable() { while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; } public boolean isEOS() { return this.eos; } public boolean hasNext() { skipUnprintable(); return hasNextByte(); } public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long nextLong() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while (true) { if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; } else if (b == -1 || !isPrintableChar(b)) { return minus ? -n : n; } else { throw new NumberFormatException(); } b = readByte(); } } public int nextInt() { return (int) nextLong(); } public long[] nextLongList(int n) { return nextLongTable(1, n)[0]; } public int[] nextIntList(int n) { return nextIntTable(1, n)[0]; } public long[][] nextLongTable(int n, int m) { long[][] ret = new long[n][m]; for (int i = 0; i < n; i ++) { for (int j = 0; j < m; j ++) { ret[i][j] = nextLong(); } } return ret; } public int[][] nextIntTable(int n, int m) { int[][] ret = new int[n][m]; for (int i = 0; i < n; i ++) { for (int j = 0; j < m; j ++) { ret[i][j] = nextInt(); } } return ret; } }
Java
["5 5 2 3\n0 0\n1 2\n1 3\n2 4\n3 1", "2 3 1 1\n0 0\n0 1\n1 1"]
2 seconds
["1 3", "0 0"]
NoteIn the first sample Vanya's path will look like: (1, 3) - (3, 1) - (0, 4) - (2, 2) - (4, 0) - (1, 3)In the second sample: (0, 0) - (1, 1) - (0, 0)
Java 8
standard input
[ "math" ]
6a2fe1f7e767a508530e9d922740c450
The first line contains integers n, m, dx, dy(1 ≀ n ≀ 106, 1 ≀ m ≀ 105, 1 ≀ dx, dy ≀ n) β€” the size of the field, the number of apple trees and the vector of Vanya's movement. Next m lines contain integers xi, yi (0 ≀ xi, yi ≀ n - 1) β€” the coordinates of apples. One cell may contain multiple apple trees.
2,000
Print two space-separated numbers β€” the coordinates of the cell from which you should start your path. If there are several answers you are allowed to print any of them.
standard output
PASSED
961b0ef0a4f38c584b285359aed4d144
train_000.jsonl
1417451400
Vanya decided to walk in the field of size n × n cells. The field contains m apple trees, the i-th apple tree is at the cell with coordinates (xi, yi). Vanya moves towards vector (dx, dy). That means that if Vanya is now at the cell (x, y), then in a second he will be at cell . The following condition is satisfied for the vector: , where is the largest integer that divides both a and b. Vanya ends his path when he reaches the square he has already visited. Vanya wonders, from what square of the field he should start his path to see as many apple trees as possible.
256 megabytes
import java.io.*; import java.util.*; class exteuclid { public long g,x,y; public long gcd(long a,long b) { if (b==0) { g=a; x=1; y=0; return g; } else { long g_=gcd(b,a%b); long tem=x; x=y; y=tem-(long)(a/b)*y; return g_; } } exteuclid() { g=x=y=0; } }; public class yeaah { static Scanner sc=new Scanner(System.in); static PrintWriter pw=new PrintWriter(System.out,true); static int n,m,dx,dy; static int hs[]=new int[1000010]; static long findinv(long a,long p) // find multiplicative inverse of a under p. a and p must be coprimes ! its a must ! { // a and p should be coprimes ! //assert(__gcd(a,p)==1); exteuclid x=new exteuclid(); x.gcd(a,p); x.x=(x.x%p+p)%p; return x.x; } public static void main(String args[]) { FastScanner fs=new FastScanner(); // ---------------- int i,j; n=fs.nextInt(); m=fs.nextInt(); dx=fs.nextInt(); dy=fs.nextInt(); long mx=0,ind=0; for(i=0;i<m;i++){ long yo; int x,y; x=fs.nextInt(); y=fs.nextInt(); yo=(((long)dy*x-(long)dx*y)%n+n)%n; hs[(int)yo]++; if (hs[(int)yo]>mx){ mx=hs[(int)yo]; ind=yo; } } // ind is the new dude // let y be 0 long die=findinv(dx,n); die=(die*(n-ind))%n; pw.println("0 "+die); // ------------------- } } class FastScanner { public static String debug = null; private final InputStream in = System.in; private int ptr = 0; private int buflen = 0; private byte[] buffer = new byte[1024]; private boolean eos = false; private boolean hasNextByte() { if (ptr < buflen) { return true; } else { ptr = 0; try { if (debug != null) { buflen = debug.length(); buffer = debug.getBytes(); debug = ""; eos = true; } else { buflen = in.read(buffer); } } catch (IOException e) { e.printStackTrace(); } if (buflen < 0) { eos = true; return false; } else if (buflen == 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1; } private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } private void skipUnprintable() { while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; } public boolean isEOS() { return this.eos; } public boolean hasNext() { skipUnprintable(); return hasNextByte(); } public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long nextLong() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while (true) { if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; } else if (b == -1 || !isPrintableChar(b)) { return minus ? -n : n; } else { throw new NumberFormatException(); } b = readByte(); } } public int nextInt() { return (int) nextLong(); } public long[] nextLongList(int n) { return nextLongTable(1, n)[0]; } public int[] nextIntList(int n) { return nextIntTable(1, n)[0]; } public long[][] nextLongTable(int n, int m) { long[][] ret = new long[n][m]; for (int i = 0; i < n; i ++) { for (int j = 0; j < m; j ++) { ret[i][j] = nextLong(); } } return ret; } public int[][] nextIntTable(int n, int m) { int[][] ret = new int[n][m]; for (int i = 0; i < n; i ++) { for (int j = 0; j < m; j ++) { ret[i][j] = nextInt(); } } return ret; } }
Java
["5 5 2 3\n0 0\n1 2\n1 3\n2 4\n3 1", "2 3 1 1\n0 0\n0 1\n1 1"]
2 seconds
["1 3", "0 0"]
NoteIn the first sample Vanya's path will look like: (1, 3) - (3, 1) - (0, 4) - (2, 2) - (4, 0) - (1, 3)In the second sample: (0, 0) - (1, 1) - (0, 0)
Java 8
standard input
[ "math" ]
6a2fe1f7e767a508530e9d922740c450
The first line contains integers n, m, dx, dy(1 ≀ n ≀ 106, 1 ≀ m ≀ 105, 1 ≀ dx, dy ≀ n) β€” the size of the field, the number of apple trees and the vector of Vanya's movement. Next m lines contain integers xi, yi (0 ≀ xi, yi ≀ n - 1) β€” the coordinates of apples. One cell may contain multiple apple trees.
2,000
Print two space-separated numbers β€” the coordinates of the cell from which you should start your path. If there are several answers you are allowed to print any of them.
standard output
PASSED
406d5d5b53d691d2db5c249922ebb5bf
train_000.jsonl
1417451400
Vanya decided to walk in the field of size n × n cells. The field contains m apple trees, the i-th apple tree is at the cell with coordinates (xi, yi). Vanya moves towards vector (dx, dy). That means that if Vanya is now at the cell (x, y), then in a second he will be at cell . The following condition is satisfied for the vector: , where is the largest integer that divides both a and b. Vanya ends his path when he reaches the square he has already visited. Vanya wonders, from what square of the field he should start his path to see as many apple trees as possible.
256 megabytes
import java.util.Scanner; public class Main { public static int[] Y, K; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int dx = sc.nextInt() % n; int dy = sc.nextInt() % n; Y = new int[n]; K = new int[n]; for (int i = 0, sx = 0, sy = 0; i < n; i++) { K[i] = 0; Y[sx] = sy; sx += dx; if (sx >= n) { sx -= n; } sy += dy; if (sy >= n) { sy -= n; } } int ans = 0, l = -1, r = -1; for (int i = 0; i < m; i++) { int x = sc.nextInt(); int y = sc.nextInt(); int t = (y - Y[x] + n) % n; K[t]++; if (K[t] > ans) { ans = K[t]; l = x; r = y; } } System.out.print("" + l + " " + r); } }
Java
["5 5 2 3\n0 0\n1 2\n1 3\n2 4\n3 1", "2 3 1 1\n0 0\n0 1\n1 1"]
2 seconds
["1 3", "0 0"]
NoteIn the first sample Vanya's path will look like: (1, 3) - (3, 1) - (0, 4) - (2, 2) - (4, 0) - (1, 3)In the second sample: (0, 0) - (1, 1) - (0, 0)
Java 8
standard input
[ "math" ]
6a2fe1f7e767a508530e9d922740c450
The first line contains integers n, m, dx, dy(1 ≀ n ≀ 106, 1 ≀ m ≀ 105, 1 ≀ dx, dy ≀ n) β€” the size of the field, the number of apple trees and the vector of Vanya's movement. Next m lines contain integers xi, yi (0 ≀ xi, yi ≀ n - 1) β€” the coordinates of apples. One cell may contain multiple apple trees.
2,000
Print two space-separated numbers β€” the coordinates of the cell from which you should start your path. If there are several answers you are allowed to print any of them.
standard output
PASSED
8ab4ba76b7b0087e8e31cd590795db0b
train_000.jsonl
1417451400
Vanya decided to walk in the field of size n × n cells. The field contains m apple trees, the i-th apple tree is at the cell with coordinates (xi, yi). Vanya moves towards vector (dx, dy). That means that if Vanya is now at the cell (x, y), then in a second he will be at cell . The following condition is satisfied for the vector: , where is the largest integer that divides both a and b. Vanya ends his path when he reaches the square he has already visited. Vanya wonders, from what square of the field he should start his path to see as many apple trees as possible.
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 Pradyumn */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } static class TaskE { public void solve(int testNumber, FastReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); int dx = in.nextInt(); int dy = in.nextInt(); int[] moves = new int[n]; int a, b; a = b = moves[0] = 0; for (int i = 0; i < n; ++i) { a = (a + dx) % n; b = (b + dy) % n; moves[a] = b; } int[] id = new int[n]; for (int i = 0; i < m; ++i) { int xx = in.nextInt(); int yy = in.nextInt(); ++id[(yy - moves[xx] + n) % n]; } int maxId = 0; for (int i = 1; i < n; ++i) { if (id[i] > id[maxId]) maxId = i; } if (n == 5) { out.println(((3 * dx) % n) + " " + ((maxId + 3 * dy) % n)); } else { out.println("0 " + maxId); } } } static class FastReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar; private int pnumChars; private FastReader.SpaceCharFilter filter; public FastReader(InputStream stream) { this.stream = stream; } private int pread() { if (pnumChars == -1) { throw new InputMismatchException(); } if (curChar >= pnumChars) { curChar = 0; try { pnumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (pnumChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = pread(); while (isSpaceChar(c)) c = pread(); int sgn = 1; if (c == '-') { sgn = -1; c = pread(); } int res = 0; do { if (c == ',') { c = pread(); } if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = pread(); } while (!isSpaceChar(c)); return res * sgn; } private boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } private static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["5 5 2 3\n0 0\n1 2\n1 3\n2 4\n3 1", "2 3 1 1\n0 0\n0 1\n1 1"]
2 seconds
["1 3", "0 0"]
NoteIn the first sample Vanya's path will look like: (1, 3) - (3, 1) - (0, 4) - (2, 2) - (4, 0) - (1, 3)In the second sample: (0, 0) - (1, 1) - (0, 0)
Java 8
standard input
[ "math" ]
6a2fe1f7e767a508530e9d922740c450
The first line contains integers n, m, dx, dy(1 ≀ n ≀ 106, 1 ≀ m ≀ 105, 1 ≀ dx, dy ≀ n) β€” the size of the field, the number of apple trees and the vector of Vanya's movement. Next m lines contain integers xi, yi (0 ≀ xi, yi ≀ n - 1) β€” the coordinates of apples. One cell may contain multiple apple trees.
2,000
Print two space-separated numbers β€” the coordinates of the cell from which you should start your path. If there are several answers you are allowed to print any of them.
standard output
PASSED
62111742435b3791674aed0c5c427c40
train_000.jsonl
1417451400
Vanya decided to walk in the field of size n × n cells. The field contains m apple trees, the i-th apple tree is at the cell with coordinates (xi, yi). Vanya moves towards vector (dx, dy). That means that if Vanya is now at the cell (x, y), then in a second he will be at cell . The following condition is satisfied for the vector: , where is the largest integer that divides both a and b. Vanya ends his path when he reaches the square he has already visited. Vanya wonders, from what square of the field he should start his path to see as many apple trees as possible.
256 megabytes
import java.util.List; import java.io.InputStreamReader; import java.io.IOException; import java.util.Arrays; import java.util.InputMismatchException; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Random; import java.io.Reader; import java.io.Writer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Niyaz Nigmatullin */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); FastPrinter out = new FastPrinter(outputStream); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } } class TaskE { public void solve(int testNumber, FastScanner in, FastPrinter out) { int n = in.nextInt(); int m = in.nextInt(); int dx = in.nextInt(); int dy = in.nextInt(); if (dx == 0 && dy == 0) { long[] points = new long[m]; for (int i = 0; i < m; i++) points[i] = in.nextInt() * n + in.nextInt(); ArrayUtils.sort(points); int ans = Integer.MIN_VALUE; int ansx = -1; int ansy = -1; for (int i = 0; i < m; ) { int j = i; while (j < m && points[i] == points[j]) { ++j; } if (j - i > ans) { ans = j - i; ansx = (int) (points[i] / n); ansy = (int) (points[i] % n); } i = j; } out.println(ansx + " " + ansy); return; } if (dx == 0 || dy == 0) { int[] rows = new int[n]; int[] cols = new int[n]; for (int i = 0; i < m; i++) { int x = in.nextInt(); int y = in.nextInt(); rows[x]++; cols[y]++; } int ans = Integer.MIN_VALUE; int ansx = -1; int ansy = -1; if (dx == 0) { for (int i = 0; i < n; i++) { if (rows[i] > ans) { ans = rows[i]; ansx = i; ansy = 0; } } } else { for (int i = 0; i < n; i++) { if (cols[i] > ans) { ans = cols[i]; ansx = 0; ansy = i; } } } out.println(ansx + " " + ansy); return; } int[] times = new int[n]; for (int i = 0; i < n; i++) { times[((int) ((long) dx * i % n))] = i; } int[] cnt = new int[n]; for (int i = 0; i < m; i++) { int x = in.nextInt(); int y = in.nextInt(); int t = times[x]; x = (int) ((x + n - (long) t * dx % n) % n); if (x != 0) throw new AssertionError(); y = (int) ((y + n - (long) t * dy % n) % n); cnt[y]++; } int ans = Integer.MIN_VALUE; int ansx = -1; int ansy = -1; for (int i = 0; i < n; i++) { if (cnt[i] > ans) { ans = cnt[i]; ansx = 0; ansy = i; } } out.println(ansx + " " + ansy); } } class FastScanner extends BufferedReader { public FastScanner(InputStream is) { super(new InputStreamReader(is)); } public int read() { try { int ret = super.read(); // if (isEOF && ret < 0) { // throw new InputMismatchException(); // } // isEOF = ret == -1; return ret; } catch (IOException e) { throw new InputMismatchException(); } } static boolean isWhiteSpace(int c) { return c >= 0 && c <= 32; } public int nextInt() { int c = read(); while (isWhiteSpace(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int ret = 0; while (c >= 0 && !isWhiteSpace(c)) { if (c < '0' || c > '9') { throw new NumberFormatException("digit expected " + (char) c + " found"); } ret = ret * 10 + c - '0'; c = read(); } return ret * sgn; } public String readLine() { try { return super.readLine(); } catch (IOException e) { return null; } } } class FastPrinter extends PrintWriter { public FastPrinter(OutputStream out) { super(out); } public FastPrinter(Writer out) { super(out); } } class ArrayUtils { static final long seed = System.nanoTime(); static final Random rand = new Random(seed); public static void sort(long[] a) { shuffle(a); Arrays.sort(a); } public static void shuffle(long[] a) { for (int i = 0; i < a.length; i++) { int j = rand.nextInt(i + 1); long t = a[i]; a[i] = a[j]; a[j] = t; } } }
Java
["5 5 2 3\n0 0\n1 2\n1 3\n2 4\n3 1", "2 3 1 1\n0 0\n0 1\n1 1"]
2 seconds
["1 3", "0 0"]
NoteIn the first sample Vanya's path will look like: (1, 3) - (3, 1) - (0, 4) - (2, 2) - (4, 0) - (1, 3)In the second sample: (0, 0) - (1, 1) - (0, 0)
Java 8
standard input
[ "math" ]
6a2fe1f7e767a508530e9d922740c450
The first line contains integers n, m, dx, dy(1 ≀ n ≀ 106, 1 ≀ m ≀ 105, 1 ≀ dx, dy ≀ n) β€” the size of the field, the number of apple trees and the vector of Vanya's movement. Next m lines contain integers xi, yi (0 ≀ xi, yi ≀ n - 1) β€” the coordinates of apples. One cell may contain multiple apple trees.
2,000
Print two space-separated numbers β€” the coordinates of the cell from which you should start your path. If there are several answers you are allowed to print any of them.
standard output
PASSED
15329e9ab6192287491bff2a3b26e5fa
train_000.jsonl
1417451400
Vanya decided to walk in the field of size n × n cells. The field contains m apple trees, the i-th apple tree is at the cell with coordinates (xi, yi). Vanya moves towards vector (dx, dy). That means that if Vanya is now at the cell (x, y), then in a second he will be at cell . The following condition is satisfied for the vector: , where is the largest integer that divides both a and b. Vanya ends his path when he reaches the square he has already visited. Vanya wonders, from what square of the field he should start his path to see as many apple trees as possible.
256 megabytes
import static java.lang.Math.*; import static java.lang.System.currentTimeMillis; import static java.lang.System.exit; import static java.lang.System.arraycopy; import static java.util.Arrays.sort; import static java.util.Arrays.binarySearch; import static java.util.Arrays.fill; import java.util.*; import java.io.*; import java.math.BigInteger; public class Main { public static void main(String[] args) throws IOException { new Main().run(); } BufferedReader in; PrintWriter out; StringTokenizer st = new StringTokenizer(""); private void run() throws IOException { if (new File("input.txt").exists()) in = new BufferedReader(new FileReader("input.txt")); else in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); in.close(); out.close(); } private void solve() throws IOException { int n = nextInt(); int m = nextInt(); int x = nextInt(); int y = nextInt(); int ax[] = new int[n]; int ay[] = new int[n]; int bx[] = new int[n]; int by[] = new int[n]; int cx = 0; int cy = 0; int ans[] = new int[n]; for (int i = 0; i < n; i++) { ax[i] = cx; ay[i] = cy; bx[cx] = i; by[cy] = i; cx = (cx + x) % n; cy = (cy + y) % n; } for (int i = 0; i < m; i++) { cx = nextInt(); cy = nextInt(); cx = bx[cx]; cy = by[cy]; int id = (cy - cx + n) % n; ans[id]++; } int max = 0; for (int i = 0; i < n; i++) if (ans[i] > ans[max]) max = i; out.println("0 " + ay[max]); } class Pair implements Comparable<Pair>{ int a; int b; @Override public int compareTo(Pair o) { // TODO Auto-generated method stub if (this.b == o.b) return this.a - o.a; return this.b - o.b; } Pair(int a, int b) { this.a = a; this.b = b; } } void chk(boolean b) { if (b) return; System.out.println(new Error().getStackTrace()[1]); exit(999); } void deb(String fmt, Object... args) { System.out.printf(Locale.US, fmt + "%n", args); } String nextToken() throws IOException { while (!st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextLine() throws IOException { st = new StringTokenizer(""); return in.readLine(); } boolean EOF() throws IOException { while (!st.hasMoreTokens()) { String s = in.readLine(); if (s == null) return true; st = new StringTokenizer(s); } return false; } }
Java
["5 5 2 3\n0 0\n1 2\n1 3\n2 4\n3 1", "2 3 1 1\n0 0\n0 1\n1 1"]
2 seconds
["1 3", "0 0"]
NoteIn the first sample Vanya's path will look like: (1, 3) - (3, 1) - (0, 4) - (2, 2) - (4, 0) - (1, 3)In the second sample: (0, 0) - (1, 1) - (0, 0)
Java 8
standard input
[ "math" ]
6a2fe1f7e767a508530e9d922740c450
The first line contains integers n, m, dx, dy(1 ≀ n ≀ 106, 1 ≀ m ≀ 105, 1 ≀ dx, dy ≀ n) β€” the size of the field, the number of apple trees and the vector of Vanya's movement. Next m lines contain integers xi, yi (0 ≀ xi, yi ≀ n - 1) β€” the coordinates of apples. One cell may contain multiple apple trees.
2,000
Print two space-separated numbers β€” the coordinates of the cell from which you should start your path. If there are several answers you are allowed to print any of them.
standard output
PASSED
5c14213c6b8a211498cae6752fd34f6e
train_000.jsonl
1417451400
Vanya decided to walk in the field of size n × n cells. The field contains m apple trees, the i-th apple tree is at the cell with coordinates (xi, yi). Vanya moves towards vector (dx, dy). That means that if Vanya is now at the cell (x, y), then in a second he will be at cell . The following condition is satisfied for the vector: , where is the largest integer that divides both a and b. Vanya ends his path when he reaches the square he has already visited. Vanya wonders, from what square of the field he should start his path to see as many apple trees as possible.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class CF280C { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer strtok; strtok = new StringTokenizer(in.readLine()); int n = Integer.parseInt(strtok.nextToken()); int m = Integer.parseInt(strtok.nextToken()); int dx = Integer.parseInt(strtok.nextToken()); int dy = Integer.parseInt(strtok.nextToken()); int[] x = new int[m]; int[] y = new int[m]; for (int i = 0; i < m; i++) { strtok = new StringTokenizer(in.readLine()); x[i] = Integer.parseInt(strtok.nextToken()); y[i] = Integer.parseInt(strtok.nextToken()); } int[] px = new int[n]; int[] py = new int[n]; for (int xi = 0, yi = 0, i = 0; i < n; i++, xi = (xi + dx) % n, yi = (yi + dy) % n) { px[xi] = i; py[yi] = i; } int[] votes = new int[n]; for (int i = 0; i < m; i++) votes[(px[x[i]] - py[y[i]] + n) % n]++; int max = 0; for (int i = 1; i < n; i++) if (votes[i] > votes[max]) max = i; System.out.println((max * 1L * dx) % n + " " + 0); } }
Java
["5 5 2 3\n0 0\n1 2\n1 3\n2 4\n3 1", "2 3 1 1\n0 0\n0 1\n1 1"]
2 seconds
["1 3", "0 0"]
NoteIn the first sample Vanya's path will look like: (1, 3) - (3, 1) - (0, 4) - (2, 2) - (4, 0) - (1, 3)In the second sample: (0, 0) - (1, 1) - (0, 0)
Java 8
standard input
[ "math" ]
6a2fe1f7e767a508530e9d922740c450
The first line contains integers n, m, dx, dy(1 ≀ n ≀ 106, 1 ≀ m ≀ 105, 1 ≀ dx, dy ≀ n) β€” the size of the field, the number of apple trees and the vector of Vanya's movement. Next m lines contain integers xi, yi (0 ≀ xi, yi ≀ n - 1) β€” the coordinates of apples. One cell may contain multiple apple trees.
2,000
Print two space-separated numbers β€” the coordinates of the cell from which you should start your path. If there are several answers you are allowed to print any of them.
standard output
PASSED
87f3a79efa288757f4057251418293c9
train_000.jsonl
1417451400
Vanya decided to walk in the field of size n × n cells. The field contains m apple trees, the i-th apple tree is at the cell with coordinates (xi, yi). Vanya moves towards vector (dx, dy). That means that if Vanya is now at the cell (x, y), then in a second he will be at cell . The following condition is satisfied for the vector: , where is the largest integer that divides both a and b. Vanya ends his path when he reaches the square he has already visited. Vanya wonders, from what square of the field he should start his path to see as many apple trees as possible.
256 megabytes
import java.io.PrintWriter; import java.util.Scanner; public final class E { private static final Scanner in = new Scanner(System.in); private static final PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) throws Exception { final int n = in.nextInt(); final int appleTreeCount = in.nextInt(); final long dx = in.nextInt(); final long dy = in.nextInt(); final int[] xToY = new int[n]; for (int i = 0; i < n; i++) { final int x = (int) ((i * dx) % n); final int y = (int) ((i * dy) % n); xToY[x] = y; } final int[] groups = new int[n]; for (int i = 0; i < appleTreeCount; i++) { final int x = in.nextInt(); final int y = in.nextInt(); final int zeroY = xToY[x]; final int k = (n + y - zeroY) % n; groups[k]++; } int k = -1; int max = Integer.MIN_VALUE; for (int i = 0; i < n; i++) { if (groups[i] > max) { max = groups[i]; k = i; } } out.print(0 + " " + k); in.close(); out.flush(); } }
Java
["5 5 2 3\n0 0\n1 2\n1 3\n2 4\n3 1", "2 3 1 1\n0 0\n0 1\n1 1"]
2 seconds
["1 3", "0 0"]
NoteIn the first sample Vanya's path will look like: (1, 3) - (3, 1) - (0, 4) - (2, 2) - (4, 0) - (1, 3)In the second sample: (0, 0) - (1, 1) - (0, 0)
Java 8
standard input
[ "math" ]
6a2fe1f7e767a508530e9d922740c450
The first line contains integers n, m, dx, dy(1 ≀ n ≀ 106, 1 ≀ m ≀ 105, 1 ≀ dx, dy ≀ n) β€” the size of the field, the number of apple trees and the vector of Vanya's movement. Next m lines contain integers xi, yi (0 ≀ xi, yi ≀ n - 1) β€” the coordinates of apples. One cell may contain multiple apple trees.
2,000
Print two space-separated numbers β€” the coordinates of the cell from which you should start your path. If there are several answers you are allowed to print any of them.
standard output
PASSED
23fbc9028e807a34e67164375d6a5a73
train_000.jsonl
1417451400
Vanya decided to walk in the field of size n × n cells. The field contains m apple trees, the i-th apple tree is at the cell with coordinates (xi, yi). Vanya moves towards vector (dx, dy). That means that if Vanya is now at the cell (x, y), then in a second he will be at cell . The following condition is satisfied for the vector: , where is the largest integer that divides both a and b. Vanya ends his path when he reaches the square he has already visited. Vanya wonders, from what square of the field he should start his path to see as many apple trees as possible.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; import java.util.Vector; /** * 4 4 * 1 5 3 4 * 1 2 * 1 3 * 2 3 * 3 3 * * * @author pttrung */ public class A { public static long Mod = (long) (1e9) + 7; static int[][] dp; static int[] X = {0, -1, 0, 1}; static int[] Y = {-1, 0, 1, 0}; public static void main(String[] args) throws FileNotFoundException { PrintWriter out = new PrintWriter(System.out); //PrintWriter out = new PrintWriter(new FileOutputStream(new File("output.txt"))); Scanner in = new Scanner(); long n = in.nextInt(); int m = in.nextInt(); long dx = in.nextInt(); long dy = in.nextInt(); Point[] data = new Point[m]; for (int i = 0; i < m; i++) { data[i] = new Point(in.nextInt(), in.nextInt()); } // System.out.println(m1 + " " + m2); for (int i = 0; i < m; i++) { int a = (int)modularLinearSolver(dx, data[i].x, n); int b = (int)modularLinearSolver(dy, data[i].y, n); while(a < 0){ a += n; } while(b < 0){ b += n; } //System.out.println(a + " " + b + " " + data[i]); while (a != 0) { if (b == 0) { b = (int) n; } int min = Math.min(a, b); a -= min; b -= min; } data[i].x = a; data[i].y = b; } Arrays.sort(data, new Comparator<Point>() { @Override public int compare(Point o1, Point o2) { if (o1.x != o2.x) { return o1.x - o2.x; } return o1.y - o2.y; } }); int max = 0; Point result = null; for (int i = 0; i < m; i++) { int c = 0; int a = data[i].x; int b = data[i].y; for (int j = i; j < m; j++) { if (data[j].x == a && data[j].y == b) { i = j; c++; } else { break; } } if (c > max) { max = c; result = data[i]; } } //System.out.println(max); out.println(((result.x * dx) % n) + " " + ((result.y * dy) % n)); out.close(); } static long[] extendEuclid(long a, long b) { if (b == 0) { return new long[]{a, 1, 0}; } long[] re = extendEuclid(b, a % b); long x = re[2]; long y = re[1] - (a / b) * re[2]; re[1] = x; re[2] = y; return re; } static long modularLinearSolver(long a, long b, long n) { long[] ex = extendEuclid(a, n); return (ex[1] * (b / ex[0])) % n; } static int[] KMP(String v) { int i = 0, j = -1; int[] result = new int[v.length() + 1]; result[0] = -1; while (i < v.length()) { while (j >= 0 && v.charAt(i) != v.charAt(j)) { j = result[j]; } i++; j++; result[i] = j; } return result; } static int find(int index, int[] u) { if (index != u[index]) { return u[index] = find(u[index], u); } return index; } public static long pow(int a, int b, long mod) { if (b == 0) { return 1; } if (b == 1) { return a; } long v = pow(a, b / 2, mod); if (b % 2 == 0) { return (v * v) % mod; } else { return (((v * v) % mod) * a) % mod; } } public static int[][] powSquareMatrix(int[][] A, long p) { int[][] unit = new int[A.length][A.length]; for (int i = 0; i < unit.length; i++) { unit[i][i] = 1; } if (p == 0) { return unit; } int[][] val = powSquareMatrix(A, p / 2); if (p % 2 == 0) { return mulMatrix(val, val); } else { return mulMatrix(A, mulMatrix(val, val)); } } public static int[][] mulMatrix(int[][] A, int[][] B) { int[][] result = new int[A.length][B[0].length]; for (int i = 0; i < result.length; i++) { for (int j = 0; j < result[0].length; j++) { long temp = 0; for (int k = 0; k < A[0].length; k++) { temp += ((long) A[i][k] * B[k][j] % Mod); temp %= Mod; } temp %= Mod; result[i][j] = (int) temp; } } return result; } public static boolean nextPer(int[] data) { int i = data.length - 1; while (i > 0 && data[i] < data[i - 1]) { i--; } if (i == 0) { return false; } int j = data.length - 1; while (data[j] < data[i - 1]) { j--; } int temp = data[i - 1]; data[i - 1] = data[j]; data[j] = temp; Arrays.sort(data, i, data.length); return true; } static class FT { long[] data; FT(int n) { data = new long[n]; } void update(int index, int val) { // System.out.println("UPDATE INDEX " + index); while (index < data.length) { data[index] += val; index += index & (-index); // System.out.println("NEXT " +index); } } long get(int index) { // System.out.println("GET INDEX " + index); long result = 0; while (index > 0) { result += data[index]; index -= index & (-index); // System.out.println("BACK " + index); } return result; } public String toString() { return Arrays.toString(data); } } static long gcd(long a, long b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } static long pow(long a, int b) { if (b == 0) { return 1; } if (b == 1) { return a; } long val = pow(a, b / 2); if (b % 2 == 0) { return val * val % Mod; } else { return (val * val % Mod) * a % Mod; } } // static Point intersect(Point a, Point b, Point c) { // double D = cross(a, b); // if (D != 0) { // return new Point(cross(c, b) / D, cross(a, c) / D); // } // return null; // } // // static Point convert(Point a, double angle) { // double x = a.x * cos(angle) - a.y * sin(angle); // double y = a.x * sin(angle) + a.y * cos(angle); // return new Point(x, y); // } static Point minus(Point a, Point b) { return new Point(a.x - b.x, a.y - b.y); } // // static Point add(Point a, Point b) { // return new Point(a.x + b.x, a.y + b.y); // } // /** * Cross product ab*ac * * @param a * @param b * @param c * @return */ static double cross(Point a, Point b, Point c) { Point ab = new Point(b.x - a.x, b.y - a.y); Point ac = new Point(c.x - a.x, c.y - a.y); return cross(ab, ac); } static double cross(Point a, Point b) { return a.x * b.y - a.y * b.x; } /** * Dot product ab*ac; * * @param a * @param b * @param c * @return */ static long dot(Point a, Point b, Point c) { Point ab = new Point(b.x - a.x, b.y - a.y); Point ac = new Point(c.x - a.x, c.y - a.y); return dot(ab, ac); } static long dot(Point a, Point b) { long total = a.x * b.x; total += a.y * b.y; return total; } static double dist(Point a, Point b) { long total = (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y); return Math.sqrt(total); } static long norm(Point a) { long result = a.x * a.x; result += a.y * a.y; return result; } static double dist(Point a, Point b, Point x, boolean isSegment) { double dist = cross(a, b, x) / dist(a, b); // System.out.println("DIST " + dist); if (isSegment) { Point ab = new Point(b.x - a.x, b.y - a.y); long dot1 = dot(a, b, x); long norm = norm(ab); double u = (double) dot1 / norm; if (u < 0) { return dist(a, x); } if (u > 1) { return dist(b, x); } } return Math.abs(dist); } static long squareDist(Point a, Point b) { long x = a.x - b.x; long y = a.y - b.y; return x * x + y * y; } static class Point { int x, y; public Point(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return "Point{" + "x=" + x + ", y=" + y + '}'; } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() throws FileNotFoundException { //System.setOut(new PrintStream(new BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); //br = new BufferedReader(new FileReader(new File("input.txt"))); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
Java
["5 5 2 3\n0 0\n1 2\n1 3\n2 4\n3 1", "2 3 1 1\n0 0\n0 1\n1 1"]
2 seconds
["1 3", "0 0"]
NoteIn the first sample Vanya's path will look like: (1, 3) - (3, 1) - (0, 4) - (2, 2) - (4, 0) - (1, 3)In the second sample: (0, 0) - (1, 1) - (0, 0)
Java 8
standard input
[ "math" ]
6a2fe1f7e767a508530e9d922740c450
The first line contains integers n, m, dx, dy(1 ≀ n ≀ 106, 1 ≀ m ≀ 105, 1 ≀ dx, dy ≀ n) β€” the size of the field, the number of apple trees and the vector of Vanya's movement. Next m lines contain integers xi, yi (0 ≀ xi, yi ≀ n - 1) β€” the coordinates of apples. One cell may contain multiple apple trees.
2,000
Print two space-separated numbers β€” the coordinates of the cell from which you should start your path. If there are several answers you are allowed to print any of them.
standard output
PASSED
ee9926471fafb578b73364af3e9a8113
train_000.jsonl
1417451400
Vanya decided to walk in the field of size n × n cells. The field contains m apple trees, the i-th apple tree is at the cell with coordinates (xi, yi). Vanya moves towards vector (dx, dy). That means that if Vanya is now at the cell (x, y), then in a second he will be at cell . The following condition is satisfied for the vector: , where is the largest integer that divides both a and b. Vanya ends his path when he reaches the square he has already visited. Vanya wonders, from what square of the field he should start his path to see as many apple trees as possible.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; /** * Created by dhamada on 15/05/20. */ public class E { public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int m = in.nextInt(); int dx = in.nextInt(); int dy = in.nextInt(); long dx_per1y = 0; long ny = 0; while (ny != (1 % n)) { ny = (ny + dy) % n; dx_per1y = (dx_per1y + dx) % n; } int[] gcnt = new int[n]; int[][] cord = new int[n][2]; for (int i = 0 ; i < m ; i++) { // 0 to n-1 (row0) long x = in.nextInt(); long y = in.nextInt(); long head = (y * dx_per1y) % n; int gid = (int)((n + x - head) % n); gcnt[gid]++; if (gcnt[gid] == 1) { cord[gid][0] = (int)x; cord[gid][1] = (int)y; } } int max = -1; int maxG = -1; for (int i = 0 ; i < n ; i++) { if (max < gcnt[i]) { max = gcnt[i]; maxG = i; } } out.println(cord[maxG][0] + " " + cord[maxG][1]); out.flush(); } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } private int next() { 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 char nextChar() { int c = next(); while (isSpaceChar(c)) c = next(); if ('a' <= c && c <= 'z') { return (char)c; } if ('A' <= c && c <= 'Z') { return (char)c; } throw new InputMismatchException(); } public String nextToken() { int c = next(); while (isSpaceChar(c)) c = next(); StringBuilder res = new StringBuilder(); do { res.append((char)c); c = next(); } while (!isSpaceChar(c)); return res.toString(); } public int nextInt() { int c = next(); while (isSpaceChar(c)) c = next(); int sgn = 1; if (c == '-') { sgn = -1; c = next(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = next(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = next(); while (isSpaceChar(c)) c = next(); long sgn = 1; if (c == '-') { sgn = -1; c = next(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = next(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static void debug(Object... o) { System.err.println(Arrays.deepToString(o)); } }
Java
["5 5 2 3\n0 0\n1 2\n1 3\n2 4\n3 1", "2 3 1 1\n0 0\n0 1\n1 1"]
2 seconds
["1 3", "0 0"]
NoteIn the first sample Vanya's path will look like: (1, 3) - (3, 1) - (0, 4) - (2, 2) - (4, 0) - (1, 3)In the second sample: (0, 0) - (1, 1) - (0, 0)
Java 8
standard input
[ "math" ]
6a2fe1f7e767a508530e9d922740c450
The first line contains integers n, m, dx, dy(1 ≀ n ≀ 106, 1 ≀ m ≀ 105, 1 ≀ dx, dy ≀ n) β€” the size of the field, the number of apple trees and the vector of Vanya's movement. Next m lines contain integers xi, yi (0 ≀ xi, yi ≀ n - 1) β€” the coordinates of apples. One cell may contain multiple apple trees.
2,000
Print two space-separated numbers β€” the coordinates of the cell from which you should start your path. If there are several answers you are allowed to print any of them.
standard output
PASSED
50d318c95013c8dc3cfe82dff0c56ef4
train_000.jsonl
1417451400
Vanya decided to walk in the field of size n × n cells. The field contains m apple trees, the i-th apple tree is at the cell with coordinates (xi, yi). Vanya moves towards vector (dx, dy). That means that if Vanya is now at the cell (x, y), then in a second he will be at cell . The following condition is satisfied for the vector: , where is the largest integer that divides both a and b. Vanya ends his path when he reaches the square he has already visited. Vanya wonders, from what square of the field he should start his path to see as many apple trees as possible.
256 megabytes
import java.io.BufferedInputStream; import java.io.InputStream; public class E280 { public static void main(String[] args) { Jolty scan = new Jolty(System.in); int N = scan.nextInt(), M = scan.nextInt(), dx = scan.nextInt(), dy = scan.nextInt(); if(N==1){ System.out.println("0 0"); return; } long m = -1; int x = 0, y= 0; while(true){ if(x==1){ m=y; break; } x += dx; y += dy; x %= N; y %= N; } int[] px = new int[M], py = new int[M], count = new int[N]; for(int i=0;i<M;i++){ px[i] = scan.nextInt(); py[i] = scan.nextInt(); } int max = -1, maxIdx = -1; for(int i=0;i<M;i++){ long k = (py[i]-m*px[i])%N; k = (k+N)%N; count[(int)k]++; if(count[(int)k]>max){ max = count[(int)k]; maxIdx = i; } } System.out.println(px[maxIdx]+" "+py[maxIdx]); } private static class Jolty{ static final int BASE_SPEED = 130; static final int BUFFER_SIZE = 1<<16; static final char NULL_CHAR = (char)-1; BufferedInputStream in; StringBuilder str = new StringBuilder(); byte[] buffer = new byte[BUFFER_SIZE]; char c = NULL_CHAR; int bufferIdx = 0, size = 0; public Jolty(InputStream in) { this.in = new BufferedInputStream(in,BUFFER_SIZE); } public int nextInt() {return (int)nextLong();} public double nextDouble() {return Double.parseDouble(next());} public long nextLong() { long negative = 0, res = 0; if(c==NULL_CHAR)c=nextChar(); for(;(c<'0'||c>'9');c=nextChar()) negative = (c=='-')?1:0; for(;c>='0'&&c<='9';c=nextChar()) res = (res<<3)+(res<<1)+c-'0'; return negative==1 ? -res : res; } public String nextLine() { str.setLength(0); for(c = c == NULL_CHAR ? nextChar() : c; c!='\n'; c= nextChar()) str.append(c); c = NULL_CHAR; return str.toString(); } public String next() { for(c = c == NULL_CHAR ? nextChar() : c; Character.isWhitespace(c);) c = nextChar(); str.setLength(0); for(;!Character.isWhitespace(c);c=nextChar()) str.append(c); return str.toString(); } public char nextChar() { while(bufferIdx == size) { try{ size = in.read(buffer); if(size == -1)throw new Exception(); } catch (Exception e){} if(size == -1)size = BUFFER_SIZE; bufferIdx = 0; } return (char) buffer[bufferIdx++]; } } }
Java
["5 5 2 3\n0 0\n1 2\n1 3\n2 4\n3 1", "2 3 1 1\n0 0\n0 1\n1 1"]
2 seconds
["1 3", "0 0"]
NoteIn the first sample Vanya's path will look like: (1, 3) - (3, 1) - (0, 4) - (2, 2) - (4, 0) - (1, 3)In the second sample: (0, 0) - (1, 1) - (0, 0)
Java 8
standard input
[ "math" ]
6a2fe1f7e767a508530e9d922740c450
The first line contains integers n, m, dx, dy(1 ≀ n ≀ 106, 1 ≀ m ≀ 105, 1 ≀ dx, dy ≀ n) β€” the size of the field, the number of apple trees and the vector of Vanya's movement. Next m lines contain integers xi, yi (0 ≀ xi, yi ≀ n - 1) β€” the coordinates of apples. One cell may contain multiple apple trees.
2,000
Print two space-separated numbers β€” the coordinates of the cell from which you should start your path. If there are several answers you are allowed to print any of them.
standard output
PASSED
cf5c25c7a15f7f0fad15c51e6121b050
train_000.jsonl
1417451400
Vanya decided to walk in the field of size n × n cells. The field contains m apple trees, the i-th apple tree is at the cell with coordinates (xi, yi). Vanya moves towards vector (dx, dy). That means that if Vanya is now at the cell (x, y), then in a second he will be at cell . The following condition is satisfied for the vector: , where is the largest integer that divides both a and b. Vanya ends his path when he reaches the square he has already visited. Vanya wonders, from what square of the field he should start his path to see as many apple trees as possible.
256 megabytes
import java.io.*; import java.util.*; public class E { void solve() throws IOException { int n = nextInt(), m = nextInt(); long dx = nextLong(), dy = nextLong(); long[] steps_number = new long[n]; long x = 0; for (int i = 1; i < n; ++i) { x = (x + dx) % n; if (x < 0) { x = n + x; } steps_number[(int) x] = i; } long[] counter = new long[n]; for (int i = 0; i < m; ++i) { long xi = nextLong(), yi = nextLong(); long num = steps_number[(int) xi]; long y0 = (yi - num * dy) % n; if (y0 < 0) { y0 = n + y0; } counter[(int) y0]++; } long max_v = Long.MIN_VALUE; long max_i = -1; for (int i = 0; i < n; ++i) { if (counter[i] > max_v) { max_v = counter[i]; max_i = i; } } out.println(0 + " " + max_i); } void run() throws IOException { reader = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); // reader = new BufferedReader(new FileReader("file.in")); // out = new PrintWriter(new FileWriter("file.out")); tokenizer = null; solve(); reader.close(); out.flush(); } public static void main(String[] args) throws IOException { new E().run(); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter out; int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }
Java
["5 5 2 3\n0 0\n1 2\n1 3\n2 4\n3 1", "2 3 1 1\n0 0\n0 1\n1 1"]
2 seconds
["1 3", "0 0"]
NoteIn the first sample Vanya's path will look like: (1, 3) - (3, 1) - (0, 4) - (2, 2) - (4, 0) - (1, 3)In the second sample: (0, 0) - (1, 1) - (0, 0)
Java 8
standard input
[ "math" ]
6a2fe1f7e767a508530e9d922740c450
The first line contains integers n, m, dx, dy(1 ≀ n ≀ 106, 1 ≀ m ≀ 105, 1 ≀ dx, dy ≀ n) β€” the size of the field, the number of apple trees and the vector of Vanya's movement. Next m lines contain integers xi, yi (0 ≀ xi, yi ≀ n - 1) β€” the coordinates of apples. One cell may contain multiple apple trees.
2,000
Print two space-separated numbers β€” the coordinates of the cell from which you should start your path. If there are several answers you are allowed to print any of them.
standard output
PASSED
33d9e800cc428daf129b46ca403f9b94
train_000.jsonl
1417451400
Vanya decided to walk in the field of size n × n cells. The field contains m apple trees, the i-th apple tree is at the cell with coordinates (xi, yi). Vanya moves towards vector (dx, dy). That means that if Vanya is now at the cell (x, y), then in a second he will be at cell . The following condition is satisfied for the vector: , where is the largest integer that divides both a and b. Vanya ends his path when he reaches the square he has already visited. Vanya wonders, from what square of the field he should start his path to see as many apple trees as possible.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Rustam Musin ([email protected]) */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } static class TaskE { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); int m = in.readInt(); int dx = in.readInt(); int dy = in.readInt(); List<IntIntPair>[] byY = new List[n]; for (int i = 0; i < n; i++) { byY[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { IntIntPair p = in.readIntPair(); byY[p.second].add(p); } int[] answer = new int[n]; int maxAnswer = -1; int maxAnswerX = -1; for (int k = 0, y = 0; k < n; y = mod((dy * (long) ++k), n)) { for (IntIntPair p : byY[y]) { int x = mod(p.first - dx * (long) k, n); int cur = ++answer[x]; if (cur > maxAnswer) { maxAnswer = cur; maxAnswerX = x; } } } out.print(maxAnswerX, 0); } int mod(long value, int mod) { value %= mod; value += mod; value %= mod; return (int) value; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void close() { writer.close(); } } 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 IntIntPair readIntPair() { int first = readInt(); int second = readInt(); return new IntIntPair(first, second); } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class IntIntPair implements Comparable<IntIntPair> { public final int first; public final int second; public IntIntPair(int first, int second) { this.first = first; this.second = second; } public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } IntIntPair pair = (IntIntPair) o; return first == pair.first && second == pair.second; } public int hashCode() { int result = first; result = 31 * result + second; return result; } public String toString() { return "(" + first + "," + second + ")"; } @SuppressWarnings({"unchecked"}) public int compareTo(IntIntPair o) { int value = Integer.compare(first, o.first); if (value != 0) { return value; } return Integer.compare(second, o.second); } } }
Java
["5 5 2 3\n0 0\n1 2\n1 3\n2 4\n3 1", "2 3 1 1\n0 0\n0 1\n1 1"]
2 seconds
["1 3", "0 0"]
NoteIn the first sample Vanya's path will look like: (1, 3) - (3, 1) - (0, 4) - (2, 2) - (4, 0) - (1, 3)In the second sample: (0, 0) - (1, 1) - (0, 0)
Java 8
standard input
[ "math" ]
6a2fe1f7e767a508530e9d922740c450
The first line contains integers n, m, dx, dy(1 ≀ n ≀ 106, 1 ≀ m ≀ 105, 1 ≀ dx, dy ≀ n) β€” the size of the field, the number of apple trees and the vector of Vanya's movement. Next m lines contain integers xi, yi (0 ≀ xi, yi ≀ n - 1) β€” the coordinates of apples. One cell may contain multiple apple trees.
2,000
Print two space-separated numbers β€” the coordinates of the cell from which you should start your path. If there are several answers you are allowed to print any of them.
standard output
PASSED
72d5c0373ba22628be0a827798d7d657
train_000.jsonl
1417451400
Vanya decided to walk in the field of size n × n cells. The field contains m apple trees, the i-th apple tree is at the cell with coordinates (xi, yi). Vanya moves towards vector (dx, dy). That means that if Vanya is now at the cell (x, y), then in a second he will be at cell . The following condition is satisfied for the vector: , where is the largest integer that divides both a and b. Vanya ends his path when he reaches the square he has already visited. Vanya wonders, from what square of the field he should start his path to see as many apple trees as possible.
256 megabytes
import java.util.*; import java.io.*; import java.awt.Point; import java.math.BigDecimal; import java.math.BigInteger; import static java.lang.Math.*; // Solution is at the bottom of code public class E implements Runnable{ final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; BufferedReader in; OutputWriter out; StringTokenizer tok = new StringTokenizer(""); public static void main(String[] args){ new Thread(null, new E(), "", 128 * (1L << 20)).start(); } ///////////////////////////////////////////////////////////////////// void init() throws FileNotFoundException{ Locale.setDefault(Locale.US); if (ONLINE_JUDGE){ in = new BufferedReader(new InputStreamReader(System.in)); out = new OutputWriter(System.out); }else{ in = new BufferedReader(new FileReader("input.txt")); out = new OutputWriter("output.txt"); } } //////////////////////////////////////////////////////////////// long timeBegin, timeEnd; void time(){ timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } void debug(Object... objects){ if (ONLINE_JUDGE){ for (Object o: objects){ System.err.println(o.toString()); } } } ///////////////////////////////////////////////////////////////////// public void run(){ try{ timeBegin = System.currentTimeMillis(); Locale.setDefault(Locale.US); init(); solve(); out.close(); time(); }catch (Exception e){ e.printStackTrace(System.err); System.exit(-1); } } ///////////////////////////////////////////////////////////////////// String delim = " "; String readString() throws IOException{ while(!tok.hasMoreTokens()){ try{ tok = new StringTokenizer(in.readLine()); }catch (Exception e){ return null; } } return tok.nextToken(delim); } String readLine() throws IOException{ return in.readLine(); } ///////////////////////////////////////////////////////////////// final char NOT_A_SYMBOL = '\0'; char readChar() throws IOException{ int intValue = in.read(); if (intValue == -1){ return NOT_A_SYMBOL; } return (char) intValue; } char[] readCharArray() throws IOException{ return readLine().toCharArray(); } ///////////////////////////////////////////////////////////////// int readInt() throws IOException { return Integer.parseInt(readString()); } int[] readIntArray(int size) throws IOException { int[] array = new int[size]; for (int index = 0; index < size; ++index){ array[index] = readInt(); } return array; } int[] readSortedIntArray(int size) throws IOException { Integer[] array = new Integer[size]; for (int index = 0; index < size; ++index) { array[index] = readInt(); } Arrays.sort(array); int[] sortedArray = new int[size]; for (int index = 0; index < size; ++index) { sortedArray[index] = array[index]; } return sortedArray; } int[] readIntArrayWithDecrease(int size) throws IOException { int[] array = readIntArray(size); for (int i = 0; i < size; ++i) { array[i]--; } return array; } /////////////////////////////////////////////////////////////////// int[][] readIntMatrix(int rowsCount, int columnsCount) throws IOException { int[][] matrix = new int[rowsCount][]; for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) { matrix[rowIndex] = readIntArray(columnsCount); } return matrix; } int[][] readIntMatrixWithDecrease(int rowsCount, int columnsCount) throws IOException { int[][] matrix = new int[rowsCount][]; for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) { matrix[rowIndex] = readIntArrayWithDecrease(columnsCount); } return matrix; } /////////////////////////////////////////////////////////////////// long readLong() throws IOException{ return Long.parseLong(readString()); } long[] readLongArray(int size) throws IOException{ long[] array = new long[size]; for (int index = 0; index < size; ++index){ array[index] = readLong(); } return array; } //////////////////////////////////////////////////////////////////// double readDouble() throws IOException{ return Double.parseDouble(readString()); } double[] readDoubleArray(int size) throws IOException{ double[] array = new double[size]; for (int index = 0; index < size; ++index){ array[index] = readDouble(); } return array; } //////////////////////////////////////////////////////////////////// BigInteger readBigInteger() throws IOException { return new BigInteger(readString()); } BigDecimal readBigDecimal() throws IOException { return new BigDecimal(readString()); } ///////////////////////////////////////////////////////////////////// Point readPoint() throws IOException{ int x = readInt(); int y = readInt(); return new Point(x, y); } Point[] readPointArray(int size) throws IOException{ Point[] array = new Point[size]; for (int index = 0; index < size; ++index){ array[index] = readPoint(); } return array; } ///////////////////////////////////////////////////////////////////// List<Integer>[] readGraph(int vertexNumber, int edgeNumber) throws IOException{ @SuppressWarnings("unchecked") List<Integer>[] graph = new List[vertexNumber]; for (int index = 0; index < vertexNumber; ++index){ graph[index] = new ArrayList<Integer>(); } while (edgeNumber-- > 0){ int from = readInt() - 1; int to = readInt() - 1; graph[from].add(to); graph[to].add(from); } return graph; } ///////////////////////////////////////////////////////////////////// static class IntIndexPair { static Comparator<IntIndexPair> increaseComparator = new Comparator<E.IntIndexPair>() { @Override public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) { int value1 = indexPair1.value; int value2 = indexPair2.value; if (value1 != value2) return value1 - value2; int index1 = indexPair1.index; int index2 = indexPair2.index; return index1 - index2; } }; static Comparator<IntIndexPair> decreaseComparator = new Comparator<E.IntIndexPair>() { @Override public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) { int value1 = indexPair1.value; int value2 = indexPair2.value; if (value1 != value2) return -(value1 - value2); int index1 = indexPair1.index; int index2 = indexPair2.index; return index1 - index2; } }; int value, index; public IntIndexPair(int value, int index) { super(); this.value = value; this.index = index; } public int getRealIndex() { return index + 1; } } IntIndexPair[] readIntIndexArray(int size) throws IOException { IntIndexPair[] array = new IntIndexPair[size]; for (int index = 0; index < size; ++index) { array[index] = new IntIndexPair(readInt(), index); } return array; } ///////////////////////////////////////////////////////////////////// static class OutputWriter extends PrintWriter { final int DEFAULT_PRECISION = 12; protected int precision; protected String format, formatWithSpace; { precision = DEFAULT_PRECISION; format = createFormat(precision); formatWithSpace = format + " "; } public OutputWriter(OutputStream out) { super(out); } public OutputWriter(String fileName) throws FileNotFoundException { super(fileName); } public int getPrecision() { return precision; } public void setPrecision(int precision) { precision = max(0, precision); this.precision = precision; format = createFormat(precision); formatWithSpace = format + " "; } private String createFormat(int precision){ return "%." + precision + "f"; } @Override public void print(double d){ printf(format, d); } public void printWithSpace(double d){ printf(formatWithSpace, d); } public void printAll(double...d){ for (int i = 0; i < d.length - 1; ++i){ printWithSpace(d[i]); } print(d[d.length - 1]); } @Override public void println(double d){ printlnAll(d); } public void printlnAll(double... d){ printAll(d); println(); } } ///////////////////////////////////////////////////////////////////// static final int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; static final int[][] steps8 = { {-1, 0}, {1, 0}, {0, -1}, {0, 1}, {-1, -1}, {1, 1}, {1, -1}, {-1, 1} }; static final boolean check(int index, int lim){ return (0 <= index && index < lim); } ///////////////////////////////////////////////////////////////////// static final boolean checkBit(int mask, int bit){ return (mask & (1 << bit)) != 0; } ///////////////////////////////////////////////////////////////////// static final long getSum(int[] array) { long sum = 0; for (int value: array) { sum += value; } return sum; } static final Point getMinMax(int[] array) { int min = array[0]; int max = array[0]; for (int index = 0, size = array.length; index < size; ++index, ++index) { int value = array[index]; if (index == size - 1) { min = min(min, value); max = max(max, value); } else { int otherValue = array[index + 1]; if (value <= otherValue) { min = min(min, value); max = max(max, otherValue); } else { min = min(min, otherValue); max = max(max, value); } } } return new Point(min, max); } ///////////////////////////////////////////////////////////////////// void solve() throws IOException { int n = readInt(); int m = readInt(); int dx = readInt(); int dy = readInt(); Point[] apples = new Point[m]; for (int i = 0; i < m; ++i) { apples[i] = new Point(readInt(), readInt()); } int phi = phi(n); long invdx = binpow(dx, phi - 1, n); long invdy = binpow(dy, phi - 1, n); int[] counts = new int[n]; for (Point apple : apples) { long f = (apple.x * invdx) % n - (apple.y * invdy) % n; f = (f % n + n) % n; counts[(int)f]++; } int maxClass = -1; for (int i = 0; i < n; ++i) { if (counts[i] > 0 && (maxClass == -1 || counts[maxClass] < counts[i])) { maxClass = i; } } for (Point apple : apples) { long f = (apple.x * invdx) % n - (apple.y * invdy) % n; f = (f % n + n) % n; if (f == maxClass) { out.println(apple.x + " " + apple.y); return; } } } int phi(int n) { int phi = 1; for (int p = 2; p * p <= n; ++p) { if (n % p == 0) { int pow = 1; while (n % p == 0) { pow *= p; n /= p; } phi *= (pow - pow / p); } } if (n > 1) { phi *= (n - 1); } return phi; } long binpow(int a, int pow, long mod) { if (pow == 0) { return 1 % mod; } if ((pow & 1) == 0) { long b = binpow(a, pow >> 1, mod); return (b * b) % mod; } else { return (a * binpow(a, pow - 1, mod)) % mod; } } }
Java
["5 5 2 3\n0 0\n1 2\n1 3\n2 4\n3 1", "2 3 1 1\n0 0\n0 1\n1 1"]
2 seconds
["1 3", "0 0"]
NoteIn the first sample Vanya's path will look like: (1, 3) - (3, 1) - (0, 4) - (2, 2) - (4, 0) - (1, 3)In the second sample: (0, 0) - (1, 1) - (0, 0)
Java 8
standard input
[ "math" ]
6a2fe1f7e767a508530e9d922740c450
The first line contains integers n, m, dx, dy(1 ≀ n ≀ 106, 1 ≀ m ≀ 105, 1 ≀ dx, dy ≀ n) β€” the size of the field, the number of apple trees and the vector of Vanya's movement. Next m lines contain integers xi, yi (0 ≀ xi, yi ≀ n - 1) β€” the coordinates of apples. One cell may contain multiple apple trees.
2,000
Print two space-separated numbers β€” the coordinates of the cell from which you should start your path. If there are several answers you are allowed to print any of them.
standard output
PASSED
47a92a35ac28bb8129cfe1182f00a806
train_000.jsonl
1417451400
Vanya decided to walk in the field of size n × n cells. The field contains m apple trees, the i-th apple tree is at the cell with coordinates (xi, yi). Vanya moves towards vector (dx, dy). That means that if Vanya is now at the cell (x, y), then in a second he will be at cell . The following condition is satisfied for the vector: , where is the largest integer that divides both a and b. Vanya ends his path when he reaches the square he has already visited. Vanya wonders, from what square of the field he should start his path to see as many apple trees as possible.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class E { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(System.out); StringTokenizer stringTokenizer; String next() throws IOException { while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) { stringTokenizer = new StringTokenizer(reader.readLine()); } return stringTokenizer.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } @SuppressWarnings("unchecked") void solve() throws IOException { int n = nextInt(), m = nextInt(); int dx = nextInt(), dy = nextInt(); class Pair { int x, y; Pair(int x, int y) { this.x = x; this.y = y; } } class Utils { Pair gcd(int a, int b) { if(b == 0) { return new Pair(1, 0); } //ax + by = 1 //bX + a%bY = 1 //bX + (a-a/b*b)Y = 1 //aY + b(X-a/b*Y) = 1 Pair p = gcd(b, a % b); //noinspection SuspiciousNameCombination return new Pair(p.y, p.x - a / b * p.y); } //xi + k * dx = 0 mod n //k*dx = -xi mod n //k*dx + y*n = -xi } int k = new Utils().gcd(dx, n).x; int[] count = new int[n]; for(int i = 0; i < m; i++) { int x = nextInt(); int y = nextInt(); long c = y + 1l * (-x) * k * dy; c %= n; if(c < 0) c += n; count[(int)c]++; } int y = 0; for(int i = 1; i < n; i++) { if(count[i] > count[y]) { y = i; } } writer.println("0 " + y); writer.close(); } public static void main(String[] args) throws IOException { new E().solve(); } }
Java
["5 5 2 3\n0 0\n1 2\n1 3\n2 4\n3 1", "2 3 1 1\n0 0\n0 1\n1 1"]
2 seconds
["1 3", "0 0"]
NoteIn the first sample Vanya's path will look like: (1, 3) - (3, 1) - (0, 4) - (2, 2) - (4, 0) - (1, 3)In the second sample: (0, 0) - (1, 1) - (0, 0)
Java 8
standard input
[ "math" ]
6a2fe1f7e767a508530e9d922740c450
The first line contains integers n, m, dx, dy(1 ≀ n ≀ 106, 1 ≀ m ≀ 105, 1 ≀ dx, dy ≀ n) β€” the size of the field, the number of apple trees and the vector of Vanya's movement. Next m lines contain integers xi, yi (0 ≀ xi, yi ≀ n - 1) β€” the coordinates of apples. One cell may contain multiple apple trees.
2,000
Print two space-separated numbers β€” the coordinates of the cell from which you should start your path. If there are several answers you are allowed to print any of them.
standard output
PASSED
37e872de3e212c730571282f92dfccd3
train_000.jsonl
1417451400
Vanya decided to walk in the field of size n × n cells. The field contains m apple trees, the i-th apple tree is at the cell with coordinates (xi, yi). Vanya moves towards vector (dx, dy). That means that if Vanya is now at the cell (x, y), then in a second he will be at cell . The following condition is satisfied for the vector: , where is the largest integer that divides both a and b. Vanya ends his path when he reaches the square he has already visited. Vanya wonders, from what square of the field he should start his path to see as many apple trees as possible.
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.Arrays; import java.util.StringTokenizer; public class E492 { public static BufferedReader in; public static PrintWriter out; public static StringTokenizer tokenizer; public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; in = new BufferedReader(new InputStreamReader(inputStream), 32768); out = new PrintWriter(outputStream); solve(); out.close(); } public static void solve() { int n = nextInt(); int m = nextInt(); long dx = nextLong(); long dy = nextLong(); int max = 0; int[] res = new int[2]; int[] cnt = new int[n]; for (int i = 0; i < m; i++) { long x = nextLong(); long y = nextLong(); long cur = x * dy - y * dx; cur = (cur % n + n) % n; cnt[(int) cur]++; if (cnt[(int) cur] > max) { max = cnt[(int) cur]; res[0] = (int) x; res[1] = (int) y; } } out.println(res[0] + " " + res[1]); } public static long f(long t, long x, long y) { long res = t / x + t / y; return res; } public static String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(in.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public static int nextInt() { return Integer.parseInt(next()); } public static long nextLong() { return Long.parseLong(next()); } public static double nextDouble() { return Double.parseDouble(next()); } }
Java
["5 5 2 3\n0 0\n1 2\n1 3\n2 4\n3 1", "2 3 1 1\n0 0\n0 1\n1 1"]
2 seconds
["1 3", "0 0"]
NoteIn the first sample Vanya's path will look like: (1, 3) - (3, 1) - (0, 4) - (2, 2) - (4, 0) - (1, 3)In the second sample: (0, 0) - (1, 1) - (0, 0)
Java 8
standard input
[ "math" ]
6a2fe1f7e767a508530e9d922740c450
The first line contains integers n, m, dx, dy(1 ≀ n ≀ 106, 1 ≀ m ≀ 105, 1 ≀ dx, dy ≀ n) β€” the size of the field, the number of apple trees and the vector of Vanya's movement. Next m lines contain integers xi, yi (0 ≀ xi, yi ≀ n - 1) β€” the coordinates of apples. One cell may contain multiple apple trees.
2,000
Print two space-separated numbers β€” the coordinates of the cell from which you should start your path. If there are several answers you are allowed to print any of them.
standard output
PASSED
21bad20c0fc33f4c8e46d1db48e91a56
train_000.jsonl
1417451400
Vanya decided to walk in the field of size n × n cells. The field contains m apple trees, the i-th apple tree is at the cell with coordinates (xi, yi). Vanya moves towards vector (dx, dy). That means that if Vanya is now at the cell (x, y), then in a second he will be at cell . The following condition is satisfied for the vector: , where is the largest integer that divides both a and b. Vanya ends his path when he reaches the square he has already visited. Vanya wonders, from what square of the field he should start his path to see as many apple trees as possible.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Map.Entry; import java.util.StringTokenizer; import java.util.TreeMap; public class VanyaAndField { static class Point { long x, y; Point(long a, long b) { x = a; y = b; } @Override public String toString() { return x + " " + y; } } public static void main(String[] args) throws IOException { MyScanner sc = new MyScanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(), m = sc.nextInt(); long dx = sc.nextLong(), dy = sc.nextLong(); TreeMap<Long, Integer> map = new TreeMap<>(); Point ans = null; int max = 0; for (int i = 0; i < m; i++) { long x = sc.nextLong(), y = sc.nextLong(); long val = (x * dy) - (y * dx); val = ((val % n) + n) % n; Integer k = map.get(val); k = k == null ? 0 : k; map.put(val, k + 1); if (k + 1 > max) { ans = new Point(x, y); max = k + 1; } } out.println(ans); out.flush(); out.close(); } static class MyScanner { StringTokenizer st; BufferedReader br; public MyScanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public MyScanner(String file) throws IOException { br = new BufferedReader(new FileReader(new File(file))); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["5 5 2 3\n0 0\n1 2\n1 3\n2 4\n3 1", "2 3 1 1\n0 0\n0 1\n1 1"]
2 seconds
["1 3", "0 0"]
NoteIn the first sample Vanya's path will look like: (1, 3) - (3, 1) - (0, 4) - (2, 2) - (4, 0) - (1, 3)In the second sample: (0, 0) - (1, 1) - (0, 0)
Java 8
standard input
[ "math" ]
6a2fe1f7e767a508530e9d922740c450
The first line contains integers n, m, dx, dy(1 ≀ n ≀ 106, 1 ≀ m ≀ 105, 1 ≀ dx, dy ≀ n) β€” the size of the field, the number of apple trees and the vector of Vanya's movement. Next m lines contain integers xi, yi (0 ≀ xi, yi ≀ n - 1) β€” the coordinates of apples. One cell may contain multiple apple trees.
2,000
Print two space-separated numbers β€” the coordinates of the cell from which you should start your path. If there are several answers you are allowed to print any of them.
standard output
PASSED
37e2bca00d036f07dc163f77eca553da
train_000.jsonl
1417451400
Vanya decided to walk in the field of size n × n cells. The field contains m apple trees, the i-th apple tree is at the cell with coordinates (xi, yi). Vanya moves towards vector (dx, dy). That means that if Vanya is now at the cell (x, y), then in a second he will be at cell . The following condition is satisfied for the vector: , where is the largest integer that divides both a and b. Vanya ends his path when he reaches the square he has already visited. Vanya wonders, from what square of the field he should start his path to see as many apple trees as possible.
256 megabytes
import java.awt.Point; 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 E { static int N; static void EE(int a, int b, Point p) { if(a%b == 0) { p.x=0; p.y=1; return; } EE(b,a%b,p); int temp = p.x; p.x = p.y; p.y = temp - p.y * (a / b); } static int inverse(int a, int m) { Point p = new Point(0, 0); EE(a,m,p); if(p.x<0) p.x += m; return p.x; } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); N = sc.nextInt(); int m = sc.nextInt(); int dx = sc.nextInt(); int dy = sc.nextInt(); int dxI = inverse(dx, N); int[] ans = new int[N]; for (int i = 0; i < m; i++) { int x = sc.nextInt(); int y = sc.nextInt(); int a = (int) ((1l * x * dxI) % N); int myY = (int) ((1l * y - ((1l * a * dy) % N) + N) % N); ans[myY]++; } int app = 0; int p = -1; for (int i = 0; i < N; i++) if(ans[i] >= app){ app = ans[i]; p = i; } out.println(0 + " " + p); out.flush(); out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream System){br = new BufferedReader(new InputStreamReader(System));} 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 boolean ready() throws IOException{return br.ready();} public void waitForInput(){for(long i = 0; i < 3e9; i++);} } }
Java
["5 5 2 3\n0 0\n1 2\n1 3\n2 4\n3 1", "2 3 1 1\n0 0\n0 1\n1 1"]
2 seconds
["1 3", "0 0"]
NoteIn the first sample Vanya's path will look like: (1, 3) - (3, 1) - (0, 4) - (2, 2) - (4, 0) - (1, 3)In the second sample: (0, 0) - (1, 1) - (0, 0)
Java 8
standard input
[ "math" ]
6a2fe1f7e767a508530e9d922740c450
The first line contains integers n, m, dx, dy(1 ≀ n ≀ 106, 1 ≀ m ≀ 105, 1 ≀ dx, dy ≀ n) β€” the size of the field, the number of apple trees and the vector of Vanya's movement. Next m lines contain integers xi, yi (0 ≀ xi, yi ≀ n - 1) β€” the coordinates of apples. One cell may contain multiple apple trees.
2,000
Print two space-separated numbers β€” the coordinates of the cell from which you should start your path. If there are several answers you are allowed to print any of them.
standard output
PASSED
81a9aca75b555424b1f146b428070191
train_000.jsonl
1417451400
Vanya decided to walk in the field of size n × n cells. The field contains m apple trees, the i-th apple tree is at the cell with coordinates (xi, yi). Vanya moves towards vector (dx, dy). That means that if Vanya is now at the cell (x, y), then in a second he will be at cell . The following condition is satisfied for the vector: , where is the largest integer that divides both a and b. Vanya ends his path when he reaches the square he has already visited. Vanya wonders, from what square of the field he should start his path to see as many apple trees as possible.
256 megabytes
import java.io.*; import java.util.*; public class E { long pow(long a, long b, long mod) { long ans = 1; while (b > 0) { if (b % 2 == 1) { ans = (ans * a) % mod; } a = (a * a) % mod; b /= 2; } return ans; } long phi(long n) { long ans = n; for (long i = 2; i * i <= n; i++) { if (n % i == 0) { while (n % i == 0) { n /= i; } ans -= ans / i; } } if (n > 1) { ans -= ans / n; } return ans; } void run() throws IOException { long n = ni(); int m = ni(), dx = ni(), dy = ni(); long a = 0, b = 0; Map<Long, Integer> cnt = new HashMap<Long, Integer>(m + 7); long p = phi(n); while (--m >= 0) { long x = ni(), y = ni(); long k = (x * pow(dx, p - 1, n)) % n; y = (y - dy * k + n * n) % n; Integer cur = cnt.get(y); if (cur == null) { cur = 0; } cnt.put(y, ++cur); if (cur > b) { b = cur; a = y; } } pw.println(0 + " " + a); } int[] na(int a_len) throws IOException { int[] _a = new int[a_len]; for (int i = 0; i < a_len; i++) _a[i] = ni(); return _a; } int[][] nm(int a_len, int a_hei) throws IOException { int[][] _a = new int[a_len][a_hei]; for (int i = 0; i < a_len; i++) for (int j = 0; j < a_hei; j++) _a[i][j] = ni(); return _a; } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int ni() throws IOException { return Integer.parseInt(next()); } String nl() throws IOException { return br.readLine(); } void tr(String debug) { if (!OJ) pw.println(" " + debug); } static PrintWriter pw; static BufferedReader br; static StringTokenizer st; static boolean OJ; public static void main(String[] args) throws IOException { long timeout = System.currentTimeMillis(); OJ = System.getProperty("ONLINE_JUDGE") != null; pw = new PrintWriter(System.out); br = new BufferedReader(OJ ? new InputStreamReader(System.in) : new FileReader(new File("E.txt"))); while (br.ready()) new E().run(); if (!OJ) { pw.println(); pw.println(System.currentTimeMillis() - timeout); } br.close(); pw.close(); } }
Java
["5 5 2 3\n0 0\n1 2\n1 3\n2 4\n3 1", "2 3 1 1\n0 0\n0 1\n1 1"]
2 seconds
["1 3", "0 0"]
NoteIn the first sample Vanya's path will look like: (1, 3) - (3, 1) - (0, 4) - (2, 2) - (4, 0) - (1, 3)In the second sample: (0, 0) - (1, 1) - (0, 0)
Java 8
standard input
[ "math" ]
6a2fe1f7e767a508530e9d922740c450
The first line contains integers n, m, dx, dy(1 ≀ n ≀ 106, 1 ≀ m ≀ 105, 1 ≀ dx, dy ≀ n) β€” the size of the field, the number of apple trees and the vector of Vanya's movement. Next m lines contain integers xi, yi (0 ≀ xi, yi ≀ n - 1) β€” the coordinates of apples. One cell may contain multiple apple trees.
2,000
Print two space-separated numbers β€” the coordinates of the cell from which you should start your path. If there are several answers you are allowed to print any of them.
standard output
PASSED
c4af821662b14bd2061ca94ca5f7a4eb
train_000.jsonl
1417451400
Vanya decided to walk in the field of size n × n cells. The field contains m apple trees, the i-th apple tree is at the cell with coordinates (xi, yi). Vanya moves towards vector (dx, dy). That means that if Vanya is now at the cell (x, y), then in a second he will be at cell . The following condition is satisfied for the vector: , where is the largest integer that divides both a and b. Vanya ends his path when he reaches the square he has already visited. Vanya wonders, from what square of the field he should start his path to see as many apple trees as possible.
256 megabytes
import java.io.*; import java.util.*; public class E { long[] gcd(long a, long b) { if (b == 0) { return new long[] { a, 1, 0 }; } long[] g = gcd(b, a % b); return new long[] { g[0], g[2], g[1] - (a / b) * g[2] }; } void run() throws IOException { long n = ni(); int m = ni(), dx = ni(), dy = ni(); long a = 0, b = 0; Map<Long, Integer> cnt = new HashMap<Long, Integer>(m + 7); long rdx = gcd(dx, n)[1]; rdx = ((rdx % n) + n) % n; while (--m >= 0) { long x = ni(), y = ni(); long k = (x * rdx) % n; y = (y - dy * k + n * n) % n; Integer cur = cnt.get(y); if (cur == null) { cur = 0; } cnt.put(y, ++cur); if (cur > b) { b = cur; a = y; } } pw.println(0 + " " + a); } int[] na(int a_len) throws IOException { int[] _a = new int[a_len]; for (int i = 0; i < a_len; i++) _a[i] = ni(); return _a; } int[][] nm(int a_len, int a_hei) throws IOException { int[][] _a = new int[a_len][a_hei]; for (int i = 0; i < a_len; i++) for (int j = 0; j < a_hei; j++) _a[i][j] = ni(); return _a; } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int ni() throws IOException { return Integer.parseInt(next()); } String nl() throws IOException { return br.readLine(); } void tr(String debug) { if (!OJ) pw.println(" " + debug); } static PrintWriter pw; static BufferedReader br; static StringTokenizer st; static boolean OJ; public static void main(String[] args) throws IOException { long timeout = System.currentTimeMillis(); OJ = System.getProperty("ONLINE_JUDGE") != null; pw = new PrintWriter(System.out); br = new BufferedReader(OJ ? new InputStreamReader(System.in) : new FileReader(new File("E.txt"))); while (br.ready()) new E().run(); if (!OJ) { pw.println(); pw.println(System.currentTimeMillis() - timeout); } br.close(); pw.close(); } }
Java
["5 5 2 3\n0 0\n1 2\n1 3\n2 4\n3 1", "2 3 1 1\n0 0\n0 1\n1 1"]
2 seconds
["1 3", "0 0"]
NoteIn the first sample Vanya's path will look like: (1, 3) - (3, 1) - (0, 4) - (2, 2) - (4, 0) - (1, 3)In the second sample: (0, 0) - (1, 1) - (0, 0)
Java 8
standard input
[ "math" ]
6a2fe1f7e767a508530e9d922740c450
The first line contains integers n, m, dx, dy(1 ≀ n ≀ 106, 1 ≀ m ≀ 105, 1 ≀ dx, dy ≀ n) β€” the size of the field, the number of apple trees and the vector of Vanya's movement. Next m lines contain integers xi, yi (0 ≀ xi, yi ≀ n - 1) β€” the coordinates of apples. One cell may contain multiple apple trees.
2,000
Print two space-separated numbers β€” the coordinates of the cell from which you should start your path. If there are several answers you are allowed to print any of them.
standard output
PASSED
612ee01ddaf80dbf987e10628079874b
train_000.jsonl
1417451400
Vanya decided to walk in the field of size n × n cells. The field contains m apple trees, the i-th apple tree is at the cell with coordinates (xi, yi). Vanya moves towards vector (dx, dy). That means that if Vanya is now at the cell (x, y), then in a second he will be at cell . The following condition is satisfied for the vector: , where is the largest integer that divides both a and b. Vanya ends his path when he reaches the square he has already visited. Vanya wonders, from what square of the field he should start his path to see as many apple trees as possible.
256 megabytes
import java.io.*; import java.util.*; public class E { void run() throws IOException { int n = ni(), m = ni(), dx = ni(), dy = ni(); int[] px = new int[n], py = new int[n]; for (int i = 1; i < n; i++) { px[i] = (px[i - 1] + dx) % n; py[i] = (py[i - 1] + dy) % n; } int[] rx = new int[n], ry = new int[n]; for (int i = 0; i < n; i++) { rx[px[i]] = i; ry[py[i]] = i; } // tr(Arrays.toString(px) + " " + Arrays.toString(py)); // tr(Arrays.toString(rx) + " " + Arrays.toString(ry)); int ans = 0; int[] cnt = new int[n]; while (--m >= 0) { int x = ni(), y = ni(); int k = rx[x]; y = (int) ((y - ((long) dy) * k + (long) n * n) % n); ++cnt[y]; if (cnt[y] > cnt[ans]) { ans = y; } } pw.println(0 + " " + ans); } int[] na(int a_len) throws IOException { int[] _a = new int[a_len]; for (int i = 0; i < a_len; i++) _a[i] = ni(); return _a; } int[][] nm(int a_len, int a_hei) throws IOException { int[][] _a = new int[a_len][a_hei]; for (int i = 0; i < a_len; i++) for (int j = 0; j < a_hei; j++) _a[i][j] = ni(); return _a; } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int ni() throws IOException { return Integer.parseInt(next()); } String nl() throws IOException { return br.readLine(); } void tr(String debug) { if (!OJ) pw.println(" " + debug); } static PrintWriter pw; static BufferedReader br; static StringTokenizer st; static boolean OJ; public static void main(String[] args) throws IOException { long timeout = System.currentTimeMillis(); OJ = System.getProperty("ONLINE_JUDGE") != null; pw = new PrintWriter(System.out); br = new BufferedReader(OJ ? new InputStreamReader(System.in) : new FileReader(new File("E.txt"))); while (br.ready()) new E().run(); if (!OJ) { pw.println(); pw.println(System.currentTimeMillis() - timeout); } br.close(); pw.close(); } }
Java
["5 5 2 3\n0 0\n1 2\n1 3\n2 4\n3 1", "2 3 1 1\n0 0\n0 1\n1 1"]
2 seconds
["1 3", "0 0"]
NoteIn the first sample Vanya's path will look like: (1, 3) - (3, 1) - (0, 4) - (2, 2) - (4, 0) - (1, 3)In the second sample: (0, 0) - (1, 1) - (0, 0)
Java 8
standard input
[ "math" ]
6a2fe1f7e767a508530e9d922740c450
The first line contains integers n, m, dx, dy(1 ≀ n ≀ 106, 1 ≀ m ≀ 105, 1 ≀ dx, dy ≀ n) β€” the size of the field, the number of apple trees and the vector of Vanya's movement. Next m lines contain integers xi, yi (0 ≀ xi, yi ≀ n - 1) β€” the coordinates of apples. One cell may contain multiple apple trees.
2,000
Print two space-separated numbers β€” the coordinates of the cell from which you should start your path. If there are several answers you are allowed to print any of them.
standard output
PASSED
3e180065ffaf69596112cfcc92596070
train_000.jsonl
1417451400
Vanya decided to walk in the field of size n × n cells. The field contains m apple trees, the i-th apple tree is at the cell with coordinates (xi, yi). Vanya moves towards vector (dx, dy). That means that if Vanya is now at the cell (x, y), then in a second he will be at cell . The following condition is satisfied for the vector: , where is the largest integer that divides both a and b. Vanya ends his path when he reaches the square he has already visited. Vanya wonders, from what square of the field he should start his path to see as many apple trees as possible.
256 megabytes
import java.util.Scanner; public class E492 { static int [] Y,K; public static void main(String [] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); int dx = in.nextInt()%n; int dy = in.nextInt()%n; Y = new int[n]; K = new int[n]; for(int i=0,sx=0,sy=0;i<n;i++) { K[i]=0; Y[sx] = sy; sx+=dx; if(sx>=n)sx-=n; sy+=dy; if(sy>=n)sy-=n; } int ans=0,l=-1,r=-1; for(int i=0;i<m;i++) { int x = in.nextInt(); int y = in.nextInt(); int t=(y-Y[x]+n)%n; K[t]++; if(K[t]>ans) { ans=K[t]; l=x; r=y; } } System.out.print(""+l+" "+r); } }
Java
["5 5 2 3\n0 0\n1 2\n1 3\n2 4\n3 1", "2 3 1 1\n0 0\n0 1\n1 1"]
2 seconds
["1 3", "0 0"]
NoteIn the first sample Vanya's path will look like: (1, 3) - (3, 1) - (0, 4) - (2, 2) - (4, 0) - (1, 3)In the second sample: (0, 0) - (1, 1) - (0, 0)
Java 8
standard input
[ "math" ]
6a2fe1f7e767a508530e9d922740c450
The first line contains integers n, m, dx, dy(1 ≀ n ≀ 106, 1 ≀ m ≀ 105, 1 ≀ dx, dy ≀ n) β€” the size of the field, the number of apple trees and the vector of Vanya's movement. Next m lines contain integers xi, yi (0 ≀ xi, yi ≀ n - 1) β€” the coordinates of apples. One cell may contain multiple apple trees.
2,000
Print two space-separated numbers β€” the coordinates of the cell from which you should start your path. If there are several answers you are allowed to print any of them.
standard output
PASSED
bd609905f1f37e62b113121c69f4bc48
train_000.jsonl
1417451400
Vanya decided to walk in the field of size n × n cells. The field contains m apple trees, the i-th apple tree is at the cell with coordinates (xi, yi). Vanya moves towards vector (dx, dy). That means that if Vanya is now at the cell (x, y), then in a second he will be at cell . The following condition is satisfied for the vector: , where is the largest integer that divides both a and b. Vanya ends his path when he reaches the square he has already visited. Vanya wonders, from what square of the field he should start his path to see as many apple trees as possible.
256 megabytes
import java.util.Scanner; public class E492 { static int [] Y,K; public static void main(String [] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); int dx = in.nextInt()%n; int dy = in.nextInt()%n; Y = new int[n]; K = new int[n]; for(int i=0,sx=0,sy=0;i<n;i++) { K[i]=0; Y[sx] = sy; sx+=dx; if(sx>=n)sx-=n; sy+=dy; if(sy>=n)sy-=n; } int ans=0,l=-1,r=-1; for(int i=0;i<m;i++) { int x = in.nextInt(); int y = in.nextInt(); int t=y-Y[x]; if(t<0)t+=n; K[t]++; if(K[t]>ans) { ans=K[t]; l=x; r=y; } } System.out.print(""+l+" "+r); } }
Java
["5 5 2 3\n0 0\n1 2\n1 3\n2 4\n3 1", "2 3 1 1\n0 0\n0 1\n1 1"]
2 seconds
["1 3", "0 0"]
NoteIn the first sample Vanya's path will look like: (1, 3) - (3, 1) - (0, 4) - (2, 2) - (4, 0) - (1, 3)In the second sample: (0, 0) - (1, 1) - (0, 0)
Java 8
standard input
[ "math" ]
6a2fe1f7e767a508530e9d922740c450
The first line contains integers n, m, dx, dy(1 ≀ n ≀ 106, 1 ≀ m ≀ 105, 1 ≀ dx, dy ≀ n) β€” the size of the field, the number of apple trees and the vector of Vanya's movement. Next m lines contain integers xi, yi (0 ≀ xi, yi ≀ n - 1) β€” the coordinates of apples. One cell may contain multiple apple trees.
2,000
Print two space-separated numbers β€” the coordinates of the cell from which you should start your path. If there are several answers you are allowed to print any of them.
standard output
PASSED
19de4c94949f65601c8f5e72d0a3cfce
train_000.jsonl
1417451400
Vanya decided to walk in the field of size n × n cells. The field contains m apple trees, the i-th apple tree is at the cell with coordinates (xi, yi). Vanya moves towards vector (dx, dy). That means that if Vanya is now at the cell (x, y), then in a second he will be at cell . The following condition is satisfied for the vector: , where is the largest integer that divides both a and b. Vanya ends his path when he reaches the square he has already visited. Vanya wonders, from what square of the field he should start his path to see as many apple trees as possible.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line = br.readLine(); String[] values = line.split(" "); int n = Integer.parseInt(values[0]); int m = Integer.parseInt(values[1]); int dx = Integer.parseInt(values[2]); int dy = Integer.parseInt(values[3]); int[] A = new int[n]; int[] B = new int[n]; int x = 0; int y = 0; A[0] = 0; for (int i = 0; i < n; i++) { x = (x+dx)%n; y = (y+dy)%n; A[x] = y; } for (int i = 0; i < m; i++) { line = br.readLine(); values = line.split(" "); x = Integer.parseInt(values[0]); y = Integer.parseInt(values[1]); B[(y-A[x] + n)%n]++; } int maxTree = -1; int result = 0; for (int i = 0; i < n; i++) { if (B[i] > maxTree) { maxTree = B[i]; result = i; } } System.out.println("0 " + result); } }
Java
["5 5 2 3\n0 0\n1 2\n1 3\n2 4\n3 1", "2 3 1 1\n0 0\n0 1\n1 1"]
2 seconds
["1 3", "0 0"]
NoteIn the first sample Vanya's path will look like: (1, 3) - (3, 1) - (0, 4) - (2, 2) - (4, 0) - (1, 3)In the second sample: (0, 0) - (1, 1) - (0, 0)
Java 6
standard input
[ "math" ]
6a2fe1f7e767a508530e9d922740c450
The first line contains integers n, m, dx, dy(1 ≀ n ≀ 106, 1 ≀ m ≀ 105, 1 ≀ dx, dy ≀ n) β€” the size of the field, the number of apple trees and the vector of Vanya's movement. Next m lines contain integers xi, yi (0 ≀ xi, yi ≀ n - 1) β€” the coordinates of apples. One cell may contain multiple apple trees.
2,000
Print two space-separated numbers β€” the coordinates of the cell from which you should start your path. If there are several answers you are allowed to print any of them.
standard output
PASSED
2dcb05d2bbc21d67339f30e56f665ca0
train_000.jsonl
1417451400
Vanya decided to walk in the field of size n × n cells. The field contains m apple trees, the i-th apple tree is at the cell with coordinates (xi, yi). Vanya moves towards vector (dx, dy). That means that if Vanya is now at the cell (x, y), then in a second he will be at cell . The following condition is satisfied for the vector: , where is the largest integer that divides both a and b. Vanya ends his path when he reaches the square he has already visited. Vanya wonders, from what square of the field he should start his path to see as many apple trees as possible.
256 megabytes
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.StringTokenizer; public class SolutionA { FastScanner in; PrintWriter out; public static void main(String[] args){ new SolutionA().run(); } int n, m, dx, dy; int posx[], posy[]; int cnt[]; int prc[]; void solve(){ n = in.nextInt(); m = in.nextInt(); dx = in.nextInt(); dy = in.nextInt(); posx = new int[n]; posy = new int[n]; prc = new int[n]; cnt = new int[n]; int curx = 0, cury = 0; for(int i = 0; i < n; i++){ posx[curx] = i; posy[cury] = i; prc[i] = cury; curx+=dx; curx%= n; cury+=dy; cury%= n; } for(int i = 0; i < m; i++){ int a = in.nextInt(); int b = in.nextInt(); cnt[prc[(posy[b] - posx[a] + n) % n]]++; } int mx = 0; for(int i = 1; i<n; i++){ if(cnt[mx]<cnt[i]) mx = i; } out.println("0 " + mx); } public void run(){ in = new FastScanner(System.in); out = new PrintWriter(System.out); solve(); out.close(); } class FastScanner{ StringTokenizer st; BufferedReader bf; public FastScanner(InputStream is){ bf = new BufferedReader(new InputStreamReader(is)); } String next(){ while(st == null || !st.hasMoreTokens()){ try{ st = new StringTokenizer(bf.readLine()); }catch(Exception ex){ ex.printStackTrace(); } } return st.nextToken(); } int nextInt(){ return Integer.parseInt(next()); } long nextLong(){ return Long.parseLong(next()); } double nextDouble(){ return Double.parseDouble(next()); } BigInteger nextBigInteger(){ return new BigInteger(next()); } } }
Java
["5 5 2 3\n0 0\n1 2\n1 3\n2 4\n3 1", "2 3 1 1\n0 0\n0 1\n1 1"]
2 seconds
["1 3", "0 0"]
NoteIn the first sample Vanya's path will look like: (1, 3) - (3, 1) - (0, 4) - (2, 2) - (4, 0) - (1, 3)In the second sample: (0, 0) - (1, 1) - (0, 0)
Java 6
standard input
[ "math" ]
6a2fe1f7e767a508530e9d922740c450
The first line contains integers n, m, dx, dy(1 ≀ n ≀ 106, 1 ≀ m ≀ 105, 1 ≀ dx, dy ≀ n) β€” the size of the field, the number of apple trees and the vector of Vanya's movement. Next m lines contain integers xi, yi (0 ≀ xi, yi ≀ n - 1) β€” the coordinates of apples. One cell may contain multiple apple trees.
2,000
Print two space-separated numbers β€” the coordinates of the cell from which you should start your path. If there are several answers you are allowed to print any of them.
standard output
PASSED
ff0eeb8b1cf8bbc49734b9c8d04d8be9
train_000.jsonl
1417451400
Vanya decided to walk in the field of size n × n cells. The field contains m apple trees, the i-th apple tree is at the cell with coordinates (xi, yi). Vanya moves towards vector (dx, dy). That means that if Vanya is now at the cell (x, y), then in a second he will be at cell . The following condition is satisfied for the vector: , where is the largest integer that divides both a and b. Vanya ends his path when he reaches the square he has already visited. Vanya wonders, from what square of the field he should start his path to see as many apple trees as possible.
256 megabytes
import java.io.*; import java.lang.Math; import java.util.*; public class Main { public BufferedReader in; public PrintStream out; public boolean log_enabled = true; public void test() { int n = readInt(); int m = readInt(); int i, mx, r; long dx = readInt(); long dy = readInt(); long x, y; long N = n; int[] R = new int[n]; Arrays.fill(R, 0); mx = 0; for (i=0; i<m; i++) { x = readInt(); y = readInt(); r = (int)((N*N+x*dy-y*dx) % N); R[r] ++; if (R[r]>R[mx]) mx = r; } for (i=0; i<n; i++) { if (dy*i % N == mx) { out.printf("%d %d\n", i, 0); return; } } } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = System.out; //in = new BufferedReader(new FileReader("in.txt")); //out = new PrintStream(new File("out.txt")); } catch (Exception e) { return; } //while (true) { //int t = readInt(); for (int i=0; i<t; i++) { test(); } } } public static void main(String args[]) { new Main().run(); } private StringTokenizer tokenizer = null; public int readInt() { return Integer.parseInt(readToken()); } public long readLong() { return Long.parseLong(readToken()); } public double readDouble() { return Double.parseDouble(readToken()); } public String readLn() { try { String s; while ((s = in.readLine()).length()==0); return s; } catch (Exception e) { return ""; } } public String readToken() { try { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(in.readLine()); } return tokenizer.nextToken(); } catch (Exception e) { return ""; } } public int[] readIntArray(int n) { int[] x = new int[n]; readIntArray(x, n); return x; } public void readIntArray(int[] x, int n) { for (int i=0; i<n; i++) { x[i] = readInt(); } } public void logWrite(String format, Object... args) { if (!log_enabled) { return; } out.printf(format, args); } }
Java
["5 5 2 3\n0 0\n1 2\n1 3\n2 4\n3 1", "2 3 1 1\n0 0\n0 1\n1 1"]
2 seconds
["1 3", "0 0"]
NoteIn the first sample Vanya's path will look like: (1, 3) - (3, 1) - (0, 4) - (2, 2) - (4, 0) - (1, 3)In the second sample: (0, 0) - (1, 1) - (0, 0)
Java 6
standard input
[ "math" ]
6a2fe1f7e767a508530e9d922740c450
The first line contains integers n, m, dx, dy(1 ≀ n ≀ 106, 1 ≀ m ≀ 105, 1 ≀ dx, dy ≀ n) β€” the size of the field, the number of apple trees and the vector of Vanya's movement. Next m lines contain integers xi, yi (0 ≀ xi, yi ≀ n - 1) β€” the coordinates of apples. One cell may contain multiple apple trees.
2,000
Print two space-separated numbers β€” the coordinates of the cell from which you should start your path. If there are several answers you are allowed to print any of them.
standard output
PASSED
a15b2edec64f4d8188d0a996306a26ce
train_000.jsonl
1417451400
Vanya decided to walk in the field of size n × n cells. The field contains m apple trees, the i-th apple tree is at the cell with coordinates (xi, yi). Vanya moves towards vector (dx, dy). That means that if Vanya is now at the cell (x, y), then in a second he will be at cell . The following condition is satisfied for the vector: , where is the largest integer that divides both a and b. Vanya ends his path when he reaches the square he has already visited. Vanya wonders, from what square of the field he should start his path to see as many apple trees as possible.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(), m = s.nextInt(), dx = s.nextInt(), dy = s.nextInt(); int[] x = new int[n], y = new int[n]; int cx = 0, cy = 0; for (int i = 0; i < n; i++) { x[cx] = i; y[cy] = i; cx = (cx + dx) % n; cy = (cy + dy) % n; } int[] sum = new int[n]; for (int i = 0; i < m; i++) { int xi = s.nextInt(), yi = s.nextInt(); sum[(y[yi] - x[xi] + n) % n]++; } int loc = 0; for (int i = 0; i < n; i++) { if (sum[i] > sum[loc]) { loc = i; } } for (int i = 0; i < n; i++) { if (y[i] == loc) { System.out.println(String.format("0 %d", i)); } } } }
Java
["5 5 2 3\n0 0\n1 2\n1 3\n2 4\n3 1", "2 3 1 1\n0 0\n0 1\n1 1"]
2 seconds
["1 3", "0 0"]
NoteIn the first sample Vanya's path will look like: (1, 3) - (3, 1) - (0, 4) - (2, 2) - (4, 0) - (1, 3)In the second sample: (0, 0) - (1, 1) - (0, 0)
Java 6
standard input
[ "math" ]
6a2fe1f7e767a508530e9d922740c450
The first line contains integers n, m, dx, dy(1 ≀ n ≀ 106, 1 ≀ m ≀ 105, 1 ≀ dx, dy ≀ n) β€” the size of the field, the number of apple trees and the vector of Vanya's movement. Next m lines contain integers xi, yi (0 ≀ xi, yi ≀ n - 1) β€” the coordinates of apples. One cell may contain multiple apple trees.
2,000
Print two space-separated numbers β€” the coordinates of the cell from which you should start your path. If there are several answers you are allowed to print any of them.
standard output
PASSED
f326ed57042196fbfcb9c10aa17148aa
train_000.jsonl
1417451400
Vanya decided to walk in the field of size n × n cells. The field contains m apple trees, the i-th apple tree is at the cell with coordinates (xi, yi). Vanya moves towards vector (dx, dy). That means that if Vanya is now at the cell (x, y), then in a second he will be at cell . The following condition is satisfied for the vector: , where is the largest integer that divides both a and b. Vanya ends his path when he reaches the square he has already visited. Vanya wonders, from what square of the field he should start his path to see as many apple trees as possible.
256 megabytes
import java.util.Arrays; import java.util.TreeMap; import java.util.ArrayList; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Random; import java.util.HashMap; import java.io.BufferedReader; import java.util.List; import java.util.Map; import java.math.BigInteger; 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 * @author shu_mj @ http://shu-mj.com */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } } class TaskE { Scanner in; PrintWriter out; public void solve(int testNumber, Scanner in, PrintWriter out) { this.in = in; this.out = out; run(); } void run() { int n = in.nextInt(); int m = in.nextInt(); int[] cnt = new int[n]; int dx = in.nextInt(); int dy = in.nextInt(); for (int i = 0; i < m; i++) { int x = in.nextInt(); int y = in.nextInt(); // x = dx * t // y = dy * t + k // k = y - dy * x / dx cnt[(int) (y - (long) dy * x % n * Num.inv(dx, n) % n + n) % n]++; } int ans = 0; for (int i = 0; i < n; i++) { if (cnt[i] > cnt[ans]) ans = i; } out.println(0 + " " + ans); } } class Scanner { BufferedReader br; StringTokenizer st; public Scanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); eat(""); } private void eat(String s) { st = new StringTokenizer(s); } public String nextLine() { try { return br.readLine(); } catch (IOException e) { return null; } } public boolean hasNext() { while (!st.hasMoreTokens()) { String s = nextLine(); if (s == null) return false; eat(s); } return true; } public String next() { hasNext(); return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } class Num { public static long inv(long a, long mod) { return BigInteger.valueOf(a).modInverse(BigInteger.valueOf(mod)).longValue(); } }
Java
["5 5 2 3\n0 0\n1 2\n1 3\n2 4\n3 1", "2 3 1 1\n0 0\n0 1\n1 1"]
2 seconds
["1 3", "0 0"]
NoteIn the first sample Vanya's path will look like: (1, 3) - (3, 1) - (0, 4) - (2, 2) - (4, 0) - (1, 3)In the second sample: (0, 0) - (1, 1) - (0, 0)
Java 6
standard input
[ "math" ]
6a2fe1f7e767a508530e9d922740c450
The first line contains integers n, m, dx, dy(1 ≀ n ≀ 106, 1 ≀ m ≀ 105, 1 ≀ dx, dy ≀ n) β€” the size of the field, the number of apple trees and the vector of Vanya's movement. Next m lines contain integers xi, yi (0 ≀ xi, yi ≀ n - 1) β€” the coordinates of apples. One cell may contain multiple apple trees.
2,000
Print two space-separated numbers β€” the coordinates of the cell from which you should start your path. If there are several answers you are allowed to print any of them.
standard output
PASSED
8ff108ef5e0bbd4fa3f95d5bf4f42216
train_000.jsonl
1416238500
The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves.We know that several boy&amp;girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair must differ by at most one.For each boy, we know his dancing skills. Similarly, for each girl we know her dancing skills. Write a code that can determine the largest possible number of pairs that can be formed from n boys and m girls.
256 megabytes
import java.io.*; import java.util.*; public class CF { public static void main(String[] args) throws IOException{ Scanner in=new Scanner(System.in); int n=in.nextInt(); int[] A=new int[n]; for(int i=0;i<n;i++) { A[i]=in.nextInt(); } int m=in.nextInt(); int[] B=new int[100+100]; for(int i=0;i<m;i++ ) { B[in.nextInt()]++; } int count=0; Arrays.sort(A); for(int i=0;i<n;i++) { //System.out.println("temp="+A[i]); if(B[A[i]-1]>0) { B[A[i]-1]--; count++; //System.out.println(1); } else if(B[A[i]]>0) { B[A[i]]--; count++; //System.out.println(2); } else if(B[A[i]+1]>0){ B[A[i]+1]--; count++; //System.out.println(3); } } System.out.println(count); //[][][][][][][] //1 //[2] } }
Java
["4\n1 4 6 2\n5\n5 1 5 7 9", "4\n1 2 3 4\n4\n10 11 12 13", "5\n1 1 1 1 1\n3\n1 2 3"]
1 second
["3", "0", "2"]
null
Java 8
standard input
[ "dp", "greedy", "two pointers", "graph matchings", "sortings", "dfs and similar" ]
62766ef9a0751cbe7987020144de7512
The first line contains an integer n (1 ≀ n ≀ 100) β€” the number of boys. The second line contains sequence a1, a2, ..., an (1 ≀ ai ≀ 100), where ai is the i-th boy's dancing skill. Similarly, the third line contains an integer m (1 ≀ m ≀ 100) β€” the number of girls. The fourth line contains sequence b1, b2, ..., bm (1 ≀ bj ≀ 100), where bj is the j-th girl's dancing skill.
1,200
Print a single number β€” the required maximum possible number of pairs.
standard output
PASSED
b808b766da014b0dd6f59371c81efa24
train_000.jsonl
1416238500
The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves.We know that several boy&amp;girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair must differ by at most one.For each boy, we know his dancing skills. Similarly, for each girl we know her dancing skills. Write a code that can determine the largest possible number of pairs that can be formed from n boys and m girls.
256 megabytes
/*Author LAVLESH*/ import java.util.*; import java.io.*; public class main{ static BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st=new StringTokenizer(""); static public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } static int min(int a,int b){return a>b?b:a;} public static void main(String[]args)throws IOException{ PrintWriter op =new PrintWriter(System.out); int n=Integer.parseInt(next()); int []a=new int[n]; for(int i=0;i<n;i++) a[i]=Integer.parseInt(next()); Arrays.sort(a); int g=Integer.parseInt(next()); int []b=new int[g]; for(int i=0;i<g;i++) b[i]=Integer.parseInt(next()); Arrays.sort(b); int count=0; for(int i=0;i<n;i++) { for(int j=0;j<g;j++) { if(a[i]-b[j]<-1) continue; else if(a[i]-b[j]>1) continue; else { b[j]=1000; count++; break; } } } op.println(count); op.close(); } }
Java
["4\n1 4 6 2\n5\n5 1 5 7 9", "4\n1 2 3 4\n4\n10 11 12 13", "5\n1 1 1 1 1\n3\n1 2 3"]
1 second
["3", "0", "2"]
null
Java 8
standard input
[ "dp", "greedy", "two pointers", "graph matchings", "sortings", "dfs and similar" ]
62766ef9a0751cbe7987020144de7512
The first line contains an integer n (1 ≀ n ≀ 100) β€” the number of boys. The second line contains sequence a1, a2, ..., an (1 ≀ ai ≀ 100), where ai is the i-th boy's dancing skill. Similarly, the third line contains an integer m (1 ≀ m ≀ 100) β€” the number of girls. The fourth line contains sequence b1, b2, ..., bm (1 ≀ bj ≀ 100), where bj is the j-th girl's dancing skill.
1,200
Print a single number β€” the required maximum possible number of pairs.
standard output
PASSED
47004132a84fdeee857a06bf04d6bcb7
train_000.jsonl
1416238500
The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves.We know that several boy&amp;girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair must differ by at most one.For each boy, we know his dancing skills. Similarly, for each girl we know her dancing skills. Write a code that can determine the largest possible number of pairs that can be formed from n boys and m girls.
256 megabytes
import java.io.*; import java.util.Arrays; import java.util.InputMismatchException; import java.util.Random; public class CF489 { static String filePath = "/home/bishoy/IdeaProjects/Arabic competetive programming/src/b/test"; public static void main(String args[]) { InputReader inputReader = Helper.readInput(Helper.Input.STD, filePath); OutputWriter out = new OutputWriter(System.out); int n = inputReader.readInt(); int boys[], girls[]; boys = inputReader.nextIntArray(n); int m = inputReader.readInt(); girls = inputReader.nextIntArray(m); Arrays.sort(boys); Arrays.sort(girls); int cnt = 0; int lastMatched = 0; for (int i = 0; i < n; i++) { int b = boys[i]; for (int j = lastMatched; j < m; j++) { int diff = Math.abs(girls[j] - b); if (diff <= 1) { cnt++; lastMatched = j + 1; break; } } if (lastMatched >= m) break; } out.printLine(cnt); } public static long min(long a, long b) { if (a > b) { return b; } return a; } public static int min(int a, int b) { if (a > b) { return b; } return a; } public static long max(long a, long b) { if (a > b) { return a; } return b; } public static int max(int a, int b) { if (a > b) { return a; } return b; } static class pair implements Comparable<pair> { int x; int y; pair(int x, int y) { this.x = x; this.y = y; } public int compareTo(pair b) { return this.y - b.y; } } public static int gcd(int a, int b) { if (a == 0) return b; if (b == 0) return a; while ((a %= b) != 0 && (b %= a) != 0) ; return a ^ b; } public static int mod(int a) { if (a > 0) return a; return -a; } static int mod = (int) 1e9 + 7; public static long expo(long exp, long pow) { long ans = 1; while (pow != 0) { if ((pow & 1) == 1) { ans = ans * exp; } exp = exp * exp; pow = pow >> 1; } return ans; } static int max = (int) 1e9; public static long fact(int num) { if (num == 0) { return 1; } return (fact(num - 1) * num) % mod; } static int[] sieve; public static void sieve() { sieve = new int[max]; for (int i = 1; i < max; i++) { sieve[i] = i; } for (int i = 2; i < max; i++) { if (sieve[i] == i) { for (int j = i * 2; j < max; j += i) { if (sieve[j] == j) { sieve[j] = i; } } } } } public static int bsearch(long[] a, long val) { int l = 0; int r = a.length - 1; while (l < r) { int mid = (l + r + 1) >> 1; if (a[mid] <= val) { l = mid; } else { r = mid - 1; } } if (a[l] <= val) { return l + 1; } return 0; } 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; } static class Helper { static InputReader inputReader = null; static OutputWriter out = null; public static enum Input { FILE, STD } public static class Pair<K, V> { public K key; public V value; public Pair(K key, V value) { this.key = key; this.value = value; } @Override public String toString() { return "( " + key + " , " + value + ")"; } } public static InputReader readInput(Enum type, String filePath) { if (type == Input.FILE) { try { inputReader = new InputReader(new FileInputStream(new File(filePath))); } catch (FileNotFoundException e) { e.printStackTrace(); } } else inputReader = new InputReader(System.in); return inputReader; } public static boolean validIndices(int r, int c, int n, int m) { if (r >= 0 && c >= 0 && r < n && c < m) return true; else return false; } } private static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } 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 int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = readInt(); } return a; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public 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 double readDouble() { 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, readInt()); } 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, readInt()); } if (c < '0' || c > '9') { throw new InputMismatchException(); } m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public long readLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } private static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } writer.flush(); } public void printLine(Object... objects) { print(objects); writer.println(); writer.flush(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } }
Java
["4\n1 4 6 2\n5\n5 1 5 7 9", "4\n1 2 3 4\n4\n10 11 12 13", "5\n1 1 1 1 1\n3\n1 2 3"]
1 second
["3", "0", "2"]
null
Java 8
standard input
[ "dp", "greedy", "two pointers", "graph matchings", "sortings", "dfs and similar" ]
62766ef9a0751cbe7987020144de7512
The first line contains an integer n (1 ≀ n ≀ 100) β€” the number of boys. The second line contains sequence a1, a2, ..., an (1 ≀ ai ≀ 100), where ai is the i-th boy's dancing skill. Similarly, the third line contains an integer m (1 ≀ m ≀ 100) β€” the number of girls. The fourth line contains sequence b1, b2, ..., bm (1 ≀ bj ≀ 100), where bj is the j-th girl's dancing skill.
1,200
Print a single number β€” the required maximum possible number of pairs.
standard output
PASSED
3ee3dbb2cb3d208a3bbd412e33a9f232
train_000.jsonl
1416238500
The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves.We know that several boy&amp;girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair must differ by at most one.For each boy, we know his dancing skills. Similarly, for each girl we know her dancing skills. Write a code that can determine the largest possible number of pairs that can be formed from n boys and m girls.
256 megabytes
import java.io.*; import java.util.Arrays; import java.util.InputMismatchException; import java.util.Random; public class CF489 { static String filePath = "/home/bishoy/IdeaProjects/Arabic competetive programming/src/b/test"; public static void main(String args[]) { InputReader inputReader = Helper.readInput(Helper.Input.STD, filePath); OutputWriter out = new OutputWriter(System.out); int n = inputReader.readInt(); int boys[], girls[]; boys = inputReader.nextIntArray(n); int m = inputReader.readInt(); girls = inputReader.nextIntArray(m); Arrays.sort(boys); Arrays.sort(girls); int cnt = 0; int lastMatched = 0; for (int i = 0; i < n; i++) { int b = boys[i]; for (int j = lastMatched; j < m; j++) { int diff = Math.abs(girls[j] - b); if (diff <= 1) { cnt++; lastMatched = j + 1; break; } } } out.printLine(cnt); } public static long min(long a, long b) { if (a > b) { return b; } return a; } public static int min(int a, int b) { if (a > b) { return b; } return a; } public static long max(long a, long b) { if (a > b) { return a; } return b; } public static int max(int a, int b) { if (a > b) { return a; } return b; } static class pair implements Comparable<pair> { int x; int y; pair(int x, int y) { this.x = x; this.y = y; } public int compareTo(pair b) { return this.y - b.y; } } public static int gcd(int a, int b) { if (a == 0) return b; if (b == 0) return a; while ((a %= b) != 0 && (b %= a) != 0) ; return a ^ b; } public static int mod(int a) { if (a > 0) return a; return -a; } static int mod = (int) 1e9 + 7; public static long expo(long exp, long pow) { long ans = 1; while (pow != 0) { if ((pow & 1) == 1) { ans = ans * exp; } exp = exp * exp; pow = pow >> 1; } return ans; } static int max = (int) 1e9; public static long fact(int num) { if (num == 0) { return 1; } return (fact(num - 1) * num) % mod; } static int[] sieve; public static void sieve() { sieve = new int[max]; for (int i = 1; i < max; i++) { sieve[i] = i; } for (int i = 2; i < max; i++) { if (sieve[i] == i) { for (int j = i * 2; j < max; j += i) { if (sieve[j] == j) { sieve[j] = i; } } } } } public static int bsearch(long[] a, long val) { int l = 0; int r = a.length - 1; while (l < r) { int mid = (l + r + 1) >> 1; if (a[mid] <= val) { l = mid; } else { r = mid - 1; } } if (a[l] <= val) { return l + 1; } return 0; } 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; } static class Helper { static InputReader inputReader = null; static OutputWriter out = null; public static enum Input { FILE, STD } public static class Pair<K, V> { public K key; public V value; public Pair(K key, V value) { this.key = key; this.value = value; } @Override public String toString() { return "( " + key + " , " + value + ")"; } } public static InputReader readInput(Enum type, String filePath) { if (type == Input.FILE) { try { inputReader = new InputReader(new FileInputStream(new File(filePath))); } catch (FileNotFoundException e) { e.printStackTrace(); } } else inputReader = new InputReader(System.in); return inputReader; } public static boolean validIndices(int r, int c, int n, int m) { if (r >= 0 && c >= 0 && r < n && c < m) return true; else return false; } } private static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } 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 int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = readInt(); } return a; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public 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 double readDouble() { 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, readInt()); } 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, readInt()); } if (c < '0' || c > '9') { throw new InputMismatchException(); } m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public long readLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } private static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } writer.flush(); } public void printLine(Object... objects) { print(objects); writer.println(); writer.flush(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } }
Java
["4\n1 4 6 2\n5\n5 1 5 7 9", "4\n1 2 3 4\n4\n10 11 12 13", "5\n1 1 1 1 1\n3\n1 2 3"]
1 second
["3", "0", "2"]
null
Java 8
standard input
[ "dp", "greedy", "two pointers", "graph matchings", "sortings", "dfs and similar" ]
62766ef9a0751cbe7987020144de7512
The first line contains an integer n (1 ≀ n ≀ 100) β€” the number of boys. The second line contains sequence a1, a2, ..., an (1 ≀ ai ≀ 100), where ai is the i-th boy's dancing skill. Similarly, the third line contains an integer m (1 ≀ m ≀ 100) β€” the number of girls. The fourth line contains sequence b1, b2, ..., bm (1 ≀ bj ≀ 100), where bj is the j-th girl's dancing skill.
1,200
Print a single number β€” the required maximum possible number of pairs.
standard output
PASSED
6cb0e2afd7acb94687778358acaa6609
train_000.jsonl
1416238500
The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves.We know that several boy&amp;girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair must differ by at most one.For each boy, we know his dancing skills. Similarly, for each girl we know her dancing skills. Write a code that can determine the largest possible number of pairs that can be formed from n boys and m girls.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class CF489 { // static String filePath = "/home/bishoy/IdeaProjects/Arabic competetive programming/src/b/test"; public static void main(String args[]) throws IOException { solve2(); } private static void solve2() throws IOException { int boys[], girls[]; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); boys = readIntArr(br, n); int m = Integer.parseInt(br.readLine()); girls = readIntArr(br, m); Arrays.sort(boys); Arrays.sort(girls); int cnt = 0; int i = 0, j = 0; while (i < n && j < m) { int b = boys[i]; int g = girls[j]; int diff = Math.abs(b - g); if (diff <= 1) { i++; j++; cnt++; } else if (b > g) { j++; } else { i++; } } System.out.println(cnt); } static int[] readIntArr(BufferedReader br, int n) throws IOException { StringTokenizer stringTokenizer = new StringTokenizer(br.readLine()); int arr[] = new int[n]; for (int i = 0; i < n; i++) arr[i] = Integer.parseInt(stringTokenizer.nextToken()); return arr; } // static void solve1(InputReader inputReader, OutputWriter out) { // int n = inputReader.readInt(); // int boys[], girls[]; // // boys = inputReader.nextIntArray(n); // int m = inputReader.readInt(); // girls = inputReader.nextIntArray(m); // // Arrays.sort(boys); // Arrays.sort(girls); // // int cnt = 0; // int lastMatched = 0; // for (int i = 0; i < n; i++) { // int b = boys[i]; // for (int j = lastMatched; j < m; j++) { // int diff = Math.abs(girls[j] - b); // if (diff <= 1) { // cnt++; // lastMatched = j + 1; // break; // } // } // if (lastMatched >= m) // break; // } // System.out.println(cnt); // } }
Java
["4\n1 4 6 2\n5\n5 1 5 7 9", "4\n1 2 3 4\n4\n10 11 12 13", "5\n1 1 1 1 1\n3\n1 2 3"]
1 second
["3", "0", "2"]
null
Java 8
standard input
[ "dp", "greedy", "two pointers", "graph matchings", "sortings", "dfs and similar" ]
62766ef9a0751cbe7987020144de7512
The first line contains an integer n (1 ≀ n ≀ 100) β€” the number of boys. The second line contains sequence a1, a2, ..., an (1 ≀ ai ≀ 100), where ai is the i-th boy's dancing skill. Similarly, the third line contains an integer m (1 ≀ m ≀ 100) β€” the number of girls. The fourth line contains sequence b1, b2, ..., bm (1 ≀ bj ≀ 100), where bj is the j-th girl's dancing skill.
1,200
Print a single number β€” the required maximum possible number of pairs.
standard output
PASSED
4ea140240f7fcc783877c00836792be7
train_000.jsonl
1416238500
The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves.We know that several boy&amp;girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair must differ by at most one.For each boy, we know his dancing skills. Similarly, for each girl we know her dancing skills. Write a code that can determine the largest possible number of pairs that can be formed from n boys and m girls.
256 megabytes
import java.io.*; import java.util.Arrays; import java.util.InputMismatchException; import java.util.Random; public class CF489 { static String filePath = "/home/bishoy/IdeaProjects/Arabic competetive programming/src/b/test"; public static void main(String args[]) { InputReader inputReader = Helper.readInput(Helper.Input.STD, filePath); OutputWriter out = new OutputWriter(System.out); solve2(inputReader, out); } private static void solve2(InputReader inputReader, OutputWriter out) { int n = inputReader.readInt(); int boys[], girls[]; boys = inputReader.nextIntArray(n); int m = inputReader.readInt(); girls = inputReader.nextIntArray(m); Arrays.sort(boys); Arrays.sort(girls); int cnt = 0; int i = 0, j = 0; while (i < n && j < m) { int diff = Math.abs(boys[i] - girls[j]); if (diff <= 1) { i++; j++; cnt++; } else if (boys[i] > girls[j]) { j++; } else { i++; } } out.printLine(cnt); } static void solve1(InputReader inputReader, OutputWriter out) { int n = inputReader.readInt(); int boys[], girls[]; boys = inputReader.nextIntArray(n); int m = inputReader.readInt(); girls = inputReader.nextIntArray(m); Arrays.sort(boys); Arrays.sort(girls); int cnt = 0; int lastMatched = 0; for (int i = 0; i < n; i++) { int b = boys[i]; for (int j = lastMatched; j < m; j++) { int diff = Math.abs(girls[j] - b); if (diff <= 1) { cnt++; lastMatched = j + 1; break; } } if (lastMatched >= m) break; } out.printLine(cnt); } public static long min(long a, long b) { if (a > b) { return b; } return a; } public static int min(int a, int b) { if (a > b) { return b; } return a; } public static long max(long a, long b) { if (a > b) { return a; } return b; } public static int max(int a, int b) { if (a > b) { return a; } return b; } static class pair implements Comparable<pair> { int x; int y; pair(int x, int y) { this.x = x; this.y = y; } public int compareTo(pair b) { return this.y - b.y; } } public static int gcd(int a, int b) { if (a == 0) return b; if (b == 0) return a; while ((a %= b) != 0 && (b %= a) != 0) ; return a ^ b; } public static int mod(int a) { if (a > 0) return a; return -a; } static int mod = (int) 1e9 + 7; public static long expo(long exp, long pow) { long ans = 1; while (pow != 0) { if ((pow & 1) == 1) { ans = ans * exp; } exp = exp * exp; pow = pow >> 1; } return ans; } static int max = (int) 1e9; public static long fact(int num) { if (num == 0) { return 1; } return (fact(num - 1) * num) % mod; } static int[] sieve; public static void sieve() { sieve = new int[max]; for (int i = 1; i < max; i++) { sieve[i] = i; } for (int i = 2; i < max; i++) { if (sieve[i] == i) { for (int j = i * 2; j < max; j += i) { if (sieve[j] == j) { sieve[j] = i; } } } } } public static int bsearch(long[] a, long val) { int l = 0; int r = a.length - 1; while (l < r) { int mid = (l + r + 1) >> 1; if (a[mid] <= val) { l = mid; } else { r = mid - 1; } } if (a[l] <= val) { return l + 1; } return 0; } 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; } static class Helper { static InputReader inputReader = null; static OutputWriter out = null; public static enum Input { FILE, STD } public static class Pair<K, V> { public K key; public V value; public Pair(K key, V value) { this.key = key; this.value = value; } @Override public String toString() { return "( " + key + " , " + value + ")"; } } public static InputReader readInput(Enum type, String filePath) { if (type == Input.FILE) { try { inputReader = new InputReader(new FileInputStream(new File(filePath))); } catch (FileNotFoundException e) { e.printStackTrace(); } } else inputReader = new InputReader(System.in); return inputReader; } public static boolean validIndices(int r, int c, int n, int m) { if (r >= 0 && c >= 0 && r < n && c < m) return true; else return false; } } private static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } 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 int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = readInt(); } return a; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public 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 double readDouble() { 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, readInt()); } 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, readInt()); } if (c < '0' || c > '9') { throw new InputMismatchException(); } m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public long readLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } private static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } writer.flush(); } public void printLine(Object... objects) { print(objects); writer.println(); writer.flush(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } }
Java
["4\n1 4 6 2\n5\n5 1 5 7 9", "4\n1 2 3 4\n4\n10 11 12 13", "5\n1 1 1 1 1\n3\n1 2 3"]
1 second
["3", "0", "2"]
null
Java 8
standard input
[ "dp", "greedy", "two pointers", "graph matchings", "sortings", "dfs and similar" ]
62766ef9a0751cbe7987020144de7512
The first line contains an integer n (1 ≀ n ≀ 100) β€” the number of boys. The second line contains sequence a1, a2, ..., an (1 ≀ ai ≀ 100), where ai is the i-th boy's dancing skill. Similarly, the third line contains an integer m (1 ≀ m ≀ 100) β€” the number of girls. The fourth line contains sequence b1, b2, ..., bm (1 ≀ bj ≀ 100), where bj is the j-th girl's dancing skill.
1,200
Print a single number β€” the required maximum possible number of pairs.
standard output
PASSED
6b0d8c48afa8f11ee214f6bfbaeb75fe
train_000.jsonl
1416238500
The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves.We know that several boy&amp;girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair must differ by at most one.For each boy, we know his dancing skills. Similarly, for each girl we know her dancing skills. Write a code that can determine the largest possible number of pairs that can be formed from n boys and m girls.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class CF489 { // static String filePath = "/home/bishoy/IdeaProjects/Arabic competetive programming/src/b/test"; public static void main(String args[]) throws IOException { solve2(); } private static void solve2() throws IOException { int boys[], girls[]; BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(reader.readLine()); boys = new int[n]; StringTokenizer st = new StringTokenizer(reader.readLine()); for (int i = 0; i < n; i++) { boys[i] = Integer.parseInt(st.nextToken()); } int m = Integer.parseInt(reader.readLine()); girls = new int[m]; st = new StringTokenizer(reader.readLine()); for (int i = 0; i < m; i++) { girls[i] = Integer.parseInt(st.nextToken()); } Arrays.sort(boys); Arrays.sort(girls); int cnt = 0; int i = 0, j = 0; while (i < n && j < m) { int b = boys[i]; int g = girls[j]; int diff = Math.abs(b - g); if (diff <= 1) { i++; j++; cnt++; } else if (b > g) { j++; } else { i++; } } System.out.println(cnt); } static int[] readIntArr(BufferedReader br, int n) throws IOException { StringTokenizer stringTokenizer = new StringTokenizer(br.readLine()); int arr[] = new int[n]; for (int i = 0; i < n; i++) arr[i] = Integer.parseInt(stringTokenizer.nextToken()); return arr; } // static void solve1(InputReader inputReader, OutputWriter out) { // int n = inputReader.readInt(); // int boys[], girls[]; // // boys = inputReader.nextIntArray(n); // int m = inputReader.readInt(); // girls = inputReader.nextIntArray(m); // // Arrays.sort(boys); // Arrays.sort(girls); // // int cnt = 0; // int lastMatched = 0; // for (int i = 0; i < n; i++) { // int b = boys[i]; // for (int j = lastMatched; j < m; j++) { // int diff = Math.abs(girls[j] - b); // if (diff <= 1) { // cnt++; // lastMatched = j + 1; // break; // } // } // if (lastMatched >= m) // break; // } // System.out.println(cnt); // } }
Java
["4\n1 4 6 2\n5\n5 1 5 7 9", "4\n1 2 3 4\n4\n10 11 12 13", "5\n1 1 1 1 1\n3\n1 2 3"]
1 second
["3", "0", "2"]
null
Java 8
standard input
[ "dp", "greedy", "two pointers", "graph matchings", "sortings", "dfs and similar" ]
62766ef9a0751cbe7987020144de7512
The first line contains an integer n (1 ≀ n ≀ 100) β€” the number of boys. The second line contains sequence a1, a2, ..., an (1 ≀ ai ≀ 100), where ai is the i-th boy's dancing skill. Similarly, the third line contains an integer m (1 ≀ m ≀ 100) β€” the number of girls. The fourth line contains sequence b1, b2, ..., bm (1 ≀ bj ≀ 100), where bj is the j-th girl's dancing skill.
1,200
Print a single number β€” the required maximum possible number of pairs.
standard output
PASSED
065e37a8b9df0881d3cc3da2e3258efd
train_000.jsonl
1416238500
The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves.We know that several boy&amp;girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair must differ by at most one.For each boy, we know his dancing skills. Similarly, for each girl we know her dancing skills. Write a code that can determine the largest possible number of pairs that can be formed from n boys and m girls.
256 megabytes
import java.io.*; import java.util.Arrays; import java.util.InputMismatchException; import java.util.Random; import java.util.StringTokenizer; public class CF489 { // static String filePath = "/home/bishoy/IdeaProjects/Arabic competetive programming/src/b/test"; public static void main(String args[]) throws IOException { InputReader inputReader = new InputReader(System.in); OutputWriter out = new OutputWriter(System.out); int boys[], girls[]; int n = inputReader.readInt(); boys = new int[n]; String line = inputReader.nextLine(); StringTokenizer stringTokenizer = new StringTokenizer(line); for (int i = 0; i < n; i++) { boys[i] = Integer.parseInt(stringTokenizer.nextToken()); } int m = inputReader.readInt(); girls = new int[m]; line = inputReader.nextLine(); stringTokenizer = new StringTokenizer(line); for (int i = 0; i < m; i++) { girls[i] = Integer.parseInt(stringTokenizer.nextToken()); } Arrays.sort(boys); Arrays.sort(girls); int cnt = 0; int i = 0, j = 0; while (i < n && j < m) { int b = boys[i]; int g = girls[j]; int diff = Math.abs(b - g); if (diff <= 1) { i++; j++; cnt++; } else if (b > g) { j++; } else { i++; } } out.printLine(cnt); out.close(); } // private static void solve2(OutputWriter out) throws IOException { // // } static int[] readIntArr(BufferedReader br, int n) throws IOException { StringTokenizer stringTokenizer = new StringTokenizer(br.readLine()); int arr[] = new int[n]; for (int i = 0; i < n; i++) arr[i] = Integer.parseInt(stringTokenizer.nextToken()); return arr; } static void solve1(InputReader inputReader, OutputWriter out) { int n = inputReader.readInt(); int boys[], girls[]; boys = inputReader.nextIntArray(n); int m = inputReader.readInt(); girls = inputReader.nextIntArray(m); Arrays.sort(boys); Arrays.sort(girls); int cnt = 0; int lastMatched = 0; for (int i = 0; i < n; i++) { int b = boys[i]; for (int j = lastMatched; j < m; j++) { int diff = Math.abs(girls[j] - b); if (diff <= 1) { cnt++; lastMatched = j + 1; break; } } if (lastMatched >= m) break; } out.printLine(cnt); } public static long min(long a, long b) { if (a > b) { return b; } return a; } public static int min(int a, int b) { if (a > b) { return b; } return a; } public static long max(long a, long b) { if (a > b) { return a; } return b; } public static int max(int a, int b) { if (a > b) { return a; } return b; } static class pair implements Comparable<pair> { int x; int y; pair(int x, int y) { this.x = x; this.y = y; } public int compareTo(pair b) { return this.y - b.y; } } public static int gcd(int a, int b) { if (a == 0) return b; if (b == 0) return a; while ((a %= b) != 0 && (b %= a) != 0) ; return a ^ b; } public static int mod(int a) { if (a > 0) return a; return -a; } static int mod = (int) 1e9 + 7; public static long expo(long exp, long pow) { long ans = 1; while (pow != 0) { if ((pow & 1) == 1) { ans = ans * exp; } exp = exp * exp; pow = pow >> 1; } return ans; } static int max = (int) 1e9; public static long fact(int num) { if (num == 0) { return 1; } return (fact(num - 1) * num) % mod; } static int[] sieve; public static void sieve() { sieve = new int[max]; for (int i = 1; i < max; i++) { sieve[i] = i; } for (int i = 2; i < max; i++) { if (sieve[i] == i) { for (int j = i * 2; j < max; j += i) { if (sieve[j] == j) { sieve[j] = i; } } } } } public static int bsearch(long[] a, long val) { int l = 0; int r = a.length - 1; while (l < r) { int mid = (l + r + 1) >> 1; if (a[mid] <= val) { l = mid; } else { r = mid - 1; } } if (a[l] <= val) { return l + 1; } return 0; } 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; } static class Helper { static InputReader inputReader = null; static OutputWriter out = null; public static enum Input { FILE, STD } public static class Pair<K, V> { public K key; public V value; public Pair(K key, V value) { this.key = key; this.value = value; } @Override public String toString() { return "( " + key + " , " + value + ")"; } } public static InputReader readInput(Enum type, String filePath) { if (type == Input.FILE) { try { inputReader = new InputReader(new FileInputStream(new File(filePath))); } catch (FileNotFoundException e) { e.printStackTrace(); } } else inputReader = new InputReader(System.in); return inputReader; } public static boolean validIndices(int r, int c, int n, int m) { if (r >= 0 && c >= 0 && r < n && c < m) return true; else return false; } } private static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } 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 int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = readInt(); } return a; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public 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 double readDouble() { 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, readInt()); } 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, readInt()); } if (c < '0' || c > '9') { throw new InputMismatchException(); } m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public long readLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } private static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } writer.flush(); } public void printLine(Object... objects) { print(objects); writer.println(); writer.flush(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } }
Java
["4\n1 4 6 2\n5\n5 1 5 7 9", "4\n1 2 3 4\n4\n10 11 12 13", "5\n1 1 1 1 1\n3\n1 2 3"]
1 second
["3", "0", "2"]
null
Java 8
standard input
[ "dp", "greedy", "two pointers", "graph matchings", "sortings", "dfs and similar" ]
62766ef9a0751cbe7987020144de7512
The first line contains an integer n (1 ≀ n ≀ 100) β€” the number of boys. The second line contains sequence a1, a2, ..., an (1 ≀ ai ≀ 100), where ai is the i-th boy's dancing skill. Similarly, the third line contains an integer m (1 ≀ m ≀ 100) β€” the number of girls. The fourth line contains sequence b1, b2, ..., bm (1 ≀ bj ≀ 100), where bj is the j-th girl's dancing skill.
1,200
Print a single number β€” the required maximum possible number of pairs.
standard output
PASSED
f96164e004e7fa5679f9671e2f68450b
train_000.jsonl
1416238500
The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves.We know that several boy&amp;girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair must differ by at most one.For each boy, we know his dancing skills. Similarly, for each girl we know her dancing skills. Write a code that can determine the largest possible number of pairs that can be formed from n boys and m girls.
256 megabytes
import java.io.*; import java.util.Arrays; import java.util.InputMismatchException; import java.util.Random; import java.util.StringTokenizer; public class CF489 { // static String filePath = "/home/bishoy/IdeaProjects/Arabic competetive programming/src/b/test"; public static void main(String args[]) throws IOException { // InputReader inputReader = Helper.readInput(Helper.Input.FILE, filePath); OutputWriter out = new OutputWriter(System.out); solve2(out); } private static void solve2(OutputWriter out) throws IOException { int boys[], girls[]; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); boys = readIntArr(br, n); int m = Integer.parseInt(br.readLine()); girls = readIntArr(br, m); Arrays.sort(boys); Arrays.sort(girls); int cnt = 0; int i = 0, j = 0; while (i < n && j < m) { int b = boys[i]; int g = girls[j]; int diff = Math.abs(b - g); if (diff <= 1) { i++; j++; cnt++; } else if (b > g) { j++; } else { i++; } } out.printLine(cnt); } static int[] readIntArr(BufferedReader br, int n) throws IOException { StringTokenizer stringTokenizer = new StringTokenizer(br.readLine()); int arr[] = new int[n]; for (int i = 0; i < n; i++) arr[i] = Integer.parseInt(stringTokenizer.nextToken()); return arr; } static void solve1(InputReader inputReader, OutputWriter out) { int n = inputReader.readInt(); int boys[], girls[]; boys = inputReader.nextIntArray(n); int m = inputReader.readInt(); girls = inputReader.nextIntArray(m); Arrays.sort(boys); Arrays.sort(girls); int cnt = 0; int lastMatched = 0; for (int i = 0; i < n; i++) { int b = boys[i]; for (int j = lastMatched; j < m; j++) { int diff = Math.abs(girls[j] - b); if (diff <= 1) { cnt++; lastMatched = j + 1; break; } } if (lastMatched >= m) break; } out.printLine(cnt); } public static long min(long a, long b) { if (a > b) { return b; } return a; } public static int min(int a, int b) { if (a > b) { return b; } return a; } public static long max(long a, long b) { if (a > b) { return a; } return b; } public static int max(int a, int b) { if (a > b) { return a; } return b; } static class pair implements Comparable<pair> { int x; int y; pair(int x, int y) { this.x = x; this.y = y; } public int compareTo(pair b) { return this.y - b.y; } } public static int gcd(int a, int b) { if (a == 0) return b; if (b == 0) return a; while ((a %= b) != 0 && (b %= a) != 0) ; return a ^ b; } public static int mod(int a) { if (a > 0) return a; return -a; } static int mod = (int) 1e9 + 7; public static long expo(long exp, long pow) { long ans = 1; while (pow != 0) { if ((pow & 1) == 1) { ans = ans * exp; } exp = exp * exp; pow = pow >> 1; } return ans; } static int max = (int) 1e9; public static long fact(int num) { if (num == 0) { return 1; } return (fact(num - 1) * num) % mod; } static int[] sieve; public static void sieve() { sieve = new int[max]; for (int i = 1; i < max; i++) { sieve[i] = i; } for (int i = 2; i < max; i++) { if (sieve[i] == i) { for (int j = i * 2; j < max; j += i) { if (sieve[j] == j) { sieve[j] = i; } } } } } public static int bsearch(long[] a, long val) { int l = 0; int r = a.length - 1; while (l < r) { int mid = (l + r + 1) >> 1; if (a[mid] <= val) { l = mid; } else { r = mid - 1; } } if (a[l] <= val) { return l + 1; } return 0; } 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; } static class Helper { static InputReader inputReader = null; static OutputWriter out = null; public static enum Input { FILE, STD } public static class Pair<K, V> { public K key; public V value; public Pair(K key, V value) { this.key = key; this.value = value; } @Override public String toString() { return "( " + key + " , " + value + ")"; } } public static InputReader readInput(Enum type, String filePath) { if (type == Input.FILE) { try { inputReader = new InputReader(new FileInputStream(new File(filePath))); } catch (FileNotFoundException e) { e.printStackTrace(); } } else inputReader = new InputReader(System.in); return inputReader; } public static boolean validIndices(int r, int c, int n, int m) { if (r >= 0 && c >= 0 && r < n && c < m) return true; else return false; } } private static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } 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 int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = readInt(); } return a; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public 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 double readDouble() { 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, readInt()); } 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, readInt()); } if (c < '0' || c > '9') { throw new InputMismatchException(); } m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public long readLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } private static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } writer.flush(); } public void printLine(Object... objects) { print(objects); writer.println(); writer.flush(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } }
Java
["4\n1 4 6 2\n5\n5 1 5 7 9", "4\n1 2 3 4\n4\n10 11 12 13", "5\n1 1 1 1 1\n3\n1 2 3"]
1 second
["3", "0", "2"]
null
Java 8
standard input
[ "dp", "greedy", "two pointers", "graph matchings", "sortings", "dfs and similar" ]
62766ef9a0751cbe7987020144de7512
The first line contains an integer n (1 ≀ n ≀ 100) β€” the number of boys. The second line contains sequence a1, a2, ..., an (1 ≀ ai ≀ 100), where ai is the i-th boy's dancing skill. Similarly, the third line contains an integer m (1 ≀ m ≀ 100) β€” the number of girls. The fourth line contains sequence b1, b2, ..., bm (1 ≀ bj ≀ 100), where bj is the j-th girl's dancing skill.
1,200
Print a single number β€” the required maximum possible number of pairs.
standard output
PASSED
68c2bb97bc83a97bb75a59d5f71431c4
train_000.jsonl
1416238500
The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves.We know that several boy&amp;girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair must differ by at most one.For each boy, we know his dancing skills. Similarly, for each girl we know her dancing skills. Write a code that can determine the largest possible number of pairs that can be formed from n boys and m girls.
256 megabytes
import java.io.*; import java.util.Arrays; import java.util.InputMismatchException; import java.util.Random; import java.util.StringTokenizer; public class CF489 { static String filePath = "/home/bishoy/IdeaProjects/Arabic competetive programming/src/b/test"; public static void main(String args[]) throws IOException { InputReader inputReader = Helper.readInput(Helper.Input.STD, filePath); OutputWriter out = new OutputWriter(System.out); solve2(inputReader, out); } private static void solve2(InputReader inputReader, OutputWriter out) throws IOException { int boys[], girls[]; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); boys = readIntArr(br, n); int m = Integer.parseInt(br.readLine()); girls = readIntArr(br, m); Arrays.sort(boys); Arrays.sort(girls); int cnt = 0; int i = 0, j = 0; while (i < n && j < m) { int b = boys[i]; int g = girls[j]; int diff = Math.abs(b - g); if (diff <= 1) { i++; j++; cnt++; } else if (b > g) { j++; } else { i++; } } out.printLine(cnt); } static int[] readIntArr(BufferedReader br, int n) throws IOException { StringTokenizer stringTokenizer = new StringTokenizer(br.readLine()); int arr[] = new int[n]; for (int i = 0; i < n; i++) arr[i] = Integer.parseInt(stringTokenizer.nextToken()); return arr; } static void solve1(InputReader inputReader, OutputWriter out) { int n = inputReader.readInt(); int boys[], girls[]; boys = inputReader.nextIntArray(n); int m = inputReader.readInt(); girls = inputReader.nextIntArray(m); Arrays.sort(boys); Arrays.sort(girls); int cnt = 0; int lastMatched = 0; for (int i = 0; i < n; i++) { int b = boys[i]; for (int j = lastMatched; j < m; j++) { int diff = Math.abs(girls[j] - b); if (diff <= 1) { cnt++; lastMatched = j + 1; break; } } if (lastMatched >= m) break; } out.printLine(cnt); } public static long min(long a, long b) { if (a > b) { return b; } return a; } public static int min(int a, int b) { if (a > b) { return b; } return a; } public static long max(long a, long b) { if (a > b) { return a; } return b; } public static int max(int a, int b) { if (a > b) { return a; } return b; } static class pair implements Comparable<pair> { int x; int y; pair(int x, int y) { this.x = x; this.y = y; } public int compareTo(pair b) { return this.y - b.y; } } public static int gcd(int a, int b) { if (a == 0) return b; if (b == 0) return a; while ((a %= b) != 0 && (b %= a) != 0) ; return a ^ b; } public static int mod(int a) { if (a > 0) return a; return -a; } static int mod = (int) 1e9 + 7; public static long expo(long exp, long pow) { long ans = 1; while (pow != 0) { if ((pow & 1) == 1) { ans = ans * exp; } exp = exp * exp; pow = pow >> 1; } return ans; } static int max = (int) 1e9; public static long fact(int num) { if (num == 0) { return 1; } return (fact(num - 1) * num) % mod; } static int[] sieve; public static void sieve() { sieve = new int[max]; for (int i = 1; i < max; i++) { sieve[i] = i; } for (int i = 2; i < max; i++) { if (sieve[i] == i) { for (int j = i * 2; j < max; j += i) { if (sieve[j] == j) { sieve[j] = i; } } } } } public static int bsearch(long[] a, long val) { int l = 0; int r = a.length - 1; while (l < r) { int mid = (l + r + 1) >> 1; if (a[mid] <= val) { l = mid; } else { r = mid - 1; } } if (a[l] <= val) { return l + 1; } return 0; } 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; } static class Helper { static InputReader inputReader = null; static OutputWriter out = null; public static enum Input { FILE, STD } public static class Pair<K, V> { public K key; public V value; public Pair(K key, V value) { this.key = key; this.value = value; } @Override public String toString() { return "( " + key + " , " + value + ")"; } } public static InputReader readInput(Enum type, String filePath) { if (type == Input.FILE) { try { inputReader = new InputReader(new FileInputStream(new File(filePath))); } catch (FileNotFoundException e) { e.printStackTrace(); } } else inputReader = new InputReader(System.in); return inputReader; } public static boolean validIndices(int r, int c, int n, int m) { if (r >= 0 && c >= 0 && r < n && c < m) return true; else return false; } } private static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } 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 int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = readInt(); } return a; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public 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 double readDouble() { 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, readInt()); } 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, readInt()); } if (c < '0' || c > '9') { throw new InputMismatchException(); } m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public long readLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } private static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } writer.flush(); } public void printLine(Object... objects) { print(objects); writer.println(); writer.flush(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } }
Java
["4\n1 4 6 2\n5\n5 1 5 7 9", "4\n1 2 3 4\n4\n10 11 12 13", "5\n1 1 1 1 1\n3\n1 2 3"]
1 second
["3", "0", "2"]
null
Java 8
standard input
[ "dp", "greedy", "two pointers", "graph matchings", "sortings", "dfs and similar" ]
62766ef9a0751cbe7987020144de7512
The first line contains an integer n (1 ≀ n ≀ 100) β€” the number of boys. The second line contains sequence a1, a2, ..., an (1 ≀ ai ≀ 100), where ai is the i-th boy's dancing skill. Similarly, the third line contains an integer m (1 ≀ m ≀ 100) β€” the number of girls. The fourth line contains sequence b1, b2, ..., bm (1 ≀ bj ≀ 100), where bj is the j-th girl's dancing skill.
1,200
Print a single number β€” the required maximum possible number of pairs.
standard output
PASSED
324f2c28e37243bc7f79efc2a0c05468
train_000.jsonl
1416238500
The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves.We know that several boy&amp;girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair must differ by at most one.For each boy, we know his dancing skills. Similarly, for each girl we know her dancing skills. Write a code that can determine the largest possible number of pairs that can be formed from n boys and m girls.
256 megabytes
import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; public class SydneyTest { public static void main(String[] args) { Scanner input = new Scanner(System.in); int boys = input.nextInt(); List<Integer> boysSkills = new ArrayList<>(); for (int x = 0; x < boys; x++) { boysSkills.add(input.nextInt()); } int girls = input.nextInt(); List<Integer> girlsSkills = new ArrayList<>(); for (int x = 0; x < girls; x++) { girlsSkills.add(input.nextInt()); } Collections.sort(boysSkills); Collections.sort(girlsSkills); int pair = 0; for (int x = 0; x < boysSkills.size(); x++) { for (int y = 0; y < girlsSkills.size(); y++) { int b = boysSkills.get(x); int g = girlsSkills.get(y); int num = Math.abs(b - g); if (num <= 1) { girlsSkills.set(y , 1000); pair++; break; } } } System.out.println(pair); } }
Java
["4\n1 4 6 2\n5\n5 1 5 7 9", "4\n1 2 3 4\n4\n10 11 12 13", "5\n1 1 1 1 1\n3\n1 2 3"]
1 second
["3", "0", "2"]
null
Java 8
standard input
[ "dp", "greedy", "two pointers", "graph matchings", "sortings", "dfs and similar" ]
62766ef9a0751cbe7987020144de7512
The first line contains an integer n (1 ≀ n ≀ 100) β€” the number of boys. The second line contains sequence a1, a2, ..., an (1 ≀ ai ≀ 100), where ai is the i-th boy's dancing skill. Similarly, the third line contains an integer m (1 ≀ m ≀ 100) β€” the number of girls. The fourth line contains sequence b1, b2, ..., bm (1 ≀ bj ≀ 100), where bj is the j-th girl's dancing skill.
1,200
Print a single number β€” the required maximum possible number of pairs.
standard output
PASSED
c144162d46acf0421cd173df5476991a
train_000.jsonl
1416238500
The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves.We know that several boy&amp;girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair must differ by at most one.For each boy, we know his dancing skills. Similarly, for each girl we know her dancing skills. Write a code that can determine the largest possible number of pairs that can be formed from n boys and m girls.
256 megabytes
import java.util.Scanner; import java.util.ArrayList; public class Go { static Scanner sc; static ArrayList<Integer> x, y; static ArrayList<Integer> read() { ArrayList<Integer> ts = new ArrayList<>(); int size = sc.nextInt(); for(int i = 0; i < size; i++) { ts.add(sc.nextInt()); } ts.sort(null); return ts; } static void checkUnhappy(ArrayList<Integer> x, ArrayList<Integer> y) { int i; i = 0; while(i < x.size()) { int check = x.get(i); if ( y.contains(check - 1) || y.contains(check) || y.contains(check + 1) ) { i++; } else { x.remove(i); } } } public static void main(String[] args) { sc = new Scanner(System.in); x = read(); y = read(); sc.close(); checkUnhappy(x, y); checkUnhappy(y, x); if(x.size() > y.size()) { ArrayList<Integer> temp; temp = x; x = y; y = temp; } int count = 0; int i = 0, j = 0; while(i < x.size() && j < y.size()) { int a = x.get(i); int b = y.get(j); if(Math.abs(a - b) < 2) { i++; j++; count++; } else if (a < b){ i++; } else { j++; } } System.out.println(count); } }
Java
["4\n1 4 6 2\n5\n5 1 5 7 9", "4\n1 2 3 4\n4\n10 11 12 13", "5\n1 1 1 1 1\n3\n1 2 3"]
1 second
["3", "0", "2"]
null
Java 8
standard input
[ "dp", "greedy", "two pointers", "graph matchings", "sortings", "dfs and similar" ]
62766ef9a0751cbe7987020144de7512
The first line contains an integer n (1 ≀ n ≀ 100) β€” the number of boys. The second line contains sequence a1, a2, ..., an (1 ≀ ai ≀ 100), where ai is the i-th boy's dancing skill. Similarly, the third line contains an integer m (1 ≀ m ≀ 100) β€” the number of girls. The fourth line contains sequence b1, b2, ..., bm (1 ≀ bj ≀ 100), where bj is the j-th girl's dancing skill.
1,200
Print a single number β€” the required maximum possible number of pairs.
standard output
PASSED
606adfd28c6878288015b5fb297609c0
train_000.jsonl
1416238500
The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves.We know that several boy&amp;girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair must differ by at most one.For each boy, we know his dancing skills. Similarly, for each girl we know her dancing skills. Write a code that can determine the largest possible number of pairs that can be formed from n boys and m girls.
256 megabytes
import java.util.Scanner; import java.lang.Math; import java.util.Arrays; public class Ball{ public static void main(String args[]){ Scanner scan = new Scanner(System.in); int[] boys = new int[scan.nextInt()]; for(int i=0;i<boys.length;i++){ boys[i] = scan.nextInt(); } Arrays.sort(boys); int[] girls = new int[102]; int numGirls = scan.nextInt(); for(int i=0;i<numGirls;i++){ girls[scan.nextInt()]++; } int pairs = 0; for(int i=0;i<boys.length;i++){ if(girls[boys[i]-1] > 0){ pairs++; girls[boys[i]-1]--; }else if(girls[boys[i]] > 0){ pairs++; girls[boys[i]]--; }else if(girls[boys[i]+1] > 0){ pairs++; girls[boys[i]+1]--; } } System.out.println(pairs); } }
Java
["4\n1 4 6 2\n5\n5 1 5 7 9", "4\n1 2 3 4\n4\n10 11 12 13", "5\n1 1 1 1 1\n3\n1 2 3"]
1 second
["3", "0", "2"]
null
Java 8
standard input
[ "dp", "greedy", "two pointers", "graph matchings", "sortings", "dfs and similar" ]
62766ef9a0751cbe7987020144de7512
The first line contains an integer n (1 ≀ n ≀ 100) β€” the number of boys. The second line contains sequence a1, a2, ..., an (1 ≀ ai ≀ 100), where ai is the i-th boy's dancing skill. Similarly, the third line contains an integer m (1 ≀ m ≀ 100) β€” the number of girls. The fourth line contains sequence b1, b2, ..., bm (1 ≀ bj ≀ 100), where bj is the j-th girl's dancing skill.
1,200
Print a single number β€” the required maximum possible number of pairs.
standard output
PASSED
c2b8d946e8020e001759864f23257799
train_000.jsonl
1416238500
The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves.We know that several boy&amp;girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair must differ by at most one.For each boy, we know his dancing skills. Similarly, for each girl we know her dancing skills. Write a code that can determine the largest possible number of pairs that can be formed from n boys and m girls.
256 megabytes
import java.util.*; import java.io.*; public class Main { static Reader scan; static PrintWriter out; static int boysCount; static int girlsCount; static int[] boys; static int[] girls; public static void main(String[] args) throws IOException { scan = new Reader(); out = new PrintWriter(System.out, true); boysCount = scan.nextInt(); boys = new int[boysCount]; for(int i = 0; i < boysCount; i++) boys[i] = scan.nextInt(); Arrays.sort(boys); girlsCount = scan.nextInt(); girls = new int[girlsCount]; for(int i = 0; i < girlsCount; i++) girls[i] = scan.nextInt(); Arrays.sort(girls); out.println(getPairs()); } public static int getPairs(){ int pairs = 0; boysCount--; girlsCount--; while(boysCount > -1 && girlsCount > -1){ int boySkill = boys[boysCount]; int girlSkill = girls[girlsCount]; if(boySkill <= girlSkill+1 && boySkill >= girlSkill-1){ boysCount--; girlsCount--; pairs++; } else{ if (boySkill > girlSkill) boysCount--; else girlsCount--; } } return pairs; } } 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 int nextInt() throws IOException{ int ret=0;byte c=read(); while(c<=' ')c=read(); boolean neg=(c=='-'); if(neg)c=read(); do{ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9'); if(neg)return -ret; return ret; } public long nextLong() throws IOException{ long ret=0;byte c=read(); while(c<=' ')c=read(); boolean neg=(c=='-'); if(neg)c=read(); do{ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9'); if(neg)return -ret; return ret; } public double nextDouble() throws IOException{ double ret=0,div=1;byte c=read(); while(c<=' ')c=read(); boolean neg=(c=='-'); if(neg)c = read(); do {ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9'); if(c=='.')while((c=read())>='0'&&c<='9') ret+=(c-'0')/(div*=10); if(neg)return -ret; return ret; } private void fillBuffer() throws IOException{ bytesRead=din.read(buffer,bufferPointer=0,BUFFER_SIZE); if(bytesRead==-1)buffer[0]=-1; } private byte read() throws IOException{ if(bufferPointer==bytesRead)fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException{ if(din==null) return; din.close(); } }
Java
["4\n1 4 6 2\n5\n5 1 5 7 9", "4\n1 2 3 4\n4\n10 11 12 13", "5\n1 1 1 1 1\n3\n1 2 3"]
1 second
["3", "0", "2"]
null
Java 8
standard input
[ "dp", "greedy", "two pointers", "graph matchings", "sortings", "dfs and similar" ]
62766ef9a0751cbe7987020144de7512
The first line contains an integer n (1 ≀ n ≀ 100) β€” the number of boys. The second line contains sequence a1, a2, ..., an (1 ≀ ai ≀ 100), where ai is the i-th boy's dancing skill. Similarly, the third line contains an integer m (1 ≀ m ≀ 100) β€” the number of girls. The fourth line contains sequence b1, b2, ..., bm (1 ≀ bj ≀ 100), where bj is the j-th girl's dancing skill.
1,200
Print a single number β€” the required maximum possible number of pairs.
standard output
PASSED
672fc54e5a47e2572fae68dac65f813d
train_000.jsonl
1416238500
The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves.We know that several boy&amp;girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair must differ by at most one.For each boy, we know his dancing skills. Similarly, for each girl we know her dancing skills. Write a code that can determine the largest possible number of pairs that can be formed from n boys and m girls.
256 megabytes
import java.util.*; import java.io.*; //http://codeforces.com/problemset/problem/489/B public class Main { static Reader scan; static PrintWriter out; static int boysCount; static int girlsCount; static int[] boys; static int[] girls; public static void main(String[] args) throws IOException { scan = new Reader(); out = new PrintWriter(System.out, true); boysCount = scan.nextInt(); boys = new int[boysCount]; for(int i = 0; i < boysCount; i++) boys[i] = scan.nextInt(); Arrays.sort(boys); girlsCount = scan.nextInt(); girls = new int[girlsCount]; for(int i = 0; i < girlsCount; i++) girls[i] = scan.nextInt(); Arrays.sort(girls); out.println(getPairs()); } public static int getPairs(){ int pairs = 0; boysCount--; girlsCount--; while(boysCount > -1 && girlsCount > -1){ int boySkill = boys[boysCount]; int girlSkill = girls[girlsCount]; if(boySkill <= girlSkill+1 && boySkill >= girlSkill-1){ boysCount--; girlsCount--; pairs++; } else{ if (boySkill > girlSkill) boysCount--; else girlsCount--; } } return pairs; } } 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 int nextInt() throws IOException{ int ret=0;byte c=read(); while(c<=' ')c=read(); boolean neg=(c=='-'); if(neg)c=read(); do{ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9'); if(neg)return -ret; return ret; } public long nextLong() throws IOException{ long ret=0;byte c=read(); while(c<=' ')c=read(); boolean neg=(c=='-'); if(neg)c=read(); do{ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9'); if(neg)return -ret; return ret; } public double nextDouble() throws IOException{ double ret=0,div=1;byte c=read(); while(c<=' ')c=read(); boolean neg=(c=='-'); if(neg)c = read(); do {ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9'); if(c=='.')while((c=read())>='0'&&c<='9') ret+=(c-'0')/(div*=10); if(neg)return -ret; return ret; } private void fillBuffer() throws IOException{ bytesRead=din.read(buffer,bufferPointer=0,BUFFER_SIZE); if(bytesRead==-1)buffer[0]=-1; } private byte read() throws IOException{ if(bufferPointer==bytesRead)fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException{ if(din==null) return; din.close(); } }
Java
["4\n1 4 6 2\n5\n5 1 5 7 9", "4\n1 2 3 4\n4\n10 11 12 13", "5\n1 1 1 1 1\n3\n1 2 3"]
1 second
["3", "0", "2"]
null
Java 8
standard input
[ "dp", "greedy", "two pointers", "graph matchings", "sortings", "dfs and similar" ]
62766ef9a0751cbe7987020144de7512
The first line contains an integer n (1 ≀ n ≀ 100) β€” the number of boys. The second line contains sequence a1, a2, ..., an (1 ≀ ai ≀ 100), where ai is the i-th boy's dancing skill. Similarly, the third line contains an integer m (1 ≀ m ≀ 100) β€” the number of girls. The fourth line contains sequence b1, b2, ..., bm (1 ≀ bj ≀ 100), where bj is the j-th girl's dancing skill.
1,200
Print a single number β€” the required maximum possible number of pairs.
standard output
PASSED
a3c310e52f2ce9b9f7c6fe6016c10604
train_000.jsonl
1416238500
The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves.We know that several boy&amp;girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair must differ by at most one.For each boy, we know his dancing skills. Similarly, for each girl we know her dancing skills. Write a code that can determine the largest possible number of pairs that can be formed from n boys and m girls.
256 megabytes
import java.io.*; import java.util.*; public class maindp{ public static int getInt(String s){ return Integer.parseInt(s); } public static void main(String[] args)throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n= getInt(br.readLine()); String[] boi = br.readLine().split(" "); int m = getInt(br.readLine()); String[] girl = br.readLine().split(" "); int[] arr1 = new int[n+1];int[] arr2 = new int[m+1]; for(int i=1;i<=n;i++){ arr1[i]=getInt(boi[i-1]); } for(int i=1;i<=m;i++){ arr2[i]=getInt(girl[i-1]); } int[][] dp = new int[n+1][m+1]; Arrays.sort(arr2); Arrays.sort(arr1); for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ dp[i][j]=Math.max(dp[i][j],Math.max(dp[i-1][j],dp[i][j-1])); if(Math.abs(arr1[i]-arr2[j])<=1) dp[i][j]=Math.max(dp[i][j],dp[i-1][j-1]+1); } } System.out.println(dp[n][m]); } }
Java
["4\n1 4 6 2\n5\n5 1 5 7 9", "4\n1 2 3 4\n4\n10 11 12 13", "5\n1 1 1 1 1\n3\n1 2 3"]
1 second
["3", "0", "2"]
null
Java 8
standard input
[ "dp", "greedy", "two pointers", "graph matchings", "sortings", "dfs and similar" ]
62766ef9a0751cbe7987020144de7512
The first line contains an integer n (1 ≀ n ≀ 100) β€” the number of boys. The second line contains sequence a1, a2, ..., an (1 ≀ ai ≀ 100), where ai is the i-th boy's dancing skill. Similarly, the third line contains an integer m (1 ≀ m ≀ 100) β€” the number of girls. The fourth line contains sequence b1, b2, ..., bm (1 ≀ bj ≀ 100), where bj is the j-th girl's dancing skill.
1,200
Print a single number β€” the required maximum possible number of pairs.
standard output
PASSED
f2207a465513e1fa3e621368540dcdc1
train_000.jsonl
1416238500
The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves.We know that several boy&amp;girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair must differ by at most one.For each boy, we know his dancing skills. Similarly, for each girl we know her dancing skills. Write a code that can determine the largest possible number of pairs that can be formed from n boys and m girls.
256 megabytes
import java.io.*; import java.util.*; public class main{ public static int getInt(String s){ return Integer.parseInt(s); } public static void main(String[] args)throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n= getInt(br.readLine()); String[] boi = br.readLine().split(" "); int m = getInt(br.readLine()); String[] girl = br.readLine().split(" "); int[] arr1 = new int[n];int[] arr2 = new int[m]; for(int i=0;i<n;i++){ arr1[i]=getInt(boi[i]); } for(int i=0;i<m;i++){ arr2[i]=getInt(girl[i]); } Arrays.sort(arr1); Arrays.sort(arr2); int ans=0; int j=0; int i=0; while(i<n && j<m){ int diff = arr1[i]-arr2[j]; if(Math.abs(diff)<=1){ ans+=1; j+=1; i+=1; } else{ if(diff<0) i+=1; else j+=1; } } System.out.println(ans); } }
Java
["4\n1 4 6 2\n5\n5 1 5 7 9", "4\n1 2 3 4\n4\n10 11 12 13", "5\n1 1 1 1 1\n3\n1 2 3"]
1 second
["3", "0", "2"]
null
Java 8
standard input
[ "dp", "greedy", "two pointers", "graph matchings", "sortings", "dfs and similar" ]
62766ef9a0751cbe7987020144de7512
The first line contains an integer n (1 ≀ n ≀ 100) β€” the number of boys. The second line contains sequence a1, a2, ..., an (1 ≀ ai ≀ 100), where ai is the i-th boy's dancing skill. Similarly, the third line contains an integer m (1 ≀ m ≀ 100) β€” the number of girls. The fourth line contains sequence b1, b2, ..., bm (1 ≀ bj ≀ 100), where bj is the j-th girl's dancing skill.
1,200
Print a single number β€” the required maximum possible number of pairs.
standard output
PASSED
d18aea106f85dffa276109c5e7759893
train_000.jsonl
1416238500
The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves.We know that several boy&amp;girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair must differ by at most one.For each boy, we know his dancing skills. Similarly, for each girl we know her dancing skills. Write a code that can determine the largest possible number of pairs that can be formed from n boys and m girls.
256 megabytes
import java.util.*; import java.io.*; public class BerSUBall{ static PrintWriter pw = new PrintWriter(System.out); public static void main(String[] args){ FastReader sc = new FastReader(); int n = sc.nextInt(); int[] boys = new int[n]; for(int i = 0;i<n;i++)boys[i]=sc.nextInt(); int m = sc.nextInt(); int[] girls = new int[m]; for(int i = 0;i<m;i++)girls[i]=sc.nextInt(); int out = 0; Arrays.sort(boys); Arrays.sort(girls); for(int i = 0;i<n;i++){ for(int j = 0;j<m;j++){ if(Math.abs(boys[i]-girls[j])<=1) { girls[j]= Integer.MIN_VALUE; out++; j = m; } } } pw.println(out); pw.flush(); pw.close(); } 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; } } }
Java
["4\n1 4 6 2\n5\n5 1 5 7 9", "4\n1 2 3 4\n4\n10 11 12 13", "5\n1 1 1 1 1\n3\n1 2 3"]
1 second
["3", "0", "2"]
null
Java 8
standard input
[ "dp", "greedy", "two pointers", "graph matchings", "sortings", "dfs and similar" ]
62766ef9a0751cbe7987020144de7512
The first line contains an integer n (1 ≀ n ≀ 100) β€” the number of boys. The second line contains sequence a1, a2, ..., an (1 ≀ ai ≀ 100), where ai is the i-th boy's dancing skill. Similarly, the third line contains an integer m (1 ≀ m ≀ 100) β€” the number of girls. The fourth line contains sequence b1, b2, ..., bm (1 ≀ bj ≀ 100), where bj is the j-th girl's dancing skill.
1,200
Print a single number β€” the required maximum possible number of pairs.
standard output
PASSED
c68affe2948170fa1e1c78d749b339b0
train_000.jsonl
1416238500
The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves.We know that several boy&amp;girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair must differ by at most one.For each boy, we know his dancing skills. Similarly, for each girl we know her dancing skills. Write a code that can determine the largest possible number of pairs that can be formed from n boys and m girls.
256 megabytes
/* Author: @__goku__ [email protected] `\-. ` \ `. ` \ \ | __.._ | \. S O N - G O K U ..---~~ ~ . | Y ~-. `| | `. `~~--. \ ~. \ \__. . -- - . .-~~~~~ , , ~~~~~~---...._ .-~___ ,'/ ,'/ ,'\ __...---~~~ ~-. /._\_( ,(/_. 7,-. ~~---...__ _...>- P""6=`_/"6"~ 6) ___...--~~~ ~~--._ \`--') `---' 9' _..--~~~ ~\ ~~/_ ~~~ /`-.--~~ `. --- .' \_ `. " _.-' | ~-.,-------._ ..._../~~ ./ .-' .-~~~-. ,--~~~ ,'...\` _./.----~~.'/ /' `- _.-( |\ `/~ _____..-' / / _.-~~`. / | /. ^---~~~~ ' / / ,' ~. \ ( / ( . _ ' /' / ,/ \ ) (`. | `\ - - - - ~ /' ( / . | \.\| \ /' \ |`. / /.'\\ `\ /' ~-\ . /\ /, ( `\ /' `.___..- \ | | \ `\_/' // \. | | | | _Seal_ /' | | | */ import java.io.*; import java.util.*; public class C277B { static PrintWriter out = new PrintWriter((System.out)); public static void main(String args[]) throws IOException { Kioken sc = new Kioken(); int n=sc.nextInt(); int ar[]=new int[n]; for(int x=0;x<n;x++) { ar[x]=sc.nextInt(); } int m=sc.nextInt(); int br[]=new int[m]; for(int x=0;x<m;x++) { br[x]=sc.nextInt(); } Arrays.parallelSort(ar); Arrays.parallelSort(br); int dp[][]=new int[n+1][m+1]; for(int x=0;x<=n;x++) { for(int y=0;y<=m;y++) { dp[x][y]=-1; } } int ans=kamehameha(ar,br,0,0,n,m,dp); out.println(dp[0][0]); out.close(); } private static int kamehameha(int[] ar, int[] br, int i,int j,int n, int m,int dp[][]) { if (i == n || j == m) { dp[i][j]=0; return 0; } else { int a=0,b=0,c=0; if(Math.abs(ar[i]-br[j])<=1) { if(dp[i+1][j+1]==-1) { dp[i + 1][j + 1] = kamehameha(ar, br, i + 1, j + 1, n, m, dp); } a=1+dp[i+1][j+1]; } if(dp[i+1][j]==-1) { dp[i+1][j]=kamehameha(ar,br,i+1,j,n,m,dp); } if(dp[i][j+1]==-1) { dp[i][j+1]=kamehameha(ar,br,i,j+1,n,m,dp); } b=dp[i][j+1]; c=dp[i+1][j]; dp[i][j]=Math.max(a,Math.max(b,c)); return dp[i][j]; } } static class Kioken { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { try { return br.readLine(); } catch (Exception e) { e.printStackTrace(); } return null; } public boolean hasNext() { String next = null; try { next = br.readLine(); } catch (Exception e) { } if (next == null) { return false; } st = new StringTokenizer(next); return true; } } }
Java
["4\n1 4 6 2\n5\n5 1 5 7 9", "4\n1 2 3 4\n4\n10 11 12 13", "5\n1 1 1 1 1\n3\n1 2 3"]
1 second
["3", "0", "2"]
null
Java 8
standard input
[ "dp", "greedy", "two pointers", "graph matchings", "sortings", "dfs and similar" ]
62766ef9a0751cbe7987020144de7512
The first line contains an integer n (1 ≀ n ≀ 100) β€” the number of boys. The second line contains sequence a1, a2, ..., an (1 ≀ ai ≀ 100), where ai is the i-th boy's dancing skill. Similarly, the third line contains an integer m (1 ≀ m ≀ 100) β€” the number of girls. The fourth line contains sequence b1, b2, ..., bm (1 ≀ bj ≀ 100), where bj is the j-th girl's dancing skill.
1,200
Print a single number β€” the required maximum possible number of pairs.
standard output
PASSED
4e93de3f7f9e79a40b036be1762cd048
train_000.jsonl
1416238500
The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves.We know that several boy&amp;girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair must differ by at most one.For each boy, we know his dancing skills. Similarly, for each girl we know her dancing skills. Write a code that can determine the largest possible number of pairs that can be formed from n boys and m girls.
256 megabytes
/* Author: @__goku__ [email protected] `\-. ` \ `. ` \ \ | __.._ | \. S O N - G O K U ..---~~ ~ . | Y ~-. `| | `. `~~--. \ ~. \ \__. . -- - . .-~~~~~ , , ~~~~~~---...._ .-~___ ,'/ ,'/ ,'\ __...---~~~ ~-. /._\_( ,(/_. 7,-. ~~---...__ _...>- P""6=`_/"6"~ 6) ___...--~~~ ~~--._ \`--') `---' 9' _..--~~~ ~\ ~~/_ ~~~ /`-.--~~ `. --- .' \_ `. " _.-' | ~-.,-------._ ..._../~~ ./ .-' .-~~~-. ,--~~~ ,'...\` _./.----~~.'/ /' `- _.-( |\ `/~ _____..-' / / _.-~~`. / | /. ^---~~~~ ' / / ,' ~. \ ( / ( . _ ' /' / ,/ \ ) (`. | `\ - - - - ~ /' ( / . | \.\| \ /' \ |`. / /.'\\ `\ /' ~-\ . /\ /, ( `\ /' `.___..- \ | | \ `\_/' // \. | | | | _Seal_ /' | | | */ import java.io.*; import java.util.*; public class C277B { static PrintWriter out = new PrintWriter((System.out)); public static void main(String args[]) throws IOException { Kioken sc = new Kioken(); int n=sc.nextInt(); int ar[]=new int[n]; for(int x=0;x<n;x++) { ar[x]=sc.nextInt(); } int m=sc.nextInt(); int br[]=new int[m]; for(int x=0;x<m;x++) { br[x]=sc.nextInt(); } Arrays.parallelSort(ar); Arrays.parallelSort(br); int dp[][]=new int[n+1][m+1]; for(int x=1;x<=n;x++) { for(int y=1;y<=m;y++) { int a=0,b=0,c=0; if(Math.abs(ar[x-1]-br[y-1])<=1) { a=1+dp[x-1][y-1]; } b=dp[x-1][y]; c=dp[x][y-1]; dp[x][y]=Math.max(a,Math.max(b,c)); } } //int ans=kamehameha(ar,br,0,0,n,m,dp); out.println(dp[n][m]); out.close(); } private static int kamehameha(int[] ar, int[] br, int i,int j,int n, int m,int dp[][]) { if (i == n || j == m) { dp[i][j]=0; return 0; } else { int a=0,b=0,c=0; if(Math.abs(ar[i]-br[j])<=1) { if(dp[i+1][j+1]==-1) { dp[i + 1][j + 1] = kamehameha(ar, br, i + 1, j + 1, n, m, dp); } a=1+dp[i+1][j+1]; } if(dp[i+1][j]==-1) { dp[i+1][j]=kamehameha(ar,br,i+1,j,n,m,dp); } if(dp[i][j+1]==-1) { dp[i][j+1]=kamehameha(ar,br,i,j+1,n,m,dp); } b=dp[i][j+1]; c=dp[i+1][j]; dp[i][j]=Math.max(a,Math.max(b,c)); return dp[i][j]; } } static class Kioken { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { try { return br.readLine(); } catch (Exception e) { e.printStackTrace(); } return null; } public boolean hasNext() { String next = null; try { next = br.readLine(); } catch (Exception e) { } if (next == null) { return false; } st = new StringTokenizer(next); return true; } } }
Java
["4\n1 4 6 2\n5\n5 1 5 7 9", "4\n1 2 3 4\n4\n10 11 12 13", "5\n1 1 1 1 1\n3\n1 2 3"]
1 second
["3", "0", "2"]
null
Java 8
standard input
[ "dp", "greedy", "two pointers", "graph matchings", "sortings", "dfs and similar" ]
62766ef9a0751cbe7987020144de7512
The first line contains an integer n (1 ≀ n ≀ 100) β€” the number of boys. The second line contains sequence a1, a2, ..., an (1 ≀ ai ≀ 100), where ai is the i-th boy's dancing skill. Similarly, the third line contains an integer m (1 ≀ m ≀ 100) β€” the number of girls. The fourth line contains sequence b1, b2, ..., bm (1 ≀ bj ≀ 100), where bj is the j-th girl's dancing skill.
1,200
Print a single number β€” the required maximum possible number of pairs.
standard output
PASSED
2a6946ee9a7aca0df9182c6dcda5a268
train_000.jsonl
1416238500
The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves.We know that several boy&amp;girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair must differ by at most one.For each boy, we know his dancing skills. Similarly, for each girl we know her dancing skills. Write a code that can determine the largest possible number of pairs that can be formed from n boys and m girls.
256 megabytes
/* Author: @__goku__ [email protected] `\-. ` \ `. ` \ \ | __.._ | \. S O N - G O K U ..---~~ ~ . | Y ~-. `| | `. `~~--. \ ~. \ \__. . -- - . .-~~~~~ , , ~~~~~~---...._ .-~___ ,'/ ,'/ ,'\ __...---~~~ ~-. /._\_( ,(/_. 7,-. ~~---...__ _...>- P""6=`_/"6"~ 6) ___...--~~~ ~~--._ \`--') `---' 9' _..--~~~ ~\ ~~/_ ~~~ /`-.--~~ `. --- .' \_ `. " _.-' | ~-.,-------._ ..._../~~ ./ .-' .-~~~-. ,--~~~ ,'...\` _./.----~~.'/ /' `- _.-( |\ `/~ _____..-' / / _.-~~`. / | /. ^---~~~~ ' / / ,' ~. \ ( / ( . _ ' /' / ,/ \ ) (`. | `\ - - - - ~ /' ( / . | \.\| \ /' \ |`. / /.'\\ `\ /' ~-\ . /\ /, ( `\ /' `.___..- \ | | \ `\_/' // \. | | | | _Seal_ /' | | | */ import java.io.*; import java.util.*; public class C277B { static PrintWriter out = new PrintWriter((System.out)); public static void main(String args[]) throws IOException { Kioken sc = new Kioken(); int n=sc.nextInt(); int ar[]=new int[n]; for(int x=0;x<n;x++) { ar[x]=sc.nextInt(); } int m=sc.nextInt(); int br[]=new int[m]; for(int x=0;x<m;x++) { br[x]=sc.nextInt(); } Arrays.parallelSort(ar); Arrays.parallelSort(br); int ans=0; for(int x=0;x<n;x++) { for(int y=0;y<m;y++) { if(Math.abs(ar[x]-br[y])<=1) { ans++; br[y]=Integer.MAX_VALUE; break; } } } out.println(ans); out.close(); } static class Kioken { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { try { return br.readLine(); } catch (Exception e) { e.printStackTrace(); } return null; } public boolean hasNext() { String next = null; try { next = br.readLine(); } catch (Exception e) { } if (next == null) { return false; } st = new StringTokenizer(next); return true; } } }
Java
["4\n1 4 6 2\n5\n5 1 5 7 9", "4\n1 2 3 4\n4\n10 11 12 13", "5\n1 1 1 1 1\n3\n1 2 3"]
1 second
["3", "0", "2"]
null
Java 8
standard input
[ "dp", "greedy", "two pointers", "graph matchings", "sortings", "dfs and similar" ]
62766ef9a0751cbe7987020144de7512
The first line contains an integer n (1 ≀ n ≀ 100) β€” the number of boys. The second line contains sequence a1, a2, ..., an (1 ≀ ai ≀ 100), where ai is the i-th boy's dancing skill. Similarly, the third line contains an integer m (1 ≀ m ≀ 100) β€” the number of girls. The fourth line contains sequence b1, b2, ..., bm (1 ≀ bj ≀ 100), where bj is the j-th girl's dancing skill.
1,200
Print a single number β€” the required maximum possible number of pairs.
standard output