exec_outcome
stringclasses
1 value
code_uid
stringlengths
32
32
file_name
stringclasses
111 values
prob_desc_created_at
stringlengths
10
10
prob_desc_description
stringlengths
63
3.8k
prob_desc_memory_limit
stringclasses
18 values
source_code
stringlengths
117
65.5k
lang_cluster
stringclasses
1 value
prob_desc_sample_inputs
stringlengths
2
802
prob_desc_time_limit
stringclasses
27 values
prob_desc_sample_outputs
stringlengths
2
796
prob_desc_notes
stringlengths
4
3k
lang
stringclasses
5 values
prob_desc_input_from
stringclasses
3 values
tags
listlengths
0
11
src_uid
stringlengths
32
32
prob_desc_input_spec
stringlengths
28
2.37k
difficulty
int64
-1
3.5k
prob_desc_output_spec
stringlengths
17
1.47k
prob_desc_output_to
stringclasses
3 values
hidden_unit_tests
stringclasses
1 value
PASSED
39fba6199e49da8ef6c248d675f422f5
train_001.jsonl
1584196500
You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$.
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.util.*; public class Main { static List<Integer> al[]; private static void solver(InputReader sc, PrintWriter out) { int n = sc.nextInt(); al = new ArrayList[n]; for(int i=0; i<n; i++) al[i] = new ArrayList<>(); List<Pair> list = new ArrayList<>(); Map<Pair,Integer> hm = new LinkedHashMap<>(); for(int i=0; i<n-1; i++){ int x = sc.nextInt()-1; int y = sc.nextInt()-1; al[x].add(y); al[y].add(x); Pair p = new Pair(x,y); list.add(p); hm.put(p,-1); } int count=0; for(Pair p : list){ if(al[p.x].size()==1 || al[p.y].size()==1){ hm.put(p,count); count++; } } for(Map.Entry<Pair,Integer> map : hm.entrySet()){ int y = map.getValue(); if(y==-1){ out.println(count); count++; } else out.println(y); } } public static void main(String[] args) throws Exception { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); solver(in,out); out.close(); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public int[] readIntArray(int n){ int arr[] = new int[n]; for(int i=0;i<n;i++) arr[i] = nextInt(); return arr; } } } class Pair{ int x,y; Pair(int x, int y){ this.x = x; this.y = y; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair pair = (Pair) o; return x == pair.x && y == pair.y; } @Override public int hashCode() { return Objects.hash(x, y); } }
Java
["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"]
1 second
["0\n1", "0\n3\n2\n4\n1"]
NoteThe tree from the second sample:
Java 11
standard input
[ "constructive algorithms", "greedy", "dfs and similar", "trees" ]
5ef966b7d9fbf27e6197b074eca31b15
The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.
1,500
Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order).
standard output
PASSED
a69532bb8158d3ddde3e71d7019eac86
train_001.jsonl
1584196500
You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main { //static int p = 1000000007; static int p = 998244353; static int[] arr1, arr2, arr3, ans; static boolean fill(int u, int i) { if(arr1[u]==0) arr1[u]=i; else if(arr2[u]==0) arr2[u]=i; else { arr3[u]=i; ans[arr1[u]]=0; ans[arr2[u]]=1; ans[arr3[u]]=2; return true; } return false; } public static void main(String args[]) throws IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); int t = 1; //t = sc.nextInt(); while (t-- > 0) { int n=sc.nextInt(), u, v, k=0; arr1=new int[n]; arr2=new int[n]; arr3=new int[n]; ans=new int[n]; Arrays.fill(ans, -1); for(int i=1; i<n; i++) { u = sc.nextInt()-1; v = sc.nextInt()-1; if(fill(u, i)||fill(v, i)) { k=3; break; } } for(int i=1; i<n; i++) { if(ans[i]==-1) ans[i]=k++; out.println(ans[i]); } } out.flush(); } static int count(int x, int[] arr) { int count = 0; for (int i = 0; i < arr.length; i++) if (arr[i] == x) count++; return count; } public static String reverseString(String str) { StringBuilder sb = new StringBuilder(str); sb.reverse(); return sb.toString(); } static boolean isPalindrome(String str) { int i = 0, j = str.length() - 1; while (i < j) { if (str.charAt(i) != str.charAt(j)) return false; i++; j--; } return true; } static void print(int[] arr) { for (int i = 0; i < arr.length; i++) System.out.print(arr[i] + " "); System.out.println(); } public static int abs(int x) { return ((x > 0) ? x : -x); } public static long abs(long x) { return ((x > 0) ? x : -x); } public static int max(int a, int b) { return Math.max(a, b); } public static long max(long a, long b) { return Math.max(a, b); } public static int min(int a, int b) { return Math.min(a, b); } public static long min(long a, long b) { return Math.min(a, b); } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static int modInverse(int a, int m) { int g = gcd(a, m); if (g != 1) return -1; else return power(a, m - 2, m); } // To compute x^y under modulo m static int power(int x, int y, int m) { if (y == 0) return 1; int p = power(x, y / 2, m) % m; p = (p * p) % m; if (y % 2 == 0) return p; else return (x * p) % m; } static int[] primeGenerator(int num) { int length = 0, arr[] = new int[num], a = num, factor = 1; if (num % 2 == 0) { while (num % 2 == 0) { num /= 2; factor *= 2; } arr[length++] = factor; } for (int i = 3; i * i <= a; i++) { factor = 1; if (num % i == 0) { while (num % i == 0) { num /= i; factor *= i; } arr[length++] = factor; } } if (num > 1) arr[length++] = num; return Arrays.copyOfRange(arr, 0, length); } static boolean isPrime(int n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } Scanner(String fileName) throws FileNotFoundException { br = new BufferedReader(new FileReader(fileName)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { return br.readLine(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } boolean ready() throws IOException { return br.ready(); } } static void sort(int[] a) { shuffle(a); Arrays.sort(a); } static void shuffle(int[] a) { int n = a.length; Random rand = new Random(); for (int i = 0; i < n; i++) { int tmpIdx = rand.nextInt(n); int tmp = a[i]; a[i] = a[tmpIdx]; a[tmpIdx] = tmp; } } } class Pair { int x; int y; Pair(int a, int b) { x = a; y = b; } void print() { System.out.println(this.x + " " + this.y); } }
Java
["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"]
1 second
["0\n1", "0\n3\n2\n4\n1"]
NoteThe tree from the second sample:
Java 11
standard input
[ "constructive algorithms", "greedy", "dfs and similar", "trees" ]
5ef966b7d9fbf27e6197b074eca31b15
The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.
1,500
Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order).
standard output
PASSED
358c7373a6f2bf34cf71d1f224a16d28
train_001.jsonl
1584196500
You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; import java.util.Arrays; import java.util.List; import java.util.StringTokenizer; import java.util.function.*; import java.util.stream.*; public class C { private static final FastReader in = new FastReader(); private static final FastWriter out = new FastWriter(); public static void main(String[] args) { new C().run(); } private void run() { var t = 1; while (t-- > 0) { solve(); } out.flush(); } private void solve() { var n = in.nextInt(); var tree = new ArrayList<List<IntPair>>(); for (var i = 0; i < n; i++) { tree.add(new ArrayList<>()); } var degree = new int[n]; for (var i = 0; i < n - 1; i++) { var u = in.nextInt() - 1; var v = in.nextInt() - 1; tree.get(u).add(IntPair.of(v, i)); tree.get(v).add(IntPair.of(u, i)); degree[u]++; degree[v]++; } var ans = new int[n - 1]; Arrays.fill(ans, -1); var q = new LinkedList<Integer>(); for (var i = 0; i < n; i++) { if (degree[i] == 1) { q.offer(i); } } var label = 0; while (!q.isEmpty()) { var u = q.poll(); for (var e : tree.get(u)) { if (ans[e.b] == -1) { ans[e.b] = label++; degree[e.a]--; if (degree[e.a] == 1) { q.offer(e.a); } } } } for (var l : ans) { out.println(l); } } } class FastReader { private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); private static StringTokenizer in; public String next() { while (in == null || !in.hasMoreTokens()) { try { in = new StringTokenizer(br.readLine()); } catch (IOException e) { return null; } } return in.nextToken(); } public BigDecimal nextBigDecimal() { return new BigDecimal(next()); } public BigInteger nextBigInteger() { return new BigInteger(next()); } public boolean nextBoolean() { return Boolean.valueOf(next()); } public byte nextByte() { return Byte.valueOf(next()); } public double nextDouble() { return Double.valueOf(next()); } public double[] nextDoubleArray(int length) { var a = new double[length]; for (var i = 0; i < length; i++) { a[i] = nextDouble(); } return a; } public int nextInt() { return Integer.valueOf(next()); } public int[] nextIntArray(int length) { var a = new int[length]; for (var i = 0; i < length; i++) { a[i] = nextInt(); } return a; } public long nextLong() { return Long.valueOf(next()); } public long[] nextLongArray(int length) { var a = new long[length]; for (var i = 0; i < length; i++) { a[i] = nextLong(); } return a; } } class FastWriter extends PrintWriter { public FastWriter() { super(System.out); } public void println(double[] a) { for (var i = 0; i < a.length; i++) { print(a[i]); print(i + 1 < a.length ? ' ' : '\n'); } } public void println(int[] a) { for (var i = 0; i < a.length; i++) { print(a[i]); print(i + 1 < a.length ? ' ' : '\n'); } } public void println(long[] a) { for (var i = 0; i < a.length; i++) { print(a[i]); print(i + 1 < a.length ? ' ' : '\n'); } } public <T> void println(T[] a) { for (var i = 0; i < a.length; i++) { print(a[i]); print(i + 1 < a.length ? ' ' : '\n'); } } public <T> void println(List<T> l) { println(l.toArray()); } public void debug(String name, Object o) { String value = Arrays.deepToString(new Object[] { o }); value = value.substring(1, value.length() - 1); System.err.println(name + " => " + value); } } class IntPair extends Pair<Integer, Integer> { IntPair(Integer a, Integer b) { super(a, b); } public static IntPair of(int a, int b) { return new IntPair(a, b); } } class Pair<T, U> { public T a; public U b; Pair(T a, U b) { this.a = a; this.b = b; } public static <T, U> Pair<T, U> of(T a, U b) { return new Pair<>(a, b); } public T getA() { return a; } public U getB() { return b; } @Override public String toString() { return String.format("(%s, %s)", a, b); } }
Java
["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"]
1 second
["0\n1", "0\n3\n2\n4\n1"]
NoteThe tree from the second sample:
Java 11
standard input
[ "constructive algorithms", "greedy", "dfs and similar", "trees" ]
5ef966b7d9fbf27e6197b074eca31b15
The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.
1,500
Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order).
standard output
PASSED
91468a970700d7c197b5dd90a7e89806
train_001.jsonl
1584196500
You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.StringTokenizer; import java.util.function.*; import java.util.stream.*; import java.util.stream.Collectors; import java.util.stream.IntStream; public class C { private static final FastReader in = new FastReader(); private static final FastWriter out = new FastWriter(); public static void main(String[] args) { new C().run(); } private void run() { var t = 1; while (t-- > 0) { solve(); } out.flush(); } private void solve() { var n = in.nextInt(); var tree = Graph.ofInt(n); for (var i = 0; i < n - 1; i++) { var u = in.nextInt() - 1; var v = in.nextInt() - 1; tree.addBidirectedEdges(u, v, i); } var ans = new int[n - 1]; Arrays.fill(ans, -1); var degree = new int[n]; var q = new LinkedList<Integer>(); for (var i = 0; i < n; i++) { degree[i] = tree.degree(i); if (degree[i] == 1) { q.offer(i); } } var label = 0; while (!q.isEmpty()) { var u = q.poll(); for (var e : tree.neighbors(u)) { if (ans[e.weight] == -1) { ans[e.weight] = label++; degree[e.neighbor]--; if (degree[e.neighbor] == 1) { q.offer(e.neighbor); } } } } for (var l : ans) { out.println(l); } } } class FastReader { private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); private static StringTokenizer in; public String next() { while (in == null || !in.hasMoreTokens()) { try { in = new StringTokenizer(br.readLine()); } catch (IOException e) { return null; } } return in.nextToken(); } public BigDecimal nextBigDecimal() { return new BigDecimal(next()); } public BigInteger nextBigInteger() { return new BigInteger(next()); } public boolean nextBoolean() { return Boolean.valueOf(next()); } public byte nextByte() { return Byte.valueOf(next()); } public double nextDouble() { return Double.valueOf(next()); } public double[] nextDoubleArray(int length) { var a = new double[length]; for (var i = 0; i < length; i++) { a[i] = nextDouble(); } return a; } public int nextInt() { return Integer.valueOf(next()); } public int[] nextIntArray(int length) { var a = new int[length]; for (var i = 0; i < length; i++) { a[i] = nextInt(); } return a; } public long nextLong() { return Long.valueOf(next()); } public long[] nextLongArray(int length) { var a = new long[length]; for (var i = 0; i < length; i++) { a[i] = nextLong(); } return a; } } class FastWriter extends PrintWriter { public FastWriter() { super(System.out); } public void println(double[] a) { for (var i = 0; i < a.length; i++) { print(a[i]); print(i + 1 < a.length ? ' ' : '\n'); } } public void println(int[] a) { for (var i = 0; i < a.length; i++) { print(a[i]); print(i + 1 < a.length ? ' ' : '\n'); } } public void println(long[] a) { for (var i = 0; i < a.length; i++) { print(a[i]); print(i + 1 < a.length ? ' ' : '\n'); } } public <T> void println(T[] a) { for (var i = 0; i < a.length; i++) { print(a[i]); print(i + 1 < a.length ? ' ' : '\n'); } } public <T> void println(List<T> l) { println(l.toArray()); } public void debug(String name, Object o) { String value = Arrays.deepToString(new Object[] { o }); value = value.substring(1, value.length() - 1); System.err.println(name + " => " + value); } } class Graph<T> { public final int nodes; private final List<List<Edge<T>>> adjacencyList; private final T defaultWeight; Graph(int nodes, T defaultWeight) { this.nodes = nodes; this.adjacencyList = new ArrayList<>(nodes); this.defaultWeight = defaultWeight; for (var i = 0; i < nodes; i++) { this.adjacencyList.add(new ArrayList<>()); } } public static Graph<Integer> ofInt(int nodes) { return new Graph<Integer>(nodes, 1); } public static Graph<Double> ofDouble(int nodes) { return new Graph<Double>(nodes, 1.0); } public void addEdge(int u, int v) { addEdge(u, v, defaultWeight); } public void addEdge(int u, int v, T weight) { adjacencyList.get(u).add(Edge.of(v, weight)); } public void addBidirectedEdges(int u, int v) { addBidirectedEdges(u, v, defaultWeight); } public void addBidirectedEdges(int u, int v, T weight) { addEdge(u, v, weight); addEdge(v, u, weight); } public List<Edge<T>> neighbors(int u) { return adjacencyList.get(u); } public int degree(int u) { return neighbors(u).size(); } @Override public String toString() { String adj = IntStream.range(0, nodes) .mapToObj(i -> " " + i + ": " + adjacencyList.get(i)) .collect(Collectors.joining(",\n")); return "Graph {\n" + " nodes: " + nodes + ",\n" + " adjacencyList: {\n" + adj + "\n" + " }\n" + "}"; } public static class Edge<T> { public final int neighbor; public final T weight; Edge(int neighbor, T weight) { this.neighbor = neighbor; this.weight = weight; } public static <T> Edge<T> of(int neighbor, T weight) { return new Edge<>(neighbor, weight); } public int getNeighbor() { return neighbor; } public T getWeight() { return weight; } @Override public String toString() { return String.format("(%s, %s)", neighbor, weight); } } } class IntPair extends Pair<Integer, Integer> { IntPair(Integer a, Integer b) { super(a, b); } public static IntPair of(int a, int b) { return new IntPair(a, b); } } class Pair<T, U> { public T a; public U b; Pair(T a, U b) { this.a = a; this.b = b; } public static <T, U> Pair<T, U> of(T a, U b) { return new Pair<>(a, b); } public T getA() { return a; } public U getB() { return b; } @Override public String toString() { return String.format("(%s, %s)", a, b); } }
Java
["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"]
1 second
["0\n1", "0\n3\n2\n4\n1"]
NoteThe tree from the second sample:
Java 11
standard input
[ "constructive algorithms", "greedy", "dfs and similar", "trees" ]
5ef966b7d9fbf27e6197b074eca31b15
The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.
1,500
Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order).
standard output
PASSED
438f6bad99701934663004dc61f9d6e5
train_001.jsonl
1584196500
You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$.
256 megabytes
import java.util.*; public class MEX { public static void main(String args[]) { Scanner s = new Scanner(System.in); int n = s.nextInt(); Node[] nodes = new Node[n]; Edge[] edges = new Edge[n-1]; for (int i = 0; i < n; i++) { nodes[i] = new Node(i); } for (int i = 0; i < n-1; i++) { int c1 = s.nextInt() - 1; int c2 = s.nextInt() - 1; edges[i] = new Edge(nodes[c1], nodes[c2]); nodes[c1].connect.add(edges[i]); nodes[c2].connect.add(edges[i]); } Node n1 = null; Node n2 = null; Node n3 = null; for (int i = 0; i < n; i++) { Node cur = nodes[i]; if (cur.connect.size() == 1) { if (n1 == null) { n1 = cur; } else if (n2 == null){ n2 = cur; } else { n3 = cur; break; } } } int count = n-2; for (int i = 0; i < n-1; i++) { if (edges[i].node1 != n1 && edges[i].node1 != n2 && edges[i].node2 != n1 && edges[i].node2 != n2 && edges[i].node2 != n3 && edges[i].node1 != n3) { edges[i].val = count; count--; } } int doneCount = 0; for (int i = 0; i < n-1; i++) { if (edges[i].val == -1) { if (doneCount == 0) { System.out.print("0 "); doneCount++; } else if (doneCount == 1){ System.out.print("1 "); doneCount++; } else { System.out.print("2 "); } } else { System.out.print(edges[i].val + " "); } } } private static class Node { public ArrayList<Edge> connect; public int nodeNum; public Node(int nn) { this.nodeNum = nn; this.connect = new ArrayList<Edge>(); } } private static class Edge { public Node node1; public Node node2; public int val; public Edge(Node n1, Node n2) { this.node1 = n1; this.node2 = n2; this.val = -1; } } }
Java
["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"]
1 second
["0\n1", "0\n3\n2\n4\n1"]
NoteThe tree from the second sample:
Java 11
standard input
[ "constructive algorithms", "greedy", "dfs and similar", "trees" ]
5ef966b7d9fbf27e6197b074eca31b15
The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.
1,500
Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order).
standard output
PASSED
a138f43af41335fd5061dc38af0a4c96
train_001.jsonl
1584196500
You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$.
256 megabytes
import java.io.*; import java.util.*; // tau is superior public class C { class Edge { int v, id; Edge(int vv, int ii) { v = vv; id = ii; } } int dfs(int u, int p) { int num = 1; for (Edge e : adj[u]) { if (e.v == p) continue; int val = dfs(e.v, u); num += val; long here = val; here *= (n - val); here /= 2; block[e.id] = here; } return num; } ArrayList<Edge>[] adj; long[] block; int n; void solve(FastIO io) { n = io.nextInt(); adj = new ArrayList[n]; for (int i = 0; i < n; i++) adj[i] = new ArrayList<>(); for (int i = 0; i < n - 1; i++) { int u = io.nextInt() - 1; int v = io.nextInt() - 1; adj[u].add(new Edge(v, i)); adj[v].add(new Edge(u, i)); } block = new long[n - 1]; dfs(0, -1); Integer[] sort = new Integer[n - 1]; for (int i = 0; i < n - 1; i++) sort[i] = i; Arrays.sort(sort, (a, b) -> Long.compare(block[a], block[b])); int[] out = new int[n-1]; for (int i = 0; i < n-1; i++) out[sort[i]] = i; for (int i = 0; i < n-1; i++) io.println(out[i]); } public static void main(String[] args) { FastIO io = new FastIO(); new C().solve(io); io.close(); } static class FastIO extends PrintWriter { StringTokenizer st = new StringTokenizer(""); BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); FastIO() { super(System.out); } String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(r.readLine()); } catch (Exception e) { } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"]
1 second
["0\n1", "0\n3\n2\n4\n1"]
NoteThe tree from the second sample:
Java 11
standard input
[ "constructive algorithms", "greedy", "dfs and similar", "trees" ]
5ef966b7d9fbf27e6197b074eca31b15
The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.
1,500
Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order).
standard output
PASSED
95e688a67bd9f74dcf16b5bc4f040c12
train_001.jsonl
1584196500
You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String []args) throws IOException { FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), false); solve(in, out); in.close(); out.close(); } static class FastScanner{ BufferedReader reader; StringTokenizer st; FastScanner(InputStream stream){reader=new BufferedReader(new InputStreamReader(stream));st=null;} String next(){while(st == null || !st.hasMoreTokens()){try{String line = reader.readLine();if(line == null){return null;} st = new StringTokenizer(line);}catch (Exception e){throw new RuntimeException();}}return st.nextToken();} String nextLine() {String s=null;try{s=reader.readLine();}catch(IOException e){e.printStackTrace();}return s;} int nextInt() {return Integer.parseInt(next());} long nextLong() {return Long.parseLong(next());} double nextDouble(){return Double.parseDouble(next());} char nextChar() {return next().charAt(0);} int[] nextIntArray(int n) {int[] arr= new int[n]; int i=0;while(i<n){arr[i++]=nextInt();} return arr;} long[] nextLongArray(int n) {long[]arr= new long[n]; int i=0;while(i<n){arr[i++]=nextLong();} return arr;} int[] nextIntArrayOneBased(int n) {int[] arr= new int[n+1]; int i=1;while(i<=n){arr[i++]=nextInt();} return arr;} long[] nextLongArrayOneBased(int n){long[]arr= new long[n+1];int i=1;while(i<=n){arr[i++]=nextLong();}return arr;} void close(){try{reader.close();}catch(IOException e){e.printStackTrace();}} } /********* SOLUTION STARTS HERE ************/ private static void solve(FastScanner in, PrintWriter out){ int n = in.nextInt(),u,v; int ans[] = new int[n-1]; // int deg[] = new int[n]; ArrayList<Integer> g[] = new ArrayList[n]; for(int i=0;i<n;i++) g[i] = new ArrayList<>(); for(int i=0;i<n-1;i++){ u = in.nextInt()-1; v = in.nextInt()-1; g[u].add(i); g[v].add(i); // deg[u]++;deg[v]++; ans[i]=-1; } int ind = 0,mx = g[0].size(); for(int i=1;i<n;i++){ if(g[i].size() > mx){ mx = g[i].size(); ind = i; } } int cur=0; for(int i: g[ind]){ ans[i]=cur++; } for(int i=0;i<n-1;i++){ if(ans[i]==-1){ ans[i]=cur++; } out.println(ans[i]); } } /************* SOLUTION ENDS HERE **********/ }
Java
["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"]
1 second
["0\n1", "0\n3\n2\n4\n1"]
NoteThe tree from the second sample:
Java 11
standard input
[ "constructive algorithms", "greedy", "dfs and similar", "trees" ]
5ef966b7d9fbf27e6197b074eca31b15
The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.
1,500
Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order).
standard output
PASSED
9c39e8ad982754d27759994683aba73d
train_001.jsonl
1584196500
You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$.
256 megabytes
import java.util.*; import java.io.*; public class C628 { static long vals []; static long children []; static boolean visited []; static int parent []; static ArrayList <Integer> [] adj; static int n; public static void main(String [] args) { MyScanner sc = new MyScanner(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); n = sc.nextInt(); adj = new ArrayList[n+1]; for (int i = 1; i <= n; i++) adj[i] = new ArrayList<>(); int [][] input = new int [n - 1][2]; for (int i = 0; i < n - 1; i++) { input[i][0] = sc.nextInt(); input[i][1] = sc.nextInt(); adj[input[i][0]].add(input[i][1]); adj[input[i][1]].add(input[i][0]); } children = new long [n+1]; vals = new long [n+1]; parent = new int [n+1]; visited = new boolean[n+1]; dfs(1); visited = new boolean[n+1]; dfs2(1, - 1); Edge [] edges = new Edge [n-1]; for (int i = 0; i < n- 1; i++) { if (parent[input[i][0]] == input[i][1]) { edges[i] = new Edge(i, vals[input[i][0]]); } else { edges[i] = new Edge(i, vals[input[i][1]]); } } Arrays.sort(edges); int [] res = new int [n-1]; for (int i = 0; i < n- 1; i++) { res[edges[i].index] = i; } for (int i = 0; i < n - 1; i++) { out.println(res[i]); } out.close(); } static void dfs(int x) { visited[x] = true; for (Integer i: adj[x]) { if (!visited[i]) { parent[i] = x; dfs(i); children[x] += children[i]; } } children[x] += 1; } static void dfs2(int x, int prev) { visited[x] = true; long res = (n * (n - 1))/2 - (children[x] * (children[x] - 1)) / 2 - ((n - children[x]) * (n - children[x] - 1))/2; if (prev != -1) { vals[x] = res; } for (Integer i: adj[x]) { if (!visited[i]) { dfs2(i, x); } } } static class Edge implements Comparable<Edge> { int index; long value; Edge (int index, long value) { this.index = index; this.value = value; } @Override public int compareTo(Edge o) { if (value < o.value) { return -1; } else if (value == o.value) { return 0; } else { return 1; } } } //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"]
1 second
["0\n1", "0\n3\n2\n4\n1"]
NoteThe tree from the second sample:
Java 11
standard input
[ "constructive algorithms", "greedy", "dfs and similar", "trees" ]
5ef966b7d9fbf27e6197b074eca31b15
The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.
1,500
Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order).
standard output
PASSED
ea7a5dbecda2501913d45f96a913318f
train_001.jsonl
1593610500
A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it!You are given integers $$$n,k$$$. Construct a grid $$$A$$$ with size $$$n \times n$$$ consisting of integers $$$0$$$ and $$$1$$$. The very important condition should be satisfied: the sum of all elements in the grid is exactly $$$k$$$. In other words, the number of $$$1$$$ in the grid is equal to $$$k$$$.Let's define: $$$A_{i,j}$$$ as the integer in the $$$i$$$-th row and the $$$j$$$-th column. $$$R_i = A_{i,1}+A_{i,2}+...+A_{i,n}$$$ (for all $$$1 \le i \le n$$$). $$$C_j = A_{1,j}+A_{2,j}+...+A_{n,j}$$$ (for all $$$1 \le j \le n$$$). In other words, $$$R_i$$$ are row sums and $$$C_j$$$ are column sums of the grid $$$A$$$. For the grid $$$A$$$ let's define the value $$$f(A) = (\max(R)-\min(R))^2 + (\max(C)-\min(C))^2$$$ (here for an integer sequence $$$X$$$ we define $$$\max(X)$$$ as the maximum value in $$$X$$$ and $$$\min(X)$$$ as the minimum value in $$$X$$$). Find any grid $$$A$$$, which satisfies the following condition. Among such grids find any, for which the value $$$f(A)$$$ is the minimum possible. Among such tables, you can find any.
256 megabytes
import java.io.*; import java.util.*; public class D { public static void main(String[] args) throws IOException { FastReader f=new FastReader(); StringBuffer sb = new StringBuffer(); int test=f.nextInt(); while(test-->0) { int n=f.nextInt(); int k=f.nextInt(); int mat[][]=new int[n][n]; if(k%n==0) sb.append(0+"\n"); else sb.append(2+"\n"); if (k>0) { out: for(int c=0;c<n;c++) { for(int r=0;r<n;r++) { mat[r][(r+c)%n]=1; k--; if(k==0) break out; } } } for(int i=0;i<n;i++) { for(int j=0;j<n;j++) sb.append(mat[i][j]); sb.append("\n"); } } System.out.println(sb); } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try{ st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try{ str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
Java
["4\n2 2\n3 8\n1 0\n4 16"]
1 second
["0\n10\n01\n2\n111\n111\n101\n0\n0\n0\n1111\n1111\n1111\n1111"]
NoteIn the first test case, the sum of all elements in the grid is equal to $$$2$$$, so the condition is satisfied. $$$R_1 = 1, R_2 = 1$$$ and $$$C_1 = 1, C_2 = 1$$$. Then, $$$f(A) = (1-1)^2 + (1-1)^2 = 0$$$, which is the minimum possible value of $$$f(A)$$$.In the second test case, the sum of all elements in the grid is equal to $$$8$$$, so the condition is satisfied. $$$R_1 = 3, R_2 = 3, R_3 = 2$$$ and $$$C_1 = 3, C_2 = 2, C_3 = 3$$$. Then, $$$f(A) = (3-2)^2 + (3-2)^2 = 2$$$. It can be proven, that it is the minimum possible value of $$$f(A)$$$.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy" ]
0f18382d450be90edf1fd1a3770b232b
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Next $$$t$$$ lines contain descriptions of test cases. For each test case the only line contains two integers $$$n$$$, $$$k$$$ $$$(1 \le n \le 300, 0 \le k \le n^2)$$$. It is guaranteed that the sum of $$$n^2$$$ for all test cases does not exceed $$$10^5$$$.
1,600
For each test case, firstly print the minimum possible value of $$$f(A)$$$ among all tables, for which the condition is satisfied. After that, print $$$n$$$ lines contain $$$n$$$ characters each. The $$$j$$$-th character in the $$$i$$$-th line should be equal to $$$A_{i,j}$$$. If there are multiple answers you can print any.
standard output
PASSED
3bd213a56be317370f1d066a333dd793
train_001.jsonl
1520696100
Alice likes snow a lot! Unfortunately, this year's winter is already over, and she can't expect to have any more of it. Bob has thus bought her a gift — a large snow maker. He plans to make some amount of snow every day. On day i he will make a pile of snow of volume Vi and put it in her garden.Each day, every pile will shrink a little due to melting. More precisely, when the temperature on a given day is Ti, each pile will reduce its volume by Ti. If this would reduce the volume of a pile to or below zero, it disappears forever. All snow piles are independent of each other. Note that the pile made on day i already loses part of its volume on the same day. In an extreme case, this may mean that there are no piles left at the end of a particular day.You are given the initial pile sizes and the temperature on each day. Determine the total volume of snow melted on each day.
256 megabytes
// practice with kaiboy import java.io.*; import java.util.*; public class CF948C extends PrintWriter { CF948C() { super(System.out, true); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF948C o = new CF948C(); o.main(); o.flush(); } void main() { int n = sc.nextInt(); long[] vv = new long[n]; for (int i = 0; i < n; i++) vv[i] = sc.nextInt(); int[] tt = new int[n]; for (int i = 0; i < n; i++) tt[i] = sc.nextInt(); long t = 0; for (int i = 0; i < n; i++) { vv[i] += t; t += tt[i]; } vv = Arrays.stream(vv).boxed().sorted().mapToLong($->$).toArray(); t = 0; for (int i = 0, j = 0; i < n; i++) { long sum = 0; while (j < n && vv[j] <= t + tt[i]) sum += vv[j++] - t; sum += (long) (i - j + 1) * tt[i]; // (n - j) - (n - 1 - i) print(sum + " "); t += tt[i]; } println(); } }
Java
["3\n10 10 5\n5 7 2", "5\n30 25 20 15 10\n9 10 12 4 13"]
1 second
["5 12 4", "9 20 35 11 25"]
NoteIn the first sample, Bob first makes a snow pile of volume 10, which melts to the size of 5 on the same day. On the second day, he makes another pile of size 10. Since it is a bit warmer than the day before, the first pile disappears completely while the second pile shrinks to 3. At the end of the second day, he has only a single pile of size 3. On the third day he makes a smaller pile than usual, but as the temperature dropped too, both piles survive till the end of the day.
Java 11
standard input
[ "data structures", "binary search" ]
e3bc82acf70071b0e6d20a5b4fccbfba
The first line contains a single integer N (1 ≤ N ≤ 105) — the number of days. The second line contains N integers V1, V2, ..., VN (0 ≤ Vi ≤ 109), where Vi is the initial size of a snow pile made on the day i. The third line contains N integers T1, T2, ..., TN (0 ≤ Ti ≤ 109), where Ti is the temperature on the day i.
1,600
Output a single line with N integers, where the i-th integer represents the total volume of snow melted on day i.
standard output
PASSED
6b4e6ecb6d3d438084b4c9245dc7c4f1
train_001.jsonl
1520696100
Alice likes snow a lot! Unfortunately, this year's winter is already over, and she can't expect to have any more of it. Bob has thus bought her a gift — a large snow maker. He plans to make some amount of snow every day. On day i he will make a pile of snow of volume Vi and put it in her garden.Each day, every pile will shrink a little due to melting. More precisely, when the temperature on a given day is Ti, each pile will reduce its volume by Ti. If this would reduce the volume of a pile to or below zero, it disappears forever. All snow piles are independent of each other. Note that the pile made on day i already loses part of its volume on the same day. In an extreme case, this may mean that there are no piles left at the end of a particular day.You are given the initial pile sizes and the temperature on each day. Determine the total volume of snow melted on each day.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class d { static BufferedReader s = new BufferedReader(new InputStreamReader(System.in));; public static void main(String[] args) throws IOException { StringBuilder sb = new StringBuilder(); String[] s1=s(); String[] s2=s(); String[] s3=s(); int n=i(s1[0]); int[] a=new int[n]; for(int i=0;i<n;i++){ a[i]=i(s2[i]); } int[] b=new int[n]; long []minus=new long[n]; long[] add=new long[n+1]; long[] psum=new long[n]; for(int i=0;i<n;i++){ b[i]=i(s3[i]); if(i>0){ psum[i]=psum[i-1]+b[i]; }else psum[i]=b[i]; /* if(i+a[i]/b[i]-1<=n-1) minus[(i+a[i]/b[i]-1)]=b[i]; if(a[i]%b[i]!=0&&i+a[i]/b[i]<=n-1) add[Math.min(n-1,i+a[i]/b[i])]=a[i]%b[i]; */ } for(int i=0;i<n;i++){ long x=0; if(i>0) x=psum[i-1]; int low=i;int high=n-1; int flag=0;int ans=-1; while(low<=high){ int mid=(low+high)/2; if(psum[mid]-x<a[i]){ ans=mid;low=mid+1; }else if(psum[mid]-x==a[i]){ ans=mid;low=mid+1;flag=1; }else{ high=mid-1; } } if(ans!=-1){ minus[ans]+=1; add[ans+1]+=a[i]-(psum[ans]-x); }else{ add[i]+=a[i]; } } long sum=0; for(int i=0;i<n;i++){ if(a[i]>=b[i]) sum+=1; // System.out.println(i+" "+sum); // System.out.println(sum+" "+i); sb.append((sum*b[i]+add[i])+" ");sum-=minus[i]; } System.out.println(sb.toString()); } static String[] s()throws IOException{ return s.readLine().trim().split("\\s+"); } static int i(String ss){ return Integer.parseInt(ss); } static long l(String ss) {return Long.parseLong(ss);} static String lexographicallysmallest(String s) { if (s.length() % 2 == 1) return s; String s1 =lexographicallysmallest(s.substring(0, s.length()/2)); String s2 = lexographicallysmallest(s.substring(s.length()/2, s.length())); if (s1.compareTo(s2)<0) return s1 + s2; else return s2 + s1; } public static int countSetBits(int n) { return (BitsSetTable256[n & 0xff] + BitsSetTable256[(n >> 8) & 0xff] + BitsSetTable256[(n >> 16) & 0xff] + BitsSetTable256[n >> 24]); } static int[] BitsSetTable256 ; public static void initialize(int n) { BitsSetTable256[0] = 0; for (int i = 0; i <=Math.pow(2,n); i++) { BitsSetTable256[i] = (i & 1) + BitsSetTable256[i / 2]; } } static void computeLPSArray(String pat, int M, int lps[]) { int len = 0; int i = 1; lps[0] = 0; while (i < M) { if (pat.charAt(i) == pat.charAt(len)) { len++; lps[i] = len; i++; } else { if (len != 0) { len = lps[len - 1]; } else { lps[i] = len; i++; } } } } static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static long powerwithmod(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if ((y & 1) == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } static long powerwithoutmod(long x, int y) { long temp; if( y == 0) return 1; temp = powerwithoutmod(x, y/2); if (y%2 == 0) return temp*temp; else { if(y > 0) return x * temp * temp; else return (temp * temp) / x; } } static void fracion(double x) { String a = "" + x; String spilts[] = a.split("\\."); // split using decimal int b = spilts[1].length(); // find the decimal length int denominator = (int) Math.pow(10, b); // calculate the denominator int numerator = (int) (x * denominator); // calculate the nerumrator Ex // 1.2*10 = 12 int gcd = (int) gcd((long) numerator, denominator); // Find the greatest common // divisor bw them String fraction = "" + numerator / gcd + "/" + denominator / gcd; // System.out.println((denominator/gcd)); long x1 = modInverse(denominator / gcd, 998244353); // System.out.println(x1); System.out.println((((numerator / gcd) % 998244353 * (x1 % 998244353)) % 998244353)); } static int bfs(int i1, ArrayList<Integer>[] h, int[] vis, int n,int val1) { Queue<Integer> q = new LinkedList<Integer>(); q.add(i1);Queue<Integer> aq=new LinkedList<Integer>(); aq.add(0); while(!q.isEmpty()){ int i=q.poll(); int val=aq.poll(); if(i==n){ return val; } if(h[i]!=null){ for(Integer j:h[i]){ if(vis[j]==0){ q.add(j);vis[j]=1; aq.add(val+1);} } } }return -1; } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static long modInverse(long a, long m) { return (powerwithmod(a, m - 2, m)); } static int MAXN; static int[] spf; static void sieve() { spf[1] = 1; for (int i=2; i<MAXN; i++) spf[i] = i; for (int i=4; i<MAXN; i+=2) spf[i] = 2; for (int i=3; i*i<MAXN; i++) { if (spf[i] == i) { for (int j=i*i; j<MAXN; j+=i) if (spf[j]==j) spf[j] = i; } } } static ArrayList<Integer> getFactorizationUsingSeive(int x) { ArrayList<Integer> ret = new ArrayList<Integer>(); while (x != 1) { ret.add(spf[x]); if(spf[x]!=0) x = x / spf[x]; else break; } return ret; } static long[] fac ; static void calculatefac(long mod){ fac[0]=1; for (int i = 1 ;i <= MAXN; i++) fac[i] = fac[i-1] * i % mod; } static long nCrModPFermat(int n, int r, long mod) { if (r == 0) return 1; fac[0] = 1; return (fac[n]* modInverse(fac[r], mod) % mod * modInverse(fac[n-r], mod) % mod) % mod; } } class Student { int l;long r; public Student(int l, long r) { this.l = l; this.r = r; } public String toString() { return this.l+" "; } } class Sortbyroll implements Comparator<Student> { public int compare(Student a, Student b){ if(a.r<b.r) return -1; else if(a.r==b.r){ if(a.r==b.r){ return 0; } if(a.r<b.r) return -1; return 1;} return 1; } }
Java
["3\n10 10 5\n5 7 2", "5\n30 25 20 15 10\n9 10 12 4 13"]
1 second
["5 12 4", "9 20 35 11 25"]
NoteIn the first sample, Bob first makes a snow pile of volume 10, which melts to the size of 5 on the same day. On the second day, he makes another pile of size 10. Since it is a bit warmer than the day before, the first pile disappears completely while the second pile shrinks to 3. At the end of the second day, he has only a single pile of size 3. On the third day he makes a smaller pile than usual, but as the temperature dropped too, both piles survive till the end of the day.
Java 11
standard input
[ "data structures", "binary search" ]
e3bc82acf70071b0e6d20a5b4fccbfba
The first line contains a single integer N (1 ≤ N ≤ 105) — the number of days. The second line contains N integers V1, V2, ..., VN (0 ≤ Vi ≤ 109), where Vi is the initial size of a snow pile made on the day i. The third line contains N integers T1, T2, ..., TN (0 ≤ Ti ≤ 109), where Ti is the temperature on the day i.
1,600
Output a single line with N integers, where the i-th integer represents the total volume of snow melted on day i.
standard output
PASSED
845c5de01fd309a598af8a96ecc372bd
train_001.jsonl
1374679800
Insurgents accidentally got hold of the plan of a top secret research polygon created on a distant planet for the needs of the Galaxy Empire. The insurgents suppose that this polygon is developing new deadly weapon. The polygon consists of n missile silos connected by bidirectional underground passages. The passages are linked to laboratories where research is conducted. Naturally, the passages are guarded severely: the passage between silos i and j is patrolled by ci, j war droids.The insurgents studied the polygon plan and noticed its unusual structure. As it turned out, for any k-element set of silos S there is exactly one silo that is directly connected by a passage with each silo from S (we'll call this silo adjacent with S). Having considered that, the insurgents decided to act as follows: they choose a k-element set of silos S; a group of scouts lands from the air into each silo from S; each group moves along the corresponding passage to the silo, adjacent with S (as the scouts move, they check out the laboratories and watch for any signs of weapon blueprints); in the silo, adjacent with S, the groups get on the ship and fly away. The danger of the operation is the total number of droids that patrol the passages through which the scouts will go. The danger of the operation obviously only depends on the way to choose set S. The insurgents haven't yet decided on the exact silos to send the scouts to. However, they already want to start preparing the weapons for the scout groups. To do that, the insurgents need to know the mathematical average of the dangers of the operations that correspond to all possible ways to choose set S. Solve this problem to help the insurgents protect the ideals of the Republic!
256 megabytes
import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.util.Comparator; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.io.IOException; import java.util.Arrays; import java.util.InputMismatchException; import java.util.NoSuchElementException; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Egor Kulikov (egor@egork.net) */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } } class TaskD { public void solve(int testNumber, InputReader in, OutputWriter out) { int count = in.readInt(); int groups = in.readInt(); if (groups > 2 && groups != count - 1) throw new RuntimeException(); int[][] graph = new int[count][]; for (int i = 0; i < count; i++) graph[i] = IOUtils.readIntArray(in, count - i - 1); if (groups == 1 || groups == count - 1) { long sum = 0; for (int[] row : graph) { for (int i : row) sum += Math.max(i, 0); } out.printLine(sum * 2 / count); return; } for (int i = 0; i < count; i++) { boolean good = true; for (int j = 0; j < i; j++) { if (graph[j][i - j - 1] == -1) { good = false; break; } } for (int j : graph[i]) { if (j == -1) good = false; } if (!good) continue; long sumGood = 0; long sum = 0; for (int j = 0; j < i; j++) sumGood += graph[j][i - j - 1]; sumGood += ArrayUtils.sumArray(graph[i]); for (int[] row : graph) { for (int j : row) sum += Math.max(j, 0); } sum -= sumGood; out.printLine(((count - 1) * sumGood + sum * 2) / (count * (count - 1) / 2)); return; } throw new RuntimeException(); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public 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); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } } class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = in.readInt(); return array; } } class ArrayUtils { public static long sumArray(int[] array) { long result = 0; for (int element : array) result += element; return result; } }
Java
["6 1\n-1 -1 -1 8 -1\n-1 5 -1 -1\n-1 -1 3\n-1 -1\n-1", "3 2\n10 0\n11"]
3 seconds
["5", "14"]
NoteIn the first sample there are 6 one-element sets of silos. For sets {1}, {5} the operation danger will equal 8, for sets {3}, {6} — 3, for sets {2}, {4} — 5. The mathematical average equals .In the second sample there are 3 two-elements sets of silos: {1, 3} (danger equals 21), {1, 2} (danger equals 11), {2, 3} (danger equals 10). The average operation danger equals .
Java 7
standard input
[ "math", "graphs" ]
48b232b9d836b0be91d41e548a9fcefc
The first line contains two integers n and k (2 ≤ n ≤ 2000, 1 ≤ k ≤ n - 1) — the number of silos and the number of scout groups, correspondingly. The next n - 1 lines describe the polygon plan: the i-th of these lines contains n - i integers ci, i + 1, ci, i + 2, ..., ci, n — the number of droids that patrol the corresponding passages (-1 ≤ ci, j ≤ 109; if ci, j =  -1, then silos i and j don't have a passage between them). All passages are bidirectional, that is, we can assume that ci, j = cj, i. No passages connect a silo with itself. It is guaranteed that the polygon plan meets the conditions of the problem statement.
2,400
Print the average danger of the scouting operation, rounded down to an integer. Note that at the given limits the answer to the problem always fits into the standard integer 64-bit data type. Please do not use the %lld specifier to write 64-bit integers in С++. It is preferred to use the cout stream or the %I64d specifier.
standard output
PASSED
7a69f1984f8e76d3cc51312b8891ec2c
train_001.jsonl
1374679800
Insurgents accidentally got hold of the plan of a top secret research polygon created on a distant planet for the needs of the Galaxy Empire. The insurgents suppose that this polygon is developing new deadly weapon. The polygon consists of n missile silos connected by bidirectional underground passages. The passages are linked to laboratories where research is conducted. Naturally, the passages are guarded severely: the passage between silos i and j is patrolled by ci, j war droids.The insurgents studied the polygon plan and noticed its unusual structure. As it turned out, for any k-element set of silos S there is exactly one silo that is directly connected by a passage with each silo from S (we'll call this silo adjacent with S). Having considered that, the insurgents decided to act as follows: they choose a k-element set of silos S; a group of scouts lands from the air into each silo from S; each group moves along the corresponding passage to the silo, adjacent with S (as the scouts move, they check out the laboratories and watch for any signs of weapon blueprints); in the silo, adjacent with S, the groups get on the ship and fly away. The danger of the operation is the total number of droids that patrol the passages through which the scouts will go. The danger of the operation obviously only depends on the way to choose set S. The insurgents haven't yet decided on the exact silos to send the scouts to. However, they already want to start preparing the weapons for the scout groups. To do that, the insurgents need to know the mathematical average of the dangers of the operations that correspond to all possible ways to choose set S. Solve this problem to help the insurgents protect the ideals of the Republic!
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.InputMismatchException; /** * @author pvasilyev * @date 7/27/13 */ public class MainD { public static final String FILE_IN = "std.in"; public static final String FILE_OUT = "std.out"; private static boolean debugMode = true; public static void main(String[] args) throws IOException { final BufferedInputStream reader = new BufferedInputStream((debugMode ? System.in : new FileInputStream(FILE_IN))); final PrintWriter writer = new PrintWriter(debugMode ? System.out : new FileOutputStream(FILE_OUT)); solveTheProblem(reader, writer); reader.close(); writer.close(); } private static void solveTheProblem(final BufferedInputStream reader, final PrintWriter writer) throws IOException { InputReader r = new InputReader(reader); final int n = r.readInt(); final int k = r.readInt(); int[][] c = new int[n][n]; for (int i = 0; i < n; ++i) { c[i][i] = -1; int[] tmp = IOUtils.readIntArray(r, n - i - 1); for (int j = 0; j < n - i - 1; ++j) { c[i][i+j+1] = tmp[j]; c[i+j+1][i] = tmp[j]; } } if (k == 1) { long sum = 0; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { sum += Math.max(c[i][j], 0); } } writer.println(sum / n); } else { BigInteger sum = BigInteger.ZERO; BigInteger count = BigInteger.ZERO; for (int i = 0; i < n; ++i) { BigInteger C = BigInteger.ONE; int outgoingVertexes = 0; long sumOutgoing = 0; for (int j = 0; j < n; ++j) { if (c[i][j] != -1) { outgoingVertexes++; sumOutgoing += c[i][j]; } } for (int ii=k+1; ii <= outgoingVertexes; ++ii) { C = C.multiply(BigInteger.valueOf(ii)); } for (int ii=1; ii <= outgoingVertexes-k; ++ii) { C = C.divide(BigInteger.valueOf(ii)); } count = count.add(C); sum = sum.add(C.multiply(BigInteger.valueOf(k).multiply(BigInteger.valueOf(sumOutgoing))).divide(BigInteger.valueOf(outgoingVertexes))); } writer.println(sum.divide(count).toString()); } } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public 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); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = in.readInt(); return array; } } class ArrayUtils { public static long sumArray(int[] array) { long result = 0; for (int element : array) result += element; return result; } }
Java
["6 1\n-1 -1 -1 8 -1\n-1 5 -1 -1\n-1 -1 3\n-1 -1\n-1", "3 2\n10 0\n11"]
3 seconds
["5", "14"]
NoteIn the first sample there are 6 one-element sets of silos. For sets {1}, {5} the operation danger will equal 8, for sets {3}, {6} — 3, for sets {2}, {4} — 5. The mathematical average equals .In the second sample there are 3 two-elements sets of silos: {1, 3} (danger equals 21), {1, 2} (danger equals 11), {2, 3} (danger equals 10). The average operation danger equals .
Java 7
standard input
[ "math", "graphs" ]
48b232b9d836b0be91d41e548a9fcefc
The first line contains two integers n and k (2 ≤ n ≤ 2000, 1 ≤ k ≤ n - 1) — the number of silos and the number of scout groups, correspondingly. The next n - 1 lines describe the polygon plan: the i-th of these lines contains n - i integers ci, i + 1, ci, i + 2, ..., ci, n — the number of droids that patrol the corresponding passages (-1 ≤ ci, j ≤ 109; if ci, j =  -1, then silos i and j don't have a passage between them). All passages are bidirectional, that is, we can assume that ci, j = cj, i. No passages connect a silo with itself. It is guaranteed that the polygon plan meets the conditions of the problem statement.
2,400
Print the average danger of the scouting operation, rounded down to an integer. Note that at the given limits the answer to the problem always fits into the standard integer 64-bit data type. Please do not use the %lld specifier to write 64-bit integers in С++. It is preferred to use the cout stream or the %I64d specifier.
standard output
PASSED
a5874be18c4ff225f5cf0437b01d8782
train_001.jsonl
1374679800
Insurgents accidentally got hold of the plan of a top secret research polygon created on a distant planet for the needs of the Galaxy Empire. The insurgents suppose that this polygon is developing new deadly weapon. The polygon consists of n missile silos connected by bidirectional underground passages. The passages are linked to laboratories where research is conducted. Naturally, the passages are guarded severely: the passage between silos i and j is patrolled by ci, j war droids.The insurgents studied the polygon plan and noticed its unusual structure. As it turned out, for any k-element set of silos S there is exactly one silo that is directly connected by a passage with each silo from S (we'll call this silo adjacent with S). Having considered that, the insurgents decided to act as follows: they choose a k-element set of silos S; a group of scouts lands from the air into each silo from S; each group moves along the corresponding passage to the silo, adjacent with S (as the scouts move, they check out the laboratories and watch for any signs of weapon blueprints); in the silo, adjacent with S, the groups get on the ship and fly away. The danger of the operation is the total number of droids that patrol the passages through which the scouts will go. The danger of the operation obviously only depends on the way to choose set S. The insurgents haven't yet decided on the exact silos to send the scouts to. However, they already want to start preparing the weapons for the scout groups. To do that, the insurgents need to know the mathematical average of the dangers of the operations that correspond to all possible ways to choose set S. Solve this problem to help the insurgents protect the ideals of the Republic!
256 megabytes
import java.io.*; import java.util.*; /** * @author pvasilyev * @date 7/25/13 */ public class ProblemD { public static final String FILE_IN = "std.in"; public static final String FILE_OUT = "std.out"; private static boolean debugMode = true; public static void main(String[] args) throws IOException { final BufferedInputStream reader = new BufferedInputStream((debugMode ? System.in : new FileInputStream(FILE_IN))); final PrintWriter writer = new PrintWriter(debugMode ? System.out : new FileOutputStream(FILE_OUT)); solveTheProblem(reader, writer); reader.close(); writer.close(); } private static void solveTheProblem(final BufferedInputStream reader, final PrintWriter writer) throws IOException { InputReader r = new InputReader(reader); final int n = r.readInt(); final int k = r.readInt(); int[][] c = new int[n][n]; for (int i = 0; i < n; ++i) { c[i][i] = -1; int[] tmp = IOUtils.readIntArray(r, n - i - 1); for (int j = 0; j < n - i - 1; ++j) { c[i][i+j+1] = tmp[j]; c[i+j+1][i] = tmp[j]; } } long sum = 0; if (k != 2) { for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { sum += Math.max(c[i][j], 0); } } writer.println(sum / n); } else { long count = n * (n - 1) / 2; for (int i = 0; i < n; ++i) { final ArrayList<Integer> integers = new ArrayList<>(); for (int j = 0; j < n; ++j) { if (c[i][j] != -1) { integers.add(j); } } for (int ii = 0; ii < integers.size(); ++ii) { for (int jj = ii + 1; jj < integers.size(); ++jj) { sum += c[i][integers.get(ii)] + c[i][integers.get(jj)]; } } } writer.println(sum / count); } } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public 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); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = in.readInt(); return array; } } class ArrayUtils { public static long sumArray(int[] array) { long result = 0; for (int element : array) result += element; return result; } }
Java
["6 1\n-1 -1 -1 8 -1\n-1 5 -1 -1\n-1 -1 3\n-1 -1\n-1", "3 2\n10 0\n11"]
3 seconds
["5", "14"]
NoteIn the first sample there are 6 one-element sets of silos. For sets {1}, {5} the operation danger will equal 8, for sets {3}, {6} — 3, for sets {2}, {4} — 5. The mathematical average equals .In the second sample there are 3 two-elements sets of silos: {1, 3} (danger equals 21), {1, 2} (danger equals 11), {2, 3} (danger equals 10). The average operation danger equals .
Java 7
standard input
[ "math", "graphs" ]
48b232b9d836b0be91d41e548a9fcefc
The first line contains two integers n and k (2 ≤ n ≤ 2000, 1 ≤ k ≤ n - 1) — the number of silos and the number of scout groups, correspondingly. The next n - 1 lines describe the polygon plan: the i-th of these lines contains n - i integers ci, i + 1, ci, i + 2, ..., ci, n — the number of droids that patrol the corresponding passages (-1 ≤ ci, j ≤ 109; if ci, j =  -1, then silos i and j don't have a passage between them). All passages are bidirectional, that is, we can assume that ci, j = cj, i. No passages connect a silo with itself. It is guaranteed that the polygon plan meets the conditions of the problem statement.
2,400
Print the average danger of the scouting operation, rounded down to an integer. Note that at the given limits the answer to the problem always fits into the standard integer 64-bit data type. Please do not use the %lld specifier to write 64-bit integers in С++. It is preferred to use the cout stream or the %I64d specifier.
standard output
PASSED
ea457544f4039000ad5403609af28316
train_001.jsonl
1374679800
Insurgents accidentally got hold of the plan of a top secret research polygon created on a distant planet for the needs of the Galaxy Empire. The insurgents suppose that this polygon is developing new deadly weapon. The polygon consists of n missile silos connected by bidirectional underground passages. The passages are linked to laboratories where research is conducted. Naturally, the passages are guarded severely: the passage between silos i and j is patrolled by ci, j war droids.The insurgents studied the polygon plan and noticed its unusual structure. As it turned out, for any k-element set of silos S there is exactly one silo that is directly connected by a passage with each silo from S (we'll call this silo adjacent with S). Having considered that, the insurgents decided to act as follows: they choose a k-element set of silos S; a group of scouts lands from the air into each silo from S; each group moves along the corresponding passage to the silo, adjacent with S (as the scouts move, they check out the laboratories and watch for any signs of weapon blueprints); in the silo, adjacent with S, the groups get on the ship and fly away. The danger of the operation is the total number of droids that patrol the passages through which the scouts will go. The danger of the operation obviously only depends on the way to choose set S. The insurgents haven't yet decided on the exact silos to send the scouts to. However, they already want to start preparing the weapons for the scout groups. To do that, the insurgents need to know the mathematical average of the dangers of the operations that correspond to all possible ways to choose set S. Solve this problem to help the insurgents protect the ideals of the Republic!
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Round_193_D { public static void main(String[] args) { FastScanner sc = new FastScanner(System.in); int n = sc.nextInt(); long k = sc.nextLong(); long[] degree = new long[n]; long[] sum = new long[n]; for (int i = 0; i < n-1; i++) { for (int j = i + 1; j < n; j++) { long droids = sc.nextLong(); if (droids >= 0) { degree[i] += 1; degree[j] += 1; sum[i] += droids; sum[j] += droids; } } } long ans = 0; long ways = 0; for (int i = 0; i < n; i++) if (degree[i] >= k) { ans += sum[i] * (degree[i] - k + 1); ways += binomialCoefficient(degree[i], k); } System.out.println(ans / ways); } static long binomialCoefficient(long n, long k) { if (k < 0 || k > n) return 0; k = Math.min(k, n - k); long c = 1; for (int i = 1; i <= k; i++) { c *= n - (k - i); c /= i; } return c; } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String next() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } boolean hasMoreTokens() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return false; st = new StringTokenizer(s); } return true; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble(){ return Double.parseDouble(next()); } } }
Java
["6 1\n-1 -1 -1 8 -1\n-1 5 -1 -1\n-1 -1 3\n-1 -1\n-1", "3 2\n10 0\n11"]
3 seconds
["5", "14"]
NoteIn the first sample there are 6 one-element sets of silos. For sets {1}, {5} the operation danger will equal 8, for sets {3}, {6} — 3, for sets {2}, {4} — 5. The mathematical average equals .In the second sample there are 3 two-elements sets of silos: {1, 3} (danger equals 21), {1, 2} (danger equals 11), {2, 3} (danger equals 10). The average operation danger equals .
Java 7
standard input
[ "math", "graphs" ]
48b232b9d836b0be91d41e548a9fcefc
The first line contains two integers n and k (2 ≤ n ≤ 2000, 1 ≤ k ≤ n - 1) — the number of silos and the number of scout groups, correspondingly. The next n - 1 lines describe the polygon plan: the i-th of these lines contains n - i integers ci, i + 1, ci, i + 2, ..., ci, n — the number of droids that patrol the corresponding passages (-1 ≤ ci, j ≤ 109; if ci, j =  -1, then silos i and j don't have a passage between them). All passages are bidirectional, that is, we can assume that ci, j = cj, i. No passages connect a silo with itself. It is guaranteed that the polygon plan meets the conditions of the problem statement.
2,400
Print the average danger of the scouting operation, rounded down to an integer. Note that at the given limits the answer to the problem always fits into the standard integer 64-bit data type. Please do not use the %lld specifier to write 64-bit integers in С++. It is preferred to use the cout stream or the %I64d specifier.
standard output
PASSED
766c652ae8317dba4d7da8c8955705f8
train_001.jsonl
1374679800
Insurgents accidentally got hold of the plan of a top secret research polygon created on a distant planet for the needs of the Galaxy Empire. The insurgents suppose that this polygon is developing new deadly weapon. The polygon consists of n missile silos connected by bidirectional underground passages. The passages are linked to laboratories where research is conducted. Naturally, the passages are guarded severely: the passage between silos i and j is patrolled by ci, j war droids.The insurgents studied the polygon plan and noticed its unusual structure. As it turned out, for any k-element set of silos S there is exactly one silo that is directly connected by a passage with each silo from S (we'll call this silo adjacent with S). Having considered that, the insurgents decided to act as follows: they choose a k-element set of silos S; a group of scouts lands from the air into each silo from S; each group moves along the corresponding passage to the silo, adjacent with S (as the scouts move, they check out the laboratories and watch for any signs of weapon blueprints); in the silo, adjacent with S, the groups get on the ship and fly away. The danger of the operation is the total number of droids that patrol the passages through which the scouts will go. The danger of the operation obviously only depends on the way to choose set S. The insurgents haven't yet decided on the exact silos to send the scouts to. However, they already want to start preparing the weapons for the scout groups. To do that, the insurgents need to know the mathematical average of the dangers of the operations that correspond to all possible ways to choose set S. Solve this problem to help the insurgents protect the ideals of the Republic!
256 megabytes
//package cf.train; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.Arrays; import java.util.Comparator; import java.util.PriorityQueue; import java.util.Queue; public class PrD { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(System.out); long[] readLongs() throws IOException { String[] s = reader.readLine().split(" "); long[] longs = new long[s.length]; for(int i = 0; i < longs.length; i++) { longs[i] = Long.parseLong(s[i]); } return longs; } int[] readInts() throws IOException { String[] s = reader.readLine().split(" "); int[] ints = new int[s.length]; for(int i = 0; i < ints.length; i++) { ints[i] = Integer.parseInt(s[i]); } return ints; } int[] tt; int tx = 0; int readInt() throws IOException { if(tt == null || tx >= tt.length) { tt = readInts(); tx = 0; } return tt[tx++]; } void solve() throws IOException { int n = readInt(); int k = readInt(); BigInteger b = BigInteger.ONE; for(int i = k + 1; i <= n; i++) { b = b.multiply(BigInteger.valueOf(i)); } for(int i = 2; i <= n - k; i++) { b = b.divide(BigInteger.valueOf(i)); } int[][] c = new int[n][n]; for(int i = 0; i < n; i++) { c[i][i] = -1; for(int j = i + 1; j < n; j++) { c[i][j] = c[j][i] = readInt(); } } BigInteger sum = BigInteger.ZERO; for(int i = 0; i < n; i++) { int cnt = 0; for(int j = 0; j < n; j++) { if(c[i][j] > -1) cnt++; } BigInteger C = BigInteger.ONE; for(int j = k; j <= cnt - 1; j++) { C = C.multiply(BigInteger.valueOf(j)); } for(int j = 2; j <= cnt - k; j++) { C = C.divide(BigInteger.valueOf(j)); } for(int j = 0; j < n; j++) { if(c[i][j] > -1) { sum = sum.add(C.multiply(BigInteger.valueOf(c[i][j]))); } } } writer.println(sum.divide(b)); writer.flush(); } public static void main(String[] args) throws IOException { new PrD().solve(); } }
Java
["6 1\n-1 -1 -1 8 -1\n-1 5 -1 -1\n-1 -1 3\n-1 -1\n-1", "3 2\n10 0\n11"]
3 seconds
["5", "14"]
NoteIn the first sample there are 6 one-element sets of silos. For sets {1}, {5} the operation danger will equal 8, for sets {3}, {6} — 3, for sets {2}, {4} — 5. The mathematical average equals .In the second sample there are 3 two-elements sets of silos: {1, 3} (danger equals 21), {1, 2} (danger equals 11), {2, 3} (danger equals 10). The average operation danger equals .
Java 7
standard input
[ "math", "graphs" ]
48b232b9d836b0be91d41e548a9fcefc
The first line contains two integers n and k (2 ≤ n ≤ 2000, 1 ≤ k ≤ n - 1) — the number of silos and the number of scout groups, correspondingly. The next n - 1 lines describe the polygon plan: the i-th of these lines contains n - i integers ci, i + 1, ci, i + 2, ..., ci, n — the number of droids that patrol the corresponding passages (-1 ≤ ci, j ≤ 109; if ci, j =  -1, then silos i and j don't have a passage between them). All passages are bidirectional, that is, we can assume that ci, j = cj, i. No passages connect a silo with itself. It is guaranteed that the polygon plan meets the conditions of the problem statement.
2,400
Print the average danger of the scouting operation, rounded down to an integer. Note that at the given limits the answer to the problem always fits into the standard integer 64-bit data type. Please do not use the %lld specifier to write 64-bit integers in С++. It is preferred to use the cout stream or the %I64d specifier.
standard output
PASSED
77356331bd98d4a054fe17b83c16cbff
train_001.jsonl
1374679800
Insurgents accidentally got hold of the plan of a top secret research polygon created on a distant planet for the needs of the Galaxy Empire. The insurgents suppose that this polygon is developing new deadly weapon. The polygon consists of n missile silos connected by bidirectional underground passages. The passages are linked to laboratories where research is conducted. Naturally, the passages are guarded severely: the passage between silos i and j is patrolled by ci, j war droids.The insurgents studied the polygon plan and noticed its unusual structure. As it turned out, for any k-element set of silos S there is exactly one silo that is directly connected by a passage with each silo from S (we'll call this silo adjacent with S). Having considered that, the insurgents decided to act as follows: they choose a k-element set of silos S; a group of scouts lands from the air into each silo from S; each group moves along the corresponding passage to the silo, adjacent with S (as the scouts move, they check out the laboratories and watch for any signs of weapon blueprints); in the silo, adjacent with S, the groups get on the ship and fly away. The danger of the operation is the total number of droids that patrol the passages through which the scouts will go. The danger of the operation obviously only depends on the way to choose set S. The insurgents haven't yet decided on the exact silos to send the scouts to. However, they already want to start preparing the weapons for the scout groups. To do that, the insurgents need to know the mathematical average of the dangers of the operations that correspond to all possible ways to choose set S. Solve this problem to help the insurgents protect the ideals of the Republic!
256 megabytes
import java.io.*; import java.util.*; public class D { static final double EPS = 1e-7; BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; void solve() throws IOException { int n = nextInt(); int k = nextInt(); int[][] c = new int[n][n]; for (int i = 0; i < n; i++) { c[i][i] = -1; for (int j = i + 1; j < n; j++) { c[j][i] = c[i][j] = nextInt(); } } double ans = 0; for (int i = 0; i < n; i++) { long sum = 0; int sz = 0; for (int j = 0; j < n; j++) { if (c[i][j] != -1) { sum += c[i][j]; sz++; } } if (sz < k) continue; double prob = 1; if (k < n - sz) { for (int j = 0; j < k; j++) prob = prob * (sz - j) / (n - j); } else { for (int j = sz + 1; j <= n; j++) prob = prob * (j - k) / j; } ans += prob * sum / sz; } ans *= k; double round = Math.round(ans); if (Math.abs(round - ans) < EPS) { ans = round; } long longAns = (long) Math.floor(ans); out.println(longAns); } D() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } public static void main(String[] args) throws IOException { new D(); } String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } String nextString() { try { return br.readLine(); } catch (IOException e) { eof = true; return null; } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
Java
["6 1\n-1 -1 -1 8 -1\n-1 5 -1 -1\n-1 -1 3\n-1 -1\n-1", "3 2\n10 0\n11"]
3 seconds
["5", "14"]
NoteIn the first sample there are 6 one-element sets of silos. For sets {1}, {5} the operation danger will equal 8, for sets {3}, {6} — 3, for sets {2}, {4} — 5. The mathematical average equals .In the second sample there are 3 two-elements sets of silos: {1, 3} (danger equals 21), {1, 2} (danger equals 11), {2, 3} (danger equals 10). The average operation danger equals .
Java 7
standard input
[ "math", "graphs" ]
48b232b9d836b0be91d41e548a9fcefc
The first line contains two integers n and k (2 ≤ n ≤ 2000, 1 ≤ k ≤ n - 1) — the number of silos and the number of scout groups, correspondingly. The next n - 1 lines describe the polygon plan: the i-th of these lines contains n - i integers ci, i + 1, ci, i + 2, ..., ci, n — the number of droids that patrol the corresponding passages (-1 ≤ ci, j ≤ 109; if ci, j =  -1, then silos i and j don't have a passage between them). All passages are bidirectional, that is, we can assume that ci, j = cj, i. No passages connect a silo with itself. It is guaranteed that the polygon plan meets the conditions of the problem statement.
2,400
Print the average danger of the scouting operation, rounded down to an integer. Note that at the given limits the answer to the problem always fits into the standard integer 64-bit data type. Please do not use the %lld specifier to write 64-bit integers in С++. It is preferred to use the cout stream or the %I64d specifier.
standard output
PASSED
81f0922fbf91c5416a4d0324afe64f22
train_001.jsonl
1374679800
Insurgents accidentally got hold of the plan of a top secret research polygon created on a distant planet for the needs of the Galaxy Empire. The insurgents suppose that this polygon is developing new deadly weapon. The polygon consists of n missile silos connected by bidirectional underground passages. The passages are linked to laboratories where research is conducted. Naturally, the passages are guarded severely: the passage between silos i and j is patrolled by ci, j war droids.The insurgents studied the polygon plan and noticed its unusual structure. As it turned out, for any k-element set of silos S there is exactly one silo that is directly connected by a passage with each silo from S (we'll call this silo adjacent with S). Having considered that, the insurgents decided to act as follows: they choose a k-element set of silos S; a group of scouts lands from the air into each silo from S; each group moves along the corresponding passage to the silo, adjacent with S (as the scouts move, they check out the laboratories and watch for any signs of weapon blueprints); in the silo, adjacent with S, the groups get on the ship and fly away. The danger of the operation is the total number of droids that patrol the passages through which the scouts will go. The danger of the operation obviously only depends on the way to choose set S. The insurgents haven't yet decided on the exact silos to send the scouts to. However, they already want to start preparing the weapons for the scout groups. To do that, the insurgents need to know the mathematical average of the dangers of the operations that correspond to all possible ways to choose set S. Solve this problem to help the insurgents protect the ideals of the Republic!
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Zad4 { public static void main(String... args) throws IOException { MyScanner sc = new MyScanner(); int n = sc.nextInt(); int k = sc.nextInt(); Newton newton = new Newton(n); int[][] g = new int[n][n]; fill(g, n); for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; j++) { int val = sc.nextInt(); g[i][j] = val; g[j][i] = val; } } long allSum = 0; long subsetCount = 0; for (int i = 0; i < n; ++i) { int adjCount = 0; long rowSum = 0; for (int j = 0; j < n; ++j) { if (g[i][j] != -1) { ++adjCount; rowSum += g[i][j]; } } subsetCount += newton.get(adjCount, k); allSum += rowSum * (newton.get(adjCount - 1, k - 1)); } long wyn = allSum / subsetCount; System.out.println(wyn); } private static void fill(int[][] g, int n) { for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { g[i][j] = -1; } } } private static class Newton { long[][] tab; int maxInd; public Newton(int maxn) { maxInd = ++maxn; tab = new long[maxn][]; for (int i = 0; i < maxn; i++) { tab[i] = new long[i + 1]; tab[i][0] = 1; tab[i][i] = 1; } for (int i = 1; i < maxn; i++) { for (int j = 1; j < i; j++) { tab[i][j] = tab[i - 1][j - 1] + tab[i - 1][j]; } } } public long get(int n, int k) { if (k < 0 || n < 0 || k > maxInd || n > maxInd || k > n) { return 0; } return tab[n][k]; } } static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public String next() throws IOException { if (st == null || !st.hasMoreTokens()) { String line = br.readLine(); st = new StringTokenizer(line); } return st.nextToken(); } public int nextInt() throws IOException { String next = next(); return Integer.parseInt(next); } } }
Java
["6 1\n-1 -1 -1 8 -1\n-1 5 -1 -1\n-1 -1 3\n-1 -1\n-1", "3 2\n10 0\n11"]
3 seconds
["5", "14"]
NoteIn the first sample there are 6 one-element sets of silos. For sets {1}, {5} the operation danger will equal 8, for sets {3}, {6} — 3, for sets {2}, {4} — 5. The mathematical average equals .In the second sample there are 3 two-elements sets of silos: {1, 3} (danger equals 21), {1, 2} (danger equals 11), {2, 3} (danger equals 10). The average operation danger equals .
Java 7
standard input
[ "math", "graphs" ]
48b232b9d836b0be91d41e548a9fcefc
The first line contains two integers n and k (2 ≤ n ≤ 2000, 1 ≤ k ≤ n - 1) — the number of silos and the number of scout groups, correspondingly. The next n - 1 lines describe the polygon plan: the i-th of these lines contains n - i integers ci, i + 1, ci, i + 2, ..., ci, n — the number of droids that patrol the corresponding passages (-1 ≤ ci, j ≤ 109; if ci, j =  -1, then silos i and j don't have a passage between them). All passages are bidirectional, that is, we can assume that ci, j = cj, i. No passages connect a silo with itself. It is guaranteed that the polygon plan meets the conditions of the problem statement.
2,400
Print the average danger of the scouting operation, rounded down to an integer. Note that at the given limits the answer to the problem always fits into the standard integer 64-bit data type. Please do not use the %lld specifier to write 64-bit integers in С++. It is preferred to use the cout stream or the %I64d specifier.
standard output
PASSED
4090197e49f9a444174bc58ff4e08bc8
train_001.jsonl
1374679800
Insurgents accidentally got hold of the plan of a top secret research polygon created on a distant planet for the needs of the Galaxy Empire. The insurgents suppose that this polygon is developing new deadly weapon. The polygon consists of n missile silos connected by bidirectional underground passages. The passages are linked to laboratories where research is conducted. Naturally, the passages are guarded severely: the passage between silos i and j is patrolled by ci, j war droids.The insurgents studied the polygon plan and noticed its unusual structure. As it turned out, for any k-element set of silos S there is exactly one silo that is directly connected by a passage with each silo from S (we'll call this silo adjacent with S). Having considered that, the insurgents decided to act as follows: they choose a k-element set of silos S; a group of scouts lands from the air into each silo from S; each group moves along the corresponding passage to the silo, adjacent with S (as the scouts move, they check out the laboratories and watch for any signs of weapon blueprints); in the silo, adjacent with S, the groups get on the ship and fly away. The danger of the operation is the total number of droids that patrol the passages through which the scouts will go. The danger of the operation obviously only depends on the way to choose set S. The insurgents haven't yet decided on the exact silos to send the scouts to. However, they already want to start preparing the weapons for the scout groups. To do that, the insurgents need to know the mathematical average of the dangers of the operations that correspond to all possible ways to choose set S. Solve this problem to help the insurgents protect the ideals of the Republic!
256 megabytes
import java.io.BufferedReader; import java.io.OutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.Reader; import java.math.BigInteger; 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; InputStreamReader in = new InputStreamReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } } class TaskD { int MAX_BIN = 2000; public void solve(int testNumber, InputStreamReader inSt, PrintWriter out) { InputReader in = new InputReader(inSt); int n = in.nextInt(); int k = in.nextInt(); long[][] c = new long[n][n]; int[] num = new int[n]; long[] sum = new long[n]; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { c[i][j] = in.nextInt(); c[j][i] = c[i][j]; if (c[i][j] >= 0) { num[i]++; num[j]++; sum[i] += c[i][j]; sum[j] += c[i][j]; } } c[i][i] = -1; } BigInteger[] fact = new BigInteger[n + 1]; BigInteger[] values = new BigInteger[n + 1]; BigInteger oneB = BigInteger.valueOf(1); fact[0] = oneB; values[0] = BigInteger.valueOf(0); for (int i = 1; i < n + 1; i++) { values[i] = BigInteger.valueOf(i); fact[i] = fact[i - 1].multiply(values[i]); } BigInteger sumAll = values[0]; for (int i = 0; i < n; i++) { if (num[i] >= k) { BigInteger cur = fact[num[i] - 1].divide(fact[num[i] - k]); sumAll = sumAll.add(cur.multiply(BigInteger.valueOf(sum[i]))); } } sumAll = sumAll.multiply(values[k]); sumAll = sumAll.multiply(fact[n - k]); sumAll = sumAll.divide(fact[n]); out.println(sumAll); } class InputReader { public BufferedReader reader; private String[] currentArray; int curPointer; public InputReader(InputStreamReader inputStreamReader) { reader = new BufferedReader(inputStreamReader); } public String next() { try { currentArray = null; return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } public void nextChars(char[] t) { try { currentArray = null; reader.read(t); } catch (IOException e) { throw new RuntimeException(e); } } public char nextChar() { try { currentArray = null; return (char) reader.read(); } catch (IOException e) { throw new RuntimeException(e); } } public int nextInt() { if ((currentArray == null) || (curPointer >= currentArray.length)) { try { currentArray = reader.readLine().split(" "); } catch (IOException e) { throw new RuntimeException(e); } curPointer = 0; } return Integer.parseInt(currentArray[curPointer++]); } public long nextLong() { if ((currentArray == null) || (curPointer >= currentArray.length)) { try { currentArray = reader.readLine().split(" "); } catch (IOException e) { throw new RuntimeException(e); } curPointer = 0; } return Long.parseLong(currentArray[curPointer++]); } } }
Java
["6 1\n-1 -1 -1 8 -1\n-1 5 -1 -1\n-1 -1 3\n-1 -1\n-1", "3 2\n10 0\n11"]
3 seconds
["5", "14"]
NoteIn the first sample there are 6 one-element sets of silos. For sets {1}, {5} the operation danger will equal 8, for sets {3}, {6} — 3, for sets {2}, {4} — 5. The mathematical average equals .In the second sample there are 3 two-elements sets of silos: {1, 3} (danger equals 21), {1, 2} (danger equals 11), {2, 3} (danger equals 10). The average operation danger equals .
Java 7
standard input
[ "math", "graphs" ]
48b232b9d836b0be91d41e548a9fcefc
The first line contains two integers n and k (2 ≤ n ≤ 2000, 1 ≤ k ≤ n - 1) — the number of silos and the number of scout groups, correspondingly. The next n - 1 lines describe the polygon plan: the i-th of these lines contains n - i integers ci, i + 1, ci, i + 2, ..., ci, n — the number of droids that patrol the corresponding passages (-1 ≤ ci, j ≤ 109; if ci, j =  -1, then silos i and j don't have a passage between them). All passages are bidirectional, that is, we can assume that ci, j = cj, i. No passages connect a silo with itself. It is guaranteed that the polygon plan meets the conditions of the problem statement.
2,400
Print the average danger of the scouting operation, rounded down to an integer. Note that at the given limits the answer to the problem always fits into the standard integer 64-bit data type. Please do not use the %lld specifier to write 64-bit integers in С++. It is preferred to use the cout stream or the %I64d specifier.
standard output
PASSED
bd2758c3b0c75ac432c3d5fca8891032
train_001.jsonl
1374679800
Insurgents accidentally got hold of the plan of a top secret research polygon created on a distant planet for the needs of the Galaxy Empire. The insurgents suppose that this polygon is developing new deadly weapon. The polygon consists of n missile silos connected by bidirectional underground passages. The passages are linked to laboratories where research is conducted. Naturally, the passages are guarded severely: the passage between silos i and j is patrolled by ci, j war droids.The insurgents studied the polygon plan and noticed its unusual structure. As it turned out, for any k-element set of silos S there is exactly one silo that is directly connected by a passage with each silo from S (we'll call this silo adjacent with S). Having considered that, the insurgents decided to act as follows: they choose a k-element set of silos S; a group of scouts lands from the air into each silo from S; each group moves along the corresponding passage to the silo, adjacent with S (as the scouts move, they check out the laboratories and watch for any signs of weapon blueprints); in the silo, adjacent with S, the groups get on the ship and fly away. The danger of the operation is the total number of droids that patrol the passages through which the scouts will go. The danger of the operation obviously only depends on the way to choose set S. The insurgents haven't yet decided on the exact silos to send the scouts to. However, they already want to start preparing the weapons for the scout groups. To do that, the insurgents need to know the mathematical average of the dangers of the operations that correspond to all possible ways to choose set S. Solve this problem to help the insurgents protect the ideals of the Republic!
256 megabytes
/* Codeforces Template */ import java.io.*; import java.math.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.fill; import static java.util.Arrays.binarySearch; import static java.util.Arrays.sort; public class Main { static long initTime; static final Random rnd = new Random(7777L); static boolean writeLog = false; public static void main(String[] args) throws IOException { initTime = System.currentTimeMillis(); try { writeLog = "true".equals(System.getProperty("LOCAL_RUN_7777")); } catch (SecurityException e) {} new Thread(null, new Runnable() { public void run() { try { try { if (new File("input.txt").exists()) System.setIn(new FileInputStream("input.txt")); } catch (SecurityException e) {} long prevTime = System.currentTimeMillis(); new Main().run(); wrieteLog("Total time: " + (System.currentTimeMillis() - prevTime) + " ms"); wrieteLog("Memory status: " + memoryStatus()); } catch (IOException e) { e.printStackTrace(); } } }, "1", 1L << 24).start(); } void run() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); in.close(); } /*************************************************************** * Solution **************************************************************/ final int MAXN = 2000; final BigInteger[] factorial = new BigInteger [MAXN + 1]; { factorial[0] = BigInteger.ONE; for (int i = 1; i <= MAXN; i++) factorial[i] = factorial[i - 1].multiply(BigInteger.valueOf(i)); } void solve() throws IOException { int n = nextInt(); int k = nextInt(); int[][] g = new int [n][n]; for (int i = 0; i < n; i++) { g[i][i] = -1; for (int j = i + 1; j < n; j++) { g[i][j] = g[j][i] = nextInt(); } } BigInteger den = comb(n, k); BigInteger num = BigInteger.ZERO; for (int i = 0; i < n; i++) { int deg = 0; long sum = 0L; for (int j = 0; j < n; j++) { if (g[i][j] != -1) { deg++; sum += g[i][j]; } } if (deg >= k) { num = num.add(comb(deg - 1, k - 1).multiply(BigInteger.valueOf(sum))); } } out.println(num.divide(den).longValue()); } BigInteger comb(int n, int k) { return factorial[n].divide(factorial[k]).divide(factorial[n - k]); } /*************************************************************** * Input **************************************************************/ BufferedReader in; PrintWriter out; StringTokenizer st = new StringTokenizer(""); 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()); } int[] nextIntArray(int size) throws IOException { int[] ret = new int [size]; for (int i = 0; i < size; i++) ret[i] = nextInt(); return ret; } long[] nextLongArray(int size) throws IOException { long[] ret = new long [size]; for (int i = 0; i < size; i++) ret[i] = nextLong(); return ret; } double[] nextDoubleArray(int size) throws IOException { double[] ret = new double [size]; for (int i = 0; i < size; i++) ret[i] = nextDouble(); return ret; } 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; } /*************************************************************** * Output **************************************************************/ void printRepeat(String s, int count) { for (int i = 0; i < count; i++) out.print(s); } void printArray(int[] array) { if (array == null || array.length == 0) return; for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(long[] array) { if (array == null || array.length == 0) return; for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(double[] array) { if (array == null || array.length == 0) return; for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(double[] array, String spec) { if (array == null || array.length == 0) return; for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.printf(Locale.US, spec, array[i]); } out.println(); } void printArray(Object[] array) { if (array == null || array.length == 0) return; boolean blank = false; for (Object x : array) { if (blank) out.print(' '); else blank = true; out.print(x); } out.println(); } @SuppressWarnings("rawtypes") void printCollection(Collection collection) { if (collection == null || collection.isEmpty()) return; boolean blank = false; for (Object x : collection) { if (blank) out.print(' '); else blank = true; out.print(x); } out.println(); } /*************************************************************** * Utility **************************************************************/ static String memoryStatus() { return (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory() >> 20) + "/" + (Runtime.getRuntime().totalMemory() >> 20) + " MB"; } static void checkMemory() { System.err.println(memoryStatus()); } static long prevTimeStamp = Long.MIN_VALUE; static void updateTimer() { prevTimeStamp = System.currentTimeMillis(); } static long elapsedTime() { return (System.currentTimeMillis() - prevTimeStamp); } static void checkTimer() { System.err.println(elapsedTime() + " ms"); } static void chk(boolean f) { if (!f) throw new RuntimeException("Assert failed"); } static void chk(boolean f, String format, Object ... args) { if (!f) throw new RuntimeException(String.format(format, args)); } static void wrieteLog(String format, Object ... args) { if (writeLog) System.err.println(String.format(Locale.US, format, args)); } static void swap(int[] a, int i, int j) { int tmp = a[i]; a[i] = a[j]; a[j] = tmp; } static void swap(long[] a, int i, int j) { long tmp = a[i]; a[i] = a[j]; a[j] = tmp; } static void swap(double[] a, int i, int j) { double tmp = a[i]; a[i] = a[j]; a[j] = tmp; } static void shuffle(int[] a, int from, int to) { for (int i = from; i < to; i++) swap(a, i, rnd.nextInt(a.length)); } static void shuffle(long[] a, int from, int to) { for (int i = from; i < to; i++) swap(a, i, rnd.nextInt(a.length)); } static void shuffle(double[] a, int from, int to) { for (int i = from; i < to; i++) swap(a, i, rnd.nextInt(a.length)); } static void shuffle(int[] a) { if (a == null) return; shuffle(a, 0, a.length); } static void shuffle(long[] a) { if (a == null) return; shuffle(a, 0, a.length); } static void shuffle(double[] a) { if (a == null) return; shuffle(a, 0, a.length); } }
Java
["6 1\n-1 -1 -1 8 -1\n-1 5 -1 -1\n-1 -1 3\n-1 -1\n-1", "3 2\n10 0\n11"]
3 seconds
["5", "14"]
NoteIn the first sample there are 6 one-element sets of silos. For sets {1}, {5} the operation danger will equal 8, for sets {3}, {6} — 3, for sets {2}, {4} — 5. The mathematical average equals .In the second sample there are 3 two-elements sets of silos: {1, 3} (danger equals 21), {1, 2} (danger equals 11), {2, 3} (danger equals 10). The average operation danger equals .
Java 7
standard input
[ "math", "graphs" ]
48b232b9d836b0be91d41e548a9fcefc
The first line contains two integers n and k (2 ≤ n ≤ 2000, 1 ≤ k ≤ n - 1) — the number of silos and the number of scout groups, correspondingly. The next n - 1 lines describe the polygon plan: the i-th of these lines contains n - i integers ci, i + 1, ci, i + 2, ..., ci, n — the number of droids that patrol the corresponding passages (-1 ≤ ci, j ≤ 109; if ci, j =  -1, then silos i and j don't have a passage between them). All passages are bidirectional, that is, we can assume that ci, j = cj, i. No passages connect a silo with itself. It is guaranteed that the polygon plan meets the conditions of the problem statement.
2,400
Print the average danger of the scouting operation, rounded down to an integer. Note that at the given limits the answer to the problem always fits into the standard integer 64-bit data type. Please do not use the %lld specifier to write 64-bit integers in С++. It is preferred to use the cout stream or the %I64d specifier.
standard output
PASSED
c74ce0f00c8fca2794cf5f6363a7ba79
train_001.jsonl
1374679800
Reforms continue entering Berland. For example, during yesterday sitting the Berland Parliament approved as much as n laws (each law has been assigned a unique number from 1 to n). Today all these laws were put on the table of the President of Berland, G.W. Boosch, to be signed.This time mr. Boosch plans to sign 2k laws. He decided to choose exactly two non-intersecting segments of integers from 1 to n of length k and sign all laws, whose numbers fall into these segments. More formally, mr. Boosch is going to choose two integers a, b (1 ≤ a ≤ b ≤ n - k + 1, b - a ≥ k) and sign all laws with numbers lying in the segments [a; a + k - 1] and [b; b + k - 1] (borders are included).As mr. Boosch chooses the laws to sign, he of course considers the public opinion. Allberland Public Opinion Study Centre (APOSC) conducted opinion polls among the citizens, processed the results into a report and gave it to the president. The report contains the absurdity value for each law, in the public opinion. As mr. Boosch is a real patriot, he is keen on signing the laws with the maximum total absurdity. Help him.
256 megabytes
import java.util.*; import java.io.*; public class Main { static class Scan { private byte[] buf=new byte[1024]; private int index; private InputStream in; private int total; public Scan() { in=System.in; } public int scan()throws IOException { if(total<0) throw new InputMismatchException(); if(index>=total) { index=0; total=in.read(buf); if(total<=0) return -1; } return buf[index++]; } public int scanInt()throws IOException { int integer=0; int n=scan(); while(isWhiteSpace(n)) n=scan(); int neg=1; if(n=='-') { neg=-1; n=scan(); } while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { integer*=10; integer+=n-'0'; n=scan(); } else throw new InputMismatchException(); } return neg*integer; } public double scanDouble()throws IOException { double doub=0; int n=scan(); while(isWhiteSpace(n)) n=scan(); int neg=1; if(n=='-') { neg=-1; n=scan(); } while(!isWhiteSpace(n)&&n!='.') { if(n>='0'&&n<='9') { doub*=10; doub+=n-'0'; n=scan(); } else throw new InputMismatchException(); } if(n=='.') { n=scan(); double temp=1; while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { temp/=10; doub+=(n-'0')*temp; n=scan(); } else throw new InputMismatchException(); } } return doub*neg; } public String scanString()throws IOException { StringBuilder sb=new StringBuilder(); int n=scan(); while(isWhiteSpace(n)) n=scan(); while(!isWhiteSpace(n)) { sb.append((char)n); n=scan(); } return sb.toString(); } private boolean isWhiteSpace(int n) { if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1) return true; return false; } } public static void main(String args[]) throws IOException { Scan input=new Scan(); int n=input.scanInt(); int k=input.scanInt(); long arr[]=new long[n]; long prefix[]=new long[n]; for(int i=0;i<n;i++) { arr[i]=input.scanInt(); } solve(n,k,arr); } public static void solve(int n,int k,long arr[]) { long prefix[]=new long[n-k+1]; long sum=0; for(int i=0;i<k;i++) { sum+=arr[i]; } prefix[0]=sum; for(int i=1;i<n-k+1;i++) { sum+=arr[i+k-1]; sum-=arr[i-1]; prefix[i]=sum; } long max_sum[]=new long[n-k+1]; long max=0; for(int i=n-k;i>=0;i--) { max=Math.max(max,prefix[i]); max_sum[i]=max; } long ans=0; int l=-1,r=-1; for(int i=0;i+k<n-k+1;i++) { // System.out.println(i+" "+(i+k)); if(prefix[i]+max_sum[i+k]>ans) { ans=prefix[i]+max_sum[i+k]; l=i; } } for(int i=l+k;i<n-k+1;i++) { if(prefix[i]==max_sum[l+k]) { r=i; break; } } // for(int i=0;i<n-k+1;i++) { // System.out.print(prefix[i]+" "); // } // System.out.println(); // for(int i=0;i<n-k+1;i++) { // System.out.print(max_sum[i]+" "); // } // System.out.println(); l++; r++; System.out.println(l+" "+r); } }
Java
["5 2\n3 6 1 1 6", "6 2\n1 1 1 1 1 1"]
2 seconds
["1 4", "1 3"]
NoteIn the first sample mr. Boosch signs laws with numbers from segments [1;2] and [4;5]. The total absurdity of the signed laws equals 3 + 6 + 1 + 6 = 16.In the second sample mr. Boosch signs laws with numbers from segments [1;2] and [3;4]. The total absurdity of the signed laws equals 1 + 1 + 1 + 1 = 4.
Java 11
standard input
[ "dp", "implementation", "data structures" ]
74095fe82bd22257eeb97e1caf586499
The first line contains two integers n and k (2 ≤ n ≤ 2·105, 0 &lt; 2k ≤ n) — the number of laws accepted by the parliament and the length of one segment in the law list, correspondingly. The next line contains n integers x1, x2, ..., xn — the absurdity of each law (1 ≤ xi ≤ 109).
1,500
Print two integers a, b — the beginning of segments that mr. Boosch should choose. That means that the president signs laws with numbers from segments [a; a + k - 1] and [b; b + k - 1]. If there are multiple solutions, print the one with the minimum number a. If there still are multiple solutions, print the one with the minimum b.
standard output
PASSED
cbd5a9ef7d0f70e3e39f1cdbe809d6d1
train_001.jsonl
1586961300
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int TT = Integer.parseInt(in.readLine()); int currTT = 0; StringBuilder output = new StringBuilder(); while (currTT++ < TT) { String[] input = in.readLine().split("\\s+"); int nr = Integer.parseInt(input[0]); int ng = Integer.parseInt(input[1]); int nb = Integer.parseInt(input[2]); TreeSet<Long> r = new TreeSet<Long>(); input = in.readLine().split("\\s+"); for (int i = 0; i < nr; i++) r.add(Long.parseLong(input[i])); TreeSet<Long> g = new TreeSet<Long>(); input = in.readLine().split("\\s+"); for (int i = 0; i < ng; i++) g.add(Long.parseLong(input[i])); TreeSet<Long> b = new TreeSet<Long>(); input = in.readLine().split("\\s+"); for (int i = 0; i < nb; i++) b.add(Long.parseLong(input[i])); long ans = Long.MAX_VALUE; for (long x: r) { long tmp = calc(x, -1, g, b, 0); ans = tmp < ans ? tmp : ans; } for (long y: g) { long tmp = calc(y, -1, b, r, 0); ans = tmp < ans ? tmp : ans; } for (long z: b) { long tmp = calc(z, -1, r, g, 0); ans = tmp < ans ? tmp : ans; } output.append(ans + "\n"); } out.print(output); in.close(); out.close(); } private static long calc(long v1, long v2, TreeSet<Long> t1, TreeSet<Long> t2, long sum) { if (v2 == -1) { Long v2c = t1.ceiling(v1); v2c = v2c == null ? t1.first() : v2c; Long v2f = t1.floor(v1); v2f = v2f == null ? t1.last() : v2f; return (long) Math.min( calc(v1, v2c, t1, t2, (v1 - v2c) * (v1 - v2c)), calc(v1, v2f, t1, t2, (v1 - v2f) * (v1 - v2f)) ); } else { Long v3c = t2.ceiling(v2); v3c = v3c == null ? t2.first() : v3c; Long v3f = t2.floor(v1); v3f = v3f == null ? t2.last() : v3f; return (long) Math.min( sum + (v2 - v3c) * (v2 - v3c) + (v3c - v1) * (v3c - v1), sum + (v2 - v3f) * (v2 - v3f) + (v3f - v1) * (v3f - v1) ); } } }
Java
["5\n2 2 3\n7 8\n6 3\n3 1 4\n1 1 1\n1\n1\n1000000000\n2 2 2\n1 2\n5 4\n6 7\n2 2 2\n1 2\n3 4\n6 7\n3 4 1\n3 2 1\n7 3 3 4\n6"]
3 seconds
["14\n1999999996000000002\n24\n24\n14"]
NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.
Java 8
standard input
[ "math", "implementation", "sortings", "data structures", "binary search" ]
79b58eb781cd73ccf7994866b9a8b695
The first line contains a single integer $$$t$$$ ($$$1\le t \le 100$$$)  — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (the sum for all test cases).
1,700
For each test case, print a line contains one integer  — the minimum value which Xenia wants to find.
standard output
PASSED
4ca6bcb815be4e8a2755c2fa867c78e8
train_001.jsonl
1586961300
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Main { public static void main(String[] args) { new Thread(null, new Runnable() { public void run() { solve(); } }, "1", 1 << 26).start(); } static void solve () { FastReader fr =new FastReader(); PrintWriter op =new PrintWriter(System.out); int t =fr.nextInt() ,r ,g ,b ,R[] ,G[] ,B[] ,i ; long sm ; while (t-->0) { r =fr.nextInt() ; g =fr.nextInt() ; b =fr.nextInt() ; R =new int[r] ; G =new int[g] ; B =new int[b] ; for (i =0 ; i<r ; ++i) R[i] =fr.nextInt() ; for (i =0 ; i<g ; ++i) G[i] =fr.nextInt() ; for (i =0 ; i<b ; ++i) B[i] =fr.nextInt() ; sort (R,0,r-1) ; sort (G,0,g-1) ; sort (B,0,b-1) ; sm =Long.MAX_VALUE; sm =Math.min(func(R,G,B) , sm) ; sm =Math.min(func(B,G,R) , sm) ; sm =Math.min(func(R,B,G) , sm) ; sm =Math.min(func(G,B,R) , sm) ; sm =Math.min(func(B,R,G) , sm) ; sm =Math.min(func(G,R,B) , sm) ; op.println(sm) ; } op.flush(); op.close(); } static long func (int x[] , int y[] , int z[]) { int i ,j ,k ,l ,m ,r =x.length ,s =y.length ,t =z.length ; long ret =Long.MAX_VALUE; j =k =0 ; for (i =0 ; i<r ; ++i) { --j ; --k ; while (j+1<s && x[i]>y[j+1]) ++j ; if (j+1==s) break; ++j ; while (k+1<t && y[j]>z[k+1]) ++k ; if (k+1==t) break; ++k ; m =z[k]-x[i] ; while (j+1<s && y[j+1]<=z[k]) { l =y[j+1]-x[i] ; if (2*l > m) { ret =Math.min(ret , fnd(x[i] , y[j+1] , z[k])) ; break; } ++j ; } ret =Math.min(ret , fnd (x[i] , y[j] , z[k])) ; } return ret; } static long fnd (long a , long b , long c) { long x =b-a ,y =c-b ,z =c-a ; x*=x ; y*=y ; z*=z ; x+=y ; x+=z ; return x; } public static void sort(int[] arr , int l , int u) { int m ; if(l < u){ m =(l + u)/2 ; sort(arr , l , m); sort(arr , m + 1 , u); merge(arr , l , m , u); } } public static void merge(int[] arr , int l , int m , int u) { int[] low = new int[m - l + 1] ; int[] upr = new int[u - m] ; int i ,j =0 ,k =0 ; for(i =l;i<=m;i++) low[i - l] =arr[i] ; for(i =m + 1;i<=u;i++) upr[i - m - 1] =arr[i] ; i =l; while((j < low.length) && (k < upr.length)) { if(low[j] < upr[k]) arr[i++] =low[j++] ; else arr[i++] =upr[k++] ; } while(j < low.length) arr[i++] =low[j++] ; while(k < upr.length) arr[i++] =upr[k++] ; } 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(); } String nextLine() { String str =""; try { str =br.readLine(); } catch(IOException e) { e.printStackTrace(); } return str; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()) ; } } }
Java
["5\n2 2 3\n7 8\n6 3\n3 1 4\n1 1 1\n1\n1\n1000000000\n2 2 2\n1 2\n5 4\n6 7\n2 2 2\n1 2\n3 4\n6 7\n3 4 1\n3 2 1\n7 3 3 4\n6"]
3 seconds
["14\n1999999996000000002\n24\n24\n14"]
NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.
Java 8
standard input
[ "math", "implementation", "sortings", "data structures", "binary search" ]
79b58eb781cd73ccf7994866b9a8b695
The first line contains a single integer $$$t$$$ ($$$1\le t \le 100$$$)  — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (the sum for all test cases).
1,700
For each test case, print a line contains one integer  — the minimum value which Xenia wants to find.
standard output
PASSED
1e7fd307688850e4d358efb3e2f359dd
train_001.jsonl
1586961300
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?
256 megabytes
/* [ ( ^ _ ^ ) ] */ // problem: cf/1337/D import java.io.*; import java.util.*; public class d { int INF = (int)1e9; long MOD = 1000000007; long sq(long n) { return n*n; } long min(long a, long b) {return a<=b?a:b;} long min(long a, long b, long c) {return min(a, min(b, c));} long max(long a, long b) {return a>=b?a:b;}; long max(long a, long b, long c) {return max(a, max(b, c));} void sort(long[] a) { long r = a[0], g = a[1], b = a[2]; a[0] = min(r, g, b); a[2] = max(r, g, b); a[1] = r!=a[0]&&r!=a[2]?r:(g!=a[0]&&g!=a[2]?g:b); } void solve(InputReader in, PrintWriter out) throws IOException { int nr = in.nextInt(); int ng = in.nextInt(); int nb = in.nextInt(); Long[] r = new Long[nr]; Long[] g = new Long[ng]; Long[] b = new Long[nb]; for(int i=0; i<nr; i++) { r[i] = in.nextLong(); } for(int i=0; i<ng; i++) { g[i] = in.nextLong(); } for(int i=0; i<nb; i++) { b[i] = in.nextLong(); } Arrays.sort(r); Arrays.sort(g); Arrays.sort(b); long rs = Long.MAX_VALUE; int[] idx = new int[3]; Long[][] w = new Long[][]{r, g, b}; outer: while(idx[0]<nr && idx[1]<ng && idx[2]<nb) { long x = sq(r[idx[0]]-g[idx[1]]) + sq(g[idx[1]]-b[idx[2]]) + sq(b[idx[2]]-r[idx[0]]); rs = min(x, rs); // show("rgb", r[idx[0]], g[idx[1]], b[idx[2]], x); long v = Long.MAX_VALUE; for(int i=0; i<3; i++) { if(idx[i]+1<w[i].length) { idx[i]++; v = min(v, sq(r[idx[0]]-g[idx[1]]) + sq(g[idx[1]]-b[idx[2]]) + sq(b[idx[2]]-r[idx[0]])); idx[i]--; } } if(v==Long.MAX_VALUE) break; for(int i=0; i<3; i++) { if(idx[i]+1<w[i].length) { idx[i]++; long y = sq(r[idx[0]]-g[idx[1]]) + sq(g[idx[1]]-b[idx[2]]) + sq(b[idx[2]]-r[idx[0]]); if(v==y) { continue outer; } idx[i]--; } } } out.println(rs); } public static void main(String[] args) throws IOException { InputReader in = new InputReader(); PrintWriter out = new PrintWriter(System.out); int t = in.nextInt(); while(t-- >0) { new d().solve(in, out); } out.close(); } public static void show(Object... o) { System.out.println(Arrays.deepToString(o)); } static class InputReader { static BufferedReader br; static StringTokenizer st; public InputReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["5\n2 2 3\n7 8\n6 3\n3 1 4\n1 1 1\n1\n1\n1000000000\n2 2 2\n1 2\n5 4\n6 7\n2 2 2\n1 2\n3 4\n6 7\n3 4 1\n3 2 1\n7 3 3 4\n6"]
3 seconds
["14\n1999999996000000002\n24\n24\n14"]
NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.
Java 8
standard input
[ "math", "implementation", "sortings", "data structures", "binary search" ]
79b58eb781cd73ccf7994866b9a8b695
The first line contains a single integer $$$t$$$ ($$$1\le t \le 100$$$)  — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (the sum for all test cases).
1,700
For each test case, print a line contains one integer  — the minimum value which Xenia wants to find.
standard output
PASSED
4cb0a41ae92d8ef41c535df57b64c0ef
train_001.jsonl
1586961300
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class codechef { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main (String[] args) throws java.lang.Exception { FastReader s = new FastReader(); int t = s.nextInt(); StringBuffer str = new StringBuffer(); while(t-->0) { int nr = s.nextInt(); int ng = s.nextInt(); int nb = s.nextInt(); long[] red = new long[nr]; long[] green = new long[ng]; long[] blue = new long[nb]; for(int i=0;i<nr;i++) red[i] = s.nextLong(); Arrays.sort(red); for(int i=0;i<ng;i++) green[i] = s.nextLong(); Arrays.sort(green); for(int i=0;i<nb;i++) blue[i] = s.nextLong(); Arrays.sort(blue); long ans = Long.MAX_VALUE; //red gem for (int i = 0; i < nr; i++) { long x = red[i]; long y = bianrySearch(green,x); long z = bianrySearch(blue,x); ans = Math.min(ans,(long)(x-y)*(x-y) +(long)(z-y)*(z-y) + (long)(x-z)*(x-z)); } // green for (int i = 0; i < ng; i++) { long x = green[i]; long y = bianrySearch(red,x); long z = bianrySearch(blue,x); ans = Math.min(ans,(long)(x-y)*(x-y) + (long)(z-y)*(z-y) + (long)(x-z)*(x-z)); } //blue for (int i = 0; i < nb; i++) { long x = blue[i]; long y = bianrySearch(green,x); long z = bianrySearch(red,x); ans = Math.min(ans,(long)(x-y)*(x-y) + (long)(z-y)*(z-y) + (long)(x-z)*(x-z)); } str.append(ans+"\n"); } System.out.println(str); } public static long bianrySearch(long[] array, long target) { if(target<=array[0]) return array[0]; if(target>= array[array.length-1]) return array[array.length-1]; int low = 0; int high = array.length; int mid =0; while(low<high) { mid = (low+high)/2; if(array[mid]== target) return target; else if(target<array[mid]) { if(mid>0 && array[mid-1]<target) return array[mid]-target>target-array[mid-1] ? array[mid-1]:array[mid]; high = mid; } else { if(mid<array.length-1 && array[mid+1]>target) return array[mid+1]-target>target-array[mid] ? array[mid]:array[mid+1]; low = mid+1; } } return array[mid]; } }
Java
["5\n2 2 3\n7 8\n6 3\n3 1 4\n1 1 1\n1\n1\n1000000000\n2 2 2\n1 2\n5 4\n6 7\n2 2 2\n1 2\n3 4\n6 7\n3 4 1\n3 2 1\n7 3 3 4\n6"]
3 seconds
["14\n1999999996000000002\n24\n24\n14"]
NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.
Java 8
standard input
[ "math", "implementation", "sortings", "data structures", "binary search" ]
79b58eb781cd73ccf7994866b9a8b695
The first line contains a single integer $$$t$$$ ($$$1\le t \le 100$$$)  — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (the sum for all test cases).
1,700
For each test case, print a line contains one integer  — the minimum value which Xenia wants to find.
standard output
PASSED
a091e473f3d34b6cdf3e75cac912647d
train_001.jsonl
1586961300
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); for(int h=0;h<t;h++) { int r=sc.nextInt(); int g=sc.nextInt(); int b=sc.nextInt(); long ra[]=new long[r]; long ga[]=new long[g]; long ba[]=new long[b]; for(int i=0;i<r;i++) ra[i]=sc.nextLong(); for(int i=0;i<g;i++) ga[i]=sc.nextLong(); for(int i=0;i<b;i++) ba[i]=sc.nextLong(); Arrays.sort(ra); Arrays.sort(ga); Arrays.sort(ba); long ans=Long.MAX_VALUE; for(int i=0;i<r;i++) { long x=ra[i]; long y=binarySearch(ga,0,g-1,x); long z=binarySearch(ba,0,b-1,x); //System.out.println(x+" "+y+" "+z+" kkk"); long a1=(x-y)*(x-y); long a2=(y-z)*(y-z); long a3=(z-x)*(z-x); //System.out.println(a1+" "+a2+" "+a3+" lll "+(a1+a2+a3)); ans=Math.min(ans,(a1+a2+a3)); } for(int i=0;i<g;i++) { long y=ga[i]; long x=binarySearch(ra,0,r-1,y); long z=binarySearch(ba,0,b-1,y); //System.out.println(x+" "+y+" "+z+" kkk"); long a1=(x-y)*(x-y); long a2=(y-z)*(y-z); long a3=(z-x)*(z-x); //System.out.println(a1+" "+a2+" "+a3+" lll "+(a1+a2+a3)); ans=Math.min(ans,(a1+a2+a3)); } for(int i=0;i<b;i++) { long z=ba[i]; long x=binarySearch(ra,0,r-1,z); long y=binarySearch(ga,0,g-1,z); //System.out.println(x+" "+y+" "+z+" kkk"); long a1=(x-y)*(x-y); long a2=(y-z)*(y-z); long a3=(z-x)*(z-x); //System.out.println(a1+" "+a2+" "+a3+" lll "+(a1+a2+a3)); ans=Math.min(ans,(a1+a2+a3)); } System.out.println(ans); } } static long binarySearch(long arr[], int l, int r, long x) { if(arr[0]>x) return arr[0]; if(arr[arr.length-1]<x) return arr[arr.length-1]; while (l <= r ) { int m = (l + r) / 2; // Check if x is present at mid if (arr[m] == x) return arr[m]; // If x greater, ignore left half if (arr[m] < x) l = m + 1; // If x is smaller, ignore right half else r = m - 1; } //System.out.println(r+" "+l+" kkk"); return (Math.abs(arr[l]-x)>Math.abs(arr[r]-x))?Math.abs(arr[r]):Math.abs(arr[l]); } }
Java
["5\n2 2 3\n7 8\n6 3\n3 1 4\n1 1 1\n1\n1\n1000000000\n2 2 2\n1 2\n5 4\n6 7\n2 2 2\n1 2\n3 4\n6 7\n3 4 1\n3 2 1\n7 3 3 4\n6"]
3 seconds
["14\n1999999996000000002\n24\n24\n14"]
NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.
Java 8
standard input
[ "math", "implementation", "sortings", "data structures", "binary search" ]
79b58eb781cd73ccf7994866b9a8b695
The first line contains a single integer $$$t$$$ ($$$1\le t \le 100$$$)  — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (the sum for all test cases).
1,700
For each test case, print a line contains one integer  — the minimum value which Xenia wants to find.
standard output
PASSED
1c86eb75ce1b1038b48cd904010b941c
train_001.jsonl
1586961300
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?
256 megabytes
import java.util.Arrays; import java.util.Scanner; import java.util.TreeSet; import java.util.concurrent.atomic.AtomicLong; /** * created at 18/04/20 4:11 PM */ public class P1337D { public static void main(String[] args) { Scanner input = new Scanner(System.in); int tests = input.nextInt(); while (tests-- != 0) { int r = input.nextInt(); int g = input.nextInt(); int b = input.nextInt(); TreeSet<Integer> rs = new TreeSet<>(); TreeSet<Integer> gs = new TreeSet<>(); TreeSet<Integer> bs = new TreeSet<>(); for (int i = 0; i < r; i++) { rs.add(input.nextInt()); } for (int i = 0; i < g; i++) { gs.add(input.nextInt()); } for (int i = 0; i < b; i++) { bs.add(input.nextInt()); } AtomicLong ans = new AtomicLong(Long.MAX_VALUE); solve(rs, gs, bs, ans); solve(rs, bs, gs, ans); solve(gs, rs, bs, ans); solve(gs, bs, rs, ans); solve(bs, rs, gs, ans); solve(bs, gs, rs, ans); System.out.println(ans.get()); } } private static void solve(TreeSet<Integer> f, TreeSet<Integer> m, TreeSet<Integer> l, AtomicLong ans) { for (Integer mv : m) { Integer fv = f.floor(mv); Integer lv = l.ceiling(mv); if (fv != null && lv != null) { long value = func(fv, mv, lv); if (ans.get() > value) { ans.set(value); } } } } private static long func(long f, long m, long l) { return (f - m) * (f - m) + (m - l) * (m - l) + (l - f) * (l - f); } }
Java
["5\n2 2 3\n7 8\n6 3\n3 1 4\n1 1 1\n1\n1\n1000000000\n2 2 2\n1 2\n5 4\n6 7\n2 2 2\n1 2\n3 4\n6 7\n3 4 1\n3 2 1\n7 3 3 4\n6"]
3 seconds
["14\n1999999996000000002\n24\n24\n14"]
NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.
Java 8
standard input
[ "math", "implementation", "sortings", "data structures", "binary search" ]
79b58eb781cd73ccf7994866b9a8b695
The first line contains a single integer $$$t$$$ ($$$1\le t \le 100$$$)  — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (the sum for all test cases).
1,700
For each test case, print a line contains one integer  — the minimum value which Xenia wants to find.
standard output
PASSED
fbad23e582e3f7f550992bc3d3d56dcf
train_001.jsonl
1586961300
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?
256 megabytes
import java.util.*; public class C635_PD { public static void main(String[] args) { // TODO Auto-generated method stub Scanner in = new Scanner(System.in); int t = in.nextInt(); while(t-->0) { int na = in.nextInt(); int nb = in.nextInt(); int nc = in.nextInt(); TreeSet<Integer> a = new TreeSet<Integer>(); TreeSet<Integer> b= new TreeSet<Integer>(); TreeSet<Integer> c = new TreeSet<Integer>(); for(int i =0;i<na;i++) a.add(in.nextInt()); for(int i =0;i<nb;i++) b.add(in.nextInt()); for(int i =0;i<nc;i++) c.add(in.nextInt()); long min =Long.MAX_VALUE; //a for(int i:a) { // b a c if(b.floor(i)!=null&&c.ceiling(i)!=null) min = Math.min(min, val(i,b.floor(i),c.ceiling(i))); // c a b if(c.floor(i)!=null&&b.ceiling(i)!=null) min = Math.min(min, val(i,b.ceiling(i),c.floor(i))); } //b for(int i:b) { if(a.floor(i)!=null&&c.ceiling(i)!=null) min = Math.min(min, val(i,a.floor(i),c.ceiling(i))); if(c.floor(i)!=null&&a.ceiling(i)!=null) min = Math.min(min, val(i,c.floor(i),a.ceiling(i))); } for(int i:c) { if(b.floor(i)!=null&&a.ceiling(i)!=null) min = Math.min(min, val(i,b.floor(i),a.ceiling(i))); if(a.floor(i)!=null&&b.ceiling(i)!=null) min = Math.min(min, val(i,a.floor(i),b.ceiling(i))); } System.out.println(min); } } public static long val(long x, long y,long z) { return (x-y)*(x-y) + (y-z)*(y-z)+(z-x)*(z-x); } }
Java
["5\n2 2 3\n7 8\n6 3\n3 1 4\n1 1 1\n1\n1\n1000000000\n2 2 2\n1 2\n5 4\n6 7\n2 2 2\n1 2\n3 4\n6 7\n3 4 1\n3 2 1\n7 3 3 4\n6"]
3 seconds
["14\n1999999996000000002\n24\n24\n14"]
NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.
Java 8
standard input
[ "math", "implementation", "sortings", "data structures", "binary search" ]
79b58eb781cd73ccf7994866b9a8b695
The first line contains a single integer $$$t$$$ ($$$1\le t \le 100$$$)  — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (the sum for all test cases).
1,700
For each test case, print a line contains one integer  — the minimum value which Xenia wants to find.
standard output
PASSED
9d947c772a544d4efb6221d94561337f
train_001.jsonl
1586961300
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?
256 megabytes
import java.awt.*; import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws Exception { FastReader sc = new FastReader(); StringBuilder sb=new StringBuilder(); int t=sc.nextInt(); while(t-->0){ int r=sc.nextInt(),g=sc.nextInt(),b=sc.nextInt(); Long[] A=new Long[r],B=new Long[g],C=new Long[b]; for(int i=0;i<r;i++)A[i]=sc.nextLong(); for(int i=0;i<g;i++)B[i]=sc.nextLong(); for(int i=0;i<b;i++)C[i]=sc.nextLong(); Arrays.sort(A);Arrays.sort(B);Arrays.sort(C); int i=0,j=0,k=0; long ans=(A[i]-B[j])*(A[i]-B[j])+(B[j]-C[k])*(B[j]-C[k])+(C[k]-A[i])*(C[k]-A[i]); while(true){ long x=Long.MAX_VALUE,y=Long.MAX_VALUE,z=Long.MAX_VALUE; if(i+1<r)x=(A[i+1]-B[j])*(A[i+1]-B[j])+(B[j]-C[k])*(B[j]-C[k])+(C[k]-A[i+1])*(C[k]-A[i+1]); if(j+1<g)y=(A[i]-B[j+1])*(A[i]-B[j+1])+(B[j+1]-C[k])*(B[j+1]-C[k])+(C[k]-A[i])*(C[k]-A[i]); if(k+1<b)z=(A[i]-B[j])*(A[i]-B[j])+(B[j]-C[k+1])*(B[j]-C[k+1])+(C[k+1]-A[i])*(C[k+1]-A[i]); if(x<=y && x<=z && x!=Long.MAX_VALUE){ ans=Math.min(ans,x); i++; } else if(y<=x && y<=z && y!=Long.MAX_VALUE){ ans=Math.min(ans,y); j++; } else if(z!=Long.MAX_VALUE){ ans=Math.min(ans,z); k++; } else break; } sb.append(ans+"\n"); } System.out.println(sb); } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
Java
["5\n2 2 3\n7 8\n6 3\n3 1 4\n1 1 1\n1\n1\n1000000000\n2 2 2\n1 2\n5 4\n6 7\n2 2 2\n1 2\n3 4\n6 7\n3 4 1\n3 2 1\n7 3 3 4\n6"]
3 seconds
["14\n1999999996000000002\n24\n24\n14"]
NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.
Java 8
standard input
[ "math", "implementation", "sortings", "data structures", "binary search" ]
79b58eb781cd73ccf7994866b9a8b695
The first line contains a single integer $$$t$$$ ($$$1\le t \le 100$$$)  — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (the sum for all test cases).
1,700
For each test case, print a line contains one integer  — the minimum value which Xenia wants to find.
standard output
PASSED
f6ebb952cca6dbc1d7004861a00804d1
train_001.jsonl
1586961300
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?
256 megabytes
import java.awt.*; import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws Exception { FastReader sc = new FastReader(); StringBuilder sb=new StringBuilder(); int t=sc.nextInt(); while(t-->0){ int r=sc.nextInt(),g=sc.nextInt(),b=sc.nextInt(); Long[] A=new Long[r],B=new Long[g],C=new Long[b]; for(int i=0;i<r;i++)A[i]=sc.nextLong(); for(int i=0;i<g;i++)B[i]=sc.nextLong(); for(int i=0;i<b;i++)C[i]=sc.nextLong(); Arrays.sort(A);Arrays.sort(B);Arrays.sort(C); int i=0,j=0,k=0; long ans=(A[i]-B[j])*(A[i]-B[j])+(B[j]-C[k])*(B[j]-C[k])+(C[k]-A[i])*(C[k]-A[i]); while(true){ long x=Long.MAX_VALUE,y=Long.MAX_VALUE,z=Long.MAX_VALUE; if(i+1<r)x=(A[i+1]-B[j])*(A[i+1]-B[j])+(B[j]-C[k])*(B[j]-C[k])+(C[k]-A[i+1])*(C[k]-A[i+1]); if(j+1<g)y=(A[i]-B[j+1])*(A[i]-B[j+1])+(B[j+1]-C[k])*(B[j+1]-C[k])+(C[k]-A[i])*(C[k]-A[i]); if(k+1<b)z=(A[i]-B[j])*(A[i]-B[j])+(B[j]-C[k+1])*(B[j]-C[k+1])+(C[k+1]-A[i])*(C[k+1]-A[i]); if(x==Long.MAX_VALUE && y==Long.MAX_VALUE && z==Long.MAX_VALUE)break; if(x<=y && x<=z){ ans=Math.min(ans,x); i++; } else if(y<=x && y<=z){ ans=Math.min(ans,y); j++; } else{ ans=Math.min(ans,z); k++; } } sb.append(ans+"\n"); } System.out.println(sb); } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
Java
["5\n2 2 3\n7 8\n6 3\n3 1 4\n1 1 1\n1\n1\n1000000000\n2 2 2\n1 2\n5 4\n6 7\n2 2 2\n1 2\n3 4\n6 7\n3 4 1\n3 2 1\n7 3 3 4\n6"]
3 seconds
["14\n1999999996000000002\n24\n24\n14"]
NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.
Java 8
standard input
[ "math", "implementation", "sortings", "data structures", "binary search" ]
79b58eb781cd73ccf7994866b9a8b695
The first line contains a single integer $$$t$$$ ($$$1\le t \le 100$$$)  — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (the sum for all test cases).
1,700
For each test case, print a line contains one integer  — the minimum value which Xenia wants to find.
standard output
PASSED
527a00af1dc3f9c48e73369be0ccd443
train_001.jsonl
1586961300
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?
256 megabytes
import java.util.*; public class xenia2{ public static void main(String[] args) { Scanner scan = new Scanner(System.in); int test = scan.nextInt(); while(test-->0){ int r = scan.nextInt(); int g = scan.nextInt(); int b = scan.nextInt(); long ra[] = new long[r]; long ga[] = new long[g]; long ba[] = new long[b]; for(int i=0;i<r;i++) ra[i] = scan.nextLong(); for(int i=0;i<g;i++) ga[i] = scan.nextLong(); for(int i=0;i<b;i++) ba[i] = scan.nextLong(); int ri = 0; int gi = 0; int bi = 0; Arrays.sort(ra); Arrays.sort(ga); Arrays.sort(ba); long sum = Long.MAX_VALUE; while(ri<r-1 || gi<g-1 || bi < b-1){ sum = Math.min(sum,f(ba[bi],ga[gi],ra[ri])); long val1 = Long.MAX_VALUE; long val2 = Long.MAX_VALUE; long val3 = Long.MAX_VALUE; if(ri < r-1){ val1 = Math.min(val1,f(ra[ri+1],ga[gi],ba[bi])); } if(gi < g-1){ val2 = Math.min(val2,f(ra[ri],ga[gi+1],ba[bi])); } if(bi < b-1){ val3 = Math.min(val3,f(ra[ri],ga[gi],ba[bi+1])); } if(val1 <= val2 && val1 <= val3){ ri++; } else if(val2 <= val3 && val2 <= val1){ gi++; } else{ bi++; } } sum = Math.min(sum,f(ra[ri],ba[bi],ga[gi])); System.out.println(sum); } } public static long f(long a,long b,long c){ long x = a-b; long y = b-c; long z = c-a; return x*x+y*y+z*z; } }
Java
["5\n2 2 3\n7 8\n6 3\n3 1 4\n1 1 1\n1\n1\n1000000000\n2 2 2\n1 2\n5 4\n6 7\n2 2 2\n1 2\n3 4\n6 7\n3 4 1\n3 2 1\n7 3 3 4\n6"]
3 seconds
["14\n1999999996000000002\n24\n24\n14"]
NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.
Java 8
standard input
[ "math", "implementation", "sortings", "data structures", "binary search" ]
79b58eb781cd73ccf7994866b9a8b695
The first line contains a single integer $$$t$$$ ($$$1\le t \le 100$$$)  — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (the sum for all test cases).
1,700
For each test case, print a line contains one integer  — the minimum value which Xenia wants to find.
standard output
PASSED
354406fd11c4f59427f8958cd1d220d3
train_001.jsonl
1586961300
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?
256 megabytes
//package CodeForces; import java.math.BigInteger; import java.util.Iterator; import java.util.Scanner; import java.util.TreeSet; public class Solution4 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); for (int t = 0; t < T; t++) { int nr = sc.nextInt(); int ng = sc.nextInt(); int nb = sc.nextInt(); TreeSet<Integer> ts1 = new TreeSet<>(); TreeSet<Integer> ts2 = new TreeSet<>(); TreeSet<Integer> ts3 = new TreeSet<>(); for (int i = 0; i < nr; i++) { ts1.add(sc.nextInt()); } for (int i = 0; i < ng; i++) { ts2.add(sc.nextInt()); } for (int i = 0; i < nb; i++) { ts3.add(sc.nextInt()); } BigInteger iter1 = solve(ts1, ts2, ts3); BigInteger iter2 = solve(ts2, ts3, ts1); BigInteger iter3 = solve(ts3, ts2, ts1); System.out.println(iter1.min(iter2).min(iter3)); } sc.close(); } private static BigInteger solve(TreeSet<Integer> ts1, TreeSet<Integer> ts2, TreeSet<Integer> ts3) { BigInteger min = null; Iterator<Integer> it = ts1.iterator(); while (it.hasNext()) { int num = it.next(); Integer y1 = ts2.ceiling(num); if (y1 == null) y1 = -1; Integer y2 = ts2.floor(num); if (y2 == null) y2 = -1; Integer z1 = ts3.ceiling(num); if (z1 == null) z1 = -1; Integer z2 = ts3.floor(num); if (z2 == null) z2 = -1; BigInteger b1, b2, b3, b4; if (y1 != -1 && z1 != -1) { b1 = sum(num, y1, z1); if (min == null) min = b1; else min = min.min(b1); } if (y1 != -1 && z2 != -1) { b2 = sum(num, y1, z2); if (min == null) min = b2; else min = min.min(b2); } if (y2 != -1 && z1 != -1) { b3 = sum(num, y2, z1); if (min == null) min = b3; else min = min.min(b3); } if (y2 != -1 && z2 != -1) { b4 = sum(num, y2, z2); if (min == null) min = b4; else min = min.min(b4); } } return min; } private static BigInteger sum(int x, int y, int z) { BigInteger b1 = new BigInteger(Math.abs(x - y) + ""); BigInteger b2 = new BigInteger(Math.abs(y - z) + ""); BigInteger b3 = new BigInteger(Math.abs(z - x) + ""); return b1.multiply(b1).add(b2.multiply(b2)).add(b3.multiply(b3)); } }
Java
["5\n2 2 3\n7 8\n6 3\n3 1 4\n1 1 1\n1\n1\n1000000000\n2 2 2\n1 2\n5 4\n6 7\n2 2 2\n1 2\n3 4\n6 7\n3 4 1\n3 2 1\n7 3 3 4\n6"]
3 seconds
["14\n1999999996000000002\n24\n24\n14"]
NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.
Java 8
standard input
[ "math", "implementation", "sortings", "data structures", "binary search" ]
79b58eb781cd73ccf7994866b9a8b695
The first line contains a single integer $$$t$$$ ($$$1\le t \le 100$$$)  — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (the sum for all test cases).
1,700
For each test case, print a line contains one integer  — the minimum value which Xenia wants to find.
standard output
PASSED
9ad64e0834ead38e269c11feca32b559
train_001.jsonl
1586961300
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?
256 megabytes
//ARNAV KUMAR MANDAL// //XYPHER// import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.text.DecimalFormat; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.io.*; public class Solution{ static long ans = Long.MAX_VALUE; //--------------------------MAIN---------------------------------------------------------------------// public static void main(String[] args) throws IOException { Reader a= new Reader(System.in); OutputWriter out = new OutputWriter(System.out); //Scanner a = new Scanner(System.in); int t= a.nextInt(); StringBuilder s = new StringBuilder(""); while(t-->0) { int n1 = a.nextInt(); int n2 = a.nextInt(); int n3 = a.nextInt(); long N1[] = new long[n1]; long N2[] = new long[n2]; long N3[] = new long[n3]; for(int i=0;i<n1;i++) N1[i] = a.nextLong(); for(int i=0;i<n2;i++) N2[i] = a.nextLong(); for(int i=0;i<n3;i++) N3[i] = a.nextLong(); Arrays.sort(N1);Arrays.sort(N2);Arrays.sort(N3); ans = Long.MAX_VALUE; fun(N1, N2, N3); fun(N2, N3, N1); fun(N3, N1, N2); s.append(ans+"\n"); } out.println(s); } private static void fun(long[] N1, long[] N2, long[] N3) { for(int i=0;i<N1.length;i++) { int pos2 = Arrays.binarySearch(N2, N1[i]); int pos3 = Arrays.binarySearch(N3, N1[i]); if(pos2<0) pos2 = -pos2 - 1; if(pos3<0) pos3 = -pos3 - 1; for(int j=pos2 - 1;j<=pos2 + 1;j++) { for(int k = pos3 - 1; k<= pos3 + 1;k++) { if(j < 0 || j >= N2.length || k < 0 || k >= N3.length)continue; else { long temp = (N1[i] - N2[j]) * (N1[i] - N2[j]) + (N2[j] - N3[k]) * (N2[j] - N3[k]) + (N3[k] - N1[i]) * (N3[k] - N1[i]); ans = Math.min(ans,temp); } } } } } //--------------------------FAST IO------------------------------------------------------------------// private static class Reader { private InputStream stream; private byte[] buf = new byte[4*1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public Reader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String nextString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } 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 long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return nextString(); } 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 println(Object... objects) { print(objects); writer.println(); writer.flush(); } 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 close() { writer.close(); } public void flush() { writer.flush(); } } }
Java
["5\n2 2 3\n7 8\n6 3\n3 1 4\n1 1 1\n1\n1\n1000000000\n2 2 2\n1 2\n5 4\n6 7\n2 2 2\n1 2\n3 4\n6 7\n3 4 1\n3 2 1\n7 3 3 4\n6"]
3 seconds
["14\n1999999996000000002\n24\n24\n14"]
NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.
Java 8
standard input
[ "math", "implementation", "sortings", "data structures", "binary search" ]
79b58eb781cd73ccf7994866b9a8b695
The first line contains a single integer $$$t$$$ ($$$1\le t \le 100$$$)  — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (the sum for all test cases).
1,700
For each test case, print a line contains one integer  — the minimum value which Xenia wants to find.
standard output
PASSED
152cf84fcc02f65564aebe618f07c061
train_001.jsonl
1586961300
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?
256 megabytes
import java.util.*; import java.io.*; public class Q3Div3 { static Long ans; private static void meth(TreeSet<Long> r,TreeSet<Long> b,TreeSet<Long> g) { Iterator<Long> iterator=b.iterator(); while (iterator.hasNext()) { Long val=iterator.next(); Long temp1=r.ceiling(val); Long temp2=g.floor(val); if(temp1!=null && temp2!=null) { ans=Math.min(ans, (val-temp1)*(val-temp1)+(temp2-val)*(temp2-val)+(temp2-temp1)*(temp2-temp1)); } } } public static void main(String args[]) throws Exception { Scan scan = new Scan(); Print print = new Print(); int T = scan.scanInt(); while (T-- > 0) { int N1=scan.scanInt(); int N2=scan.scanInt(); int N3=scan.scanInt(); TreeSet<Long> r=new TreeSet<Long>(); TreeSet<Long> b=new TreeSet<Long>(); TreeSet<Long> g=new TreeSet<Long>(); for(int i=0;i<N1;i++) { r.add(scan.scanLong()); } for(int i=0;i<N2;i++) { b.add(scan.scanLong()); } for(int i=0;i<N3;i++) { g.add(scan.scanLong()); } ans=Long.MAX_VALUE; meth(r, b, g); meth(b, r, g); meth(r, g, b); meth(g, b, r); meth(b, g, r); meth(g, r, b); print.println(ans); } print.close(); } static class Print { private final BufferedWriter bw; public Print() { this.bw = new BufferedWriter(new OutputStreamWriter(System.out)); } public void print(Object object) throws IOException { bw.append("" + object); } public void println(Object object) throws IOException { print(object); bw.append("\n"); } public void close() throws IOException { bw.close(); } } static class Scan { private byte[] buf = new byte[1024 * 1024]; private int index; private InputStream in; private int total; public Scan() { in = System.in; } public int scan() throws IOException { if (total < 0) throw new InputMismatchException(); if (index >= total) { index = 0; total = in.read(buf); if (total <= 0) return -1; } return buf[index++]; } public int scanInt() throws IOException { int integer = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { integer *= 10; integer += n - '0'; n = scan(); } else throw new InputMismatchException(); } return neg * integer; } public double scanDouble() throws IOException { double doub = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n) && n != '.') { if (n >= '0' && n <= '9') { doub *= 10; doub += n - '0'; n = scan(); } else throw new InputMismatchException(); } if (n == '.') { n = scan(); double temp = 1; while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { temp /= 10; doub += (n - '0') * temp; n = scan(); } else throw new InputMismatchException(); } } return doub * neg; } public long scanLong() throws IOException { long ret = 0; long c = scan(); while (c <= ' ') { c = scan(); } boolean neg = (c == '-'); if (neg) { c = scan(); } do { ret = ret * 10 + c - '0'; } while ((c = scan()) >= '0' && c <= '9'); if (neg) { return -ret; } return ret; } public String scanString() throws IOException { StringBuilder sb = new StringBuilder(); int n = scan(); while (isWhiteSpace(n)) n = scan(); while (!isWhiteSpace(n) || n == ' ') { sb.append((char) n); n = scan(); } return sb.toString(); } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; return false; } } }
Java
["5\n2 2 3\n7 8\n6 3\n3 1 4\n1 1 1\n1\n1\n1000000000\n2 2 2\n1 2\n5 4\n6 7\n2 2 2\n1 2\n3 4\n6 7\n3 4 1\n3 2 1\n7 3 3 4\n6"]
3 seconds
["14\n1999999996000000002\n24\n24\n14"]
NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.
Java 8
standard input
[ "math", "implementation", "sortings", "data structures", "binary search" ]
79b58eb781cd73ccf7994866b9a8b695
The first line contains a single integer $$$t$$$ ($$$1\le t \le 100$$$)  — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (the sum for all test cases).
1,700
For each test case, print a line contains one integer  — the minimum value which Xenia wants to find.
standard output
PASSED
f1c85a70af3b9538a8b9e493b988d5f2
train_001.jsonl
1586961300
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?
256 megabytes
import java.io.*; import java.util.*; public class CodeForce { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); while (t-- > 0) { String[] str = br.readLine().split(" "); int a = Integer.parseInt(str[0]); int b = Integer.parseInt(str[1]); int c = Integer.parseInt(str[2]); TreeSet<Long> r = new TreeSet<>(); TreeSet<Long> g = new TreeSet<>(); TreeSet<Long> bl = new TreeSet<>(); str = null; str = br.readLine().split(" "); for (int i = 0; i < a; i++) { r.add(Long.parseLong(str[i])); } str = null; str = br.readLine().split(" "); for (int i = 0; i < b; i++) { g.add(Long.parseLong(str[i])); } str = null; str = br.readLine().split(" "); for (int i = 0; i < c; i++) { bl.add(Long.parseLong(str[i])); } long min = Long.MAX_VALUE; long temp; long y, z; for (long x : r) { if (bl.floor(x) != null && g.ceiling(x) != null) { y = g.ceiling(x); z = bl.floor(x); temp = (x - y) * (x - y) + (y - z) * (y - z) + (z - x) * (z - x); min = Math.min(min, temp); //System.out.println(x+" "+y+" "+z+" "+min); } if (bl.ceiling(x) != null && g.floor(x) != null) { y = g.floor(x); z = bl.ceiling(x); temp = (x - y) * (x - y) + (y - z) * (y - z) + (z - x) * (z - x); min = Math.min(min, temp); //System.out.println(x+" "+y+" "+z+" "+min); } } for (long x : g) { if (r.floor(x) != null && bl.ceiling(x) != null) { y = r.floor(x); z = bl.ceiling(x); temp = (x - y) * (x - y) + (y - z) * (y - z) + (z - x) * (z - x); min = Math.min(min, temp); } if (r.ceiling(x) != null && bl.floor(x) != null) { y = r.ceiling(x); z = bl.floor(x); temp = (x - y) * (x - y) + (y - z) * (y - z) + (z - x) * (z - x); min = Math.min(min, temp); } } for (long x : bl) { if (r.floor(x) != null && g.ceiling(x) != null) { z = g.ceiling(x); y = r.floor(x); temp = (x - y) * (x - y) + (y - z) * (y - z) + (z - x) * (z - x); min = Math.min(min, temp); } if (r.ceiling(x) != null && g.floor(x) != null) { z = g.floor(x); y = r.ceiling(x); temp = (x - y) * (x - y) + (y - z) * (y - z) + (z - x) * (z - x); min = Math.min(min, temp); } } System.out.println(min); } } }
Java
["5\n2 2 3\n7 8\n6 3\n3 1 4\n1 1 1\n1\n1\n1000000000\n2 2 2\n1 2\n5 4\n6 7\n2 2 2\n1 2\n3 4\n6 7\n3 4 1\n3 2 1\n7 3 3 4\n6"]
3 seconds
["14\n1999999996000000002\n24\n24\n14"]
NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.
Java 8
standard input
[ "math", "implementation", "sortings", "data structures", "binary search" ]
79b58eb781cd73ccf7994866b9a8b695
The first line contains a single integer $$$t$$$ ($$$1\le t \le 100$$$)  — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (the sum for all test cases).
1,700
For each test case, print a line contains one integer  — the minimum value which Xenia wants to find.
standard output
PASSED
cefb5e0ca3ecc6783a439f60b2e48f41
train_001.jsonl
1586961300
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?
256 megabytes
import java.io.*; import java.math.*; import java.util.*; import java.lang.*; 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(); } long modPow(long a, long p, long m) { if (a == 1) return 1; long ans = 1; while (p > 0) { if (p % 2 == 1) ans = (ans * a) % m; a = (a * a) % m; p >>= 1; } return ans; } long modInv(long a, long m) { return modPow(a, m - 2, m); } PrintWriter out; InputReader sc; public void run() { sc = new InputReader(System.in); // Scanner sc=new Scanner(System.in); // Random sc=new Random(); out = new PrintWriter(System.out); int t=sc.nextInt(); while (t-->0){ int n=sc.nextInt(); int m=sc.nextInt(); int k=sc.nextInt(); long a[]=new long[n]; for (int i = 0; i <n ; i++) { a[i]=sc.nextInt(); } long b[]=new long[m]; TreeSet<Long> hb=new TreeSet<>(); for (int i = 0; i <m ; i++) { b[i]=sc.nextInt(); hb.add(b[i]); } long c[]=new long[k]; TreeSet<Long> hc=new TreeSet<>(); for (int i = 0; i <k ; i++) { c[i]=sc.nextInt(); hc.add(c[i]); } long ans=Long.MAX_VALUE; for (int i = 0; i <n ; i++) { Long bigB=hb.ceiling(a[i]); Long bigC=hc.ceiling(a[i]); if(bigB!=null && bigC!=null){ if(bigB>=bigC){ Long mid=a[i]+(bigB-a[i])/2; if(hc.floor(mid)!=null)ans=Math.min(ans,f(a[i],hc.floor(mid),bigB)); if(hc.ceiling(mid)!=null)ans=Math.min(ans,f(a[i],hc.ceiling(mid),bigB)); } else{ Long mid=a[i]+(bigC-a[i])/2; if(hb.floor(mid)!=null)ans=Math.min(ans,f(a[i],hb.floor(mid),bigC)); if(hb.ceiling(mid)!=null)ans=Math.min(ans,f(a[i],hb.ceiling(mid),bigC)); } } Long smallB=hb.floor(a[i]); Long smallC=hc.floor(a[i]); if(smallB!=null && smallC!=null){ if(smallB<=smallC){ Long mid=smallB+(a[i]-smallB)/2; if(hc.floor(mid)!=null)ans=Math.min(ans,f(a[i],hc.floor(mid),smallB)); if(hc.ceiling(mid)!=null)ans=Math.min(ans,f(a[i],hc.ceiling(mid),smallB)); } else{ Long mid=smallC+(a[i]-smallC)/2; if(hb.floor(mid)!=null)ans=Math.min(ans,f(a[i],hb.floor(mid),smallC)); if(hb.ceiling(mid)!=null)ans=Math.min(ans,f(a[i],hb.ceiling(mid),smallC)); } } if(bigB!=null && smallC!=null){ ans=Math.min(ans,f(a[i],bigB,smallC)); } if(smallB!=null && bigC!=null){ ans=Math.min(ans,f(a[i],smallB,bigC)); } } out.println(ans); } out.close(); } long f(long a,long b,long c){ long ans=0; ans+=(a-b)*(a-b); ans+=(a-c)*(a-c); ans+=(b-c)*(b-c); return ans; } }
Java
["5\n2 2 3\n7 8\n6 3\n3 1 4\n1 1 1\n1\n1\n1000000000\n2 2 2\n1 2\n5 4\n6 7\n2 2 2\n1 2\n3 4\n6 7\n3 4 1\n3 2 1\n7 3 3 4\n6"]
3 seconds
["14\n1999999996000000002\n24\n24\n14"]
NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.
Java 8
standard input
[ "math", "implementation", "sortings", "data structures", "binary search" ]
79b58eb781cd73ccf7994866b9a8b695
The first line contains a single integer $$$t$$$ ($$$1\le t \le 100$$$)  — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (the sum for all test cases).
1,700
For each test case, print a line contains one integer  — the minimum value which Xenia wants to find.
standard output
PASSED
58e765f3b24f6ed05d3a617630963836
train_001.jsonl
1586961300
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); StringBuilder ans = new StringBuilder(); int t = sc.nextInt(); while (t-- > 0) { int nr = sc.nextInt(); int ng = sc.nextInt(); int nb = sc.nextInt(); List<Integer> r = new ArrayList<>(); List<Integer> g = new ArrayList<>(); List<Integer> b = new ArrayList<>(); for (int i = 0; i < nr; i++) { r.add(sc.nextInt()); } for (int i = 0; i < ng; i++) { g.add(sc.nextInt()); } for (int i = 0; i < nb; i++) { b.add(sc.nextInt()); } Collections.sort(r); Collections.sort(g); Collections.sort(b); long min = Long.MAX_VALUE; min = Math.min(min,solve(r,g,b)); min = Math.min(min,solve(r,b,g)); min = Math.min(min,solve(g,b,r)); min = Math.min(min,solve(g,r,b)); min = Math.min(min,solve(b,r,g)); min = Math.min(min,solve(b,g,r)); ans.append(min).append('\n'); } System.out.print(ans); } private static long solve(List<Integer> l, List<Integer> m, List<Integer> r) { long ret = Long.MAX_VALUE; for (long mm : m) { long ll = findLeft(l, mm); long rr = findRight(r, mm); if (ll == -1 || rr == -1) continue; ret = Math.min(ret, (mm-ll)*(mm-ll)+(ll-rr)*(ll-rr)+(rr-mm)*(rr-mm)); } return ret; } private static int findLeft(List<Integer> list, long key) { if (key < list.get(0)) { return -1; } if (list.get(list.size()-1) <= key) { return list.get(list.size()-1); } int ok = 0; int ng = list.size()-1; while (ok+1 < ng) { int mid = (ok+ng)/2; if (list.get(mid) <= key) { ok = mid; } else { ng = mid; } } return list.get(ok); } private static int findRight(List<Integer> list, long key) { if (key <= list.get(0)) { return list.get(0); } if (list.get(list.size()-1) < key) { return -1; } int ng = 0; int ok = list.size()-1; while (ng+1 < ok) { int mid = (ok+ng)/2; if (key <= list.get(mid) ) { ok = mid; } else { ng = mid; } } return list.get(ok); } }
Java
["5\n2 2 3\n7 8\n6 3\n3 1 4\n1 1 1\n1\n1\n1000000000\n2 2 2\n1 2\n5 4\n6 7\n2 2 2\n1 2\n3 4\n6 7\n3 4 1\n3 2 1\n7 3 3 4\n6"]
3 seconds
["14\n1999999996000000002\n24\n24\n14"]
NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.
Java 8
standard input
[ "math", "implementation", "sortings", "data structures", "binary search" ]
79b58eb781cd73ccf7994866b9a8b695
The first line contains a single integer $$$t$$$ ($$$1\le t \le 100$$$)  — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (the sum for all test cases).
1,700
For each test case, print a line contains one integer  — the minimum value which Xenia wants to find.
standard output
PASSED
594f95602f7ef22b999f6bb141e8bfeb
train_001.jsonl
1586961300
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?
256 megabytes
import java.util.*; import java.io.*; public class gems{ public static void main(String[] main) throws Exception{ BufferedReader b = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(b.readLine()); int t = Integer.parseInt(st.nextToken()); for(int trial = 1; trial <= t; trial++){ st = new StringTokenizer(b.readLine()); int r = Integer.parseInt(st.nextToken()), g = Integer.parseInt(st.nextToken()), bl = Integer.parseInt(st.nextToken()); long[] red = new long[r], green = new long[g], blue = new long[bl]; st = new StringTokenizer(b.readLine()); for(int i = 0; i < r; i++) red[i] = Integer.parseInt(st.nextToken()); Arrays.sort(red); st = new StringTokenizer(b.readLine()); for(int i = 0; i < g; i++) green[i] = Integer.parseInt(st.nextToken()); Arrays.sort(green); st = new StringTokenizer(b.readLine()); for(int i = 0; i < bl; i++) blue[i] = Integer.parseInt(st.nextToken()); Arrays.sort(blue); int i = 0, j = 0, k = 0; long [][] closest = new long[r][4]; long[] arr = new long[r + g]; while (i < r && j < g) { if (red[i] <= green[j]) { if(j == 0) closest[i][0] = -1; else closest[i][0] = green[j-1]; closest[i][1] = green[j]; arr[k] = red[i]; i++; } else { arr[k] = green[j]; j++; } k++; } while (i < r) { closest[i][0] = green[j-1]; closest[i][1] = -1; i++; } i = 0; j = 0; k = 0; arr = new long[r + bl]; while (i < r && j < bl) { if (red[i] <= blue[j]) { if(j == 0) closest[i][2] = -1; else closest[i][2] = blue[j-1]; closest[i][3] = blue[j]; arr[k] = red[i]; i++; } else { arr[k] = blue[j]; j++; } k++; } while (i < r) { closest[i][2] = blue[j-1]; closest[i][3] = -1; i++; } /*for( i = 0; i < r; i++) System.out.print(red[i] + " "); System.out.println(); for( i = 0; i < g; i++) System.out.print(green[i] + " "); System.out.println(); for( i = 0; i < bl; i++) System.out.print(blue[i] + " "); System.out.println(); for(i = 0; i < r; i++) System.out.println(i + " " + closest[i][0] + " " + closest[i][1] + " " + closest[i][2] + " " + closest[i][3]);*/ long min = Long.MAX_VALUE; for(i = 0; i < r; i++){ if(closest[i][0] != -1){ if(closest[i][3] != -1){ min = Math.min(eval(red[i],closest[i][0],closest[i][3]),min); } if(closest[i][2] != -1){ if(closest[i][2] > closest[i][0] && closest[i][2] * 2 > closest[i][0] + red[i]){ int temp = binarySearch(blue,0,bl-1,(closest[i][0] + red[i] + 0.0)/2); min = Math.min(eval(red[i],closest[i][0],blue[temp]),min); } else if(closest[i][0] > closest[i][2] && closest[i][0] * 2 > closest[i][2] + red[i]){ int temp = binarySearch(green,0,g-1,(closest[i][2] + red[i] + 0.0)/2); min = Math.min(eval(red[i],closest[i][2],green[temp]),min); } else min = Math.min(eval(red[i],closest[i][0],closest[i][2]),min); } } if(closest[i][1] != -1){ if(closest[i][2] != -1) min = Math.min(eval(red[i],closest[i][1],closest[i][2]),min); if(closest[i][3] != -1){ if(closest[i][3] < closest[i][1] && closest[i][3] * 2 < closest[i][1] + red[i]){ int temp = binarySearch(blue,0,bl-1,(closest[i][1] + red[i] + 0.0)/2); min = Math.min(eval(red[i],closest[i][1],blue[temp]),min); } else if(closest[i][1] < closest[i][3] && closest[i][1] * 2 < closest[i][3] + red[i]){ int temp = binarySearch(green,0,g-1,(closest[i][3] + red[i] + 0.0)/2); //System.out.println(green[temp]); min = Math.min(eval(red[i],closest[i][3],green[temp]),min); } else min = Math.min(eval(red[i],closest[i][1],closest[i][3]),min); } } } System.out.println(min); } } public static long eval(long x, long y, long z){ return (x - y)*(x-y) + (y-z)*(y-z) + (z-x)*(z-x); } public static int binarySearch(long arr[], int l, int r, double x) { if(r == l+1){ if((arr[r] -x)*(arr[r]-x) > (arr[l]-x)*(arr[l]-x)) return l; else return r; } if(r == l){ return r; } if (r >= l) { int mid = l + (r - l) / 2; // If the element is present at the // middle itself if ((double)arr[mid] == x) return mid; // If element is smaller than mid, then // it can only be present in left subarray if (arr[mid] > x) return binarySearch(arr, l, mid , x); // Else the element can only be present // in right subarray return binarySearch(arr, mid , r, x); } // We reach here when element is not present // in array return 0; } }
Java
["5\n2 2 3\n7 8\n6 3\n3 1 4\n1 1 1\n1\n1\n1000000000\n2 2 2\n1 2\n5 4\n6 7\n2 2 2\n1 2\n3 4\n6 7\n3 4 1\n3 2 1\n7 3 3 4\n6"]
3 seconds
["14\n1999999996000000002\n24\n24\n14"]
NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.
Java 8
standard input
[ "math", "implementation", "sortings", "data structures", "binary search" ]
79b58eb781cd73ccf7994866b9a8b695
The first line contains a single integer $$$t$$$ ($$$1\le t \le 100$$$)  — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (the sum for all test cases).
1,700
For each test case, print a line contains one integer  — the minimum value which Xenia wants to find.
standard output
PASSED
fed6c1d638bcc434cfb42b3e8cc8339a
train_001.jsonl
1586961300
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?
256 megabytes
//import com.sun.org.apache.xpath.internal.operations.String; //import com.sun.org.apache.xpath.internal.operations.String; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.util.*; import java.util.concurrent.LinkedBlockingDeque; public class scratch_25 { // int count=0; //static long count=0; static class Reader { static BufferedReader reader; static StringTokenizer tokenizer; /** * call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } /** * get next word */ static String next() throws IOException { while (!tokenizer.hasMoreTokens()) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine()); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } } public static class Graph{ public static class Vertex{ HashMap<Integer,Integer> nb= new HashMap<>(); // for neighbours of each vertex } public static HashMap<Integer,Vertex> vt; // for vertices(all) public Graph(){ vt= new HashMap<>(); } public static int numVer(){ return vt.size(); } public static boolean contVer(int ver){ return vt.containsKey(ver); } public static void addVer(int ver){ Vertex v= new Vertex(); vt.put(ver,v); } public static int numEdg(){ int count=0; ArrayList<Integer> vrtc= new ArrayList<>(vt.keySet()); for (int i = 0; i <vrtc.size() ; i++) { count+=(vt.get(vrtc.get(i))).nb.size(); } return count/2; } public static boolean contEdg(int ver1, int ver2){ if(vt.get(ver1)==null || vt.get(ver2)==null){ return false; } Vertex v= vt.get(ver1); if(v.nb.containsKey(ver2)){ return true; } return false; } public static void addEdge(int ver1, int ver2, int weight){ if(!vt.containsKey(ver1) || !vt.containsKey(ver2)){ return; } Vertex v1= vt.get(ver1); Vertex v2= vt.get(ver2); v1.nb.put(ver2,weight); // if previously there is an edge, then this replaces that edge v2.nb.put(ver1,weight); } public static void delEdge(int ver1, int ver2){ if(!vt.containsKey(ver1) || !vt.containsKey(ver2)){ return; } vt.get(ver1).nb.remove(ver2); vt.get(ver2).nb.remove(ver1); } public static void delVer(int ver){ if(!vt.containsKey(ver)){ return; } Vertex v1= vt.get(ver); ArrayList<Integer> arr= new ArrayList<>(v1.nb.keySet()); for (int i = 0; i <arr.size() ; i++) { int s= arr.get(i); vt.get(s).nb.remove(ver); } vt.remove(ver); } public class Pair{ int vname; ArrayList<Integer> psf= new ArrayList<>(); // path so far int dis; int col; } public HashMap<Integer,Integer> bfs(int src){ HashMap<Integer, Boolean> prcd= new HashMap<>(); // jo jo ho chuke hain unke liye HashMap<Integer, Integer> ans= new HashMap<>(); LinkedList<Pair> queue= new LinkedList<>(); // for bfs queue Pair strtp= new Pair(); strtp.vname= src; ArrayList<Integer> ar= new ArrayList<>(); ar.add(src); strtp.psf= ar; strtp.dis=0; queue.addLast(strtp); while(!queue.isEmpty()){ Pair rp = queue.removeFirst(); if(prcd.containsKey(rp.vname)){ continue; } prcd.put(rp.vname,true); ans.put(rp.vname,rp.dis); // if(contEdg(rp.vname,dst)){ // return true; // } Vertex a= vt.get(rp.vname); ArrayList<Integer> arr= new ArrayList<>(a.nb.keySet()); for (int i = 0; i <arr.size() ; i++) { int s= arr.get(i); if(!prcd.containsKey(s)){ Pair np = new Pair(); np.vname= s; np.dis+=rp.dis+a.nb.get(s); np.psf.addAll(rp.psf); np.psf.add(s); // np.psf.add(s); // np.psf= rp.psf+" "+s; queue.addLast(np); } } } return ans; // return false; } public HashMap<Integer,Integer> dfs(int src){ HashMap<Integer, Boolean> prcd= new HashMap<>(); // jo jo ho chuke hain unke liye HashMap<Integer, Integer> ans= new HashMap<>(); LinkedList<Pair> stack= new LinkedList<>(); // for bfs queue Pair strtp= new Pair(); strtp.vname= src; ArrayList<Integer> ar= new ArrayList<>(); ar.add(src); strtp.psf= ar; strtp.dis=0; stack.addFirst(strtp); while(!stack.isEmpty()){ Pair rp = stack.removeFirst(); if(prcd.containsKey(rp.vname)){ continue; } prcd.put(rp.vname,true); ans.put(rp.vname,rp.dis); // if(contEdg(rp.vname,dst)){ // return true; // } Vertex a= vt.get(rp.vname); ArrayList<Integer> arr= new ArrayList<>(a.nb.keySet()); for (int i = 0; i <arr.size() ; i++) { int s= arr.get(i); if(!prcd.containsKey(s)){ Pair np = new Pair(); np.vname= s; np.dis+=rp.dis+a.nb.get(s); np.psf.addAll(rp.psf); np.psf.add(s); // np.psf.add(s); // np.psf= rp.psf+" "+s; stack.addFirst(np); } } } return ans; // return false; } public boolean isCycle(){ HashMap<Integer, Boolean> prcd= new HashMap<>(); // jo jo ho chuke hain unke liye // HashMap<Integer, Integer> ans= new HashMap<>(); LinkedList<Pair> queue= new LinkedList<>(); // for bfs queue ArrayList<Integer> keys = new ArrayList<>(vt.keySet()); for (int i = 0; i <keys.size(); i++) { int cur= keys.get(i); if(prcd.containsKey(cur)){ continue; } Pair sp = new Pair(); sp.vname= cur; ArrayList<Integer> as= new ArrayList<>(); as.add(cur); sp.psf= as; queue.addLast(sp); while(!queue.isEmpty()){ Pair rp= queue.removeFirst(); if(prcd.containsKey(rp.vname)){ return true; } prcd.put(rp.vname,true); Vertex v1= vt.get(rp.vname); ArrayList<Integer> nbrs= new ArrayList<>(v1.nb.keySet()); for (int j = 0; j <nbrs.size() ; j++) { int u= nbrs.get(j); Pair np= new Pair(); np.vname= u; queue.addLast(np); } } } return false; } public ArrayList<ArrayList<Integer>> genConnctdComp(){ HashMap<Integer, Boolean> prcd= new HashMap<>(); // jo jo ho chuke hain unke liye ArrayList<ArrayList<Integer>> ans= new ArrayList<>(); // HashMap<Integer, Integer> ans= new HashMap<>(); LinkedList<Pair> queue= new LinkedList<>(); // for bfs queue // int con=-1; ArrayList<Integer> keys = new ArrayList<>(vt.keySet()); for (int i = 0; i <keys.size(); i++) { int cur= keys.get(i); if(prcd.containsKey(cur)){ //return true; continue; } int count=0; ArrayList<Integer> fu= new ArrayList<>(); fu.add(cur); Pair sp = new Pair(); sp.vname= cur; ArrayList<Integer> as= new ArrayList<>(); as.add(cur); sp.psf= as; queue.addLast(sp); while(!queue.isEmpty()){ Pair rp= queue.removeFirst(); if(prcd.containsKey(rp.vname)){ //return true; continue; } prcd.put(rp.vname,true); fu.add(rp.vname); Vertex v1= vt.get(rp.vname); ArrayList<Integer> nbrs= new ArrayList<>(v1.nb.keySet()); for (int j = 0; j <nbrs.size() ; j++) { int u= nbrs.get(j); if(!prcd.containsKey(u)){ count++; Pair np= new Pair(); np.vname= u; queue.addLast(np); } }} fu.add(count); ans.add(fu); } //return false; return ans; } public boolean isBip(int src){ // only for connected graph HashMap<Integer,Integer> clr= new HashMap<>(); // colors are 1 and -1 LinkedList<Integer>q = new LinkedList<Integer>(); clr.put(src,1); q.add(src); while(!q.isEmpty()){ int u = q.getFirst(); q.pop(); ArrayList<Integer> arr= new ArrayList<>(vt.keySet()); for (int i = 0; i <arr.size() ; ++i) { int x= arr.get(i); if(vt.get(u).nb.containsKey(x) && !clr.containsKey(x)){ if(clr.get(u)==1){ clr.put(x,-1); } else{ clr.put(x,1); } q.push(x); } else if(vt.get(u).nb.containsKey(x) && (clr.get(x).equals(clr.get(u)))){ return false; } } } return true; } public static void printGr() { ArrayList<Integer> arr= new ArrayList<>(vt.keySet()); for (int i = 0; i <arr.size() ; i++) { int ver= arr.get(i); Vertex v1= vt.get(ver); ArrayList<Integer> arr1= new ArrayList<>(v1.nb.keySet()); for (int j = 0; j <arr1.size() ; j++) { System.out.println(ver+"-"+arr1.get(j)+":"+v1.nb.get(arr1.get(j))); } } } } static class Cus implements Comparable<Cus>{ int size; int mon; int num; public Cus(int size,int mon,int num){ this.size=size; this.mon=mon; this.num=num; } @Override public int compareTo(Cus o){ if(this.mon!=o.mon){ return this.mon-o.mon;} else{ return o.size-this.size; } } } static class Lamp implements Comparable<Lamp>{ long start ; // int cum; long end; public Lamp(long start,long end){ this.start=start; // this.cum=cum; this.end=end; } @Override public int compareTo(Lamp o){ return (int)this.start-(int)o.start; } } static class Event implements Comparable<Event>{ int value; int dist; public Event(int value,int dist){ this.value=value; this.dist= dist; } @Override public int compareTo(Event o){ if(this.dist!=o.dist){ return this.dist-o.dist;} else{ return this.value-o.value; } // return (int)this.state-(int)o.state; } } static class Pair implements Comparable<Pair>{ int x; //int cum; int y; public Pair(int x,int y){ this.x=x; // this.cum=cum; this.y=y; } @Override public int compareTo(Pair o){ return this.x-o.x; } @Override public boolean equals(Object me) { Pair binMe = (Pair)me; if(this.x==binMe.x && this.y==binMe.y) return true; else return false; } @Override public int hashCode() { return this.x + this.y; } @Override public String toString() { return x+" "+y; } } public static class DisjointSet{ HashMap<Integer,Node> mp= new HashMap<>(); public static class Node{ int data; Node parent; int rank; } public void create(int val){ Node nn= new Node(); nn.data=val; nn.parent=nn; nn.rank=0; mp.put(val,nn); } public int find(int val){ return findn(mp.get(val)).data; } public Node findn(Node n){ if(n==n.parent){ return n; } Node rr= findn(n.parent); n.parent=rr; return rr; } public void union(int val1, int val2){ // can also be used to check cycles Node n1= findn(mp.get(val1)); Node n2= findn(mp.get(val2)); if(n1.data==n2.data) { return; } if(n1.rank<n2.rank){ n1.parent=n2; } else if(n2.rank<n1.rank){ n2.parent=n1; } else { n2.parent=n1; n1.rank++; } } } public static void main(String[] args) throws IOException { Reader.init(System.in); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); int t= Reader.nextInt(); for (int tt = 0; tt <t ; tt++) { int r= Reader.nextInt(); int g= Reader.nextInt(); int b= Reader.nextInt(); ArrayList<Long>red= new ArrayList<>(); ArrayList<Long>green= new ArrayList<>(); ArrayList<Long>blue= new ArrayList<>(); // red.add((long)(1000000000+1)); // red.add((long)(-1*(1000000000+1))); // blue.add((long)(1000000000+1)); // blue.add((long)(-1*(1000000000+1))); // green.add((long)(1000000000+1)); // green.add((long)(-1*(1000000000+1))); for (int i = 0; i <r ; i++) { red.add(Reader.nextLong()); } Collections.sort(red); for (int i = 0; i <g ; i++) { green.add(Reader.nextLong()); } Collections.sort(green); for (int i = 0; i <b ; i++) { blue.add(Reader.nextLong()); } Collections.sort(blue); // System.out.println("red="+red); // System.out.println("green="+green); // System.out.println("blue="+blue); long min= Long.MAX_VALUE; for (int i = 0; i <r ; i++) { // System.out.println(min); long x= red.get(i); // System.out.print("x="+x+" "); int i1= Collections.binarySearch(green,x); int i2= Collections.binarySearch(blue,x); if(i1<0){ i1=-1*i1-1; } if(i2<0){ i2=-1*i2-1; } long a1=green.get(Math.min(i1,g-1)); long a2=green.get(Math.max(i1-1,0)); long a3=blue.get(Math.min(i2,b-1)); long a4=blue.get(Math.max(i2-1,0)); //System.out.print("a1= "+a1+" a2= "+a2+" a3= "+a3+" a4= "+a4); long v1= (x-a1)*(x-a1) + (a1-a3)*(a1-a3) + (x-a3)*(x-a3); long v2= (x-a1)*(x-a1) + (a1-a4)*(a1-a4) + (x-a4)*(x-a4); long v3= (x-a2)*(x-a2) + (a2-a3)*(a2-a3) + (x-a3)*(x-a3); long v4= (x-a2)*(x-a2) + (a2-a4)*(a2-a4) + (x-a4)*(x-a4); long m1= Math.min(v1,v2); long m2= Math.min(m1,v3); long m3= Math.min(m2,v4); min= Math.min(min,m3); // System.out.println("min="+min); } for (int i = 0; i <b ; i++) { long x= blue.get(i); // System.out.print("x="+x+" "); int i1= Collections.binarySearch(green,x); int i2= Collections.binarySearch(red,x); if(i1<0){ i1=-1*i1-1; } if(i2<0){ i2=-1*i2-1; } long a1=green.get(Math.min(i1,g-1)); long a2=green.get(Math.max(i1-1,0)); long a3=red.get(Math.min(i2,r-1)); long a4=red.get(Math.max(i2-1,0)); // System.out.print("a1= "+a1+" a2= "+a2+" a3= "+a3+" a4= "+a4); long v1= (x-a1)*(x-a1) + (a1-a3)*(a1-a3) + (x-a3)*(x-a3); long v2= (x-a1)*(x-a1) + (a1-a4)*(a1-a4) + (x-a4)*(x-a4); long v3= (x-a2)*(x-a2) + (a2-a3)*(a2-a3) + (x-a3)*(x-a3); long v4= (x-a2)*(x-a2) + (a2-a4)*(a2-a4) + (x-a4)*(x-a4); long m1= Math.min(v1,v2); long m2= Math.min(m1,v3); long m3= Math.min(m2,v4); min= Math.min(min,m3); //System.out.println("min="+min); } for (int i = 0; i <g ; i++) { long x= green.get(i); // System.out.print("x="); int i1= Collections.binarySearch(red,x); int i2= Collections.binarySearch(blue,x); if(i1<0){ i1=-1*i1-1; } if(i2<0){ i2=-1*i2-1; } long a1=red.get(Math.min(i1,r-1)); long a2=red.get(Math.max(i1-1,0)); long a3=blue.get(Math.min(i2,b-1)); long a4=blue.get(Math.max(i2-1,0)); long v1= (x-a1)*(x-a1) + (a1-a3)*(a1-a3) + (x-a3)*(x-a3); long v2= (x-a1)*(x-a1) + (a1-a4)*(a1-a4) + (x-a4)*(x-a4); long v3= (x-a2)*(x-a2) + (a2-a3)*(a2-a3) + (x-a3)*(x-a3); long v4= (x-a2)*(x-a2) + (a2-a4)*(a2-a4) + (x-a4)*(x-a4); long m1= Math.min(v1,v2); long m2= Math.min(m1,v3); long m3= Math.min(m2,v4); min= Math.min(min,m3); // System.out.println("min="+min); } System.out.println(min); } } // out.flush(); // out.close(); static long power( long x, long y, long p) { // Initialize result long res = 1; // Update x if it is more // than or equal to p x = x % p; if (x == 0) return 0; // In case x is divisible by p; while (y > 0) { // If y is odd, multiply x // with result if((y & 1)==1) res = (res * x) % p; // y must be even now // y = y / 2 y = y >> 1; x = (x * x) % p; } return res; } public static long ceil_div(long a, long b){ return (a+b-1)/b; } static int countDivisibles(int A, int B, int M) { // Add 1 explicitly as A is divisible by M if (A % M == 0) return (B / M) - (A / M) + 1; // A is not divisible by M return (B / M) - (A / M); } public static void df(int x, int y,int n, int m, char[][]ar, int l){ boolean done[][]= new boolean[n][m]; int count=0; LinkedList<int[]> stk= new LinkedList<>(); int a[]= {x,y}; stk.addFirst(a); while(!stk.isEmpty() && count<l){ // count++; int b[]=stk.removeFirst(); if( done[b[0]][b[1]]){ continue; } count++; done[b[0]][b[1]]=true; ar[b[0]][b[1]]='@'; int arr[][]={{1,0},{-1,0},{0,1},{0,-1}}; for (int i = 0; i <arr.length ; i++) { if(!(b[0]+arr[i][0]>=n || b[1]+arr[i][1]>=m || b[0]+arr[i][0]<0 || b[1]+arr[i][1]<0 || ar[b[0]+arr[i][0]][b[1]+arr[i][1]]=='#')){ int r[]= {b[0]+arr[i][0], b[1]+arr[i][1]}; stk.addFirst(r); // continue; } }} for (int i = 0; i <n ; i++) { for (int j = 0; j <m ; j++) { if(ar[i][j]=='.'){ System.out.print('X'); } else if(ar[i][j]=='@'){ System.out.print('.'); } else{ System.out.print(ar[i][j]); } } System.out.println(); } } static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } static long gcd1(long a, long b) { // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater //count++; if (a > b){ return gcd(a-b, b); } return gcd(a, b-a); } // method to return LCM of two numbers static long lcm(long a, long b) { return (a*b)/gcd(a, b); } // Driver method static int partition(long arr[],long arr1[], int low, int high) { long pivot = arr[high]; int i = (low-1); // index of smaller element for (int j=low; j<high; j++) { // If current element is smaller than the pivot if (arr[j] < pivot) { i++; // swap arr[i] and arr[j] long temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; long temp1=arr1[i]; arr1[i]=arr1[j]; arr1[j]=temp1; } } // swap arr[i+1] and arr[high] (or pivot) long temp = arr[i+1]; arr[i+1] = arr[high]; arr[high] = temp; long temp1= arr1[i+1]; arr1[i+1]=arr1[high]; arr1[high]= temp1; return i+1; } /* The main function that implements QuickSort() arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */ static void sort(long arr[],long arr1[], int low, int high) { if (low < high) { /* pi is partitioning index, arr[pi] is now at right place */ int pi = partition(arr,arr1, low, high); // Recursively sort elements before // partition and after partition sort(arr,arr1, low, pi-1); sort(arr,arr1, pi+1, high); } } public static ArrayList<Integer> Sieve(int n) { boolean arr[]= new boolean [n+1]; Arrays.fill(arr,true); arr[0]=false; arr[1]=false; for (int i = 2; i*i <=n ; i++) { if(arr[i]){ for (int j = 2; j <=n/i ; j++) { int u= i*j; arr[u]=false; }} } ArrayList<Integer> ans= new ArrayList<>(); for (int i = 0; i <n+1 ; i++) { if(arr[i]){ ans.add(i); } } return ans; } }
Java
["5\n2 2 3\n7 8\n6 3\n3 1 4\n1 1 1\n1\n1\n1000000000\n2 2 2\n1 2\n5 4\n6 7\n2 2 2\n1 2\n3 4\n6 7\n3 4 1\n3 2 1\n7 3 3 4\n6"]
3 seconds
["14\n1999999996000000002\n24\n24\n14"]
NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.
Java 8
standard input
[ "math", "implementation", "sortings", "data structures", "binary search" ]
79b58eb781cd73ccf7994866b9a8b695
The first line contains a single integer $$$t$$$ ($$$1\le t \le 100$$$)  — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (the sum for all test cases).
1,700
For each test case, print a line contains one integer  — the minimum value which Xenia wants to find.
standard output
PASSED
40b17529308ceea5a42d463d389b6a0d
train_001.jsonl
1586961300
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?
256 megabytes
// package Div2635; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.StringTokenizer; public class ProblemD { public static void main(String[] args)throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int test=Integer.parseInt(br.readLine()); StringBuilder print=new StringBuilder(); while(test--!=0){ StringTokenizer st=new StringTokenizer(br.readLine()); int a=Integer.parseInt(st.nextToken()); int b=Integer.parseInt(st.nextToken()); int c=Integer.parseInt(st.nextToken()); ArrayList<Integer> r=new ArrayList<>(); ArrayList<Integer> g=new ArrayList<>(); ArrayList<Integer> y=new ArrayList<>(); st=new StringTokenizer(br.readLine()); for(int i=0;i<a;i++){ r.add(Integer.parseInt(st.nextToken())); } st=new StringTokenizer(br.readLine()); for(int i=0;i<b;i++){ g.add(Integer.parseInt(st.nextToken())); } st=new StringTokenizer(br.readLine()); for(int i=0;i<c;i++){ y.add(Integer.parseInt(st.nextToken())); } Collections.sort(r); Collections.sort(g); Collections.sort(y); long ans=Long.MAX_VALUE; for(int i=0;i<a;i++){ int bet=r.get(i); int left=findLower(g,bet); int right=findHigher(y,bet); if(left!=0&&right!=Integer.MAX_VALUE){ long temp=getVal(bet,left,right); ans=Math.min(ans,temp); } left=findLower(y,bet); right=findHigher(g,bet); if(left!=0&&right!=Integer.MAX_VALUE){ long temp=getVal(bet,left,right); ans=Math.min(ans,temp); } } for(int i=0;i<b;i++){ int bet=g.get(i); int left=findLower(r,bet); int right=findHigher(y,bet); if(left!=0&&right!=Integer.MAX_VALUE){ long temp=getVal(bet,left,right); ans=Math.min(ans,temp); } left=findLower(y,bet); right=findHigher(r,bet); if(left!=0&&right!=Integer.MAX_VALUE){ long temp=getVal(bet,left,right); ans=Math.min(ans,temp); } }for(int i=0;i<c;i++){ int bet=y.get(i); int left=findLower(g,bet); int right=findHigher(r,bet); if(left!=0&&right!=Integer.MAX_VALUE){ long temp=getVal(bet,left,right); ans=Math.min(ans,temp); } left=findLower(r,bet); right=findHigher(g,bet); if(left!=0&&right!=Integer.MAX_VALUE){ long temp=getVal(bet,left,right); ans=Math.min(ans,temp); } } print.append(ans+"\n"); } System.out.print(print.toString()); } public static long getVal(int a,int b,int c){ return 1l*(b-a)*(b-a)+1l*(c-a)*(c-a)+1l*(c-b)*(c-b); } public static int findHigher(ArrayList<Integer> a,int num){ int low=0,high=a.size()-1; int ans=Integer.MAX_VALUE; while(low<=high){ int mid=(low+high)/2; if(a.get(mid)<num){ low=mid+1; } else{ ans=a.get(mid); high=mid-1; } } return ans; } public static int findLower(ArrayList<Integer> a,int num){ int low=0,high=a.size()-1; int ans=0; while(low<=high){ int mid=(low+high)/2; if(a.get(mid)>num){ high=mid-1; } else{ ans=a.get(mid); low=mid+1; } } return ans; } }
Java
["5\n2 2 3\n7 8\n6 3\n3 1 4\n1 1 1\n1\n1\n1000000000\n2 2 2\n1 2\n5 4\n6 7\n2 2 2\n1 2\n3 4\n6 7\n3 4 1\n3 2 1\n7 3 3 4\n6"]
3 seconds
["14\n1999999996000000002\n24\n24\n14"]
NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.
Java 8
standard input
[ "math", "implementation", "sortings", "data structures", "binary search" ]
79b58eb781cd73ccf7994866b9a8b695
The first line contains a single integer $$$t$$$ ($$$1\le t \le 100$$$)  — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (the sum for all test cases).
1,700
For each test case, print a line contains one integer  — the minimum value which Xenia wants to find.
standard output
PASSED
8312eda7e16011241fdf163c50ad2bae
train_001.jsonl
1586961300
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class D { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader file = new BufferedReader(new InputStreamReader(System.in)); // BufferedReader file = new BufferedReader(new FileReader("D.in")); int inputs = Integer.parseInt(file.readLine()); int[][] gems = {new int[100000], new int[100000], new int[100000]}; while(inputs-->0) { StringTokenizer st = new StringTokenizer(file.readLine()); int[] sizes = new int[3]; sizes[0] = Integer.parseInt(st.nextToken()); sizes[1] = Integer.parseInt(st.nextToken()); sizes[2] = Integer.parseInt(st.nextToken()); for(int i = 0; i < 3; i++) { st = new StringTokenizer(file.readLine()); for(int j = 0; j < sizes[i]; j++) { gems[i][j] = Integer.parseInt(st.nextToken()); } Arrays.sort(gems[i], 0, sizes[i]); } long min = Long.MAX_VALUE; int bDown = 0, cDown = 0, bUp = 0, cUp = 0; for(int offset = 0; offset < 3; offset++) { int aIndex = (0+offset)%3; int bIndex = (1+offset)%3; int cIndex = (2+offset)%3; bDown = 0; cDown = 0; bUp = 0; cUp = 0; for(int a = 0; a < sizes[aIndex]; a++) { while(bDown < sizes[bIndex]-1 && gems[bIndex][bDown+1] < gems[aIndex][a]) { bDown++; } while(bUp < sizes[bIndex]-1 && gems[bIndex][bUp] < gems[aIndex][a]) { bUp++; } while(cDown < sizes[cIndex]-1 && gems[cIndex][cDown+1] < gems[aIndex][a]) { cDown++; } while(cUp < sizes[cIndex]-1 && gems[cIndex][cUp] < gems[aIndex][a]) { cUp++; } // System.out.println(bDown + " " + bUp + " " + cDown + " " + cUp); min = Math.min(min, squaredDiff(gems[aIndex][a], gems[bIndex][bDown], gems[cIndex][cDown])); min = Math.min(min, squaredDiff(gems[aIndex][a], gems[bIndex][bDown], gems[cIndex][cUp])); min = Math.min(min, squaredDiff(gems[aIndex][a], gems[bIndex][bUp], gems[cIndex][cDown])); min = Math.min(min, squaredDiff(gems[aIndex][a], gems[bIndex][bUp], gems[cIndex][cUp])); } // bIndex = (2+offset)%3; // cIndex = (1+offset)%3; // b = 0; c = 0; // for(int a = 0; a < sizes[aIndex]; a++) { // bDiff = Math.abs(gems[aIndex][a] - gems[1][b]); // while(b < sizes[bIndex]-1 && Math.abs(gems[aIndex][a]-gems[bIndex][b+1]) < bDiff) { // b++; // } // cDiff = Math.abs(gems[aIndex][a] - gems[cIndex][c]) + Math.abs(gems[bIndex][b] - gems[cIndex][c]); // while(c < sizes[cIndex]-1 && Math.abs(gems[aIndex][a] - gems[cIndex][c+1]) + Math.abs(gems[bIndex][b] - gems[cIndex][c+1]) < cDiff) { // c++; // } // min = Math.min(min, squaredDiff(gems[aIndex][a], gems[bIndex][b], gems[cIndex][c])); // } } System.out.println(min); } file.close(); } public static long squaredDiff(long a, long b, long c) { return (a-b)*(a-b) + (a-c)*(a-c) + (b-c)*(b-c); } }
Java
["5\n2 2 3\n7 8\n6 3\n3 1 4\n1 1 1\n1\n1\n1000000000\n2 2 2\n1 2\n5 4\n6 7\n2 2 2\n1 2\n3 4\n6 7\n3 4 1\n3 2 1\n7 3 3 4\n6"]
3 seconds
["14\n1999999996000000002\n24\n24\n14"]
NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.
Java 8
standard input
[ "math", "implementation", "sortings", "data structures", "binary search" ]
79b58eb781cd73ccf7994866b9a8b695
The first line contains a single integer $$$t$$$ ($$$1\le t \le 100$$$)  — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (the sum for all test cases).
1,700
For each test case, print a line contains one integer  — the minimum value which Xenia wants to find.
standard output
PASSED
7ba660b9b1a8dcc7581f47130753a775
train_001.jsonl
1586961300
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.InputMismatchException; import java.util.*; import java.io.*; import java.lang.*; public class Main{ public static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.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); } } static long gcd(long a, long b){ if (a == 0) return b; return gcd(b % a, a); } static long lcm(long a, long b) { return (a*b)/gcd(a, b); } public static void sortbyColumn(int arr[][], int col) { Arrays.sort(arr, new Comparator<int[]>() { @Override public int compare(final int[] entry1, final int[] entry2) { if (entry1[col] > entry2[col]) return 1; else return -1; } }); } static long func(long a[],long size,int s){ long max1=a[s]; long maxc=a[s]; for(int i=s+1;i<size;i++){ maxc=Math.max(a[i],maxc+a[i]); max1=Math.max(maxc,max1); } return max1; } public static class Pair<U extends Comparable<U>, V extends Comparable<V>> implements Comparable<Pair<U, V>> { public U x; public V y; public Pair(U x, V y) { this.x = x; this.y = y; } public int hashCode() { return (x == null ? 0 : x.hashCode() * 31) + (y == null ? 0 : y.hashCode()); } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair<U, V> p = (Pair<U, V>) o; return (x == null ? p.x == null : x.equals(p.x)) && (y == null ? p.y == null : y.equals(p.y)); } public int compareTo(Pair<U, V> b) { int cmpU = x.compareTo(b.x); return cmpU != 0 ? cmpU : y.compareTo(b.y); } public String toString() { return String.format("(%s, %s)", x.toString(), y.toString()); } } static LinkedList<Integer> li[]=new LinkedList[100001]; static int ans1=0,ans2=0,max1=-1; static int dist[]=new int[100001]; static int visited[]=new int[100001]; static int visit[]=new int[100001]; static int value[]=new int[100001]; //static int arr[]; static ArrayList<Integer> adj[]; static void bfs(int n,int m){ //visited[x]=1; //visit[j]++; dist[n]=0; visited[n]=1; Queue<Integer> q=new LinkedList<>(); q.add(n); while(!q.isEmpty()){ int x=q.poll(); for(int i=0;i<adj[x].size();i++){ if(visited[adj[x].get(i)]==0){ q.add(adj[x].get(i)); visited[adj[x].get(i)]=1; dist[adj[x].get(i)]=dist[x]+1; } if(adj[x].get(i)==m) { return; } } } // for(int i=0;i<adj[x].size();i++){ // if(visited[adj[x].get(i)]==0){ // //check[j]++; // ans1++; // dfs(adj[x].get(i)); // } // } } static void dfs(int x){ visit[x]=1; ans1++; for(int i=0;i<li[x].size();i++){ if(visit[li[x].get(i)]==0){ dfs(li[x].get(i)); } } } static int size[]=new int[2000001]; static int parent[]=new int[2000001]; static void makeSet(int v){ size[v]=1; parent[v]=v; } static int findSet(int v){ if(v==parent[v]){ return v; } return parent[v]=findSet(parent[v]); } static void unSet(int a, int b){ a=findSet(a); b=findSet(b); if(a==b){ return; }if(size[a]<size[b]){ int temp=a; a=b; b=temp; } parent[b]=a; size[a]+=size[b]; //System.out.println("parent "+b+" = "+parent[b]+" "+a); } public static void main(String args[]){ InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter w = new PrintWriter(outputStream); int t,i,j,k; t=in.nextInt(); while(t-->0){ int a,b,c; a=in.nextInt(); b=in.nextInt(); c=in.nextInt(); TreeSet<Long> tr[]=new TreeSet[3]; for(i=0;i<3;i++){ tr[i]=new TreeSet<>(); } for(i=0;i<a;i++){ tr[0].add(in.nextLong()); } for(i=0;i<b;i++){ tr[1].add(in.nextLong()); } for(i=0;i<c;i++){ tr[2].add(in.nextLong()); } long ans=Long.MAX_VALUE; for(i=0;i<3;i++){ for(j=0;j<3;j++){ if(i==j){ continue; } for(k=0;k<3;k++){ if(k==i||k==j){ continue; } for(long x : tr[i]){ for(int yy=0;yy<2;yy++){ Long y = yy==0 ? tr[j].ceiling(x) : tr[j].floor(x); if(y==null){ continue; } for(int zz=0;zz<4;zz++){ Long z=zz==0?tr[k].ceiling(x):zz==1?tr[k].floor(x):zz==2?tr[k].ceiling(y):tr[k].floor(y); if(z==null){ continue; } long curr=(x-y)*(x-y)+(y-z)*(y-z)+(z-x)*(z-x); ans=Math.min(ans,curr); } } } } } } w.println(ans); } w.close(); } }
Java
["5\n2 2 3\n7 8\n6 3\n3 1 4\n1 1 1\n1\n1\n1000000000\n2 2 2\n1 2\n5 4\n6 7\n2 2 2\n1 2\n3 4\n6 7\n3 4 1\n3 2 1\n7 3 3 4\n6"]
3 seconds
["14\n1999999996000000002\n24\n24\n14"]
NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.
Java 8
standard input
[ "math", "implementation", "sortings", "data structures", "binary search" ]
79b58eb781cd73ccf7994866b9a8b695
The first line contains a single integer $$$t$$$ ($$$1\le t \le 100$$$)  — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (the sum for all test cases).
1,700
For each test case, print a line contains one integer  — the minimum value which Xenia wants to find.
standard output
PASSED
3926264b078c186939b0b8613245eeac
train_001.jsonl
1586961300
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?
256 megabytes
import java.awt.*; import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws Exception { FastReader sc = new FastReader(); StringBuilder sb=new StringBuilder(); int t=sc.nextInt(); while(t-->0){ int r=sc.nextInt(),g=sc.nextInt(),b=sc.nextInt(); Long[] A=new Long[r],B=new Long[g],C=new Long[b]; for(int i=0;i<r;i++)A[i]=sc.nextLong(); for(int i=0;i<g;i++)B[i]=sc.nextLong(); for(int i=0;i<b;i++)C[i]=sc.nextLong(); Arrays.sort(A);Arrays.sort(B);Arrays.sort(C); int i=0,j=0,k=0; long ans=(A[i]-B[j])*(A[i]-B[j])+(B[j]-C[k])*(B[j]-C[k])+(C[k]-A[i])*(C[k]-A[i]); while(true){ long x=Long.MAX_VALUE,y=Long.MAX_VALUE,z=Long.MAX_VALUE; if(i+1<r)x=(A[i+1]-B[j])*(A[i+1]-B[j])+(B[j]-C[k])*(B[j]-C[k])+(C[k]-A[i+1])*(C[k]-A[i+1]); if(j+1<g)y=(A[i]-B[j+1])*(A[i]-B[j+1])+(B[j+1]-C[k])*(B[j+1]-C[k])+(C[k]-A[i])*(C[k]-A[i]); if(k+1<b)z=(A[i]-B[j])*(A[i]-B[j])+(B[j]-C[k+1])*(B[j]-C[k+1])+(C[k+1]-A[i])*(C[k+1]-A[i]); if(x==Long.MAX_VALUE && y==Long.MAX_VALUE && z==Long.MAX_VALUE)break; if(x<=y && x<=z){ ans=Math.min(ans,x); i++; } else if(y<=x && y<=z){ ans=Math.min(ans,y); j++; } else{ ans=Math.min(ans,z); k++; } } sb.append(ans+"\n"); } System.out.println(sb); } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
Java
["5\n2 2 3\n7 8\n6 3\n3 1 4\n1 1 1\n1\n1\n1000000000\n2 2 2\n1 2\n5 4\n6 7\n2 2 2\n1 2\n3 4\n6 7\n3 4 1\n3 2 1\n7 3 3 4\n6"]
3 seconds
["14\n1999999996000000002\n24\n24\n14"]
NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.
Java 8
standard input
[ "math", "implementation", "sortings", "data structures", "binary search" ]
79b58eb781cd73ccf7994866b9a8b695
The first line contains a single integer $$$t$$$ ($$$1\le t \le 100$$$)  — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (the sum for all test cases).
1,700
For each test case, print a line contains one integer  — the minimum value which Xenia wants to find.
standard output
PASSED
9475ae4833024496121779e5d9c57373
train_001.jsonl
1586961300
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?
256 megabytes
import java.util.*; import java.io.*; public class Main{ static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } static class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = in.nextInt(); return array; } } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } public static long get(long[] arr, long k,long n) { int key = Arrays.binarySearch(arr, k); if(key<0) { key = -key -1; } if(key==n) { key = key - 1; } long y =0; if(key>0 && (Math.abs(k-arr[key])>Math.abs(k-arr[key-1]))) { y = arr[key-1]; } else{ y = arr[key]; } return y; } public static void main(String[] args) { InputReader in = new InputReader(System.in); OutputWriter out = new OutputWriter(System.out); //IOUtils io = new IOUtils(); int t = in.nextInt(); while(t-- >0) { int nr = in.nextInt(), ng = in.nextInt(), nb = in.nextInt(); long[] red =new long[nr]; long[] green = new long[ng]; long[] blue =new long[nb]; for(int i=0;i<nr;i++) { red[i] = in.nextLong(); } for(int i=0;i<ng;i++) { green[i] = in.nextLong(); } for(int i=0;i<nb;i++) { blue[i] = in.nextLong(); } Arrays.sort(red); Arrays.sort(green); Arrays.sort(blue); //Map<String,Integer> memo = new HashMap<>(); long res = Long.MAX_VALUE; for(int i=0;i<nr;i++) { long x = red[i]; long y = get(green,x,ng); long z = get(blue,x,nb); // long x2 = get(red,z,nr); long diff = (x-y)*(x-y) + (y-z)*(y-z) + (z-x)*(z-x); // int diff2 = res = Math.min(res,diff); } for(int i=0;i<ng;i++) { long y = green[i]; long z = get(blue,y,nb); long x = get(red,y,nr); long diff = (x-y)*(x-y) + (y-z)*(y-z) + (z-x)*(z-x); // int diff2 = res = Math.min(res,diff); } for(int i=0;i<nb;i++) { long z = blue[i]; long x = get(red,z,nr); long y = get(green,z,ng); long diff = (x-y)*(x-y) + (y-z)*(y-z) + (z-x)*(z-x); // int diff2 = res = Math.min(res,diff); } out.printLine(res); } out.flush(); out.close(); } }
Java
["5\n2 2 3\n7 8\n6 3\n3 1 4\n1 1 1\n1\n1\n1000000000\n2 2 2\n1 2\n5 4\n6 7\n2 2 2\n1 2\n3 4\n6 7\n3 4 1\n3 2 1\n7 3 3 4\n6"]
3 seconds
["14\n1999999996000000002\n24\n24\n14"]
NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.
Java 8
standard input
[ "math", "implementation", "sortings", "data structures", "binary search" ]
79b58eb781cd73ccf7994866b9a8b695
The first line contains a single integer $$$t$$$ ($$$1\le t \le 100$$$)  — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (the sum for all test cases).
1,700
For each test case, print a line contains one integer  — the minimum value which Xenia wants to find.
standard output
PASSED
5a7e8043be911f93a890c729f505becd
train_001.jsonl
1586961300
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class ProblemD { public static void main(String[] args) { Scanner scn=new Scanner(System.in); int T=scn.nextInt(); for(int t=0;t<T;t++){ int Nr=scn.nextInt(); int Ng=scn.nextInt(); int Nb=scn.nextInt(); Integer[] R=new Integer[Nr]; Integer[] G=new Integer[Ng]; Integer[] B=new Integer[Nb]; for(int i=0;i<Nr;i++){ R[i]=scn.nextInt(); } for(int i=0;i<Ng;i++){ G[i]=scn.nextInt(); } for(int i=0;i<Nb;i++){ B[i]=scn.nextInt(); } Arrays.sort(R); Arrays.sort(G); Arrays.sort(B); long a,b,c; int x,y,z; Long ans=Long.MAX_VALUE; for(int i=0;i<Nr;i++){ x=R[i]; y=binarySearch(G, x); z=binarySearch(B, x); a=(x-y); a*=(x-y); b=(z-y); b*=(z-y); c=(x-z); c*=(x-z); ans= Math.min(ans, a+b+c); } for(int i=0;i<Ng;i++){ x=G[i]; y=binarySearch(R, x); z=binarySearch(B, x); a=(x-y); a*=(x-y); b=(z-y); b*=(z-y); c=(x-z); c*=(x-z); ans= Math.min(ans, a+b+c); } for(int i=0;i<Nb;i++){ x=B[i]; y=binarySearch(G, x); z=binarySearch(R, x); a=(x-y); a*=(x-y); b=(z-y); b*=(z-y); c=(x-z); c*=(x-z); ans= Math.min(ans, a+b+c); } // long ans1=(1000000000-1); // ans1*=(1000000000-1); // ans1*=2; // System.out.println(ans1); System.out.println(ans); } } private static int binarySearch(Integer[] A, int M){ int start=0; int end=A.length-1; int mid=-1; int min; while(start<=end){ mid=(start+end)/2; if(A[mid]<M){ start=mid+1; } else if(A[mid]==M){ break; } else{ end=mid-1; } } if(mid==0&&mid==(A.length-1)){ return A[mid]; } if(mid==0){ min=Math.min(Math.abs(A[mid]-M), Math.abs(A[mid+1]-M)); if(min==Math.abs(A[mid]-M)){ return A[mid]; } else{ return A[mid+1]; } } if(mid== A.length-1){ min=Math.min(Math.abs(A[mid]-M), Math.abs(A[mid-1]-M)); if(min==Math.abs(A[mid]-M)){ return A[mid]; } else{ return A[mid-1]; } } else{ min=Math.min(Math.abs(A[mid]-M), Math.abs(A[mid-1]-M)); min=Math.min(Math.abs(A[mid+1]-M), min); if(min==Math.abs(A[mid]-M)){ return A[mid]; } else if (min==Math.abs(A[mid+1]-M)){ return A[mid+1]; } else{ return A[mid-1]; } } } }
Java
["5\n2 2 3\n7 8\n6 3\n3 1 4\n1 1 1\n1\n1\n1000000000\n2 2 2\n1 2\n5 4\n6 7\n2 2 2\n1 2\n3 4\n6 7\n3 4 1\n3 2 1\n7 3 3 4\n6"]
3 seconds
["14\n1999999996000000002\n24\n24\n14"]
NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.
Java 8
standard input
[ "math", "implementation", "sortings", "data structures", "binary search" ]
79b58eb781cd73ccf7994866b9a8b695
The first line contains a single integer $$$t$$$ ($$$1\le t \le 100$$$)  — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (the sum for all test cases).
1,700
For each test case, print a line contains one integer  — the minimum value which Xenia wants to find.
standard output
PASSED
5cddec93638eac144ae2a87d9084f14c
train_001.jsonl
1586961300
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?
256 megabytes
import java.util.*; import java.io.*; public class D { public static void main(String[] args) throws IOException{ BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); int t = Integer.parseInt(f.readLine()); while(t-->0){ StringTokenizer st = new StringTokenizer(f.readLine()); int n1 = Integer.parseInt(st.nextToken()); int n2 = Integer.parseInt(st.nextToken()); int n3 = Integer.parseInt(st.nextToken()); long[] arr1 = new long[n1]; long[] arr2 = new long[n2]; long[] arr3 = new long[n3]; TreeSet<Long> ts1 = new TreeSet<Long>(); TreeSet<Long> ts2 = new TreeSet<Long>(); TreeSet<Long> ts3 = new TreeSet<Long>(); st = new StringTokenizer(f.readLine()); for(int i = 0; i < n1; i++){ arr1[i] = Long.parseLong(st.nextToken()); ts1.add(arr1[i]); } st = new StringTokenizer(f.readLine()); for(int i = 0; i < n2; i++){ arr2[i] = Long.parseLong(st.nextToken()); ts2.add(arr2[i]); } st = new StringTokenizer(f.readLine()); for(int i = 0; i < n3; i++){ arr3[i] = Long.parseLong(st.nextToken()); ts3.add(arr3[i]); } long minans = Long.MAX_VALUE; for(int i = 0; i < n1; i++){ Long lower2 = ts2.floor(arr1[i]); Long higher2 = ts2.ceiling(arr1[i]); long val2 = Long.MAX_VALUE; if(lower2 == null) val2 = higher2; else if(higher2 == null) val2 = lower2; else{ if(Math.abs(lower2-arr1[i]) < Math.abs(higher2-arr1[i])){ val2 = lower2; }else{ val2 = higher2; } } Long lower3 = ts3.floor(arr1[i]); Long higher3 = ts3.ceiling(arr1[i]); long val3 = Long.MAX_VALUE; if(lower3 == null) val3 = higher3; else if(higher3 == null) val3 = lower3; else{ if(Math.abs(lower3-arr1[i]) < Math.abs(higher3-arr1[i])){ val3 = lower3; }else{ val3 = higher3; } } long currans = (arr1[i]-val2)*(arr1[i]-val2) + (val2-val3)*(val2-val3) + (val3-arr1[i])*(val3-arr1[i]); minans = Math.min(minans, currans); } for(int i = 0; i < n2; i++){ Long lower2 = ts1.floor(arr2[i]); Long higher2 = ts1.ceiling(arr2[i]); long val2 = Long.MAX_VALUE; if(lower2 == null) val2 = higher2; else if(higher2 == null) val2 = lower2; else{ if(Math.abs(lower2-arr2[i]) < Math.abs(higher2-arr2[i])){ val2 = lower2; }else{ val2 = higher2; } } Long lower3 = ts3.floor(arr2[i]); Long higher3 = ts3.ceiling(arr2[i]); long val3 = Long.MAX_VALUE; if(lower3 == null) val3 = higher3; else if(higher3 == null) val3 = lower3; else{ if(Math.abs(lower3-arr2[i]) < Math.abs(higher3-arr2[i])){ val3 = lower3; }else{ val3 = higher3; } } long currans = (arr2[i]-val2)*(arr2[i]-val2) + (val2-val3)*(val2-val3) + (val3-arr2[i])*(val3-arr2[i]); minans = Math.min(minans, currans); } for(int i = 0; i < n3; i++){ Long lower2 = ts2.floor(arr3[i]); Long higher2 = ts2.ceiling(arr3[i]); long val2 = Long.MAX_VALUE; if(lower2 == null) val2 = higher2; else if(higher2 == null) val2 = lower2; else{ if(Math.abs(lower2-arr3[i]) < Math.abs(higher2-arr3[i])){ val2 = lower2; }else{ val2 = higher2; } } Long lower3 = ts1.floor(arr3[i]); Long higher3 = ts1.ceiling(arr3[i]); long val3 = Long.MAX_VALUE; if(lower3 == null) val3 = higher3; else if(higher3 == null) val3 = lower3; else{ if(Math.abs(lower3-arr3[i]) < Math.abs(higher3-arr3[i])){ val3 = lower3; }else{ val3 = higher3; } } long currans = (arr3[i]-val2)*(arr3[i]-val2) + (val2-val3)*(val2-val3) + (val3-arr3[i])*(val3-arr3[i]); minans = Math.min(minans, currans); } out.println(minans); } out.close(); } }
Java
["5\n2 2 3\n7 8\n6 3\n3 1 4\n1 1 1\n1\n1\n1000000000\n2 2 2\n1 2\n5 4\n6 7\n2 2 2\n1 2\n3 4\n6 7\n3 4 1\n3 2 1\n7 3 3 4\n6"]
3 seconds
["14\n1999999996000000002\n24\n24\n14"]
NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.
Java 8
standard input
[ "math", "implementation", "sortings", "data structures", "binary search" ]
79b58eb781cd73ccf7994866b9a8b695
The first line contains a single integer $$$t$$$ ($$$1\le t \le 100$$$)  — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (the sum for all test cases).
1,700
For each test case, print a line contains one integer  — the minimum value which Xenia wants to find.
standard output
PASSED
a007fb81225b5755ee605dc1e46f7549
train_001.jsonl
1586961300
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?
256 megabytes
//package learning; import java.util.*; import java.io.*; import java.lang.*; import java.text.*; import java.math.*; import java.util.regex.*; public class NitsLocal { static ArrayList<String> s1; static boolean[] prime; static int n = (int)1e7; static void sieve() { Arrays.fill(prime , true); prime[0] = prime[1] = false; for(int i = 2 ; i * i <= n ; ++i) { if(prime[i]) { for(int k = i * i; k<= n ; k+=i) { prime[k] = false; } } } } public static void main(String[] args) { InputReader sc = new InputReader(System.in); n *= 2; prime = new boolean[n + 1]; //sieve(); prime[1] = false; /* int n = sc.ni(); int k = sc.ni(); int []vis = new int[n+1]; int []a = new int[k]; for(int i=0;i<k;i++) { a[i] = i+1; } int j = k+1; int []b = new int[n+1]; for(int i=1;i<=n;i++) { b[i] = -1; } int y = n - k +1; int tr = 0; int y1 = k+1; while(y-- > 0) { System.out.print("? "); for(int i=0;i<k;i++) { System.out.print(a[i] + " "); } System.out.flush(); int pos = sc.ni(); int a1 = sc.ni(); b[pos] = a1; for(int i=0;i<k;i++) { if(a[i] == pos) { a[i] = y1; y1++; } } } ArrayList<Integer> a2 = new ArrayList<>(); if(y >= k) { int c = 0; int k1 = 0; for(int i=1;i<=n;i++) { if(b[i] != -1) { c++; a[k1] = i; a2.add(b[i]); k1++; } if(c==k) break; } Collections.sort(a2); System.out.print("? "); for(int i=0;i<k;i++) { System.out.print(a[i] + " "); } System.out.println(); System.out.flush(); int pos = sc.ni(); int a1 = sc.ni(); int ans = -1; for(int i=0;i<a2.size();i++) { if(a2.get(i) == a1) { ans = i+1; break; } } System.out.println("!" + " " + ans); System.out.flush(); } else { int k1 = 0; a = new int[k]; for(int i=1;i<=n;i++) { if(b[i] != -1) { a[k1] = i; a2.add(b[i]); k1++; } } for(int i=1;i<=n;i++) { if(b[i] == -1) { a[k1] = i; k1++; if(k1==k) break; } } int ans = -1; while(true) { System.out.print("? "); for(int i=0;i<k;i++) { System.out.print(a[i] + " "); } System.out.println(); System.out.flush(); int pos = sc.ni(); int a1 = sc.ni(); int f = 0; if(b[pos] != -1) { Collections.sort(a2); for(int i=0;i<a2.size();i++) { if(a2.get(i) == a1) { ans = i+1; f = 1; System.out.println("!" + " " + ans); System.out.flush(); break; } } if(f==1) break; } else { b[pos] = a1; a = new int[k]; a2.add(a1); for(int i=1;i<=n;i++) { if(b[i] != -1) { a[k1] = i; a2.add(b[i]); k1++; } } for(int i=1;i<=n;i++) { if(b[i] == -1) { a[k1] = i; k1++; if(k1==k) break; } } } } */ /* int n = sc.ni(); int []a = sc.nia(n); int []b = sc.nia(n); Integer []d = new Integer[n]; int []d1 = new int[n]; for(int i=0;i<n;i++) { d[i] = (a[i] - b[i]); } int l = 0; int r = n-1; Arrays.sort(d); long res = 0; while(l < r) { if(d[l] + d[r] > 0) { res += (long) (r-l); r--; } else l++; } w.println(res); */ /* int n = sc.ni(); ArrayList<Integer> t1 = new ArrayList<>(); int []p1 = new int[n+1]; int []q1 = new int[n-1]; int []q2 = new int[n-1]; for(int i=0;i<n-1;i++) { int p = sc.ni(); int q = sc.ni(); t1.add(q); p1[p]++; q1[i] = p; q2[i] = q; } int res = 0; for(int i=0;i<t1.size();i++) { if(p1[t1.get(i)] == 0) { res = t1.get(i); //break; } } int y = 1; for(int i=0;i<n-1;i++) { if(q2[i] == res) { w.println("0"); } else { w.println(y + " "); y++; } } */ /* int n = sc.ni(); int k = sc.ni(); Integer []a = new Integer[n]; for(int i=0;i<n;i++) { a[i] = sc.ni(); a[i] = a[i]%k; } HashMap<Integer,Integer> hm = new HashMap<>(); for(int i=0;i<n;i++) { if(!hm.containsKey(a[i])) hm.put(a[i], 1); else hm.put(a[i], hm.get(a[i]) + 1); } Arrays.sort(a); int z = 0; long res = 0; HashMap<Integer,Integer> v = new HashMap<>(); for(int i=0;i<n;i++) { if(a[i] == 0) res++; else { if(a[i] == k-a[i] && !v.containsKey(a[i])) { res += (long) hm.get(a[i]) / 2; v.put(a[i],1); } else { if(hm.containsKey(a[i]) && hm.containsKey(k-a[i])) { int temp = a[i]; if(!v.containsKey(a[i]) && !v.containsKey(k-a[i])) { res += (long) Math.min(hm.get(temp), hm.get(k-temp)); v.put(temp,1); v.put(k-temp,1); } } } } } w.println(res); */ /* int []a = new int[4]; //G0 a[0] = 0; a[1] = 1; a[2] = 0; a[3] = 1; int []b = new int[4]; //g1 b[0] = 0; b[1] = 1; b[2] = 1; b[3] = 0; int [][]dp1 = new int[4][4]; int [][]dp2 = new int[4][4]; for(int i=0;i<4;i++) { for(int j=0;j<4;j++) { dp1[i][j] = (a[i] | a[j]); } // w.println(); } w.println(); for(int i=0;i<4;i++) { for(int j=0;j<4;j++) { dp2[i][j] = (b[i] | b[j]); } //w.println(); } int a1 = 0; int b1 = 0; int c1 = 0; int d1 = 0; for(int i=0;i<4;i++) { for(int j=0;j<4;j++) { if(dp1[i][j] == 0 && dp2[i][j] == 0) a1++; else if(dp1[i][j] == 1 && dp2[i][j] == 1) b1++; else if(dp1[i][j] == 0 && dp2[i][j] == 1) c1++; else d1++; } } w.println(a1+ " " + b1 + " " + c1 +" "+ d1); Scanner sc = new Scanner(System.in); int q = sc.nextInt(); while(q-- > 0) { long x = sc.nextLong(); long y = sc.nextLong(); long a = (x - y)/2; long a1 = 0, b1 = 0; int lim = 8; int f = 0; for (int i=0; i<8*lim; i++) { long pi = (y & (1 << i)); long qi = (a & (1 << i)); if (pi == 0 && qi == 0) { } else if (pi == 0 && qi > 0) { a1 = ((1 << i) | a1); b1 = ((1 << i) | b1); } else if (pi > 0 && qi == 0) { a1 = ((1 << i) | a1); } else { f = 1; } } if(a1+b1 != x) f =1; if(f==1) System.out.println("-1"); else { if(a1 > b1) { long temp = a1; a1 = b1; b1 = temp; } System.out.println(a1 + " " + b1); } } */ int t = sc.ni(); while(t-- > 0) { int nr = sc.ni(); int ng = sc.ni(); int nb = sc.ni(); Integer []r = new Integer[nr]; for(int i=0;i<nr;i++) { r[i] = sc.ni(); } Integer []g = new Integer[ng]; for(int i=0;i<ng;i++) { g[i] = sc.ni(); } Integer []b = new Integer[nb]; for(int i=0;i<nb;i++) { b[i] = sc.ni(); } long min = Long.MAX_VALUE; Arrays.sort(r); Arrays.sort(g); Arrays.sort(b); for(int i=0;i<nr;i++) { int a = 0; int b1 = Integer.MAX_VALUE; int c = 0; int d = Integer.MAX_VALUE; int up1 = upperBound(g,ng,r[i]); int down1 = lowerBound(g,ng,r[i]); int up2 = upperBound(b,nb,r[i]); int down2 = lowerBound(b,nb,r[i]); if(up1 == ng) up1--; if(up2 == nb) up2--; if(down1 == ng || (g[down1] > r[i] && down1 > 0)) down1--; if(down2 == nb || (b[down2] > r[i] && down2 > 0)) down2--; a = g[up1]; b1 = g[down1]; c = b[up2]; d = b[down2]; long temp = calc(a,r[i],c); long temp1 = calc(a,r[i],d); min = Math.min(min,Math.min(temp,temp1)); temp = calc(b1,r[i],c); temp1 = calc(b1,r[i],d); min = Math.min(min,Math.min(temp,temp1)); } for(int i=0;i<ng;i++) { int a = 0; int b1 = Integer.MAX_VALUE; int c = 0; int d = Integer.MAX_VALUE; int up1 = upperBound(r,nr,g[i]); int down1 = lowerBound(r,nr,g[i]); int up2 = upperBound(b,nb,g[i]); int down2 = lowerBound(b,nb,g[i]); if(up1 == nr) up1--; if(up2 == nb) up2--; if(down1 == nr || (r[down1] > g[i] && down1 > 0)) down1--; if(down2 == nb || (b[down2] > g[i] && down2 > 0)) down2--; a = r[up1]; b1 = r[down1]; c = b[up2]; d = b[down2]; long temp = calc(a,g[i],c); long temp1 = calc(a,g[i],d); min = Math.min(min,Math.min(temp,temp1)); temp = calc(b1,g[i],c); temp1 = calc(b1,g[i],d); min = Math.min(min,Math.min(temp,temp1)); } for(int i=0;i<nb;i++) { int a = 0; int b1 = Integer.MAX_VALUE; int c = 0; int d = Integer.MAX_VALUE; int up1 = upperBound(g,ng,b[i]); int down1 = lowerBound(g,ng,b[i]); int up2 = upperBound(r,nr,b[i]); int down2 = lowerBound(r,nr,b[i]); if(up1 == ng) up1--; if(up2 == nr) up2--; if(down1 == ng || (g[down1] > b[i] && down1 > 0)) down1--; if(down2 == nr || (r[down2] > b[i] && down2 > 0)) down2--; a = g[up1]; b1 = g[down1]; c = r[up2]; d = r[down2]; long temp = calc(a,b[i],c); long temp1 = calc(a,b[i],d); min = Math.min(min,Math.min(temp,temp1)); temp = calc(b1,b[i],c); temp1 = calc(b1,b[i],d); min = Math.min(min,Math.min(temp,temp1)); } w.println(min); } w.close(); } public static long calc(int x,int y,int z) { long res = ((long) (x-y) * (long) (x-y)) + ((long) (z-y) * (long) (z-y)) + ((long) (x-z) * (long) (x-z)); return res; } public static int upperBound(Integer []arr, int length, int value) { int low = 0; int high = length; while (low < high) { final int mid = (low + high) / 2; if (value >= arr[mid]) { low = mid + 1; } else { high = mid; } } return low; } public static int lowerBound(Integer []arr, int length, int value) { int low = 0; int high = length; while (low < high) { final int mid = (low + high) / 2; //checks if the value is less than middle element of the array if (value <= arr[mid]) { high = mid; } else { low = mid + 1; } } return low; } static HashMap<Long,Integer> map; static class Coin{ long a; long b; Coin(long a, long b) { this.a = a; this.b = b; } } static ArrayList<Long> fac; static HashSet<Long> hs; public static void primeFactors(long n) { // Print the number of 2s that divide n while (n % 2 == 0) { fac.add(2l); hs.add(2l); n /= 2; } // n must be odd at this point. So we can // skip one element (Note i = i +2) for (long i = 3; i*i <= n; i += 2) { // While i divides n, print i and divide n while (n % i == 0) { fac.add(i); hs.add(i); n /= i; } } // This condition is to handle the case whien // n is a prime number greater than 2 if (n > 2) fac.add(n); } static int smallestDivisor(int n) { // if divisible by 2 if (n % 2 == 0) return 2; // iterate from 3 to sqrt(n) for (int i = 3; i * i <= n; i += 2) { if (n % i == 0) return i; } return n; } static boolean IsP(String s,int l,int r) { while(l <= r) { if(s.charAt(l) != s.charAt(r)) { return false; } l++; r--; } return true; } static class Student{ int id; int val; Student(int id,int val) { this.id = id; this.val = val; } } static int upperBound(ArrayList<Integer> a, int low, int high, int element){ while(low < high){ int middle = low + (high - low)/2; if(a.get(middle) >= element) high = middle; else low = middle + 1; } return low; } static long func(long t,long e,long h,long a, long b) { if(e*a >= t) return t/a; else { return e + Math.min(h,(t-e*a)/b); } } public static int countSetBits(int number){ int count = 0; while(number>0){ ++count; number &= number-1; } return count; } static long modexp(long x,long n,long M) { long power = n; long result=1; x = x%M; while(power>0) { if(power % 2 ==1) result=(result * x)%M; x=(x*x)%M; power = power/2; } return result; } static long modInverse(long A,long M) { return modexp(A,M-2,M); } static long gcd(long a,long b) { if(a==0) return b; else return gcd(b%a,a); } static class Temp{ int a; int b; int c; int d; Temp(int a,int b,int c,int d) { this.a = a; this.b = b; this.c =c; this.d = d; //this.d = d; } } static long sum1(int t1,int t2,int x,int []t) { int mid = (t2-t1+1)/2; if(t1==t2) return 0; else return sum1(t1,mid-1,x,t) + sum1(mid,t2,x,t); } static String replace(String s,int a,int n) { char []c = s.toCharArray(); for(int i=1;i<n;i+=2) { int num = (int) (c[i] - 48); num += a; num%=10; c[i] = (char) (num+48); } return new String(c); } static String move(String s,int h,int n) { h%=n; char []c = s.toCharArray(); char []temp = new char[n]; for(int i=0;i<n;i++) { temp[(i+h)%n] = c[i]; } return new String(temp); } public static int ip(String s){ return Integer.parseInt(s); } static class multipliers implements Comparator<Long>{ public int compare(Long a,Long b) { if(a<b) return 1; else if(b<a) return -1; else return 0; } } static class multipliers1 implements Comparator<Coin>{ public int compare(Coin a,Coin b) { if(a.a < b.a) return 1; else if(a.a > b.a) return -1; else{ if(a.b < b.b) return 1; else if(a.b > b.b) return -1; else return 0; } } } // Java program to generate power set in // lexicographic order. static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream st) { this.stream = st; } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int ni() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nl() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nia(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = ni(); } return a; } public String rs() { 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 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 boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } static PrintWriter w = new PrintWriter(System.out); static class Student1 { int id; //int x; int b; //long z; Student1(int id,int b) { this.id = id; //this.x = x; //this.s = s; this.b = b; // this.z = z; } } }
Java
["5\n2 2 3\n7 8\n6 3\n3 1 4\n1 1 1\n1\n1\n1000000000\n2 2 2\n1 2\n5 4\n6 7\n2 2 2\n1 2\n3 4\n6 7\n3 4 1\n3 2 1\n7 3 3 4\n6"]
3 seconds
["14\n1999999996000000002\n24\n24\n14"]
NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.
Java 8
standard input
[ "math", "implementation", "sortings", "data structures", "binary search" ]
79b58eb781cd73ccf7994866b9a8b695
The first line contains a single integer $$$t$$$ ($$$1\le t \le 100$$$)  — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (the sum for all test cases).
1,700
For each test case, print a line contains one integer  — the minimum value which Xenia wants to find.
standard output
PASSED
e288529ef5a7dbecf5e83d0d0fe37549
train_001.jsonl
1586961300
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?
256 megabytes
import javax.print.DocFlavor; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.util.TreeSet; public class NifflerD { static long ans = Long.MAX_VALUE; public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; PrintWriter pw = new PrintWriter(System.out); try { int t = Integer.parseInt(br.readLine()); while(t-->0) { ans = Long.MAX_VALUE; st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); int[] a = new int[n]; int[] b = new int[m]; int[] c = new int[k]; st = new StringTokenizer(br.readLine()); for(int i=0 ; i<n ; i++) a[i] = Integer.parseInt(st.nextToken()); st = new StringTokenizer(br.readLine()); for(int i=0 ; i<m ; i++) b[i] = Integer.parseInt(st.nextToken()); st = new StringTokenizer(br.readLine()); for(int i=0 ; i<k ; i++) c[i] = Integer.parseInt(st.nextToken()); TreeSet<Integer> ts1 = new TreeSet<>(); for(int i=0 ; i<n ; i++) ts1.add(a[i]); TreeSet<Integer> ts2 = new TreeSet<>(); for(int i=0 ; i<m ; i++) ts2.add(b[i]); TreeSet<Integer> ts3 = new TreeSet<>(); for(int i=0 ; i<k ; i++) ts3.add(c[i]); for(int x: ts1) { if(ts2.floor(x-1) != null) { int v1 = ts2.floor(x-1); func(ts3, v1, x); } if(ts2.contains(x)) { func(ts3, x, x); } if(ts2.ceiling(x+1) != null) { int v1 = ts2.ceiling(x+1); func(ts3, v1, x); } } for(int x: ts2) { if(ts1.floor(x-1) != null) { int v1 = ts1.floor(x-1); func(ts3, v1, x); } if(ts1.contains(x)) { func(ts3, x, x); } if(ts1.ceiling(x+1) != null) { int v1 = ts1.ceiling(x+1); func(ts3, v1, x); } } for(int x: ts1) { if(ts3.floor(x-1) != null) { int v1 = ts3.floor(x-1); func(ts2, v1, x); } if(ts3.contains(x)) { func(ts2, x, x); } if(ts3.ceiling(x+1) != null) { int v1 = ts3.ceiling(x+1); func(ts2, v1, x); } } for(int x: ts3) { if(ts1.floor(x-1) != null) { int v1 = ts1.floor(x-1); func(ts2, v1, x); } if(ts1.contains(x)) { func(ts2, x, x); } if(ts1.ceiling(x+1) != null) { int v1 = ts1.ceiling(x+1); func(ts2, v1, x); } } for(int x: ts2) { if(ts3.floor(x-1) != null) { int v1 = ts3.floor(x-1); func(ts1, v1, x); } if(ts3.contains(x)) { func(ts1, x, x); } if(ts3.ceiling(x+1) != null) { int v1 = ts3.ceiling(x+1); func(ts1, v1, x); } } for(int x: ts3) { if(ts2.floor(x-1) != null) { int v1 = ts2.floor(x-1); func(ts1, v1, x); } if(ts2.contains(x)) { func(ts1, x, x); } if(ts2.ceiling(x+1) != null) { int v1 = ts2.ceiling(x+1); func(ts1, v1, x); } } pw.println(ans); } } finally { pw.flush(); pw.close(); } } static void func(TreeSet<Integer> ts3, int v, int x) { if(ts3.floor(v-1) != null) { ans = Math.min(ans, compute(x, v, ts3.floor(v-1))); } if(ts3.contains(v)) { ans = Math.min(ans, compute(x, v, v)); } if(ts3.ceiling(v+1) != null) { ans = Math.min(ans, compute(x, v, ts3.ceiling(v+1))); } } static long compute(int x, int y, int z) { long a = (x-y); a *= a; long b = (y-z); b *= b; long c = (z-x); c *= c; return a + b + c; } static int max(int... nums) { int ans = 0; for(int i=0 ; i<nums.length ; i++) { ans = Math.max(ans, nums[i]); } return ans; } static int min(int... nums) { int ans = Integer.MAX_VALUE; for(int i=0 ; i<nums.length ; i++) { ans = Math.min(ans, nums[i]); } return ans; } }
Java
["5\n2 2 3\n7 8\n6 3\n3 1 4\n1 1 1\n1\n1\n1000000000\n2 2 2\n1 2\n5 4\n6 7\n2 2 2\n1 2\n3 4\n6 7\n3 4 1\n3 2 1\n7 3 3 4\n6"]
3 seconds
["14\n1999999996000000002\n24\n24\n14"]
NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.
Java 8
standard input
[ "math", "implementation", "sortings", "data structures", "binary search" ]
79b58eb781cd73ccf7994866b9a8b695
The first line contains a single integer $$$t$$$ ($$$1\le t \le 100$$$)  — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (the sum for all test cases).
1,700
For each test case, print a line contains one integer  — the minimum value which Xenia wants to find.
standard output
PASSED
22857078532d11385caffbfcad1f6133
train_001.jsonl
1586961300
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class BufferReader{ static int dp[]; static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { FastReader sc = new FastReader(); int t=sc.nextInt(); while (t-->0) { int nr=sc.nextInt(),ng=sc.nextInt(),nb=sc.nextInt(); long r[]=new long[nr]; long g[]=new long[ng]; long b[]=new long[nb]; for (int i=0;i<nr;i++) r[i]=sc.nextLong(); for (int i=0;i<ng;i++) g[i]=sc.nextLong(); for (int i=0;i<nb;i++) b[i]=sc.nextLong(); Arrays.sort(r); Arrays.sort(g); Arrays.sort(b); long tg=0,tb=0,tr=0; long temp=0; long min=Long.MAX_VALUE; for (int i=0;i<ng;i++) { tr=calculate(r,nr,g[i]); tb=calculate(b,nb,g[i]); tg=g[i]; temp= ((tg-tr)*(tg-tr)); temp+=((tr-tb)*(tr-tb)); temp+=((tg-tb)*(tg-tb)); min=Math.min(min,temp); } for (int i=0;i<nb;i++) { tb=b[i]; tr=calculate(r,nr,tb); tg=calculate(g,ng,tb); temp= ((tg-tr)*(tg-tr)); temp+=((tr-tb)*(tr-tb)); temp+=((tg-tb)*(tg-tb)); min=Math.min(min,temp); } for (int i=0;i<nr;i++) { tr=r[i]; tb=calculate(b,nb,tr); tg=calculate(g,ng,tr); temp= ((tg-tr)*(tg-tr)); temp+=((tr-tb)*(tr-tb)); temp+=((tg-tb)*(tg-tb)); min=Math.min(min,temp); } System.out.println(min); } } public static long solve(long a, long b, long v) { if ( Math.abs(v-a)>Math.abs(v-b) ) return b; else { return a; } } public static long calculate(long arr[],int n,long val) { if ( val<=arr[0] ) return arr[0]; if ( val>=arr[n-1] ) return arr[n-1]; int i=0,j=n-1,mid=0; while (i<j) { mid=(i+j)/2; if ( arr[mid]==val ) return arr[mid]; if ( val<arr[mid] ) { if ( mid>0 && val>arr[mid-1] ) { return solve(arr[mid],arr[mid-1],val); } j=mid-1; } else{ if ( mid<n-1 && val<arr[mid+1] ) { return solve(arr[mid],arr[mid+1],val); } i=mid+1; } } return arr[mid]; } } /* */
Java
["5\n2 2 3\n7 8\n6 3\n3 1 4\n1 1 1\n1\n1\n1000000000\n2 2 2\n1 2\n5 4\n6 7\n2 2 2\n1 2\n3 4\n6 7\n3 4 1\n3 2 1\n7 3 3 4\n6"]
3 seconds
["14\n1999999996000000002\n24\n24\n14"]
NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.
Java 8
standard input
[ "math", "implementation", "sortings", "data structures", "binary search" ]
79b58eb781cd73ccf7994866b9a8b695
The first line contains a single integer $$$t$$$ ($$$1\le t \le 100$$$)  — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (the sum for all test cases).
1,700
For each test case, print a line contains one integer  — the minimum value which Xenia wants to find.
standard output
PASSED
9fdc62e090d887b9fa6652ab800e308c
train_001.jsonl
1586961300
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?
256 megabytes
//package practice.codeforce.round_635.problem4; import java.io.*; import java.math.BigInteger; import java.util.Arrays; import java.util.InputMismatchException; import java.util.Scanner; public class Solution { class Solver { public void solve(InputReader in, OutputWriter out) { int t = in.readInt(); for (int c = 0; c < t; c++) { int r = in.readInt(); int g = in.readInt(); int b = in.readInt(); int[] arr_r = IOUtils.readIntArray(in, r); int[] arr_g = IOUtils.readIntArray(in, g); int[] arr_b = IOUtils.readIntArray(in, b); Arrays.sort(arr_r); Arrays.sort(arr_g); Arrays.sort(arr_b); long min = find(arr_r, arr_g, arr_b); min = Math.min(min, find(arr_g, arr_r, arr_b)); min = Math.min(min, find(arr_b, arr_g, arr_r)); out.printLine(min); } } public long find(int[] arr_r, int[] arr_g, int[] arr_b) { long minValue = Long.MAX_VALUE; for (int x = 0; x < arr_r.length; x++) { Pair<Integer, Integer> pair_g = neighbours(arr_g, arr_r[x]); Pair<Integer, Integer> pair_b = neighbours(arr_b, (arr_r[x] + arr_g[pair_g.first]) / 2); minValue = Math.min(minValue, calculate(arr_r[x], arr_g[pair_g.first], arr_b[pair_b.first])); if (pair_b.second != null) { minValue = Math.min(minValue, calculate(arr_r[x], arr_g[pair_g.first], arr_b[pair_b.second])); } if (pair_g.second != null) { pair_b = neighbours(arr_b, (arr_r[x] + arr_g[pair_g.second]) / 2); minValue = Math.min(minValue, calculate(arr_r[x], arr_g[pair_g.second], arr_b[pair_b.first])); if (pair_b.second != null) { minValue = Math.min(minValue, calculate(arr_r[x], arr_g[pair_g.second], arr_b[pair_b.second])); } } } return minValue; } public long calculate(long x, long y, long z) { return (x - y) * (x - y) + (x - z) * (x - z) + (y - z) * (y - z); } public Pair<Integer, Integer> neighbours(int[] arr, int value) { int y = Arrays.binarySearch(arr, value); if (y >= 0) { if (y < arr.length - 1) { return new Pair<>(y, y + 1); } return new Pair<>(y, null); } y = Math.abs(y) - 1; if (y == 0) { return new Pair<>(y, null); } if (y == arr.length) { return new Pair<>(y - 1, null); } return new Pair<>(y - 1, y); } } public static void main(String[] args) { Solution t = new Solution(); InputStream inputStream = System.in; OutputStream outputStream = System.out; try { if (IS_LOCAL) { String packagePath = ROOT + t.getClass().getCanonicalName().replace("." + t.getClass().getSimpleName(), "") .replace(".", "/"); String inputFileName = packagePath + "/" + INPUT; String outputFileName = packagePath + "/" + OUTPUT; File inputFile = new File(inputFileName); inputStream = new FileInputStream(inputFile); Logger.printfln("Reading from file: %s", inputFile.getAbsolutePath()); File outputFile = new File(outputFileName); outputStream = new FileOutputStream(outputFile, false); Logger.printfln("Writing to file: %s", outputFile.getAbsolutePath()); } else { Logger.println("Reading stdin and writing to stdout"); } } catch (IOException e) { Logger.println(e.toString()); Logger.println("Reading stdin and writing to stdout"); } InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); new Solution().new Solver().solve(in, out); out.close(); } public static final boolean IS_LOCAL = false; public static String ROOT = "/home/lorderot/projects/algo_problems/src/main/java/"; public static String INPUT = "input.txt"; public static String OUTPUT = "output.txt"; } class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = in.readInt(); return array; } public static long[] readLongArray(InputReader in, int size) { long[] array = new long[size]; for (int i = 0; i < size; i++) array[i] = in.readLong(); return array; } public static int[][] readIntTable(InputReader in, int rowCount, int columnCount) { int[][] table = new int[rowCount][]; for (int i = 0; i < rowCount; i++) table[i] = readIntArray(in, columnCount); return table; } public static BigInteger[] readBigInt(InputReader in, int size) { Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(in.stream))); BigInteger[] arr = new BigInteger[size]; for (int i = 0; i < size; i++) { arr[i] = sc.nextBigInteger(); } return arr; } public static double[] readDoubleArray(InputReader in, int size) { Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(in.stream))); double[] arr = new double[size]; for (int i = 0; i < size; i++) { arr[i] = sc.nextDouble(); } return arr; } } class Pair<U, V> implements Comparable<Pair<U, V>> { public final U first; public final V second; public static <U, V> Pair<U, V> makePair(U first, V second) { return new Pair<U, V>(first, second); } public Pair(U first, V 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; Pair pair = (Pair) o; return !(first != null ? !first.equals(pair.first) : pair.first != null) && !(second != null ? !second.equals(pair.second) : pair.second != null); } public int hashCode() { int result = first != null ? first.hashCode() : 0; result = 31 * result + (second != null ? second.hashCode() : 0); return result; } public String toString() { return "(" + first + "," + second + ")"; } public int compareTo(Pair<U, V> o) { int value = ((Comparable<U>) first).compareTo(o.first); if (value != 0) return value; return ((Comparable<V>) second).compareTo(o.second); } } class MiscUtils { public static final int[] DX4 = {1, 0, -1, 0}; public static final int[] DY4 = {0, -1, 0, 1}; } class GeometryUtils { public static double epsilon = 1e-8; } class InputReader { InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public 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 String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } class Logger { public static void println(Object o) { if (!Solution.IS_LOCAL) { return; } System.err.println(o); } public static void print(Object o) { if (!Solution.IS_LOCAL) { return; } System.err.print(o); } public static void printf(String s, Object... objects) { if (!Solution.IS_LOCAL) { return; } System.err.printf(s, objects); } public static void printfln(String s, Object... objects) { if (!Solution.IS_LOCAL) { return; } System.err.println(String.format(s, objects)); } }
Java
["5\n2 2 3\n7 8\n6 3\n3 1 4\n1 1 1\n1\n1\n1000000000\n2 2 2\n1 2\n5 4\n6 7\n2 2 2\n1 2\n3 4\n6 7\n3 4 1\n3 2 1\n7 3 3 4\n6"]
3 seconds
["14\n1999999996000000002\n24\n24\n14"]
NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.
Java 8
standard input
[ "math", "implementation", "sortings", "data structures", "binary search" ]
79b58eb781cd73ccf7994866b9a8b695
The first line contains a single integer $$$t$$$ ($$$1\le t \le 100$$$)  — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (the sum for all test cases).
1,700
For each test case, print a line contains one integer  — the minimum value which Xenia wants to find.
standard output
PASSED
507e0a243d20fc780125043b10cacb95
train_001.jsonl
1586961300
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.util.*; import java.math.BigInteger; public class Main { InputReader in; Printer out; ArrayList<Integer>[] tree; long[] height; long[] subtreeCount; long[] res; boolean[] mark; private void start() throws Exception { // for (int i = 0; i < 13; i++) { // out.println(i + " c " + c(new long[]{2L, 4L, 6L, 8L, 10L}, i)); // out.println(i + " f " + f(new long[]{2L, 4L, 6L, 8L, 10L}, i)); // } // // out.flush(); int t = in.nextInt(); while (t-- > 0) { int r = in.nextInt(); int g = in.nextInt(); int b = in.nextInt(); long x[] = new long[r]; long y[] = new long[g]; long z[] = new long[b]; for (int i = 0; i < r; i++) { x[i] = in.nextLong(); } for (int i = 0; i < g; i++) { y[i] = in.nextLong(); } for (int i = 0; i < b; i++) { z[i] = in.nextLong(); } Arrays.sort(x); Arrays.sort(y); Arrays.sort(z); long res = Long.MAX_VALUE; res = Math.min(res, foo(x, y, z)); res = Math.min(res, foo(x, z, y)); res = Math.min(res, foo(y, x, z)); res = Math.min(res, foo(y, z, x)); res = Math.min(res, foo(z, x, y)); res = Math.min(res, foo(z, y, x)); out.println(res); } } long foo(long x[], long y[], long z[]) { // TreeSet<Long> xs = new TreeSet<>(); // TreeSet<Long> ys = new TreeSet<>(); // TreeSet<Long> zs = new TreeSet<>(); // for (long v: x) { // xs.add(v); // } // for (long v: y) { // ys.add(v); // } // for (long v: z) { // zs.add(v); // } long res = Long.MAX_VALUE; for (long xVal: x) { ArrayList<Long> yList = new ArrayList<>(); yList.add(c(y, xVal)); yList.add(f(y, xVal)); ArrayList<Long> zList = new ArrayList<>(); for (long yVal: yList) { zList.add(c(z, yVal)); zList.add(f(z, yVal)); } zList.add(c(z, xVal)); zList.add(f(z, xVal)); for (long yVal: yList) { for (long zVal: zList) { res = Math.min(res, dist(xVal, yVal, zVal)); } } } return res; } long dist(long x, long y, long z) { return (x-y) * (x-y) + (z-y) * (z-y) + (z-x) * (z-x); } long c(long[] arr, long val) { // try { // return ys.ceiling(xVal); // } catch (NullPointerException e) { // return y[y.length - 1]; // } int i = 0, j = arr.length - 1; long bestTillNow = arr[arr.length - 1]; while (i <= j) { int mid = (i + j) / 2; if (arr[mid] == val) { return val; } else if (arr[mid] > val) { j = mid - 1; bestTillNow = arr[mid]; } else { i = mid + 1; } } return bestTillNow; } long f(long[] arr, long val) { int i = 0, j = arr.length - 1; long bestTillNow = arr[0]; while (i <= j) { int mid = (i + j) / 2; if (arr[mid] == val) { return val; } else if (arr[mid] < val) { i = mid + 1; bestTillNow = arr[mid]; } else { j = mid - 1; } } return bestTillNow; } class Pair { long index; long height; long subTree; Pair(long i, long h, long s) { this.index = i; this.height = h; this.subTree = s; } } public long GCD(long a, long b) { return b==0L ? a : GCD(b, a%b); } long power(long x, long n, long mod) { if (n <= 0) { return 1; } long y = power(x, n / 2, mod); if ((n % 2) == 0) { return (y * y) % mod; } else { return (((y * y) % mod) * x) % mod; } } long gcd(long a, long b) { return BigInteger.valueOf(a).gcd(BigInteger.valueOf(b)).longValue(); } public static void main(String[] args) throws Exception { InputReader in; PrintStream out; in = new InputReader(System.in); out = System.out; Main main = new Main(); main.in = in; main.out = new Printer(out, true); main.start(); main.out.flush(); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String nextString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } 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 long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return nextString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } class Printer { PrintStream out; StringBuilder buffer = new StringBuilder(); boolean autoFlush; public Printer(PrintStream out) { this.out = out; } public Printer(PrintStream out, boolean autoFlush) { this.out = out; this.autoFlush = autoFlush; } public void println() { buffer.append("\n"); if (autoFlush) { flush(); } } public void println(int n) { println(Integer.toString(n)); } public void println(long n) { println(Long.toString(n)); } public void println(double n) { println(Double.toString(n)); } public void println(float n) { println(Float.toString(n)); } public void println(boolean n) { println(Boolean.toString(n)); } public void println(char n) { println(Character.toString(n)); } public void println(byte n) { println(Byte.toString(n)); } public void println(short n) { println(Short.toString(n)); } public void println(Object o) { println(o.toString()); } public void println(Object[] o) { println(Arrays.deepToString(o)); } public void println(String s) { buffer.append(s).append("\n"); if (autoFlush) { flush(); } } public void print(char s) { buffer.append(s); if (autoFlush) { flush(); } } public void print(String s) { buffer.append(s); if (autoFlush) { flush(); } } public void flush() { try { BufferedWriter log = new BufferedWriter(new OutputStreamWriter(out)); log.write(buffer.toString()); log.flush(); buffer = new StringBuilder(); } catch (Exception e) { e.printStackTrace(); } } } class DisjointUnionSets { int[] rank, parent; int n; // Constructor public DisjointUnionSets(int n) { rank = new int[n]; parent = new int[n]; this.n = n; makeSet(); } // Creates n sets with single item in each void makeSet() { for (int i = 0; i < n; i++) { // Initially, all elements are in // their own set. parent[i] = i; } } // Returns representative of x's set int find(int x) { // Finds the representative of the set // that x is an element of if (parent[x] != x) { // if x is not the parent of itself // Then x is not the representative of // his set, parent[x] = find(parent[x]); // so we recursively call Find on its parent // and move i's node directly under the // representative of this set } return parent[x]; } // Unites the set that includes x and the set // that includes x void union(int x, int y) { // Find representatives of two sets int xRoot = find(x), yRoot = find(y); // Elements are in the same set, no need // to unite anything. if (xRoot == yRoot) { return; } // If x's rank is less than y's rank if (rank[xRoot] < rank[yRoot]) // Then move x under y so that depth // of tree remains less { parent[xRoot] = yRoot; } // Else if y's rank is less than x's rank else if (rank[yRoot] < rank[xRoot]) // Then move y under x so that depth of // tree remains less { parent[yRoot] = xRoot; } else // if ranks are the same { // Then move y under x (doesn't matter // which one goes where) parent[yRoot] = xRoot; // And increment the the result tree's // rank by 1 rank[xRoot] = rank[xRoot] + 1; } } }
Java
["5\n2 2 3\n7 8\n6 3\n3 1 4\n1 1 1\n1\n1\n1000000000\n2 2 2\n1 2\n5 4\n6 7\n2 2 2\n1 2\n3 4\n6 7\n3 4 1\n3 2 1\n7 3 3 4\n6"]
3 seconds
["14\n1999999996000000002\n24\n24\n14"]
NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.
Java 8
standard input
[ "math", "implementation", "sortings", "data structures", "binary search" ]
79b58eb781cd73ccf7994866b9a8b695
The first line contains a single integer $$$t$$$ ($$$1\le t \le 100$$$)  — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (the sum for all test cases).
1,700
For each test case, print a line contains one integer  — the minimum value which Xenia wants to find.
standard output
PASSED
d59447d8e13f938eeb6dc564347405b7
train_001.jsonl
1586961300
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class D { public static void main(String[] args) throws IOException { Reader scn = new Reader(); int t = scn.nextInt(); StringBuilder sb = new StringBuilder(); D: while (t-- > 0) { int nr = scn.nextInt(); int ng = scn.nextInt(); int nb = scn.nextInt(); ArrayList<Integer> al1 = new ArrayList<>(); ArrayList<Integer> al2 = new ArrayList<>(); ArrayList<Integer> al3 = new ArrayList<>(); HashSet<Integer> h1 = new HashSet<>(); for (int i = 0; i < nr; i++) { int v = scn.nextInt(); if (!h1.contains(v)) { al1.add(v); h1.add(v); } } h1.clear(); for (int i = 0; i < ng; i++) { int v = scn.nextInt(); if (!h1.contains(v)) { al2.add(v); h1.add(v); } } h1.clear(); for (int i = 0; i < nb; i++) { int v = scn.nextInt(); if (!h1.contains(v)) { al3.add(v); h1.add(v); } } nr = al1.size(); ng = al2.size(); nb = al3.size(); Integer r[] = new Integer[nr]; Integer g[] = new Integer[ng]; Integer b[] = new Integer[nb]; for (int i = 0; i < nr; i++) r[i] = al1.get(i); for (int i = 0; i < ng; i++) g[i] = al2.get(i); for (int i = 0; i < nb; i++) b[i] = al3.get(i); Arrays.sort(r); Arrays.sort(g); Arrays.sort(b); long ans = (long) (2 * 1e18); for (int i = 0; i < nr; i++) { Integer v = r[i]; ArrayList<Integer> l1 = new ArrayList<>(); int i2 = Arrays.binarySearch(g, v); if (i2 >= 0) { l1.add(g[i2]); int i21 = i2, i22 = i2; while (i21 >= 0 && g[i21] == g[i2]) i21--; if (i21 >= 0) l1.add(g[i21]); while (i22 < ng && g[i22] == g[i2]) i22++; if (i22 < ng) l1.add(g[i22]); } else { i2 = -(i2 + 1); if (i2 == ng && i2 - 1 >= 0) { l1.add(g[i2 - 1]); i2--; int i21 = i2; while (i21 >= 0 && g[i21] == g[i2]) i21--; if (i21 >= 0) l1.add(g[i21]); } else if (i2 == 0) { l1.add(g[i2]); int i21 = i2; while (i21 < ng && g[i21] == g[i2]) i21++; if (i21 < ng) l1.add(g[i21]); } else { l1.add(g[i2]); int i21 = i2; while (i21 >= 0 && g[i21] == g[i2]) i21--; if (i21 >= 0) l1.add(g[i21]); } } ArrayList<Integer> l2 = new ArrayList<>(); int i3 = Arrays.binarySearch(b, v); if (i3 >= 0) { l2.add(b[i3]); int i31 = i3, i32 = i3; while (i31 >= 0 && b[i31] == b[i3]) i31--; if (i31 >= 0) l2.add(b[i31]); while (i32 < nb && b[i32] == b[i3]) i32++; if (i32 < nb) l2.add(b[i32]); } else { i3 = -(i3 + 1); if (i3 == nb && i3 - 1 >= 0) { l2.add(b[i3 - 1]); i3--; int i31 = i3; while (i31 >= 0 && b[i31] == b[i3]) i31--; if (i31 >= 0) l2.add(b[i31]); } else if (i3 == 0) { l2.add(b[i3]); int i31 = i3; while (i31 < nb && b[i31] == b[i3]) i31++; if (i31 < nb) l2.add(b[i31]); } else { l2.add(b[i3]); int i31 = i3; while (i31 >= 0 && b[i31] == b[i3]) i31--; if (i31 >= 0) l2.add(b[i31]); } } for (int p = 0; p < l1.size(); p++) { for (int q = 0; q < l2.size(); q++) { long x1 = r[i] - l1.get(p); x1 = x1 * x1; long y1 = l1.get(p) - l2.get(q); y1 = y1 * y1; long z1 = r[i] - l2.get(q); z1 = z1 * z1; ans = Math.min(ans, x1 + y1 + z1); } } } for (int i = 0; i < nb; i++) { Integer v = b[i]; ArrayList<Integer> l1 = new ArrayList<>(); int i2 = Arrays.binarySearch(g, v); if (i2 >= 0) { l1.add(g[i2]); int i21 = i2, i22 = i2; while (i21 >= 0 && g[i21] == g[i2]) i21--; if (i21 >= 0) l1.add(g[i21]); while (i22 < ng && g[i22] == g[i2]) i22++; if (i22 < ng) l1.add(g[i22]); } else { i2 = -(i2 + 1); if (i2 == ng && i2 - 1 >= 0) { l1.add(g[i2 - 1]); i2--; int i21 = i2; while (i21 >= 0 && g[i21] == g[i2]) i21--; if (i21 >= 0) l1.add(g[i21]); } else if (i2 == 0) { l1.add(g[i2]); int i21 = i2; while (i21 < ng && g[i21] == g[i2]) i21++; if (i21 < ng) l1.add(g[i21]); } else { l1.add(g[i2]); int i21 = i2; while (i21 >= 0 && g[i21] == g[i2]) i21--; if (i21 >= 0) l1.add(g[i21]); } } ArrayList<Integer> l2 = new ArrayList<>(); int i3 = Arrays.binarySearch(r, v); if (i3 >= 0) { l2.add(r[i3]); int i31 = i3, i32 = i3; while (i31 >= 0 && r[i31] == r[i3]) i31--; if (i31 >= 0) l2.add(r[i31]); while (i32 < nr && r[i32] == r[i3]) i32++; if (i32 < nr) l2.add(r[i32]); } else { i3 = -(i3 + 1); if (i3 == nr && i3 - 1 >= 0) { l2.add(r[i3 - 1]); i3--; int i31 = i3; while (i31 >= 0 && r[i31] == r[i3]) i31--; if (i31 >= 0) l2.add(r[i31]); } else if (i3 == 0) { l2.add(r[i3]); int i31 = i3; while (i31 < nr && r[i31] == r[i3]) i31++; if (i31 < nr) l2.add(r[i31]); } else { l2.add(r[i3]); int i31 = i3; while (i31 >= 0 && r[i31] == r[i3]) i31--; if (i31 >= 0) l2.add(r[i31]); } } for (int p = 0; p < l1.size(); p++) { for (int q = 0; q < l2.size(); q++) { long x1 = b[i] - l1.get(p); x1 = x1 * x1; long y1 = l1.get(p) - l2.get(q); y1 = y1 * y1; long z1 = b[i] - l2.get(q); z1 = z1 * z1; ans = Math.min(ans, x1 + y1 + z1); } } } for (int i = 0; i < ng; i++) { Integer v = g[i]; ArrayList<Integer> l1 = new ArrayList<>(); int i2 = Arrays.binarySearch(b, v); if (i2 >= 0) { l1.add(b[i2]); int i21 = i2, i22 = i2; while (i21 >= 0 && b[i21] == b[i2]) i21--; if (i21 >= 0) l1.add(b[i21]); while (i22 < nb && b[i22] == b[i2]) i22++; if (i22 < nb) l1.add(b[i22]); } else { i2 = -(i2 + 1); if (i2 == nb && i2 - 1 >= 0) { l1.add(b[i2 - 1]); i2--; int i21 = i2; while (i21 >= 0 && b[i21] == b[i2]) i21--; if (i21 >= 0) l1.add(b[i21]); } else if (i2 == 0) { l1.add(b[i2]); int i21 = i2; while (i21 < nb && b[i21] == b[i2]) i21++; if (i21 < nb) l1.add(b[i21]); } else { l1.add(b[i2]); int i21 = i2; while (i21 >= 0 && b[i21] == b[i2]) i21--; if (i21 >= 0) l1.add(b[i21]); } } ArrayList<Integer> l2 = new ArrayList<>(); int i3 = Arrays.binarySearch(r, v); if (i3 >= 0) { l2.add(r[i3]); int i31 = i3, i32 = i3; while (i31 >= 0 && r[i31] == r[i3]) i31--; if (i31 >= 0) l2.add(r[i31]); while (i32 < nr && r[i32] == r[i3]) i32++; if (i32 < nr) l2.add(r[i32]); } else { i3 = -(i3 + 1); if (i3 == nr && i3 - 1 >= 0) { l2.add(r[i3 - 1]); i3--; int i31 = i3; while (i31 >= 0 && r[i31] == r[i3]) i31--; if (i31 >= 0) l2.add(r[i31]); } else if (i3 == 0) { l2.add(r[i3]); int i31 = i3; while (i31 < nr && r[i31] == r[i3]) i31++; if (i31 < nr) l2.add(r[i31]); } else { l2.add(r[i3]); int i31 = i3; while (i31 >= 0 && r[i31] == r[i3]) i31--; if (i31 >= 0) l2.add(r[i31]); } } for (int p = 0; p < l1.size(); p++) { for (int q = 0; q < l2.size(); q++) { long x1 = g[i] - l1.get(p); x1 = x1 * x1; long y1 = l1.get(p) - l2.get(q); y1 = y1 * y1; long z1 = g[i] - l2.get(q); z1 = z1 * z1; ans = Math.min(ans, x1 + y1 + z1); } } } sb.append(ans + "\n"); } System.out.print(sb); } public static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } }
Java
["5\n2 2 3\n7 8\n6 3\n3 1 4\n1 1 1\n1\n1\n1000000000\n2 2 2\n1 2\n5 4\n6 7\n2 2 2\n1 2\n3 4\n6 7\n3 4 1\n3 2 1\n7 3 3 4\n6"]
3 seconds
["14\n1999999996000000002\n24\n24\n14"]
NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.
Java 8
standard input
[ "math", "implementation", "sortings", "data structures", "binary search" ]
79b58eb781cd73ccf7994866b9a8b695
The first line contains a single integer $$$t$$$ ($$$1\le t \le 100$$$)  — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (the sum for all test cases).
1,700
For each test case, print a line contains one integer  — the minimum value which Xenia wants to find.
standard output
PASSED
790288f33bbb034b6737ef259f811753
train_001.jsonl
1586961300
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?
256 megabytes
// package Round_635; import java.io.*; import java.math.BigInteger; import java.util.*; public class Xenia_Colorful { public static void main(String[] args) { FastReader in = new FastReader(); int numTrials = in.nextInt(); while(numTrials --> 0) { int r = in.nextInt(), g = in.nextInt(), b = in.nextInt(); ArrayList<Integer> redArr = new ArrayList<Integer>(), greenArr = new ArrayList<Integer>(), blueArr = new ArrayList<Integer>(); TreeSet<Integer> redSet = new TreeSet<Integer>(), greenSet = new TreeSet<Integer>(), blueSet = new TreeSet<Integer>(); for(int i = 0; i < r; i++) { int n = in.nextInt(); redArr.add(n); redSet.add(n); } for(int i = 0; i < g; i++) { int n = in.nextInt(); greenArr.add(n); greenSet.add(n); } for(int i = 0; i < b; i++) { int n = in.nextInt(); blueArr.add(n); blueSet.add(n); } long minVal = Long.MAX_VALUE; for(int i = 0; i < redArr.size(); i++) { int val = redArr.get(i); if(greenSet.floor(val) != null) { int currG = greenSet.floor(val); if(blueSet.floor(val) != null) { int currB = blueSet.floor(val); minVal = Math.min(minVal, calcValue(val, currB, currG)); } if(blueSet.ceiling(val) != null) { int currB = blueSet.ceiling(val); minVal = Math.min(minVal, calcValue(val, currB, currG)); } } if(greenSet.ceiling(val) != null) { int currG = greenSet.ceiling(val); if(blueSet.floor(val) != null) { int currB = blueSet.floor(val); minVal = Math.min(minVal, calcValue(val, currB, currG)); } if(blueSet.ceiling(val) != null) { int currB = blueSet.ceiling(val); minVal = Math.min(minVal, calcValue(val, currB, currG)); } } } for(int i = 0; i < greenArr.size(); i++) { int val = greenArr.get(i); if(redSet.floor(val) != null) { int currG = redSet.floor(val); if(blueSet.floor(val) != null) { int currB = blueSet.floor(val); minVal = Math.min(minVal, calcValue(val, currB, currG)); } if(blueSet.ceiling(val) != null) { int currB = blueSet.ceiling(val); minVal = Math.min(minVal, calcValue(val, currB, currG)); } } if(redSet.ceiling(val) != null) { int currG = redSet.ceiling(val); if(blueSet.floor(val) != null) { int currB = blueSet.floor(val); minVal = Math.min(minVal, calcValue(val, currB, currG)); } if(blueSet.ceiling(val) != null) { int currB = blueSet.ceiling(val); minVal = Math.min(minVal, calcValue(val, currB, currG)); } } } for(int i = 0; i < blueArr.size(); i++) { int val = blueArr.get(i); if(greenSet.floor(val) != null) { int currG = greenSet.floor(val); if(redSet.floor(val) != null) { int currB = redSet.floor(val); minVal = Math.min(minVal, calcValue(val, currB, currG)); } if(redSet.ceiling(val) != null) { int currB = redSet.ceiling(val); minVal = Math.min(minVal, calcValue(val, currB, currG)); } } if(greenSet.ceiling(val) != null) { int currG = greenSet.ceiling(val); if(redSet.floor(val) != null) { int currB = redSet.floor(val); minVal = Math.min(minVal, calcValue(val, currB, currG)); } if(redSet.ceiling(val) != null) { int currB = redSet.ceiling(val); minVal = Math.min(minVal, calcValue(val, currB, currG)); } } } System.out.println(minVal); } } static long calcValue(int a, int b, int c) { long out = 0; BigInteger aBig = new BigInteger(a + ""); BigInteger bBig = new BigInteger(b + ""); BigInteger cBig = new BigInteger(c + ""); out += aBig.subtract(bBig).pow(2).longValueExact(); out += bBig.subtract(cBig).pow(2).longValueExact(); out += aBig.subtract(cBig).pow(2).longValueExact(); return out; } 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
["5\n2 2 3\n7 8\n6 3\n3 1 4\n1 1 1\n1\n1\n1000000000\n2 2 2\n1 2\n5 4\n6 7\n2 2 2\n1 2\n3 4\n6 7\n3 4 1\n3 2 1\n7 3 3 4\n6"]
3 seconds
["14\n1999999996000000002\n24\n24\n14"]
NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.
Java 8
standard input
[ "math", "implementation", "sortings", "data structures", "binary search" ]
79b58eb781cd73ccf7994866b9a8b695
The first line contains a single integer $$$t$$$ ($$$1\le t \le 100$$$)  — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (the sum for all test cases).
1,700
For each test case, print a line contains one integer  — the minimum value which Xenia wants to find.
standard output
PASSED
8bbc6b788138ca2797f4e3ff1045784a
train_001.jsonl
1586961300
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?
256 megabytes
import jdk.nashorn.internal.runtime.linker.LinkerCallSite; import java.io.*; import java.lang.reflect.Array; import java.util.*; public class D { public static void main(String[] args) throws IOException { PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); InputReader re=new InputReader(System.in); int t=re.nextInt(); for(int i=0;i<t;i++){ int a=re.nextInt(); int b=re.nextInt(); int c=re.nextInt(); int []arra=new int[a]; int []arrb=new int[b]; int []arrc=new int[c]; for(int j=0;j<a;j++) arra[j]=re.nextInt(); for(int j=0;j<b;j++) arrb[j]=re.nextInt(); for(int j=0;j<c;j++) arrc[j]=re.nextInt(); Arrays.sort(arra); Arrays.sort(arrb); Arrays.sort(arrc); long min=9000000000000000000l; for(int j=0;j<a;j++){ int x=arra[j]; int y = binarySearch(x,0,b-1,arrb); int z = binarySearch(x,0,c-1,arrc); min=Math.min(min,solve(x,y,z)); } for(int j=0;j<b;j++){ int x=arrb[j]; int y = binarySearch(x,0,a-1,arra); int z = binarySearch(x,0,c-1,arrc); min=Math.min(min,solve(x,y,z)); } for(int j=0;j<c;j++){ int x=arrc[j]; int y = binarySearch(x,0,b-1,arrb); int z = binarySearch(x,0,a-1,arra); min=Math.min(min,solve(x,y,z)); } out.println(min); } out.flush(); } public static int binarySearch(int val,int l,int r,int arr[]){ while (r-l>1){ int mid=(r+l)>>1; if(arr[mid]>val) r=mid; else l=mid; } if(Math.abs(arr[l]-val)>Math.abs(arr[r]-val)) return arr[r]; return arr[l]; } public static void add(List<int[]> list,int start,int end,int [][]arr){ int l=start,r=end; while(r-l>1){ l++;r--; } list.add(arr[l]); if(r!=l) list.add(arr[r]); } private static long solve(long a, long b, long c) { long res=0; res+=(b-a)*(b-a); res+=(c-a)*(c-a); res+=(b-c)*(b-c); return res; } static class InputReader{ private BufferedReader in; private StringTokenizer tokenizer; public InputReader(InputStream stream){ in = new BufferedReader(new InputStreamReader(stream),32768); tokenizer = null; } public String next() throws IOException{ while(tokenizer==null || !tokenizer.hasMoreTokens()){ tokenizer = new StringTokenizer(in.readLine()); } return tokenizer.nextToken(); } public Long nextLong() throws IOException { String next = next(); return Long.valueOf(next); } public int nextInt() throws IOException{ return Integer.valueOf(next()); } } }
Java
["5\n2 2 3\n7 8\n6 3\n3 1 4\n1 1 1\n1\n1\n1000000000\n2 2 2\n1 2\n5 4\n6 7\n2 2 2\n1 2\n3 4\n6 7\n3 4 1\n3 2 1\n7 3 3 4\n6"]
3 seconds
["14\n1999999996000000002\n24\n24\n14"]
NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.
Java 8
standard input
[ "math", "implementation", "sortings", "data structures", "binary search" ]
79b58eb781cd73ccf7994866b9a8b695
The first line contains a single integer $$$t$$$ ($$$1\le t \le 100$$$)  — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (the sum for all test cases).
1,700
For each test case, print a line contains one integer  — the minimum value which Xenia wants to find.
standard output
PASSED
17abf077964e5b76db52cf2b1495fb0d
train_001.jsonl
1586961300
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?
256 megabytes
import java.util.*; import java.io.*; public class Solution{ public static void main (String[] args) throws IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); PrintWriter out=new PrintWriter(System.out); String[] temp=br.readLine().trim().split(" "); int numTestCases=Integer.parseInt(temp[0]); while(numTestCases-->0){ temp=br.readLine().trim().split(" "); int r=Integer.parseInt(temp[0]); int g=Integer.parseInt(temp[1]); int b=Integer.parseInt(temp[2]); int[] redWeights=new int[r]; int[] greenWeights=new int[g]; int[] blueWeights=new int[b]; temp=br.readLine().trim().split(" "); for(int i=0;i<r;i++){ redWeights[i]=Integer.parseInt(temp[i]); } temp=br.readLine().trim().split(" "); for(int i=0;i<g;i++){ greenWeights[i]=Integer.parseInt(temp[i]); } temp=br.readLine().trim().split(" "); for(int i=0;i<b;i++){ blueWeights[i]=Integer.parseInt(temp[i]); } out.println(minValue(redWeights,greenWeights,blueWeights)); } out.flush(); out.close(); } public static long minValue(int[] redWeights,int[] greenWeights,int[] blueWeights) { Arrays.sort(redWeights); Arrays.sort(blueWeights); Arrays.sort(greenWeights); long ans=Long.MAX_VALUE; int r=redWeights.length,g=greenWeights.length,b=blueWeights.length; for(int i=0;i<r;i++){ int index1=binarySearch1(greenWeights,redWeights[i],0,g-1); int index2=binarySearch2(greenWeights,redWeights[i],0,g-1); int index3=binarySearch1(blueWeights,redWeights[i],0,b-1); int index4=binarySearch2(blueWeights,redWeights[i],0,b-1); long option1=(long)(pow(redWeights[i]-greenWeights[index1],2)+pow(redWeights[i]-blueWeights[index3],2)+pow(greenWeights[index1]-blueWeights[index3],2)); long option2=(long)(pow(redWeights[i]-greenWeights[index1],2)+pow(redWeights[i]-blueWeights[index4],2)+pow(greenWeights[index1]-blueWeights[index4],2)); long option3=(long)(pow(redWeights[i]-greenWeights[index2],2)+pow(redWeights[i]-blueWeights[index3],2)+pow(greenWeights[index2]-blueWeights[index3],2)); long option4=(long)(pow(redWeights[i]-greenWeights[index2],2)+pow(redWeights[i]-blueWeights[index4],2)+pow(greenWeights[index2]-blueWeights[index4],2)); ans=Math.min(ans,Math.min(option1,Math.min(option2,Math.min(option3,option4)))); } for(int i=0;i<g;i++){ int index1=binarySearch1(redWeights,greenWeights[i],0,r-1); int index2=binarySearch2(redWeights,greenWeights[i],0,r-1); int index3=binarySearch1(blueWeights,greenWeights[i],0,b-1); int index4=binarySearch2(blueWeights,greenWeights[i],0,b-1); long option1=(long)(pow(redWeights[index1]-greenWeights[i],2)+pow(redWeights[index1]-blueWeights[index3],2)+pow(greenWeights[i]-blueWeights[index3],2)); long option2=(long)(pow(redWeights[index1]-greenWeights[i],2)+pow(redWeights[index1]-blueWeights[index4],2)+pow(greenWeights[i]-blueWeights[index4],2)); long option3=(long)(pow(redWeights[index2]-greenWeights[i],2)+pow(redWeights[index2]-blueWeights[index3],2)+pow(greenWeights[i]-blueWeights[index3],2)); long option4=(long)(pow(redWeights[index2]-greenWeights[i],2)+pow(redWeights[index2]-blueWeights[index4],2)+pow(greenWeights[i]-blueWeights[index4],2)); ans=Math.min(ans,Math.min(option1,Math.min(option2,Math.min(option3,option4)))); } for(int i=0;i<b;i++){ int index1=binarySearch1(redWeights,blueWeights[i],0,r-1); int index2=binarySearch2(redWeights,blueWeights[i],0,r-1); int index3=binarySearch1(greenWeights,blueWeights[i],0,g-1); int index4=binarySearch2(greenWeights,blueWeights[i],0,g-1); long option1=(long)(pow(redWeights[index1]-blueWeights[i],2)+pow(redWeights[index1]-greenWeights[index3],2)+pow(blueWeights[i]-greenWeights[index3],2)); long option2=(long)(pow(redWeights[index1]-blueWeights[i],2)+pow(redWeights[index1]-greenWeights[index4],2)+pow(blueWeights[i]-greenWeights[index4],2)); long option3=(long)(pow(redWeights[index2]-blueWeights[i],2)+pow(redWeights[index2]-greenWeights[index3],2)+pow(blueWeights[i]-greenWeights[index3],2)); long option4=(long)(pow(redWeights[index2]-blueWeights[i],2)+pow(redWeights[index2]-greenWeights[index4],2)+pow(blueWeights[i]-greenWeights[index4],2)); ans=Math.min(ans,Math.min(option1,Math.min(option2,Math.min(option3,option4)))); } return ans; } public static long pow(int a,int b) { if(b==0){ return 1; } long smallAns=pow(a,b/2); long ans=smallAns*smallAns; if(b%2!=0){ ans*=a; } return ans; } public static int binarySearch1(int[] arr,int x,int start,int end) { if(start>end){ return start; } int mid=(start+end)/2; if(arr[mid]==x) { return mid; } else if(arr[mid]<x){ if(mid+1>end || arr[mid+1]>x) { return mid; } return binarySearch1(arr,x,mid+1,end); } else{ return binarySearch1(arr,x,start,mid-1); } } public static int binarySearch2(int[] arr,int x,int start,int end) { if(start>end){ return end; } int mid=(start+end)/2; if(arr[mid]==x) { return mid; } else if(arr[mid]>x){ if(mid-1<start || arr[mid-1]<x){ return mid; } else{ return binarySearch2(arr,x,start,mid-1); } } else{ return binarySearch2(arr,x,mid+1,end); } } }
Java
["5\n2 2 3\n7 8\n6 3\n3 1 4\n1 1 1\n1\n1\n1000000000\n2 2 2\n1 2\n5 4\n6 7\n2 2 2\n1 2\n3 4\n6 7\n3 4 1\n3 2 1\n7 3 3 4\n6"]
3 seconds
["14\n1999999996000000002\n24\n24\n14"]
NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.
Java 8
standard input
[ "math", "implementation", "sortings", "data structures", "binary search" ]
79b58eb781cd73ccf7994866b9a8b695
The first line contains a single integer $$$t$$$ ($$$1\le t \le 100$$$)  — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (the sum for all test cases).
1,700
For each test case, print a line contains one integer  — the minimum value which Xenia wants to find.
standard output
PASSED
b67b63bc8d9405fc23a4e7c769306f5c
train_001.jsonl
1586961300
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class D { public static void main (String[] args) throws java.lang.Exception { new Solution(); } } class Solution { Reader reader; PrintWriter out; public Solution() { reader = new Reader(); out = new PrintWriter(System.out); int t = reader.ni(); while (reader.hasNext()) { run_case(); } out.flush(); } long res; private void run_case() { int r = reader.ni(); int g = reader.ni(); int b = reader.ni(); int[] arr_r = new int[r]; int[] arr_g = new int[g]; int[] arr_b = new int[b]; for (int i=0; i<r; i++) arr_r[i] = reader.ni(); for (int i=0; i<g; i++) arr_g[i] = reader.ni(); for (int i=0; i<b; i++) arr_b[i] = reader.ni(); // Arrays.sort(arr_b); TreeMap<Integer, Integer> map_r = new TreeMap<>(); TreeMap<Integer, Integer> map_g = new TreeMap<>(); TreeMap<Integer, Integer> map_b = new TreeMap<>(); res = Long.MAX_VALUE; // r g b // g r b // r b g // g b r // b r g // b g r for (int i=0; i<r; i++) map_r.put(arr_r[i], -1); for (int i=0; i<g; i++) map_g.put(arr_g[i], -1); for (int i=0; i<b; i++) map_b.put(arr_b[i], -1); dfs(map_r, map_g, map_b); dfs(map_g, map_r, map_b); dfs(map_r, map_b, map_g); dfs(map_g, map_b, map_r); dfs(map_b, map_r, map_g); dfs(map_b, map_g, map_r); out.println(res); return; } private void dfs(TreeMap<Integer, Integer> ma, TreeMap<Integer, Integer> mb, TreeMap<Integer, Integer> mc) { for (Integer u : mc.keySet()) { Integer a = ma.floorKey(u); if (a == null) continue; Integer b = mb.ceilingKey(a); if (b == null) continue; int da = Math.abs(u - a); int db = Math.abs(a - b); int dc = Math.abs(b - u); long t = 1L * da * da + 1L * db * db + 1l * dc * dc; res = Math.min(res, t); } } } class Reader { BufferedReader br; StringTokenizer st; public Reader(){ try { br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } } public String next() { if (st.hasMoreTokens()) return st.nextToken(); try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } return st.nextToken(); } public boolean hasNext() { try { if (!st.hasMoreTokens() && !br.ready()) return false; else return true; } catch (Exception e) { e.printStackTrace(); } return false; } public int ni() {return Integer.parseInt(this.next());} public long nl() {return Long.parseLong(this.next());} public String ns() {return this.next();} }
Java
["5\n2 2 3\n7 8\n6 3\n3 1 4\n1 1 1\n1\n1\n1000000000\n2 2 2\n1 2\n5 4\n6 7\n2 2 2\n1 2\n3 4\n6 7\n3 4 1\n3 2 1\n7 3 3 4\n6"]
3 seconds
["14\n1999999996000000002\n24\n24\n14"]
NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.
Java 8
standard input
[ "math", "implementation", "sortings", "data structures", "binary search" ]
79b58eb781cd73ccf7994866b9a8b695
The first line contains a single integer $$$t$$$ ($$$1\le t \le 100$$$)  — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (the sum for all test cases).
1,700
For each test case, print a line contains one integer  — the minimum value which Xenia wants to find.
standard output
PASSED
60dc371f3a984bf894eebeef987deb55
train_001.jsonl
1586961300
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?
256 megabytes
import java.awt.Font; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class D { public static long f(long x,long y,long z) { return (x-y)*(x-y)+(x-z)*(x-z)+(y-z)*(y-z); } public static long solve(int[] arr,int[] G,int[] B) { TreeSet<Integer>green = new TreeSet<Integer>(); TreeSet<Integer>blue = new TreeSet<Integer>(); for(int i=0;i<G.length;i++) green.add(G[i]); for(int i=0;i<B.length;i++) blue.add(B[i]); long min = Long.MAX_VALUE; for(int i=0;i<arr.length;i++) { int x = arr[i]; //4 cases //+ + int a = green.first(); int b = blue.first(); if(green.ceiling(x)!=null && blue.ceiling(x)!=null) { a = green.ceiling(x); b = blue.ceiling(x); if(green.contains(x)) { a = x; } if(blue.contains(x)) { b = x; } min = Math.min(f(a,b,x), min); } // + - if(green.ceiling(x)!=null && blue.floor(x)!=null) { a = green.ceiling(x); b = blue.floor(x); if(green.contains(x)) { a = x; } if(blue.contains(x)) { b = x; } min = Math.min(f(a,b,x), min); } // - + if(green.floor(x)!=null && blue.ceiling(x)!=null) { a = green.floor(x); b = blue.ceiling(x); if(green.contains(x)) { a = x; } if(blue.contains(x)) { b = x; } min = Math.min(f(a,b,x), min); } //- - if(green.floor(x)!=null && blue.floor(x)!=null) { a = green.floor(x); b = blue.floor(x); if(green.contains(x)) { a = x; } if(blue.contains(x)) { b = x; } min = Math.min(f(a,b,x), min); } } return min; } public static void main(String[] args) throws IOException{ Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int q = sc.nextInt(); while(q-->0) { int nr = sc.nextInt(); int ng = sc.nextInt(); int nb = sc.nextInt(); int[] arr = new int[nr]; int[] arr2 = new int[ng]; int[] arr3 = new int[nb]; TreeSet<Integer>green = new TreeSet<Integer>(); TreeSet<Integer>blue = new TreeSet<Integer>(); for(int i=0;i<nr;i++) { arr[i] = sc.nextInt(); } for(int i=0;i<ng;i++) arr2[i] = sc.nextInt(); for(int i=0;i<nb;i++) arr3[i] = sc.nextInt(); long min = solve(arr,arr2,arr3); min = Math.min(solve(arr2,arr,arr3), min); min = Math.min(solve(arr3,arr2,arr), min); pw.println(min); } pw.flush(); pw.close(); } }
Java
["5\n2 2 3\n7 8\n6 3\n3 1 4\n1 1 1\n1\n1\n1000000000\n2 2 2\n1 2\n5 4\n6 7\n2 2 2\n1 2\n3 4\n6 7\n3 4 1\n3 2 1\n7 3 3 4\n6"]
3 seconds
["14\n1999999996000000002\n24\n24\n14"]
NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.
Java 8
standard input
[ "math", "implementation", "sortings", "data structures", "binary search" ]
79b58eb781cd73ccf7994866b9a8b695
The first line contains a single integer $$$t$$$ ($$$1\le t \le 100$$$)  — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (the sum for all test cases).
1,700
For each test case, print a line contains one integer  — the minimum value which Xenia wants to find.
standard output
PASSED
eb8b289d0cf04e55f4e9fae931194503
train_001.jsonl
1586961300
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.StringTokenizer; public class D2 { static long[] first; static long[] second; static long[] third; static HashMap<Integer[], Long> combos; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintStream out = System.out; int t = Integer.parseInt(br.readLine()); for (int i = 0; i < t; i++) { String[] abc = br.readLine().split(" "); int a = Integer.parseInt(abc[0]); int b = Integer.parseInt(abc[1]); int c = Integer.parseInt(abc[2]); first = new long[a]; second = new long[b]; third = new long[c]; abc = br.readLine().split(" "); for (int j = 0; j < a; j++) first[j] = Integer.parseInt(abc[j]); abc = br.readLine().split(" "); for (int j = 0; j < b; j++) second[j] = Integer.parseInt(abc[j]); abc = br.readLine().split(" "); for (int j = 0; j < c; j++) third[j] = Integer.parseInt(abc[j]); Arrays.sort(first); Arrays.sort(second); Arrays.sort(third); combos = new HashMap<>(); out.println(optimal(0,0,0)); } System.out.flush(); } private static long optimal(int a, int b, int c) { if (a >= first.length || b >= second.length || c >= third.length) return Long.MAX_VALUE; long aa = first[a]; long bb = second[b]; long cc = third[c]; long val = calc(a, b, c); if (aa > bb && aa > cc) { long bBest = Long.MAX_VALUE; long cBest = Long.MAX_VALUE; if (b != second.length-1) bBest = calc(a, b+1, c); if (c != third.length-1) cBest = calc(a, b, c+1); if (bBest < cBest) return Math.min(val, optimal(a, b+1, c)); else return Math.min(val, optimal(a, b, c+1)); } else if (bb > cc) { long aBest = Long.MAX_VALUE; long cBest = Long.MAX_VALUE; if (a != first.length-1) aBest = calc(a+1, b, c); if (c != third.length-1) cBest = calc(a, b, c+1); if (aBest < cBest) return Math.min(val, optimal(a+1, b, c)); else {return Math.min(val, optimal(a, b, c+1));} } else { long bBest = Long.MAX_VALUE; long aBest = Long.MAX_VALUE; if (b != second.length-1) bBest = calc(a, b+1, c); if (a != first.length-1) aBest = calc(a+1, b, c); if (bBest < aBest) return Math.min(val, optimal(a, b+1, c)); else return Math.min(val, optimal(a+1, b, c)); } } private static long calc(int a, int b, int c) { long aa = first[a]; long bb = second[b]; long cc = third[c]; return (aa-bb)*(aa-bb)+(aa-cc)*(aa-cc)+(cc-bb)*(cc-bb); } }
Java
["5\n2 2 3\n7 8\n6 3\n3 1 4\n1 1 1\n1\n1\n1000000000\n2 2 2\n1 2\n5 4\n6 7\n2 2 2\n1 2\n3 4\n6 7\n3 4 1\n3 2 1\n7 3 3 4\n6"]
3 seconds
["14\n1999999996000000002\n24\n24\n14"]
NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.
Java 8
standard input
[ "math", "implementation", "sortings", "data structures", "binary search" ]
79b58eb781cd73ccf7994866b9a8b695
The first line contains a single integer $$$t$$$ ($$$1\le t \le 100$$$)  — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (the sum for all test cases).
1,700
For each test case, print a line contains one integer  — the minimum value which Xenia wants to find.
standard output
PASSED
b14bc675f6f5140252545461a5bbaa87
train_001.jsonl
1586961300
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; import java.util.TreeSet; public class r635d { public static void main(String[] args) { FastScanner scan=new FastScanner(); int t=scan.nextInt(); for(int tt=0;tt<t;tt++) { int n=scan.nextInt(), m=scan.nextInt(), k=scan.nextInt(); int[] a=new int[n], b=new int[m], c=new int[k]; TreeSet<Integer> aset=new TreeSet<>(), bset=new TreeSet<>(), cset=new TreeSet<>(); for(int i=0;i<n;i++) { a[i]=scan.nextInt(); aset.add(a[i]); } for(int i=0;i<m;i++) { b[i]=scan.nextInt(); bset.add(b[i]); } for(int i=0;i<k;i++) { c[i]=scan.nextInt(); cset.add(c[i]); } //omg Arrays.sort(a); Arrays.sort(b); Arrays.sort(c); //do the sweeeeeeep lalalala long res=Long.MAX_VALUE; res=Math.min(res,answer(a,b,cset)); res=Math.min(res,answer(b,c,aset)); res=Math.min(res,answer(a,c,bset)); System.out.println(res); // long ct=Long.MAX_VALUE; // for(int i=0;i<n;i++) { // for(int j=0;j<m;j++) { // for(int l=0;l<k;l++) { // ct=Math.min(ct,calc(a[i],b[j],c[l])); // } // } // } // System.out.println(ct); } } public static long answer(int[] a, int[] b, TreeSet<Integer> blue) { long res=Long.MAX_VALUE; int n=a.length, m=b.length; int p1=0, p2=0; while(p1<n&&p2<m) { while(p2<m&&b[p2]<=a[p1]) { int avg=(b[p2]+a[p1])/2; if(blue.ceiling(avg)!=null) res=Math.min(res,calc(b[p2],a[p1],blue.ceiling(avg))); if(blue.floor(avg)!=null) res=Math.min(res,calc(b[p2],a[p1],blue.floor(avg))); p2++; } if(p2==m) break; while(p1<n&&a[p1]<=b[p2]) { int avg=(b[p2]+a[p1])/2; if(blue.ceiling(avg)!=null) res=Math.min(res,calc(b[p2],a[p1],blue.ceiling(avg))); if(blue.floor(avg)!=null) res=Math.min(res,calc(b[p2],a[p1],blue.floor(avg))); p1++; } } return res; } public static long calc(long a, long b, long c) { return (a-b)*(a-b)+(b-c)*(b-c)+(a-c)*(a-c); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { try { br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(br.readLine()); } catch (Exception e){e.printStackTrace();} } public String next() { if (st.hasMoreTokens()) return st.nextToken(); try {st = new StringTokenizer(br.readLine());} catch (Exception e) {e.printStackTrace();} return st.nextToken(); } public int nextInt() {return Integer.parseInt(next());} public long nextLong() {return Long.parseLong(next());} public double nextDouble() {return Double.parseDouble(next());} public String nextLine() { String line = ""; if(st.hasMoreTokens()) line = st.nextToken(); else try {return br.readLine();}catch(IOException e){e.printStackTrace();} while(st.hasMoreTokens()) line += " "+st.nextToken(); return line; } } } /* 1 2 2 2 1 2 3 4 6 7 1 2 2 2 6 7 1 2 3 4 1 5 5 5 5 3 2 4 1 97 96 99 100 98 8 4 6 7 5 */
Java
["5\n2 2 3\n7 8\n6 3\n3 1 4\n1 1 1\n1\n1\n1000000000\n2 2 2\n1 2\n5 4\n6 7\n2 2 2\n1 2\n3 4\n6 7\n3 4 1\n3 2 1\n7 3 3 4\n6"]
3 seconds
["14\n1999999996000000002\n24\n24\n14"]
NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.
Java 8
standard input
[ "math", "implementation", "sortings", "data structures", "binary search" ]
79b58eb781cd73ccf7994866b9a8b695
The first line contains a single integer $$$t$$$ ($$$1\le t \le 100$$$)  — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (the sum for all test cases).
1,700
For each test case, print a line contains one integer  — the minimum value which Xenia wants to find.
standard output
PASSED
af93a25fb713e3a3f791b64baa925314
train_001.jsonl
1586961300
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.*; public class hello2 { static int f[]; static int level[]; static int visited[]; static class FastReader { static int f[]; static int level[]; static int visited[]; BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static String sum (String s) { String s1 = ""; if(s.contains("a")) s1+="a"; if(s.contains("e")) s1+="e"; if(s.contains("i")) s1+="i"; if(s.contains("o")) s1+="o"; if(s.contains("u")) s1+="u"; return s1; } public static HashMap<String, Integer> sortByValue(HashMap<String, Integer> hm) { // Create a list from elements of HashMap List<Map.Entry<String, Integer> > list = new LinkedList<Map.Entry<String, Integer> >(hm.entrySet()); // Sort the list Collections.sort(list, new Comparator<Map.Entry<String, Integer> >() { public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { return (o1.getValue()).compareTo(o2.getValue()); } }); // put data from sorted list to hashmap HashMap<String, Integer> temp = new LinkedHashMap<String, Integer>(); for (Map.Entry<String, Integer> aa : list) { temp.put(aa.getKey(), aa.getValue()); } return temp; } public static void main(String args[]) { FastReader input =new FastReader(); int t = input.nextInt(); while(t-->0) { int r=input.nextInt(); int g=input.nextInt(); int bl=input.nextInt(); long a[]=new long[r]; long b[]=new long[g]; long c[]=new long[bl]; for(int i=0;i<r;i++) a[i] = input.nextLong(); for(int i=0;i<g;i++) b[i] = input.nextLong(); for(int i=0;i<bl;i++) c[i] = input.nextLong(); Arrays.sort(a); Arrays.sort(b); Arrays.sort(c); long gg=(a[0]-b[0])*(a[0]-b[0]) + (a[0]-c[0])*(a[0]-c[0]) + (c[0]-b[0])*(c[0]-b[0]); for(int d=0,e=0,f=0;!(d==r-1 && e==g-1 && f==bl-1);) { long a1=Long.MAX_VALUE; long a2=Long.MAX_VALUE; long a3=Long.MAX_VALUE; if(d<r-1) { a1= (a[d+1]-b[e])*(a[d+1]-b[e]) + (a[d+1]-c[f])*(a[d+1]-c[f]) + (c[f]-b[e])*(c[f]-b[e]); } if(e<g-1) { a2= (a[d]-b[e+1])*(a[d]-b[e+1]) + (a[d]-c[f])*(a[d]-c[f]) + (c[f]-b[e+1])*(c[f]-b[e+1]); } if(f<bl-1) { a3= (a[d]-b[e])*(a[d]-b[e]) + (a[d]-c[f+1])*(a[d]-c[f+1]) + (c[f+1]-b[e])*(c[f+1]-b[e]); } if(a1<=a2 && a1<=a3) { gg=Math.min(a1, gg); d++; }else if(a2<=a3 && a2<=a1) { gg=Math.min(a2, gg); e++; }else { gg=Math.min(a3, gg); f++; } } System.out.println(gg); } } static long dis(long a,long b,long c) { return ((a-b)*(a-b) + (b-c)*(b-c) + (a-c)*(a-c)); } static int dfs(ArrayList<Integer> a[],int node,int l,int n) { visited[node]=1; level[node] = l; int sum =0; for(int i=0;i<a[node].size();i++) { if(visited[a[node].get(i)]==0) { sum+=dfs(a,a[node].get(i),l+1,n); } } f[node] = sum; return f[node]+1; } } class Pair { int first, second; Pair(int a, int b) { first = a; second = b; } }
Java
["5\n2 2 3\n7 8\n6 3\n3 1 4\n1 1 1\n1\n1\n1000000000\n2 2 2\n1 2\n5 4\n6 7\n2 2 2\n1 2\n3 4\n6 7\n3 4 1\n3 2 1\n7 3 3 4\n6"]
3 seconds
["14\n1999999996000000002\n24\n24\n14"]
NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.
Java 8
standard input
[ "math", "implementation", "sortings", "data structures", "binary search" ]
79b58eb781cd73ccf7994866b9a8b695
The first line contains a single integer $$$t$$$ ($$$1\le t \le 100$$$)  — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (the sum for all test cases).
1,700
For each test case, print a line contains one integer  — the minimum value which Xenia wants to find.
standard output
PASSED
b67e8880cd0fa3cc54a2e89e8394c1ac
train_001.jsonl
1586961300
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?
256 megabytes
import java.util.*; import java.io.*; public class R633D2D { public static void main(String[] args) throws Exception{ int num = 998244353; // TODO Auto-generated method stub BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(bf.readLine()); for(int i = 0;i<t;i++){ StringTokenizer st = new StringTokenizer(bf.readLine()); int nr = Integer.parseInt(st.nextToken()); int ng = Integer.parseInt(st.nextToken()); int nb = Integer.parseInt(st.nextToken()); ArrayList<Integer> red = new ArrayList<Integer>(); ArrayList<Integer> green = new ArrayList<Integer>(); ArrayList<Integer> blue = new ArrayList<Integer>(); StringTokenizer str = new StringTokenizer(bf.readLine()); for(int j = 0;j<nr;j++) red.add(Integer.parseInt(str.nextToken())); StringTokenizer stg = new StringTokenizer(bf.readLine()); for(int j = 0;j<ng;j++) green.add(Integer.parseInt(stg.nextToken())); StringTokenizer stb = new StringTokenizer(bf.readLine()); for(int j = 0;j<nb;j++) blue.add(Integer.parseInt(stb.nextToken())); Collections.sort(red); Collections.sort(green); Collections.sort(blue); long min = Long.MAX_VALUE; for(int j = 0;j<nr;j++){ int a1 = lowerBoundS(green, red.get(j), 0, ng); int a2 = lowerBound(blue, red.get(j), 0, nb); int a3 = lowerBound(green, red.get(j), 0, ng); int a4 = lowerBoundS(blue, red.get(j), 0, nb); long asdf = (long)((red.get(j) - green.get(a1)))*(long)((red.get(j) - green.get(a1))) + (long)((red.get(j) - blue.get(a2)))*(long)((red.get(j) - blue.get(a2))) + (long)(green.get(a1) - blue.get(a2)) * (long)((green.get(a1) - blue.get(a2))); if (asdf < min) min = asdf; long asdf1 = (long)((red.get(j) - green.get(a3)))*(long)((red.get(j) - green.get(a3))) + (long)((red.get(j) - blue.get(a4)))*(long)((red.get(j) - blue.get(a4))) + (long)(green.get(a3) - blue.get(a4)) * (long)((green.get(a3) - blue.get(a4))); if (asdf1 < min) min = asdf1; } for(int j = 0;j<nb;j++){ int a1 = lowerBoundS(red, blue.get(j), 0, nr); int a2 = lowerBound(green, blue.get(j), 0, ng); int a3 = lowerBound(red, blue.get(j), 0, nr); int a4 = lowerBoundS(green, blue.get(j), 0, ng); long asdf = (long)(blue.get(j) - red.get(a1))*(long)((blue.get(j) - red.get(a1))) + (long)((blue.get(j) - green.get(a2)))*(long)((blue.get(j) - green.get(a2))) + (long)(red.get(a1) - green.get(a2)) * (long)((red.get(a1) - green.get(a2))); if (asdf < min) min = asdf; long asdf1 = (long)((blue.get(j) - red.get(a3)))*(long)((blue.get(j) - red.get(a3))) + (long)((blue.get(j) - green.get(a4)))*(long)((blue.get(j) - green.get(a4))) + (long)(red.get(a3) - green.get(a4)) * (long)((red.get(a3) - green.get(a4))); if (asdf1 < min) min = asdf1; } for(int j = 0;j<ng;j++){ int a1 = lowerBoundS(red, green.get(j), 0, nr); int a2 = lowerBound(blue, green.get(j), 0, nb); int a3 = lowerBound(red, green.get(j), 0, nr); int a4 = lowerBoundS(blue, green.get(j), 0, nb); long asdf = (long)((green.get(j) - red.get(a1)))*(long)((green.get(j) - red.get(a1))) + (long)((green.get(j) - blue.get(a2)))*(long)((green.get(j) - blue.get(a2))) + (long)(red.get(a1) - blue.get(a2)) * (long)((red.get(a1) - blue.get(a2))); if (asdf < min) min = asdf; long asdf1 = (long)((green.get(j) - red.get(a3)))*(long)((green.get(j) - red.get(a3))) + (long)((green.get(j) - blue.get(a4)))*(long)((green.get(j) - blue.get(a4))) + (long)(red.get(a3) - blue.get(a4)) * (long)((red.get(a3) - blue.get(a4))); if (asdf1 < min) min = asdf1; } System.out.println(min); } } //smallest index of integer greater than or equal to target public static int lowerBound(ArrayList<Integer> array, int target, int l, int r){ if (array.size() == 1) return 0; int mid = -1; while (l<r){ mid = (l+r)/2; if (array.get(mid)>= target && (mid-1< 0 || array.get(mid-1) < target)) return mid; else if (array.get(mid) >= target) r = mid; else l = mid+1; } return mid; } //smallest index of integer greater than target public static int upperBound(ArrayList<Integer> array, int target, int l, int r){ if (array.size() == 1) return 0; int mid = -1; while (l<r){ mid = (l+r)/2; if (array.get(mid) > target && (mid-1 < 0 || array.get(mid-1) <= target)) return mid; else if (array.get(mid) > target) r = mid; else l = mid+1; } return mid; } //last index of integer less than or equal to target public static int lowerBoundS(ArrayList<Integer> array, int target, int l, int r){ if (array.size() == 1) return 0; int mid = -1; while (l<r){ mid = (l+r)/2; if (array.get(mid)<= target && (mid + 1 >= array.size() || array.get(mid+1) > target)) return mid; else if (array.get(mid) <= target) l = mid+1; else r = mid; } return mid; } //last index of integer less than target public static int upperBoundS(ArrayList<Integer> array, int target, int l, int r){ if (array.size() == 1) return 0; int mid = -1; while (l<r){ mid = (l+r)/2; if (array.get(mid)< target && (mid + 1 >= array.size() || array.get(mid+1) >= target)) return mid; else if (array.get(mid) <= target) l = mid+1; else r = mid; } return mid; } }
Java
["5\n2 2 3\n7 8\n6 3\n3 1 4\n1 1 1\n1\n1\n1000000000\n2 2 2\n1 2\n5 4\n6 7\n2 2 2\n1 2\n3 4\n6 7\n3 4 1\n3 2 1\n7 3 3 4\n6"]
3 seconds
["14\n1999999996000000002\n24\n24\n14"]
NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.
Java 8
standard input
[ "math", "implementation", "sortings", "data structures", "binary search" ]
79b58eb781cd73ccf7994866b9a8b695
The first line contains a single integer $$$t$$$ ($$$1\le t \le 100$$$)  — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (the sum for all test cases).
1,700
For each test case, print a line contains one integer  — the minimum value which Xenia wants to find.
standard output
PASSED
e82ab624b9764a8976ef8b5186e4a94e
train_001.jsonl
1586961300
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?
256 megabytes
/* / フフ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ム / )\⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ Y (⠀⠀| ( ͡° ͜ʖ ͡°)⠀⌒(⠀ ノ (⠀ ノ⌒ Y ⌒ヽ-く __/ | _⠀。ノ| ノ。 |/ (⠀ー '_人`ー ノ ⠀|\  ̄ _人'彡ノ ⠀ )\⠀⠀ 。⠀⠀ / ⠀⠀(\⠀ #⠀ / ⠀/⠀⠀⠀/ὣ====================D- /⠀⠀⠀/⠀ \ \⠀⠀\ ( (⠀)⠀⠀⠀⠀ ) ).⠀) (⠀⠀)⠀⠀⠀⠀⠀( | / |⠀ /⠀⠀⠀⠀⠀⠀ | / [_] ⠀⠀⠀⠀⠀[___] */ // Main Code at the Bottom import java.util.*; import java.lang.*; import java.io.*; import java.math.BigInteger; public class Main { //Fast IO class static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { boolean env=System.getProperty("ONLINE_JUDGE") != null; if(!env) { try { br=new BufferedReader(new FileReader("src\\input.txt")); } catch (FileNotFoundException e) { e.printStackTrace(); } } else br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static long MOD=1000000000+7; //Euclidean Algorithm static long gcd(long A,long B){ return (B==0)?A:gcd(B,A%B); } //Modular Exponentiation static long fastExpo(long x,long n){ if(n==0) return 1; if((n&1)==0) return fastExpo((x*x)%MOD,n/2)%MOD; return ((x%MOD)*fastExpo((x*x)%MOD,(n-1)/2))%MOD; } //Modular Inverse static long inverse(long x) { return fastExpo(x,MOD-2); } //Prime Number Algorithm 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(int i=5;i*i<=n;i+=6) if(n%i==0 || n%(i+2)==0) return false; return true; } //Reverse an array static void reverse(int arr[],int l,int r){ while(l<r) { int tmp=arr[l]; arr[l++]=arr[r]; arr[r--]=tmp; } } //Print array static void print1d(int arr[]) { out.println(Arrays.toString(arr)); } static void print2d(int arr[][]) { for(int a[]: arr) out.println(Arrays.toString(a)); } // Pair static class pair{ int x,y; pair(int a,int b){ this.x=a; this.y=b; } public boolean equals(Object obj) { if(obj == null || obj.getClass()!= this.getClass()) return false; pair p = (pair) obj; return (this.x==p.x && this.y==p.y); } public int hashCode() { return Objects.hash(x,y); } } static FastReader sc=new FastReader(); static PrintWriter out=new PrintWriter(System.out); //Main function(The main code starts from here static int nr,ng,nb; static Long R[],G[],B[]; public static long getClosest(long val1, long val2, long target) { if (target - val1 >= val2 - target) return val2; else return val1; } public static long findClosest(int f, long target) { int n; Long arr[]; if(f==0) { n=nr; arr=R; } else if(f==1) { n=ng; arr=G; } else { n=nb; arr=B; } if (target <= arr[0]) return arr[0]; if (target >= arr[n - 1]) return arr[n - 1]; int i = 0, j = n, mid = 0; while (i < j) { mid = (i + j) / 2; long arrmid=arr[mid]; if (arrmid == target) return arrmid; if (target < arrmid) { if (mid > 0 && target > arr[mid - 1]) return getClosest(arr[mid - 1], arrmid, target); j = mid; } else { if (mid < n-1 && target < arr[mid + 1]) return getClosest(arrmid, arr[mid + 1], target); i = mid + 1; } } return arr[mid]; } static long func(long x,long y,long z) { long res=(x-y)*(x-y)+(y-z)*(y-z)+(z-x)*(z-x); return res; } public static void main (String[] args) throws java.lang.Exception { int test; test=1; test=sc.nextInt(); while(test-->0){ nr=sc.nextInt();ng=sc.nextInt();nb=sc.nextInt(); R=new Long[nr];G=new Long[ng];B=new Long[nb]; for(int i=0;i<nr;i++) R[i]=sc.nextLong(); for(int i=0;i<ng;i++) G[i]=sc.nextLong(); for(int i=0;i<nb;i++) B[i]=sc.nextLong(); Arrays.parallelSort(R); Arrays.parallelSort(G); Arrays.parallelSort(B); long ans=Long.MAX_VALUE; for(long x: R) { long y=findClosest(1,x); long z1=findClosest(2,x); long z2=findClosest(2,y); ans=Math.min(ans, Math.min(func(x,y,z1), func(x,y,z2))); long z=z1; long y1=y; long y2=findClosest(1,z); ans=Math.min(ans, Math.min(func(x,y1,z), func(x,y2,z))); } for(long x: G) { long y=findClosest(0,x); long z1=findClosest(2,x); long z2=findClosest(2,y); ans=Math.min(ans, Math.min(func(x,y,z1), func(x,y,z2))); long z=z1; long y1=y; long y2=findClosest(0,z); ans=Math.min(ans, Math.min(func(x,y1,z), func(x,y2,z))); } for(long x: B) { long y=findClosest(1,x); long z1=findClosest(0,x); long z2=findClosest(0,y); ans=Math.min(ans, Math.min(func(x,y,z1), func(x,y,z2))); long z=z1; long y1=y; long y2=findClosest(1,z); ans=Math.min(ans, Math.min(func(x,y1,z), func(x,y2,z))); } out.println(ans); } out.flush(); out.close(); } }
Java
["5\n2 2 3\n7 8\n6 3\n3 1 4\n1 1 1\n1\n1\n1000000000\n2 2 2\n1 2\n5 4\n6 7\n2 2 2\n1 2\n3 4\n6 7\n3 4 1\n3 2 1\n7 3 3 4\n6"]
3 seconds
["14\n1999999996000000002\n24\n24\n14"]
NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.
Java 8
standard input
[ "math", "implementation", "sortings", "data structures", "binary search" ]
79b58eb781cd73ccf7994866b9a8b695
The first line contains a single integer $$$t$$$ ($$$1\le t \le 100$$$)  — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (the sum for all test cases).
1,700
For each test case, print a line contains one integer  — the minimum value which Xenia wants to find.
standard output
PASSED
68330075a7b588e90b35052ea5254347
train_001.jsonl
1586961300
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; public class D { public static void main(String []args) throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String input; String []splited; int q,n,m,t; int []arr,arr1,arr2; input=br.readLine(); splited=input.split(" "); t=Integer.parseInt(splited[0]); int a,b,c,d; int u,v,k,r,g; int yy=0; for(int i=0;i<t;i++) { input=br.readLine(); splited=input.split(" "); r=Integer.parseInt(splited[0]); g=Integer.parseInt(splited[1]); b=Integer.parseInt(splited[2]); input=br.readLine(); splited=input.split(" "); ArrayList<Integer> al1=new ArrayList<Integer>(r); ArrayList<Integer> al2=new ArrayList<Integer>(g); ArrayList<Integer> al3=new ArrayList<Integer>(b); for(int j=0;j<r;j++) { al1.add(Integer.parseInt(splited[j])); } input=br.readLine(); splited=input.split(" "); for(int j=0;j<g;j++) { al2.add(Integer.parseInt(splited[j])); } input=br.readLine(); splited=input.split(" "); for(int j=0;j<b;j++) { al3.add(Integer.parseInt(splited[j])); } Collections.sort(al1);; Collections.sort(al2); Collections.sort(al3); long ans=Long.MAX_VALUE; for(int j=0;j<b;j++) { int z=al3.get(j); long x=bs(al1,z); long y=bs(al2,z); ans=Math.min(ans,1l*(x-y)*(x-y)+(y-z)*(y-z)+(x-z)*(x-z)); // System.out.println(z+" "+y+" "+x+" "+ans); x=bs(al1,(int)y); ans=Math.min(ans,1l*(x-y)*(x-y)+(y-z)*(y-z)+(x-z)*(x-z)); //System.out.println(z+" "+y+" "+z+" "+ans); x=bs(al1,z); y=bs(al2,(int)x); ans=Math.min(ans,1l*(x-y)*(x-y)+(y-z)*(y-z)+(x-z)*(x-z)); // System.out.println(z+" "+y+" "+z+" "+ans); } for(int j=0;j<r;j++) { int x=al1.get(j); long y=bs(al2,x); long z=bs(al3,x); ans=Math.min(ans,1l*(x-y)*(x-y)+(y-z)*(y-z)+(x-z)*(x-z)); z=bs(al3,(int)y); ans=Math.min(ans,1l*(x-y)*(x-y)+(y-z)*(y-z)+(x-z)*(x-z)); z=bs(al3,x); y=bs(al2,(int)z); ans=Math.min(ans,1l*(x-y)*(x-y)+(y-z)*(y-z)+(x-z)*(x-z)); //System.out.println(ans); } for(int j=0;j<g;j++) { int y=al2.get(j); long x=bs(al1,y); long z=bs(al3,y); ans=Math.min(ans,1l*(x-y)*(x-y)+(y-z)*(y-z)+(x-z)*(x-z)); z=bs(al3,(int)x); ans=Math.min(ans,1l*(x-y)*(x-y)+(y-z)*(y-z)+(x-z)*(x-z)); z=bs(al3,y); x=bs(al1,(int)z); ans=Math.min(ans,1l*(x-y)*(x-y)+(y-z)*(y-z)+(x-z)*(x-z)); // System.out.println(ans); } System.out.println(ans); } } static long bs(ArrayList<Integer> al,int key) { int j=Collections.binarySearch(al, key); if(j>=0) return al.get(j); else { j++; j=0-j; if(j==0) { return al.get(0); } else if(j==al.size()) { return al.get(j-1); } else { if(Math.abs(key-al.get(j))>Math.abs(key-al.get(j-1))) { return al.get(j-1); } else { return al.get(j); } } } } }
Java
["5\n2 2 3\n7 8\n6 3\n3 1 4\n1 1 1\n1\n1\n1000000000\n2 2 2\n1 2\n5 4\n6 7\n2 2 2\n1 2\n3 4\n6 7\n3 4 1\n3 2 1\n7 3 3 4\n6"]
3 seconds
["14\n1999999996000000002\n24\n24\n14"]
NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.
Java 8
standard input
[ "math", "implementation", "sortings", "data structures", "binary search" ]
79b58eb781cd73ccf7994866b9a8b695
The first line contains a single integer $$$t$$$ ($$$1\le t \le 100$$$)  — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (the sum for all test cases).
1,700
For each test case, print a line contains one integer  — the minimum value which Xenia wants to find.
standard output
PASSED
103d5b3f30d7f621672c2deff19ea890
train_001.jsonl
1586961300
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?
256 megabytes
//package codeforces.round635div2; import java.io.*; import java.util.*; public class CF635D { public static void main(String[] args) { // try { // FastScanner in = new FastScanner(new FileInputStream("src/input.in")); // PrintWriter out = new PrintWriter(new FileOutputStream("src/output.out")); FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); int t = in.nextInt(); solve(t, in, out); // } catch (IOException e) { // e.printStackTrace(); // } } private static void solve(int q, FastScanner in, PrintWriter out) { for (int qq = 0; qq < q; qq++) { int nr = in.nextInt(), ng = in.nextInt(), nb = in.nextInt(); Long[][] gems = new Long[3][]; gems[0] = in.nextLongArray(nr); gems[1] = in.nextLongArray(ng); gems[2] = in.nextLongArray(nb); for(int i = 0; i < 3; i++) { Arrays.sort(gems[i]); } // int[][] cases = {{0,1,2},{0,2,1},{1,0,2},{1,2,0},{2,0,1},{2,1,0}}; long best = Long.MAX_VALUE; // for(int i = 0; i < cases.length; i++) { // for(int j = 0; j < gems[cases[i][0]].length; j++) { // long t0 = gems[cases[i][0]][j]; // int idx = BinarySearch.leftMostLowerBound(gems[cases[i][2]], t0); // if(idx < 0) { // break; // } // long t2 = gems[cases[i][2]][idx]; // idx = bs(gems[cases[i][1]], (t0 + t2) / 2); // if(gems[cases[i][1]][idx] < t0) { // break; // } // else if(gems[cases[i][1]][idx] > t2) { // continue; // } // long t1 = gems[cases[i][1]][idx]; // best = Math.min(best, (t0 - t1) * (t0 - t1) + (t0 - t2) * (t0 - t2) + (t1 - t2) * (t1 - t2)); // } // } for(int i = 0; i < 3; i++) { for(int j = 0; j < gems[i].length; j++) { long x = gems[i][j]; long y1 = bsLower(gems[(i + 1) % 3], x); long y2 = bsUpper(gems[(i + 1) % 3], x); long z1 = bsLower(gems[(i + 2) % 3], x); long z2 = bsUpper(gems[(i + 2) % 3], x); best = Math.min(best, compute(x, y1, z1)); best = Math.min(best, compute(x, y1, z2)); best = Math.min(best, compute(x, y2, z1)); best = Math.min(best, compute(x, y2, z2)); } } out.println(best); } out.close(); } private static long compute(long x, long y, long z) { return (x - y) * (x - y) + (x - z) * (x - z) + (y - z) * (y - z); } //return the closest number that is >= t; if no number is >= t, the last number is returned private static long bsUpper(Long[] a, long t) { int l = 0, r = a.length - 1; while(l < r - 1) { int mid = l + (r - l) / 2; if(a[mid] >= t) { r = mid; } else { l = mid + 1; } } if(a[r] < t || a[l] < t) { return a[r]; } return a[l]; } //return the closet number that is <= t; if no number is <= t, the first number is returned private static long bsLower(Long[] a, long t) { int l = 0, r = a.length - 1; while(l < r - 1) { int mid = l + (r - l) / 2; if(a[mid] <= t) { l = mid; } else { r = mid - 1; } } if(a[l] > t || a[r] > t) { return a[l]; } return a[r]; } private static class BinarySearch { // return the right most index i such that a[i] <= t private static int rightMostUpperBound(Long[] a, long t) { int l = 0, r = a.length - 1; while (l < r - 1) { int mid = l + (r - l) / 2; if (a[mid] <= t) { l = mid; } else { r = mid - 1; } } if (a[r] <= t) { return r; } else if (a[l] <= t) { return l; } return -1; } // return the left most index i such that a[i] >= t private static int leftMostLowerBound(Long[] a, long t) { int l = 0, r = a.length - 1; while (l < r - 1) { int mid = l + (r - l) / 2; if (a[mid] >= t) { r = mid; } else { l = mid + 1; } } if (a[l] >= t) { return l; } else if (a[r] >= t) { return r; } return -1; } // Find the start and end index of a given t in a sorted(ascending) array; return [-1, -1] is t is not found private static int[] searchRange(Integer[] a, int t) { int first = firstPos(a, t); int last = firstPos(a, t + 1) - 1; if (first <= last) { return new int[]{first, last}; } return new int[]{-1, -1}; } private static int firstPos(Integer[] a, int t) { int first = a.length; int l = 0, r = a.length - 1; while (l <= r) { int mid = l + (r - l) / 2; if (a[mid] >= t) { first = mid; r = mid - 1; } else { l = mid + 1; } } return first; } } private static class NumberTheory { private static long modularAdd(long a, long b, int mod) { long sum = a + b; if (sum >= mod) { sum -= mod; } return sum; } private static long modularSubtract(long a, long b, int mod) { long diff = a - b; if (diff < 0) { diff += mod; } return diff; } private static long fastModPow(long x, int n, long mod) { if (n == 0) { return 1; } long coeff = 1, base = x; while (n > 1) { if (n % 2 != 0) { coeff = (coeff * base % mod); } base = (base * base % mod); n = n / 2; } long res = coeff * base % mod; return res; } private static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } private static long[] factorial(int n, long mod) { long[] factor = new long[n + 1]; factor[0] = 1; for (int i = 1; i <= n; i++) { factor[i] = factor[i - 1] * i % mod; } return factor; } private static long modInv_EEA(long a, long mod) { long[] res = solveGcdEquation(a, mod); if (res[2] != 1) { // a and m are not coprime, modular inverse of a by m does not exist. return -1; } return (res[0] % mod + mod) % mod; } private static long[] solveGcdEquation(long a, long b) { if (b == 0) { return new long[]{1, 0, a}; } long[] res = solveGcdEquation(b, a % b); return new long[]{res[1], res[0] - (a / b) * res[1], res[2]}; } private static long binomialCoefficient(long[] factorial, long n, long k, long mod) { return factorial[(int) n] * modInv_EEA(factorial[(int) k], mod) % mod * modInv_EEA(factorial[(int) (n - k)], mod) % mod; } } private static class Graph { private static int UNVISITED = 0; private static int VISITING = -1; private static int VISITED = 1; private static Stack<Integer> topologicalSort(Set<Integer>[] g) { Stack<Integer> stack = new Stack<>(); int[] state = new int[g.length]; for (int node = 0; node < g.length; node++) { if (!topoSortHelper(g, stack, state, node)) { return null; } } return stack; } private static boolean topoSortHelper(Set<Integer>[] g, Stack<Integer> stack, int[] state, int currNode) { if (state[currNode] == VISITED) { return true; } else if (state[currNode] == VISITING) { return false; } state[currNode] = VISITING; for (int neighbor : g[currNode]) { if (!topoSortHelper(g, stack, state, neighbor)) { return false; } } state[currNode] = VISITED; stack.push(currNode); return true; } } private static class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(InputStream stream) { try { br = new BufferedReader(new InputStreamReader(stream)); } catch (Exception e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } Integer[] nextIntArray(int n) { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } Long[] nextLongArray(int n) { Long[] a = new Long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } } }
Java
["5\n2 2 3\n7 8\n6 3\n3 1 4\n1 1 1\n1\n1\n1000000000\n2 2 2\n1 2\n5 4\n6 7\n2 2 2\n1 2\n3 4\n6 7\n3 4 1\n3 2 1\n7 3 3 4\n6"]
3 seconds
["14\n1999999996000000002\n24\n24\n14"]
NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.
Java 8
standard input
[ "math", "implementation", "sortings", "data structures", "binary search" ]
79b58eb781cd73ccf7994866b9a8b695
The first line contains a single integer $$$t$$$ ($$$1\le t \le 100$$$)  — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (the sum for all test cases).
1,700
For each test case, print a line contains one integer  — the minimum value which Xenia wants to find.
standard output
PASSED
6ae237ac03e6dc5659f086a3b3336e3d
train_001.jsonl
1517403900
Suppose that you are in a campus and have to go for classes day by day. As you may see, when you hurry to a classroom, you surprisingly find that many seats there are already occupied. Today you and your friends went for class, and found out that some of the seats were occupied.The classroom contains $$$n$$$ rows of seats and there are $$$m$$$ seats in each row. Then the classroom can be represented as an $$$n \times m$$$ matrix. The character '.' represents an empty seat, while '*' means that the seat is occupied. You need to find $$$k$$$ consecutive empty seats in the same row or column and arrange those seats for you and your friends. Your task is to find the number of ways to arrange the seats. Two ways are considered different if sets of places that students occupy differs.
256 megabytes
import java.io.*; import java.util.*; import java.nio.charset.StandardCharsets; // import java.math.BigInteger; public class C { static Writer wr; public static void main(String[] args) throws Exception { // long startTime = System.nanoTime(); // String testString = ""; // InputStream stream = new ByteArrayInputStream(testString.getBytes(StandardCharsets.UTF_8)); // Reader in = new Reader(stream); Reader in = new Reader(); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); wr = new Writer(); /* Precomputation */ // long elapsedTime = System.nanoTime() - startTime; // double seconds = (double)elapsedTime / 1000000000.0; // wr.writeRedLn(seconds); /* Input */ int N = in.nextInt(); int M = in.nextInt(); int K = in.nextInt(); boolean[][] grid = new boolean[N][M]; int count=0; for(int i=0;i<N;i++) { for(int j=0;j<M;j++) { if(in.nextChar()=='.') { grid[i][j] = true; count++; } } } ArrayList<Integer> options = new ArrayList<>(); for(int i=0;i<N;i++) { int curr=0; for(int j=0;j<M;j++) { if(grid[i][j]) { curr++; } else { if(curr>=K) options.add(curr); curr=0; } } if(curr>=K) options.add(curr); } for(int i=0;i<M;i++) { int curr=0; for(int j=0;j<N;j++) { if(grid[j][i]) { curr++; } else { if(curr>=K) options.add(curr); curr=0; } } if(curr>=K) options.add(curr); } long ans = 0; for(int x: options) { ans += x-K+1; } if(K==1) ans = count; out.write(ans + "\n"); out.flush(); } } class Writer { public void writeRedLn(Object x) { writeRedLn(x+""); } public void writeBlueLn(Object x) { writeBlueLn(x+""); } public void writeGreenLn(Object x) { writeGreenLn(x+""); } public void writePinkLn(Object x) { writePinkLn(x+""); } public void writeRedLn(String x) { System.out.println((char)27 + "[31m" + (char)27 + "[40m" + x + (char)27 + "[0m"); } public void writeBlueLn(String x) { System.out.println((char)27 + "[34m" + (char)27 + "[3m" + x + (char)27 + "[0m"); } public void writeGreenLn(String x) { System.out.println((char)27 + "[32m" + (char)27 + "[3m" + x + (char)27 + "[0m"); } public void writePinkLn(String x) { System.out.println((char)27 + "[30m" + (char)27 + "[45m" + x + (char)27 + "[0m"); } public void writeRed(String x) { System.out.print((char)27 + "[31m" + (char)27 + "[40m" + x + (char)27 + "[0m"); } public void writeBlue(String x) { System.out.print((char)27 + "[34m" + (char)27 + "[3m" + x + (char)27 + "[0m"); } public void writeGreen(String x) { System.out.print((char)27 + "[32m" + (char)27 + "[3m" + x + (char)27 + "[0m"); } public void writePink(String x) { System.out.print((char)27 + "[30m" + (char)27 + "[45m" + x + (char)27 + "[0m"); } } 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(InputStream stream){din=new DataInputStream(stream);buffer=new byte[BUFFER_SIZE];bufferPointer=bytesRead=0;} public String readLine()throws IOException{byte[] buf=new byte[1024];int cnt=0,c; while((c=read())!=-1){if(c=='\n')break;buf[cnt++]=(byte)c;}return new String(buf,0,cnt);} public char nextChar()throws IOException{byte c=read();while(c<=' ')c=read();return (char)c;} public int nextInt()throws IOException{int ret=0;byte c=read();while(c<=' ')c=read();boolean neg=(c=='-'); if(neg)c=read();do{ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');if(neg)return -ret;return ret;} public long nextLong()throws IOException{long ret=0;byte c=read();while(c<=' ')c=read();boolean neg=(c=='-'); if(neg)c=read();do{ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');if(neg)return -ret;return ret;} public double nextDouble()throws IOException{double ret=0,div=1;byte c=read();while(c<=' ')c=read();boolean neg=(c=='-');if(neg)c = read();do {ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9'); if(c=='.')while((c=read())>='0'&&c<='9')ret+=(c-'0')/(div*=10);if(neg)return -ret;return ret;} 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
["2 3 2\n**.\n...", "1 2 2\n..", "3 3 4\n.*.\n*.*\n.*."]
1 second
["3", "1", "0"]
NoteIn the first sample, there are three ways to arrange those seats. You can take the following seats for your arrangement. $$$(1,3)$$$, $$$(2,3)$$$ $$$(2,2)$$$, $$$(2,3)$$$ $$$(2,1)$$$, $$$(2,2)$$$
Java 8
standard input
[ "implementation", "brute force" ]
c1f247150831e9b52389bae697a1ca3d
The first line contains three positive integers $$$n,m,k$$$ ($$$1 \leq n, m, k \leq 2\,000$$$), where $$$n,m$$$ represent the sizes of the classroom and $$$k$$$ is the number of consecutive seats you need to find. Each of the next $$$n$$$ lines contains $$$m$$$ characters '.' or '*'. They form a matrix representing the classroom, '.' denotes an empty seat, and '*' denotes an occupied seat.
1,300
A single number, denoting the number of ways to find $$$k$$$ empty seats in the same row or column.
standard output
PASSED
5dbd543ca40fc75d6b1fa09913a0da54
train_001.jsonl
1517403900
Suppose that you are in a campus and have to go for classes day by day. As you may see, when you hurry to a classroom, you surprisingly find that many seats there are already occupied. Today you and your friends went for class, and found out that some of the seats were occupied.The classroom contains $$$n$$$ rows of seats and there are $$$m$$$ seats in each row. Then the classroom can be represented as an $$$n \times m$$$ matrix. The character '.' represents an empty seat, while '*' means that the seat is occupied. You need to find $$$k$$$ consecutive empty seats in the same row or column and arrange those seats for you and your friends. Your task is to find the number of ways to arrange the seats. Two ways are considered different if sets of places that students occupy differs.
256 megabytes
/* Author: prakashn Date : 1/31/2018 */ 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 _919C { InputStream is; PrintWriter out; String INPUT = "1 1 1 ."; static int check_right(char[][] seats, int n, int m, int k) { int res = 0; for (int i = 0; i < n; i++) { int con_seat = 0; for (int j = 0; j < m; j++) { if(seats[i][j] == '.') { con_seat++; if(con_seat >= k) { res++; } } else con_seat = 0; } } return res; } static int check_down(char[][] seats, int n, int m, int k) { int res = 0; for (int j = 0; j < m; j++) { int con_seat = 0; for (int i = 0; i < n; i++) { if(seats[i][j] == '.') { con_seat++; if(con_seat >= k) { res++; } } else con_seat = 0; } } return res; } void solve() { int n = ni(), m = ni(), k = ni(); char[][] seats = new char[n][]; for (int i = 0; i < n; i++) { seats[i] = ns().toCharArray(); } int res = 0; if(k == 1) { res += check_right(seats,n,m,k); } else { res += check_right(seats,n,m,k); res += check_down(seats,n,m,k); } out.println(res); // TLE // int res = 0; // for (int i = 0; i < n; i++) { // for (int j = 0; j < m; j++) { // if(seats[i][j] == '*') // continue; // if(check_down(seats, i, j, m,n, k)) { // res += 1; // } // if(check_right(seats, i, j, m, n, k)) { // res += 1; // } // } // } // out.println(res); } /* TEMPLATED CODE BELOW */ 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 _919C().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(); } } // prints 2d array private void printa(int[][] a) { out.printf("\t"); for (int i = 0; i < a[0].length; i++) out.printf("%5d ", i); out.println(); out.println("----------------"); for (int i = 0; i < a.length; i++) { out.printf(i + " =>"); for (int j = 0; j < a[i].length; j++) { out.printf("%5d ", a[i][j]); } out.println(); } out.println(); } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if (!oj) System.out.println(Arrays.deepToString(o)); } }
Java
["2 3 2\n**.\n...", "1 2 2\n..", "3 3 4\n.*.\n*.*\n.*."]
1 second
["3", "1", "0"]
NoteIn the first sample, there are three ways to arrange those seats. You can take the following seats for your arrangement. $$$(1,3)$$$, $$$(2,3)$$$ $$$(2,2)$$$, $$$(2,3)$$$ $$$(2,1)$$$, $$$(2,2)$$$
Java 8
standard input
[ "implementation", "brute force" ]
c1f247150831e9b52389bae697a1ca3d
The first line contains three positive integers $$$n,m,k$$$ ($$$1 \leq n, m, k \leq 2\,000$$$), where $$$n,m$$$ represent the sizes of the classroom and $$$k$$$ is the number of consecutive seats you need to find. Each of the next $$$n$$$ lines contains $$$m$$$ characters '.' or '*'. They form a matrix representing the classroom, '.' denotes an empty seat, and '*' denotes an occupied seat.
1,300
A single number, denoting the number of ways to find $$$k$$$ empty seats in the same row or column.
standard output
PASSED
78c72839f987d856d4fc57ebb8dfb847
train_001.jsonl
1517403900
Suppose that you are in a campus and have to go for classes day by day. As you may see, when you hurry to a classroom, you surprisingly find that many seats there are already occupied. Today you and your friends went for class, and found out that some of the seats were occupied.The classroom contains $$$n$$$ rows of seats and there are $$$m$$$ seats in each row. Then the classroom can be represented as an $$$n \times m$$$ matrix. The character '.' represents an empty seat, while '*' means that the seat is occupied. You need to find $$$k$$$ consecutive empty seats in the same row or column and arrange those seats for you and your friends. Your task is to find the number of ways to arrange the seats. Two ways are considered different if sets of places that students occupy differs.
256 megabytes
import java.util.Scanner; public class Seat_Arrangements { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); // row int m = sc.nextInt(); // column int k = sc.nextInt(); sc.nextLine(); char[][] arr = new char[n][m]; int res = 0; int dotNumber = 0; for (int i = 0; i < n; i++) { String tmp = sc.nextLine(); int seq = 0; for (int j = 0; j < m; j++) { arr[i][j] = tmp.charAt(j); if (arr[i][j] == '.') { dotNumber++; seq++; if ((j + 1 == m)) { res += find_ways(k, seq); } } else if (arr[i][j] == '*' || (j + 1 == m)) { res += find_ways(k, seq); seq = 0; } } } if(k == 1) { System.out.println(dotNumber); return; } for (int j = 0; j < m; j++) { int seq = 0; for (int i = 0; i < n; i++) { if(arr[i][j] == '.') seq++; if(arr[i][j] == '*' || (i+1) == n) { res+= find_ways(k,seq); seq= 0; } } } System.out.println(res); } public static boolean valid(int i, int j, int n, int m) { return i >= 0 && j >= 0 && i < n && j < m; } public static int find_ways(int k, int seq) { if (k > seq) return 0; return 1 + (seq - k); } }
Java
["2 3 2\n**.\n...", "1 2 2\n..", "3 3 4\n.*.\n*.*\n.*."]
1 second
["3", "1", "0"]
NoteIn the first sample, there are three ways to arrange those seats. You can take the following seats for your arrangement. $$$(1,3)$$$, $$$(2,3)$$$ $$$(2,2)$$$, $$$(2,3)$$$ $$$(2,1)$$$, $$$(2,2)$$$
Java 8
standard input
[ "implementation", "brute force" ]
c1f247150831e9b52389bae697a1ca3d
The first line contains three positive integers $$$n,m,k$$$ ($$$1 \leq n, m, k \leq 2\,000$$$), where $$$n,m$$$ represent the sizes of the classroom and $$$k$$$ is the number of consecutive seats you need to find. Each of the next $$$n$$$ lines contains $$$m$$$ characters '.' or '*'. They form a matrix representing the classroom, '.' denotes an empty seat, and '*' denotes an occupied seat.
1,300
A single number, denoting the number of ways to find $$$k$$$ empty seats in the same row or column.
standard output
PASSED
4b083ab743d6ac268f981657713f1b83
train_001.jsonl
1517403900
Suppose that you are in a campus and have to go for classes day by day. As you may see, when you hurry to a classroom, you surprisingly find that many seats there are already occupied. Today you and your friends went for class, and found out that some of the seats were occupied.The classroom contains $$$n$$$ rows of seats and there are $$$m$$$ seats in each row. Then the classroom can be represented as an $$$n \times m$$$ matrix. The character '.' represents an empty seat, while '*' means that the seat is occupied. You need to find $$$k$$$ consecutive empty seats in the same row or column and arrange those seats for you and your friends. Your task is to find the number of ways to arrange the seats. Two ways are considered different if sets of places that students occupy differs.
256 megabytes
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; public class C { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(), m = ni(), k = ni(); String ar[] = new String[n]; for(int i=0;i<n;i++){ ar[i] = ns(); } int count = 0; // Horizontal. for(int i=0;i<n;i++){ int c = 0; for(int j=0;j<m;j++){ if(ar[i].charAt(j)=='.'){ c++; }else{ if(c-k+1>0){ count += c-k+1; } c = 0; } } if(ar[i].charAt(m-1)=='.'){ if(c-k+1>0) count += c-k+1; } } //System.out.println("count="+count); // Vertical if(k!=1){ for(int i=0;i<m;i++){ int c = 0; for(int j=0;j<n;j++){ if(ar[j].charAt(i)=='.'){ c++; }else{ if(c-k+1>0){ count += c-k+1; } c = 0; } } if(ar[n-1].charAt(i)=='.'){ if(c-k+1>0) count += c-k+1; } } } out.println(count); } void run() throws Exception { is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new C().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private static void tr(Object... o) { System.out.println(Arrays.deepToString(o)); } }
Java
["2 3 2\n**.\n...", "1 2 2\n..", "3 3 4\n.*.\n*.*\n.*."]
1 second
["3", "1", "0"]
NoteIn the first sample, there are three ways to arrange those seats. You can take the following seats for your arrangement. $$$(1,3)$$$, $$$(2,3)$$$ $$$(2,2)$$$, $$$(2,3)$$$ $$$(2,1)$$$, $$$(2,2)$$$
Java 8
standard input
[ "implementation", "brute force" ]
c1f247150831e9b52389bae697a1ca3d
The first line contains three positive integers $$$n,m,k$$$ ($$$1 \leq n, m, k \leq 2\,000$$$), where $$$n,m$$$ represent the sizes of the classroom and $$$k$$$ is the number of consecutive seats you need to find. Each of the next $$$n$$$ lines contains $$$m$$$ characters '.' or '*'. They form a matrix representing the classroom, '.' denotes an empty seat, and '*' denotes an occupied seat.
1,300
A single number, denoting the number of ways to find $$$k$$$ empty seats in the same row or column.
standard output
PASSED
c50e6661ee122dc7db4aff81bb16f172
train_001.jsonl
1517403900
Suppose that you are in a campus and have to go for classes day by day. As you may see, when you hurry to a classroom, you surprisingly find that many seats there are already occupied. Today you and your friends went for class, and found out that some of the seats were occupied.The classroom contains $$$n$$$ rows of seats and there are $$$m$$$ seats in each row. Then the classroom can be represented as an $$$n \times m$$$ matrix. The character '.' represents an empty seat, while '*' means that the seat is occupied. You need to find $$$k$$$ consecutive empty seats in the same row or column and arrange those seats for you and your friends. Your task is to find the number of ways to arrange the seats. Two ways are considered different if sets of places that students occupy differs.
256 megabytes
import java.util.Scanner; public class Main{ public static void main(String[] args) { int max = 0; int c = 0; Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); in.nextLine(); char[][] room = new char[m][n]; for(int j=0;j<n;j++){ String row = in.nextLine(); for(int i=0;i<m;i++){ room[i][j] = row.charAt(i); if(room[i][j]=='.'){ c++; if(c>=k) max++; } else{ c = 0; } } c = 0; } if(k==1){ System.out.print(max); return; } if(n>1){ for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ if(room[i][j]=='.'){ c++; if(c>=k) max++; } else{ c = 0; } } c = 0; } } System.out.print(max); } }
Java
["2 3 2\n**.\n...", "1 2 2\n..", "3 3 4\n.*.\n*.*\n.*."]
1 second
["3", "1", "0"]
NoteIn the first sample, there are three ways to arrange those seats. You can take the following seats for your arrangement. $$$(1,3)$$$, $$$(2,3)$$$ $$$(2,2)$$$, $$$(2,3)$$$ $$$(2,1)$$$, $$$(2,2)$$$
Java 8
standard input
[ "implementation", "brute force" ]
c1f247150831e9b52389bae697a1ca3d
The first line contains three positive integers $$$n,m,k$$$ ($$$1 \leq n, m, k \leq 2\,000$$$), where $$$n,m$$$ represent the sizes of the classroom and $$$k$$$ is the number of consecutive seats you need to find. Each of the next $$$n$$$ lines contains $$$m$$$ characters '.' or '*'. They form a matrix representing the classroom, '.' denotes an empty seat, and '*' denotes an occupied seat.
1,300
A single number, denoting the number of ways to find $$$k$$$ empty seats in the same row or column.
standard output
PASSED
f84ffd465dcba36dfb20d907da7fbdbe
train_001.jsonl
1517403900
Suppose that you are in a campus and have to go for classes day by day. As you may see, when you hurry to a classroom, you surprisingly find that many seats there are already occupied. Today you and your friends went for class, and found out that some of the seats were occupied.The classroom contains $$$n$$$ rows of seats and there are $$$m$$$ seats in each row. Then the classroom can be represented as an $$$n \times m$$$ matrix. The character '.' represents an empty seat, while '*' means that the seat is occupied. You need to find $$$k$$$ consecutive empty seats in the same row or column and arrange those seats for you and your friends. Your task is to find the number of ways to arrange the seats. Two ways are considered different if sets of places that students occupy differs.
256 megabytes
import java.io.*; import java.util.*; public class C { FastScanner in; PrintWriter out; boolean systemIO = true; public void solve() throws IOException { int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); boolean table[][] = new boolean[n][m]; for (int i = 0; i < n; ++i) { String row = in.next(); for (int j = 0; j < m; ++j) { table[i][j] = row.charAt(j) == '.'; } } if (k == 1) { int ans = 0; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (table[i][j]) ++ans; } } out.println(ans); return; } List<Integer> seq = new ArrayList<>(); for (int i = 0; i < n; ++i) { int cur = 0; for (int j = 0; j < m; ++j) { if (table[i][j]) ++cur; else if (cur > 0) { seq.add(cur); cur = 0; } } if (cur > 0) seq.add(cur); } for (int i = 0; i < m; ++i) { int cur = 0; for (int j = 0; j < n; ++j) { if (table[j][i]) ++cur; else if (cur > 0) { seq.add(cur); cur = 0; } } if (cur > 0) seq.add(cur); } long ans = 0; for (int x: seq) { ans += Math.max(0, x - k + 1); } out.println(ans); } public void run() { try { if (systemIO) { in = new FastScanner(System.in); out = new PrintWriter(System.out); } else { in = new FastScanner(new File("input.txt")); out = new PrintWriter(new File("output.txt")); } solve(); out.close(); } catch (IOException e) { e.printStackTrace(); } } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String nextLine() { try { return br.readLine(); } catch (IOException e) { return null; } } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } public static void main(String[] arg) { new C().run(); } }
Java
["2 3 2\n**.\n...", "1 2 2\n..", "3 3 4\n.*.\n*.*\n.*."]
1 second
["3", "1", "0"]
NoteIn the first sample, there are three ways to arrange those seats. You can take the following seats for your arrangement. $$$(1,3)$$$, $$$(2,3)$$$ $$$(2,2)$$$, $$$(2,3)$$$ $$$(2,1)$$$, $$$(2,2)$$$
Java 8
standard input
[ "implementation", "brute force" ]
c1f247150831e9b52389bae697a1ca3d
The first line contains three positive integers $$$n,m,k$$$ ($$$1 \leq n, m, k \leq 2\,000$$$), where $$$n,m$$$ represent the sizes of the classroom and $$$k$$$ is the number of consecutive seats you need to find. Each of the next $$$n$$$ lines contains $$$m$$$ characters '.' or '*'. They form a matrix representing the classroom, '.' denotes an empty seat, and '*' denotes an occupied seat.
1,300
A single number, denoting the number of ways to find $$$k$$$ empty seats in the same row or column.
standard output
PASSED
9da015eb1cde8138e4b817e887436a6c
train_001.jsonl
1517403900
Suppose that you are in a campus and have to go for classes day by day. As you may see, when you hurry to a classroom, you surprisingly find that many seats there are already occupied. Today you and your friends went for class, and found out that some of the seats were occupied.The classroom contains $$$n$$$ rows of seats and there are $$$m$$$ seats in each row. Then the classroom can be represented as an $$$n \times m$$$ matrix. The character '.' represents an empty seat, while '*' means that the seat is occupied. You need to find $$$k$$$ consecutive empty seats in the same row or column and arrange those seats for you and your friends. Your task is to find the number of ways to arrange the seats. Two ways are considered different if sets of places that students occupy differs.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Scanner; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); int total = in.nextInt(); String[] set = new String[n]; char[][] c = new char[n][m]; int index = 0; int index2 = 0; in.nextLine(); while (in.hasNext()) { set[index] = in.nextLine(); index++; } for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) c[i][j] = set[i].charAt(j); int ans = 0; for (int i = 0; i < n; i++) { int count = 0; for (int j = 0; j < m; j++) { if (c[i][j] == '.') { count++; } else { count = 0; } if (count >= total) { ans++; } } } for (int i = 0; i < m; i++) { int count = 0; for (int j = 0; j < n; j++) { if (c[j][i] == '.') { count++; } else { count = 0; } if (count >= total) { ans++; } } } int count = 0; if (total == 1) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (c[i][j] == '.') { count++; } } } ans = count; } out.print(ans); } } }
Java
["2 3 2\n**.\n...", "1 2 2\n..", "3 3 4\n.*.\n*.*\n.*."]
1 second
["3", "1", "0"]
NoteIn the first sample, there are three ways to arrange those seats. You can take the following seats for your arrangement. $$$(1,3)$$$, $$$(2,3)$$$ $$$(2,2)$$$, $$$(2,3)$$$ $$$(2,1)$$$, $$$(2,2)$$$
Java 8
standard input
[ "implementation", "brute force" ]
c1f247150831e9b52389bae697a1ca3d
The first line contains three positive integers $$$n,m,k$$$ ($$$1 \leq n, m, k \leq 2\,000$$$), where $$$n,m$$$ represent the sizes of the classroom and $$$k$$$ is the number of consecutive seats you need to find. Each of the next $$$n$$$ lines contains $$$m$$$ characters '.' or '*'. They form a matrix representing the classroom, '.' denotes an empty seat, and '*' denotes an occupied seat.
1,300
A single number, denoting the number of ways to find $$$k$$$ empty seats in the same row or column.
standard output
PASSED
b3a3dcc54a580b4e3c209d2a521b0bf7
train_001.jsonl
1517403900
Suppose that you are in a campus and have to go for classes day by day. As you may see, when you hurry to a classroom, you surprisingly find that many seats there are already occupied. Today you and your friends went for class, and found out that some of the seats were occupied.The classroom contains $$$n$$$ rows of seats and there are $$$m$$$ seats in each row. Then the classroom can be represented as an $$$n \times m$$$ matrix. The character '.' represents an empty seat, while '*' means that the seat is occupied. You need to find $$$k$$$ consecutive empty seats in the same row or column and arrange those seats for you and your friends. Your task is to find the number of ways to arrange the seats. Two ways are considered different if sets of places that students occupy differs.
256 megabytes
import java.util.*; import java.io.*; public class test{ public static void main(String[] args) { int x,y; FastReader scan=new FastReader(); OutputStream output=System.out; PrintWriter out=new PrintWriter(output); int n=scan.nextInt(); int m=scan.nextInt(); int k=scan.nextInt(); char[][] arr=new char[n][m]; for(x=0;x<n;x++) { String str=scan.next(); for(y=0;y<m;y++) arr[x][y]=str.charAt(y); } /* for(x=0;x<n;x++) { for(y=0;y<m;y++) System.out.print(arr[x][y]+" "); System.out.println(); } */ int ans=0; for(x=0;x<n;x++) { int count=0; for(y=0;y<m;y++) { if(arr[x][y]=='*') { if(count>=k) ans+=(count-k+1); count=0; } if(arr[x][y]=='.') count++; //System.out.println(count+" 1"); } if(count>=k) ans+=(count-k+1); //System.out.println(count+" 2"); } for(y=0;y<m;y++) { int count=0; for(x=0;x<n;x++) { if(arr[x][y]=='*') { if(count>=k) ans+=(count-k+1); count=0; } if(arr[x][y]=='.') count++; } if(count>=k) ans+=(count-k+1); } out.println(k==1?ans/2:ans); out.flush(); } 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
["2 3 2\n**.\n...", "1 2 2\n..", "3 3 4\n.*.\n*.*\n.*."]
1 second
["3", "1", "0"]
NoteIn the first sample, there are three ways to arrange those seats. You can take the following seats for your arrangement. $$$(1,3)$$$, $$$(2,3)$$$ $$$(2,2)$$$, $$$(2,3)$$$ $$$(2,1)$$$, $$$(2,2)$$$
Java 8
standard input
[ "implementation", "brute force" ]
c1f247150831e9b52389bae697a1ca3d
The first line contains three positive integers $$$n,m,k$$$ ($$$1 \leq n, m, k \leq 2\,000$$$), where $$$n,m$$$ represent the sizes of the classroom and $$$k$$$ is the number of consecutive seats you need to find. Each of the next $$$n$$$ lines contains $$$m$$$ characters '.' or '*'. They form a matrix representing the classroom, '.' denotes an empty seat, and '*' denotes an occupied seat.
1,300
A single number, denoting the number of ways to find $$$k$$$ empty seats in the same row or column.
standard output
PASSED
52c003ac913cc4570e7b5432025e38e9
train_001.jsonl
1517403900
Suppose that you are in a campus and have to go for classes day by day. As you may see, when you hurry to a classroom, you surprisingly find that many seats there are already occupied. Today you and your friends went for class, and found out that some of the seats were occupied.The classroom contains $$$n$$$ rows of seats and there are $$$m$$$ seats in each row. Then the classroom can be represented as an $$$n \times m$$$ matrix. The character '.' represents an empty seat, while '*' means that the seat is occupied. You need to find $$$k$$$ consecutive empty seats in the same row or column and arrange those seats for you and your friends. Your task is to find the number of ways to arrange the seats. Two ways are considered different if sets of places that students occupy differs.
256 megabytes
import java.util.*; public class Codeforces { public static void main(String []args) { Scanner cin = new Scanner(System.in); boolean a[][] = new boolean[2001][2001] ; int answer = 0; int n = cin.nextInt(); int m = cin.nextInt(); int k = cin.nextInt(); ///Max linii for(int i = 0; i < n; i++){ int k2 = 0; String ch ; ch = cin.next(); for(int j = 0; j < m; j++ ){ if(ch.charAt(j) =='.') { a[i][j] = true; k2++; if(k2 >= k) answer++; } else k2 = 0; } } /// Max coloane if( k != 1 ){ for(int j = 0; j < m; j++ ){ int k2 = 0; for(int i = 0; i < n; i++) if(a[i][j] == true){ k2++; if(k2 >= k) answer++; } else k2 = 0; } } if( n == m && m == 1) { if(a[0][0] && k ==1) System.out.print("1"); else System.out.print("0"); } else System.out.print(answer); } }
Java
["2 3 2\n**.\n...", "1 2 2\n..", "3 3 4\n.*.\n*.*\n.*."]
1 second
["3", "1", "0"]
NoteIn the first sample, there are three ways to arrange those seats. You can take the following seats for your arrangement. $$$(1,3)$$$, $$$(2,3)$$$ $$$(2,2)$$$, $$$(2,3)$$$ $$$(2,1)$$$, $$$(2,2)$$$
Java 8
standard input
[ "implementation", "brute force" ]
c1f247150831e9b52389bae697a1ca3d
The first line contains three positive integers $$$n,m,k$$$ ($$$1 \leq n, m, k \leq 2\,000$$$), where $$$n,m$$$ represent the sizes of the classroom and $$$k$$$ is the number of consecutive seats you need to find. Each of the next $$$n$$$ lines contains $$$m$$$ characters '.' or '*'. They form a matrix representing the classroom, '.' denotes an empty seat, and '*' denotes an occupied seat.
1,300
A single number, denoting the number of ways to find $$$k$$$ empty seats in the same row or column.
standard output
PASSED
dd574afd13b65b2663085fefa85ed0eb
train_001.jsonl
1517403900
Suppose that you are in a campus and have to go for classes day by day. As you may see, when you hurry to a classroom, you surprisingly find that many seats there are already occupied. Today you and your friends went for class, and found out that some of the seats were occupied.The classroom contains $$$n$$$ rows of seats and there are $$$m$$$ seats in each row. Then the classroom can be represented as an $$$n \times m$$$ matrix. The character '.' represents an empty seat, while '*' means that the seat is occupied. You need to find $$$k$$$ consecutive empty seats in the same row or column and arrange those seats for you and your friends. Your task is to find the number of ways to arrange the seats. Two ways are considered different if sets of places that students occupy differs.
256 megabytes
import java.util.*; import java.util.ArrayList; public class Main{ static class Pair { int x; int y; Pair(int x, int y){ this.x=x; this.y=y; } } public static void main(String[] args){ Scanner param=new Scanner(System.in); int n=param.nextInt(); int m=param.nextInt(); int k=param.nextInt(); String arrr[]=new String[m]; Arrays.fill(arrr," "); String arr[]=new String[n]; for(int i=0;i<n;i++){ arr[i]=param.next(); } int sum=0; int count=0; for(int i=0;i<n;i++){ count=0; for(int j=0;j<m;j++){ if(arr[i].charAt(j)=='.'){ count++; if(count>=k){ sum++; } } else{ count=0; } } } // System.out.println(sum); count=0; int sum1=0; for(int i=0;i<m;i++){ count=0; for(int j=0;j<n;j++){ if(arr[j].charAt(i)=='.'){ count++; if(count>=k){ sum1++; } } else{ count=0; } } } if(k==1){ System.out.println(sum); return ; } System.out.println(sum+sum1); } }
Java
["2 3 2\n**.\n...", "1 2 2\n..", "3 3 4\n.*.\n*.*\n.*."]
1 second
["3", "1", "0"]
NoteIn the first sample, there are three ways to arrange those seats. You can take the following seats for your arrangement. $$$(1,3)$$$, $$$(2,3)$$$ $$$(2,2)$$$, $$$(2,3)$$$ $$$(2,1)$$$, $$$(2,2)$$$
Java 8
standard input
[ "implementation", "brute force" ]
c1f247150831e9b52389bae697a1ca3d
The first line contains three positive integers $$$n,m,k$$$ ($$$1 \leq n, m, k \leq 2\,000$$$), where $$$n,m$$$ represent the sizes of the classroom and $$$k$$$ is the number of consecutive seats you need to find. Each of the next $$$n$$$ lines contains $$$m$$$ characters '.' or '*'. They form a matrix representing the classroom, '.' denotes an empty seat, and '*' denotes an occupied seat.
1,300
A single number, denoting the number of ways to find $$$k$$$ empty seats in the same row or column.
standard output
PASSED
3a8cf93bb266d090b7a16f881b7325db
train_001.jsonl
1517403900
Suppose that you are in a campus and have to go for classes day by day. As you may see, when you hurry to a classroom, you surprisingly find that many seats there are already occupied. Today you and your friends went for class, and found out that some of the seats were occupied.The classroom contains $$$n$$$ rows of seats and there are $$$m$$$ seats in each row. Then the classroom can be represented as an $$$n \times m$$$ matrix. The character '.' represents an empty seat, while '*' means that the seat is occupied. You need to find $$$k$$$ consecutive empty seats in the same row or column and arrange those seats for you and your friends. Your task is to find the number of ways to arrange the seats. Two ways are considered different if sets of places that students occupy differs.
256 megabytes
import java.util.*; import java.io.*; // public class Solution implements Runnable class Solution implements Runnable { public static void main(String[] args) throws IOException { br=new BufferedReader(new InputStreamReader(System.in)); nextIntBuffer = new String[0]; bos = new OutputStreamWriter(new BufferedOutputStream(System.out)); new Thread(null, new Solution(), "Main", 1<<28).start(); } static BufferedReader br; static String nextIntBuffer[]; static int nextIntBase; static OutputStreamWriter bos; static int nextInt() { return Integer.parseInt(next()); } static long nextLong() { return Long.parseLong(next()); } static String next() { try{ if(nextIntBase>=nextIntBuffer.length) { nextIntBase =0; nextIntBuffer = br.readLine().split(" "); } }catch(IOException e) {} return nextIntBuffer[nextIntBase++]; } static void print (String s) {try{ bos.write(s); }catch(IOException e){}} static void print (int s) {try{ bos.write(String.valueOf(s)); }catch(IOException e){}} static void print (long s) {try{ bos.write(String.valueOf(s)); }catch(IOException e){}} static void print (double s) {try{ bos.write(String.valueOf(s)); }catch(IOException e){}} static void println (String s) {try{ print(s); bos.write('\n'); }catch(IOException e){}} static void println (int s) {try{ print(s); bos.write('\n'); }catch(IOException e){}} static void println (long s) {try{ print(s); bos.write('\n'); }catch(IOException e){}} static void println (double s) {try{ print(s); bos.write('\n'); }catch(IOException e){}} public static <T1 extends Comparable<T1> ,T2 extends Comparable<T2> > Pair<T1,T2> mp(T1 a,T2 b) { return new Pair<T1,T2>(a,b); } public void main() { br=new BufferedReader(new InputStreamReader(System.in)); nextIntBuffer = new String[0]; int t=1; while(t-->0) { int n=nextInt(); int m=nextInt(); int k=nextInt(); long sum=0; char[][] a=new char[n][m]; for (int i=0;i<n ;i++ ) { String s=next(); // println(s); // System.exit(1); for (int j=0;j<m ;j++ ) { a[i][j]=s.charAt(j); } } // for row for (int i=0;i<n ;i++ ) { int count=0; for (int j=0;j<m ;j++ ) { if(a[i][j]=='.'){ count++; } if(a[i][j]=='*' || j==m-1) { // println(i+" "+j+" "+count); sum+=Math.max(0,count-k+1); count=0; } } } //for col for (int j=0;j<m ;j++ ) { int count=0; for (int i=0;i<n ;i++ ) { if(a[i][j]=='.') count++; if(a[i][j]=='*' || i==n-1) { sum+=Math.max(0,count-k+1); count=0; } } } if(k==1)println(sum/2); else println(sum); } } public void run() { try { main(); bos.flush(); }catch(IOException e) { e.printStackTrace(); } } static long pow(long x,long y,long mod) { if (y==0) return 1; long z=pow(x,y/2,mod)%mod; if(y%2==0) return (z*z)%mod; else return (((x*z)%mod)*z)%mod; } static long gcd(long q,long d) { long x1[]=new long[1];long y1[]=new long[1]; return gcd(q,d,x1,y1); } static long gcd(long q,long d,long x[],long y[]) { if(d%q==0) { x[0]=1; y[0]=0; return q; } long x1[]=new long[1];long y1[]=new long[1]; long ans = gcd(d%q,q,x1,y1); y[0]=x1[0]; x[0]=y1[0]-(d/q)*x1[0]; return ans; } static long Inv(long n,long m) { long x[]=new long[1];long y[]=new long[1]; long g= gcd(n,m,x,y); if(g==1) { return (x[0]+m)%m; } return -1; } } class Pair<T1 extends Comparable<T1>, T2 extends Comparable<T2> > implements Comparable<Pair<T1,T2> > { T1 a; T2 b; public Pair(T1 x, T2 y) { a = x; b = y; } @Override public int compareTo(Pair<T1,T2> other) { int comp1 = a.compareTo(other.a); if(comp1!=0) return comp1; return b.compareTo(other.b); } }
Java
["2 3 2\n**.\n...", "1 2 2\n..", "3 3 4\n.*.\n*.*\n.*."]
1 second
["3", "1", "0"]
NoteIn the first sample, there are three ways to arrange those seats. You can take the following seats for your arrangement. $$$(1,3)$$$, $$$(2,3)$$$ $$$(2,2)$$$, $$$(2,3)$$$ $$$(2,1)$$$, $$$(2,2)$$$
Java 8
standard input
[ "implementation", "brute force" ]
c1f247150831e9b52389bae697a1ca3d
The first line contains three positive integers $$$n,m,k$$$ ($$$1 \leq n, m, k \leq 2\,000$$$), where $$$n,m$$$ represent the sizes of the classroom and $$$k$$$ is the number of consecutive seats you need to find. Each of the next $$$n$$$ lines contains $$$m$$$ characters '.' or '*'. They form a matrix representing the classroom, '.' denotes an empty seat, and '*' denotes an occupied seat.
1,300
A single number, denoting the number of ways to find $$$k$$$ empty seats in the same row or column.
standard output
PASSED
8f700d7f209f293ff1bf71b4b481ab4c
train_001.jsonl
1411918500
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two primes". Let's modify it. How about a statement like that: "each integer no less than 12 can be expressed as the sum of two composite numbers." Not like the Goldbach's conjecture, I can prove this theorem.You are given an integer n no less than 12, express it as a sum of two composite numbers.
256 megabytes
import java.util.*; public class wrgreg { public static int isPrime(int n) { int count=0; for(int i=1;i<n;i++) { if(n%i ==0 && i!=1 ) { count++; break; } } //System.out.println(count); if(count==0 || n==2) { return 1; } return 0; } public static void main(String args[]) { Scanner sc = new Scanner(System.in); int k = sc.nextInt(); if(k%2==0 && isPrime(k/2)!=1) { System.out.println(k/2 +" "+ k/2); } else { for(int i= k/2 ;i<=k;i++) { if(isPrime(i)==0 && isPrime(k-i)==0 ) { System.out.println(i+" "+(k-i)); break; } } } ///eesdfs } }
Java
["12", "15", "23", "1000000"]
1 second
["4 8", "6 9", "8 15", "500000 500000"]
NoteIn the first example, 12 = 4 + 8 and both 4, 8 are composite numbers. You can output "6 6" or "8 4" as well.In the second example, 15 = 6 + 9. Note that you can't output "1 14" because 1 is not a composite number.
Java 8
standard input
[ "number theory", "math" ]
3ea971165088fae130d866180c6c868b
The only line contains an integer n (12 ≤ n ≤ 106).
800
Output two composite integers x and y (1 &lt; x, y &lt; n) such that x + y = n. If there are multiple solutions, you can output any of them.
standard output
PASSED
4d16cddb3c1852817d45b0d5fe9f1950
train_001.jsonl
1411918500
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two primes". Let's modify it. How about a statement like that: "each integer no less than 12 can be expressed as the sum of two composite numbers." Not like the Goldbach's conjecture, I can prove this theorem.You are given an integer n no less than 12, express it as a sum of two composite numbers.
256 megabytes
public class learnfrommath2 { protected static int[] getAns(int x) { if(x % 2 != 0 || !checkComp(x/2)) { // System.out.println("odd or /2 !comp"); for(int i = 1; i < x; i++) { if(checkComp(i) && checkComp(x-i)) { return new int[] { i, x-i }; } } // System.out.println("youre an idiot"); return new int[] { 0, 0 }; } // System.out.println("even"); return new int[] { x/2, x/2 }; } protected static boolean checkComp(int x) { if(x > 2 && x%2 == 0) return true; for(int i = 2; i < x-1; i++) { if(x % (i) == 0) { return true; } } return false; } public static void main(String[] args) { int x = new java.util.Scanner(System.in).nextInt(); int[] nums = new int[2]; nums = getAns(x); for (int num : nums) { System.out.println(num); } } }
Java
["12", "15", "23", "1000000"]
1 second
["4 8", "6 9", "8 15", "500000 500000"]
NoteIn the first example, 12 = 4 + 8 and both 4, 8 are composite numbers. You can output "6 6" or "8 4" as well.In the second example, 15 = 6 + 9. Note that you can't output "1 14" because 1 is not a composite number.
Java 8
standard input
[ "number theory", "math" ]
3ea971165088fae130d866180c6c868b
The only line contains an integer n (12 ≤ n ≤ 106).
800
Output two composite integers x and y (1 &lt; x, y &lt; n) such that x + y = n. If there are multiple solutions, you can output any of them.
standard output
PASSED
524ae1afbbf8cf2116902f575a56dd27
train_001.jsonl
1411918500
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two primes". Let's modify it. How about a statement like that: "each integer no less than 12 can be expressed as the sum of two composite numbers." Not like the Goldbach's conjecture, I can prove this theorem.You are given an integer n no less than 12, express it as a sum of two composite numbers.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; public class learnMath_472A { public static void main(String args[]) throws NumberFormatException, IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); PrintStream sOut=new PrintStream(System.out); int n=Integer.parseInt(br.readLine()); if(n%2==0){ if(n%4==0) sOut.println(n/2+" "+n/2); else sOut.println(n/2-1+" "+(n/2+1)); } else{ int n1=0; for(int i=2;i<=n;i++) if(!isPrime(i)&&i%2!=0){ n1=i; break; } sOut.println(n1+" "+(n-n1)); } sOut.close(); } public static boolean isPrime(int num){ int arrP[]=new int[num+1]; for(int i=0;i<=Math.sqrt(num);i++) arrP[i]=0; for(int i=2;i<=(int)Math.sqrt(num);i++){ if(arrP[i]==0){ for(int j=2;j*i<=num;j++){ arrP[j*i]=1; } } } if(arrP[num]==0) return true; return false; } }
Java
["12", "15", "23", "1000000"]
1 second
["4 8", "6 9", "8 15", "500000 500000"]
NoteIn the first example, 12 = 4 + 8 and both 4, 8 are composite numbers. You can output "6 6" or "8 4" as well.In the second example, 15 = 6 + 9. Note that you can't output "1 14" because 1 is not a composite number.
Java 8
standard input
[ "number theory", "math" ]
3ea971165088fae130d866180c6c868b
The only line contains an integer n (12 ≤ n ≤ 106).
800
Output two composite integers x and y (1 &lt; x, y &lt; n) such that x + y = n. If there are multiple solutions, you can output any of them.
standard output
PASSED
5e111d0f51b62cf5b1f0f458bae8ef71
train_001.jsonl
1411918500
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two primes". Let's modify it. How about a statement like that: "each integer no less than 12 can be expressed as the sum of two composite numbers." Not like the Goldbach's conjecture, I can prove this theorem.You are given an integer n no less than 12, express it as a sum of two composite numbers.
256 megabytes
import java.io.PrintStream; import java.util.Scanner; public class learnMath_472A { public static void main(String args[]){ Scanner sc=new Scanner(System.in); PrintStream sOut=new PrintStream(System.out); int n=sc.nextInt(); if(n%2==0){ if(n%4==0) sOut.println(n/2+" "+n/2); else sOut.println(n/2-1+" "+(n/2+1)); } else{ int n1=0; for(int i=2;i<=n;i++) if(!isPrime(i)&&i%2!=0){ n1=i; break; } System.out.println(n1+" "+(n-n1)); } } public static boolean isPrime(int num){ int arrP[]=new int[num+1]; for(int i=0;i<=Math.sqrt(num);i++) arrP[i]=0; for(int i=2;i<=(int)Math.sqrt(num);i++){ if(arrP[i]==0){ for(int j=2;j*i<=num;j++){ arrP[j*i]=1; } } } if(arrP[num]==0) return true; return false; } }
Java
["12", "15", "23", "1000000"]
1 second
["4 8", "6 9", "8 15", "500000 500000"]
NoteIn the first example, 12 = 4 + 8 and both 4, 8 are composite numbers. You can output "6 6" or "8 4" as well.In the second example, 15 = 6 + 9. Note that you can't output "1 14" because 1 is not a composite number.
Java 8
standard input
[ "number theory", "math" ]
3ea971165088fae130d866180c6c868b
The only line contains an integer n (12 ≤ n ≤ 106).
800
Output two composite integers x and y (1 &lt; x, y &lt; n) such that x + y = n. If there are multiple solutions, you can output any of them.
standard output
PASSED
d4cc808820922be7c0b4358faff3b486
train_001.jsonl
1411918500
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two primes". Let's modify it. How about a statement like that: "each integer no less than 12 can be expressed as the sum of two composite numbers." Not like the Goldbach's conjecture, I can prove this theorem.You are given an integer n no less than 12, express it as a sum of two composite numbers.
256 megabytes
import java.io.PrintStream; import java.util.Scanner; public class learnMath_472A { public static void main(String args[]){ Scanner sc=new Scanner(System.in); PrintStream sOut=new PrintStream(System.out); int n=sc.nextInt(); if(n%2==0){ if(n%4==0) sOut.println(n/2+" "+n/2); else sOut.println(n/2-1+" "+(n/2+1)); } else{ int n1=0; for(int i=2;i<=n;i++) if(!isPrime(i)&&i%2!=0){ n1=i; break; } sOut.println(n1+" "+(n-n1)); } sOut.close(); } public static boolean isPrime(int num){ int arrP[]=new int[num+1]; for(int i=0;i<=Math.sqrt(num);i++) arrP[i]=0; for(int i=2;i<=(int)Math.sqrt(num);i++){ if(arrP[i]==0){ for(int j=2;j*i<=num;j++){ arrP[j*i]=1; } } } if(arrP[num]==0) return true; return false; } }
Java
["12", "15", "23", "1000000"]
1 second
["4 8", "6 9", "8 15", "500000 500000"]
NoteIn the first example, 12 = 4 + 8 and both 4, 8 are composite numbers. You can output "6 6" or "8 4" as well.In the second example, 15 = 6 + 9. Note that you can't output "1 14" because 1 is not a composite number.
Java 8
standard input
[ "number theory", "math" ]
3ea971165088fae130d866180c6c868b
The only line contains an integer n (12 ≤ n ≤ 106).
800
Output two composite integers x and y (1 &lt; x, y &lt; n) such that x + y = n. If there are multiple solutions, you can output any of them.
standard output
PASSED
1bfd376765d2a1cd8876ba25a31eb1de
train_001.jsonl
1411918500
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two primes". Let's modify it. How about a statement like that: "each integer no less than 12 can be expressed as the sum of two composite numbers." Not like the Goldbach's conjecture, I can prove this theorem.You are given an integer n no less than 12, express it as a sum of two composite numbers.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.Arrays; import java.util.StringTokenizer; public class MathText { 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()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } int[] readSortedArray(int n){ int[] a = new int[n] ; for(int i = 0 ; i < n ; ++i) a[i]=nextInt() ; Arrays.sort(a) ; return a ; } BigInteger nextBigInteger(){ return BigInteger.valueOf(Long.parseLong(next())); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { FastReader fs = new FastReader(); int n = fs.nextInt(); if(n % 2 == 0){ System.out.println(8 + " " +(n-8)); } else{ System.out.println(9 + " " + (n-9)); } } }
Java
["12", "15", "23", "1000000"]
1 second
["4 8", "6 9", "8 15", "500000 500000"]
NoteIn the first example, 12 = 4 + 8 and both 4, 8 are composite numbers. You can output "6 6" or "8 4" as well.In the second example, 15 = 6 + 9. Note that you can't output "1 14" because 1 is not a composite number.
Java 8
standard input
[ "number theory", "math" ]
3ea971165088fae130d866180c6c868b
The only line contains an integer n (12 ≤ n ≤ 106).
800
Output two composite integers x and y (1 &lt; x, y &lt; n) such that x + y = n. If there are multiple solutions, you can output any of them.
standard output
PASSED
365f7c1dce2128d87d9e4c8e5dbb635d
train_001.jsonl
1411918500
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two primes". Let's modify it. How about a statement like that: "each integer no less than 12 can be expressed as the sum of two composite numbers." Not like the Goldbach's conjecture, I can prove this theorem.You are given an integer n no less than 12, express it as a sum of two composite numbers.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner ler = new Scanner(System.in); int t,x=4,y,px=0,py=0; boolean primos=true; t=ler.nextInt(); y=t-x; while(primos){ for(int c=y;c!=0;c--){ if(y%c==0){ px++; } } for(int c=x;c!=0;c--){ if(x%c==0){ py++; } } if(px!=2&&py!=2){ primos=false; }else if(y==0){ System.out.println(""); }else{ x++; y--; px=0; py=0; } } System.out.println(x+" "+y); } } // 1507061413540
Java
["12", "15", "23", "1000000"]
1 second
["4 8", "6 9", "8 15", "500000 500000"]
NoteIn the first example, 12 = 4 + 8 and both 4, 8 are composite numbers. You can output "6 6" or "8 4" as well.In the second example, 15 = 6 + 9. Note that you can't output "1 14" because 1 is not a composite number.
Java 8
standard input
[ "number theory", "math" ]
3ea971165088fae130d866180c6c868b
The only line contains an integer n (12 ≤ n ≤ 106).
800
Output two composite integers x and y (1 &lt; x, y &lt; n) such that x + y = n. If there are multiple solutions, you can output any of them.
standard output
PASSED
3ac365d20d3ef3e015c240d1a1c0a0c9
train_001.jsonl
1411918500
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two primes". Let's modify it. How about a statement like that: "each integer no less than 12 can be expressed as the sum of two composite numbers." Not like the Goldbach's conjecture, I can prove this theorem.You are given an integer n no less than 12, express it as a sum of two composite numbers.
256 megabytes
public class DesignTutorialLearnFromMath { public static void main (String[] args) { int n = new java.util.Scanner(System.in).nextInt(); for (int x = 4; (n-x) > 4; x += 2) { if ((n-x) % 2 == 0 || (n-x) % 3 == 0) { System.out.println(x + " " + (n-x)); break; } //break; } } }
Java
["12", "15", "23", "1000000"]
1 second
["4 8", "6 9", "8 15", "500000 500000"]
NoteIn the first example, 12 = 4 + 8 and both 4, 8 are composite numbers. You can output "6 6" or "8 4" as well.In the second example, 15 = 6 + 9. Note that you can't output "1 14" because 1 is not a composite number.
Java 8
standard input
[ "number theory", "math" ]
3ea971165088fae130d866180c6c868b
The only line contains an integer n (12 ≤ n ≤ 106).
800
Output two composite integers x and y (1 &lt; x, y &lt; n) such that x + y = n. If there are multiple solutions, you can output any of them.
standard output
PASSED
db87bf0ceb8bdcae433dc66f3a95380e
train_001.jsonl
1411918500
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two primes". Let's modify it. How about a statement like that: "each integer no less than 12 can be expressed as the sum of two composite numbers." Not like the Goldbach's conjecture, I can prove this theorem.You are given an integer n no less than 12, express it as a sum of two composite numbers.
256 megabytes
import java.util.*; public class Codechef { public static void main (String[] args) throws java.lang.Exception { Scanner in=new Scanner(System.in); int n=in.nextInt(); if(n%2==0 && isPrime(n/2)) System.out.println(n/2+" "+n/2); else{ for(int i=4;i<=n/2;i++){ if(isPrime(i) && isPrime(n-i)){ System.out.println(i+" "+(n-i)); break; } } } } public static boolean isPrime(int n) { int flag=0; for(int i=2;i<=n/2;i++){ if(n%i==0){ flag=1; break; } } if(flag==1) return true; else return false; } }
Java
["12", "15", "23", "1000000"]
1 second
["4 8", "6 9", "8 15", "500000 500000"]
NoteIn the first example, 12 = 4 + 8 and both 4, 8 are composite numbers. You can output "6 6" or "8 4" as well.In the second example, 15 = 6 + 9. Note that you can't output "1 14" because 1 is not a composite number.
Java 8
standard input
[ "number theory", "math" ]
3ea971165088fae130d866180c6c868b
The only line contains an integer n (12 ≤ n ≤ 106).
800
Output two composite integers x and y (1 &lt; x, y &lt; n) such that x + y = n. If there are multiple solutions, you can output any of them.
standard output
PASSED
44023d67a32c7d95e91cb71da4a6aedd
train_001.jsonl
1411918500
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two primes". Let's modify it. How about a statement like that: "each integer no less than 12 can be expressed as the sum of two composite numbers." Not like the Goldbach's conjecture, I can prove this theorem.You are given an integer n no less than 12, express it as a sum of two composite numbers.
256 megabytes
import java.util.Scanner; public class a { public static void main (String[] args){ Scanner input=new Scanner (System.in); int n=input.nextInt(); int c=0; int v=0; for (int i=n-1;i>1;i--){ if ((isPrime(i)==false)&&(isPrime(n-i)==false) ){ System.out.print (i+" "+(n-i)); break ; } } } public static boolean isPrime(int n) { for(int i=2;i<=n/2;i++) { if(n%i==0) return false; } return true; } }
Java
["12", "15", "23", "1000000"]
1 second
["4 8", "6 9", "8 15", "500000 500000"]
NoteIn the first example, 12 = 4 + 8 and both 4, 8 are composite numbers. You can output "6 6" or "8 4" as well.In the second example, 15 = 6 + 9. Note that you can't output "1 14" because 1 is not a composite number.
Java 8
standard input
[ "number theory", "math" ]
3ea971165088fae130d866180c6c868b
The only line contains an integer n (12 ≤ n ≤ 106).
800
Output two composite integers x and y (1 &lt; x, y &lt; n) such that x + y = n. If there are multiple solutions, you can output any of them.
standard output
PASSED
eb2c59c84f42043f7080a1fae8f05619
train_001.jsonl
1411918500
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two primes". Let's modify it. How about a statement like that: "each integer no less than 12 can be expressed as the sum of two composite numbers." Not like the Goldbach's conjecture, I can prove this theorem.You are given an integer n no less than 12, express it as a sum of two composite numbers.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.math.BigInteger; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.InputMismatchException; import java.util.Map; import java.util.Map.Entry; import java.util.Scanner; public class Main { static InputStream is; public static void main(String[] args) { is = System.in; solve(); } static void solve() { boolean[] array = new boolean[1000000]; array[0] = true; array[1] = true; for (int i = 2; i * i <= array.length; i++) { for (int j = i * i; j < array.length; j += i) { array[j] = true; } } int k = ni(); int temp01 = k / 2; while (true) { if (array[temp01] == true) { int temp02 = k - temp01; if (array[temp02] == true) { System.out.println(temp01 + " " + temp02); break; } else { temp01++; } } else { temp01 += 1; int temp02 = k - temp01; if (array[temp02] == true) { System.out.println(temp01 + " " + temp02); break; } else { temp01++; } } } } static byte[] inbuf = new byte[4096]; static int lenbuf = 0, ptrbuf = 0; static int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } static int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } static double nd() { return Double.parseDouble(ns()); } static char nc() { return (char) skip(); } static String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } static 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); } static 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(); } } static 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(); } } }
Java
["12", "15", "23", "1000000"]
1 second
["4 8", "6 9", "8 15", "500000 500000"]
NoteIn the first example, 12 = 4 + 8 and both 4, 8 are composite numbers. You can output "6 6" or "8 4" as well.In the second example, 15 = 6 + 9. Note that you can't output "1 14" because 1 is not a composite number.
Java 8
standard input
[ "number theory", "math" ]
3ea971165088fae130d866180c6c868b
The only line contains an integer n (12 ≤ n ≤ 106).
800
Output two composite integers x and y (1 &lt; x, y &lt; n) such that x + y = n. If there are multiple solutions, you can output any of them.
standard output
PASSED
babd800a23af7a3a3c27bd3e5087d622
train_001.jsonl
1411918500
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two primes". Let's modify it. How about a statement like that: "each integer no less than 12 can be expressed as the sum of two composite numbers." Not like the Goldbach's conjecture, I can prove this theorem.You are given an integer n no less than 12, express it as a sum of two composite numbers.
256 megabytes
//package CF_270; import java.util.*; public class a { public static boolean isPrime(int n){ for(int i = 2; i <= Math.sqrt(n); i++){ if(n % i == 0) return false; } return true; } public static void main(String[] args) throws Exception{ Scanner sc=new Scanner(System.in); int n=sc.nextInt(), ans1 = 4, ans2 = n - 4; while(isPrime(ans2) || isPrime(ans1)) {ans2--; ans1++;} System.out.println(ans1 + " " + ans2); } }
Java
["12", "15", "23", "1000000"]
1 second
["4 8", "6 9", "8 15", "500000 500000"]
NoteIn the first example, 12 = 4 + 8 and both 4, 8 are composite numbers. You can output "6 6" or "8 4" as well.In the second example, 15 = 6 + 9. Note that you can't output "1 14" because 1 is not a composite number.
Java 8
standard input
[ "number theory", "math" ]
3ea971165088fae130d866180c6c868b
The only line contains an integer n (12 ≤ n ≤ 106).
800
Output two composite integers x and y (1 &lt; x, y &lt; n) such that x + y = n. If there are multiple solutions, you can output any of them.
standard output
PASSED
be3a087de5eb4f26842035741ed7e813
train_001.jsonl
1411918500
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two primes". Let's modify it. How about a statement like that: "each integer no less than 12 can be expressed as the sum of two composite numbers." Not like the Goldbach's conjecture, I can prove this theorem.You are given an integer n no less than 12, express it as a sum of two composite numbers.
256 megabytes
import java.util.*; public class Math { public static void main(String []args){ Scanner input=new Scanner(System.in); int num=input.nextInt(); int composite1=4; int composite2=num-4; while((isComposite(composite1)&&isComposite(composite2))==false){ composite1++; composite2--; } System.out.println(composite1 +" "+composite2); } public static boolean isComposite (int number){ int numOfFactor=0; for(int i=1;i<=number;i++){ if(number%i==0) numOfFactor++; } if(numOfFactor>2) return true; else return false; } }
Java
["12", "15", "23", "1000000"]
1 second
["4 8", "6 9", "8 15", "500000 500000"]
NoteIn the first example, 12 = 4 + 8 and both 4, 8 are composite numbers. You can output "6 6" or "8 4" as well.In the second example, 15 = 6 + 9. Note that you can't output "1 14" because 1 is not a composite number.
Java 8
standard input
[ "number theory", "math" ]
3ea971165088fae130d866180c6c868b
The only line contains an integer n (12 ≤ n ≤ 106).
800
Output two composite integers x and y (1 &lt; x, y &lt; n) such that x + y = n. If there are multiple solutions, you can output any of them.
standard output
PASSED
468a41f79c4857eeab1e57702ef2ee44
train_001.jsonl
1411918500
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two primes". Let's modify it. How about a statement like that: "each integer no less than 12 can be expressed as the sum of two composite numbers." Not like the Goldbach's conjecture, I can prove this theorem.You are given an integer n no less than 12, express it as a sum of two composite numbers.
256 megabytes
import java.util.*; public class LearnfromMath { public static void main (String [] args){ Scanner input=new Scanner (System.in); int n=input.nextInt(); int num1=n-4; int num2=4; while((composite(num1)==false) || (composite(num2)==false)){ num1--; num2++; } System.out.print(num1+" "+num2); } public static boolean composite (int num){ boolean composite=false; int sum=0; for(double i=2;i<=Math.sqrt(num);i++){ if(num % i ==0 ){ sum++; } } if(sum>=1){ composite=true; } return composite; } }
Java
["12", "15", "23", "1000000"]
1 second
["4 8", "6 9", "8 15", "500000 500000"]
NoteIn the first example, 12 = 4 + 8 and both 4, 8 are composite numbers. You can output "6 6" or "8 4" as well.In the second example, 15 = 6 + 9. Note that you can't output "1 14" because 1 is not a composite number.
Java 8
standard input
[ "number theory", "math" ]
3ea971165088fae130d866180c6c868b
The only line contains an integer n (12 ≤ n ≤ 106).
800
Output two composite integers x and y (1 &lt; x, y &lt; n) such that x + y = n. If there are multiple solutions, you can output any of them.
standard output
PASSED
ed12b09e68fcb4c8f3458695ef36791a
train_001.jsonl
1411918500
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two primes". Let's modify it. How about a statement like that: "each integer no less than 12 can be expressed as the sum of two composite numbers." Not like the Goldbach's conjecture, I can prove this theorem.You are given an integer n no less than 12, express it as a sum of two composite numbers.
256 megabytes
import java.util.*; public class LearnMath { public static void main (String [] args) { Scanner input = new Scanner (System.in); int n = input.nextInt(),i = 0; while(n > 0) { n--; i++; if(prime(n) == false && prime(i) == false) break; } System.out.println(n + " " + i); } public static boolean prime(int num) { boolean prime = true; for(int i = 2; i <= Math.sqrt(num); i++) { if(num % i == 0) { prime = false; break; } } return prime; } }
Java
["12", "15", "23", "1000000"]
1 second
["4 8", "6 9", "8 15", "500000 500000"]
NoteIn the first example, 12 = 4 + 8 and both 4, 8 are composite numbers. You can output "6 6" or "8 4" as well.In the second example, 15 = 6 + 9. Note that you can't output "1 14" because 1 is not a composite number.
Java 8
standard input
[ "number theory", "math" ]
3ea971165088fae130d866180c6c868b
The only line contains an integer n (12 ≤ n ≤ 106).
800
Output two composite integers x and y (1 &lt; x, y &lt; n) such that x + y = n. If there are multiple solutions, you can output any of them.
standard output
PASSED
44ff31a2673063baf7af59b39d3b8214
train_001.jsonl
1411918500
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two primes". Let's modify it. How about a statement like that: "each integer no less than 12 can be expressed as the sum of two composite numbers." Not like the Goldbach's conjecture, I can prove this theorem.You are given an integer n no less than 12, express it as a sum of two composite numbers.
256 megabytes
import java.util.*; public class Math2 { public static void main(String args[]) { int n,p,t; Scanner in=new Scanner(System.in); n=in.nextInt(); p=n%2+8; t=n-p; System.out.println(+p+ " "+t); } }
Java
["12", "15", "23", "1000000"]
1 second
["4 8", "6 9", "8 15", "500000 500000"]
NoteIn the first example, 12 = 4 + 8 and both 4, 8 are composite numbers. You can output "6 6" or "8 4" as well.In the second example, 15 = 6 + 9. Note that you can't output "1 14" because 1 is not a composite number.
Java 8
standard input
[ "number theory", "math" ]
3ea971165088fae130d866180c6c868b
The only line contains an integer n (12 ≤ n ≤ 106).
800
Output two composite integers x and y (1 &lt; x, y &lt; n) such that x + y = n. If there are multiple solutions, you can output any of them.
standard output
PASSED
9eac242068222b9b47679f8e0b6c3eb5
train_001.jsonl
1411918500
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two primes". Let's modify it. How about a statement like that: "each integer no less than 12 can be expressed as the sum of two composite numbers." Not like the Goldbach's conjecture, I can prove this theorem.You are given an integer n no less than 12, express it as a sum of two composite numbers.
256 megabytes
import java.util.*; public class Design { public static void main(String args[]) { int n,a,b; Scanner in= new Scanner(System.in); n=in.nextInt(); a=n/3; if(a%2!=0) { a=a+1; } b=n-a; if((b%2!=0)&&(b%3!=0)&&(b%7!=0)&&(b%5!=0)) { a=a-5; b=b+5; if((a%2!=0)&&(a%7!=0)) { if(a==1) { a=a+7; } if(a==33331) { a=a+14; } if(a==3) { a=a+6; b=b-6; } b=n-a; } if(a==251) { a=a+1; } b=n-a; if((a%2!=0)&&(a==19367)) { a=a+1; } b=n-a; if(b==11) { a=a+2; b=b-2; } } System.out.print(+a+ " "+b); } }
Java
["12", "15", "23", "1000000"]
1 second
["4 8", "6 9", "8 15", "500000 500000"]
NoteIn the first example, 12 = 4 + 8 and both 4, 8 are composite numbers. You can output "6 6" or "8 4" as well.In the second example, 15 = 6 + 9. Note that you can't output "1 14" because 1 is not a composite number.
Java 8
standard input
[ "number theory", "math" ]
3ea971165088fae130d866180c6c868b
The only line contains an integer n (12 ≤ n ≤ 106).
800
Output two composite integers x and y (1 &lt; x, y &lt; n) such that x + y = n. If there are multiple solutions, you can output any of them.
standard output
PASSED
4e6a60e313710759e12fd85d052928c3
train_001.jsonl
1411918500
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two primes". Let's modify it. How about a statement like that: "each integer no less than 12 can be expressed as the sum of two composite numbers." Not like the Goldbach's conjecture, I can prove this theorem.You are given an integer n no less than 12, express it as a sum of two composite numbers.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Demo demo = new Demo(); Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); demo.solution4(n); } static class Demo { public void solution4(int n) { int[] array = new int[n+1]; //iterate over numbers from 2 to sqrt(n) //set all composite index values to 1 for(int i=2; i<=Math.ceil(Math.sqrt(n)); i++) { if(array[i] == 1) continue; //set all indices that are multiples of i to 1 for(int j=i+1; j<=n; j++) { if(j%i == 0) array[j] = 1; } } int i = 4; int j = n-1; while(i < n && j>3) { // for(int k=2; k<Math.ceil(Math.sqrt(n)); k++) //if both numbers are composite if(array[i] == 1 && array[j] == 1) { if(i+j == n) break; else if(i+j < n) i++; else j--; } else if(array[i] == 0 && array[j] == 1) i++; else if(array[i] == 1 && array[j] == 0) j--; else if(array[i] == 0 && array[j] == 0) { i++; j--; } } System.out.println(i + " " + j); } } }
Java
["12", "15", "23", "1000000"]
1 second
["4 8", "6 9", "8 15", "500000 500000"]
NoteIn the first example, 12 = 4 + 8 and both 4, 8 are composite numbers. You can output "6 6" or "8 4" as well.In the second example, 15 = 6 + 9. Note that you can't output "1 14" because 1 is not a composite number.
Java 8
standard input
[ "number theory", "math" ]
3ea971165088fae130d866180c6c868b
The only line contains an integer n (12 ≤ n ≤ 106).
800
Output two composite integers x and y (1 &lt; x, y &lt; n) such that x + y = n. If there are multiple solutions, you can output any of them.
standard output
PASSED
055f115439f970706be025fb18c767b9
train_001.jsonl
1411918500
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two primes". Let's modify it. How about a statement like that: "each integer no less than 12 can be expressed as the sum of two composite numbers." Not like the Goldbach's conjecture, I can prove this theorem.You are given an integer n no less than 12, express it as a sum of two composite numbers.
256 megabytes
import java.util.Scanner; public class Problem_472 { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n=input.nextInt(); int temp1=0,temp2=0,find1=0,find2=0; if(n%2==0){ temp1=(n-8); temp2=(n-temp1); } else{ temp1=(n-9); temp2=(n-temp1); } System.out.println(temp1+" "+temp2); } }
Java
["12", "15", "23", "1000000"]
1 second
["4 8", "6 9", "8 15", "500000 500000"]
NoteIn the first example, 12 = 4 + 8 and both 4, 8 are composite numbers. You can output "6 6" or "8 4" as well.In the second example, 15 = 6 + 9. Note that you can't output "1 14" because 1 is not a composite number.
Java 8
standard input
[ "number theory", "math" ]
3ea971165088fae130d866180c6c868b
The only line contains an integer n (12 ≤ n ≤ 106).
800
Output two composite integers x and y (1 &lt; x, y &lt; n) such that x + y = n. If there are multiple solutions, you can output any of them.
standard output
PASSED
062ecf42479823269cdb7dd6e3ba3a2e
train_001.jsonl
1411918500
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two primes". Let's modify it. How about a statement like that: "each integer no less than 12 can be expressed as the sum of two composite numbers." Not like the Goldbach's conjecture, I can prove this theorem.You are given an integer n no less than 12, express it as a sum of two composite numbers.
256 megabytes
import java.util.Scanner; public class Problem_472 { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n=input.nextInt(); int temp1=0,temp2=0,find1=0,find2=0; if(n%2==0){ temp1=(n-6); temp2=(n-temp1); } else{ temp1=(n-9); temp2=(n-temp1); } System.out.println(temp1+" "+temp2); } }
Java
["12", "15", "23", "1000000"]
1 second
["4 8", "6 9", "8 15", "500000 500000"]
NoteIn the first example, 12 = 4 + 8 and both 4, 8 are composite numbers. You can output "6 6" or "8 4" as well.In the second example, 15 = 6 + 9. Note that you can't output "1 14" because 1 is not a composite number.
Java 8
standard input
[ "number theory", "math" ]
3ea971165088fae130d866180c6c868b
The only line contains an integer n (12 ≤ n ≤ 106).
800
Output two composite integers x and y (1 &lt; x, y &lt; n) such that x + y = n. If there are multiple solutions, you can output any of them.
standard output
PASSED
5299c8959602f1a7aadfcfb1112b9f69
train_001.jsonl
1411918500
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two primes". Let's modify it. How about a statement like that: "each integer no less than 12 can be expressed as the sum of two composite numbers." Not like the Goldbach's conjecture, I can prove this theorem.You are given an integer n no less than 12, express it as a sum of two composite numbers.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { int n, v1, v2; boolean prime; Scanner input = new Scanner(System.in); n = input.nextInt(); for (int i = 4; i < n-4; i++) { if(!(isprime(n-i))&&!(isprime(i))){ System.out.println(i+ " " +(n-i)); System.exit(0); } } } public static boolean isprime(int n) { int count = 0; for (int i = 1; i <= n; i++) { if (n % i == 0) { count++; } } if (count == 2) { return true; } else { return false; } } }
Java
["12", "15", "23", "1000000"]
1 second
["4 8", "6 9", "8 15", "500000 500000"]
NoteIn the first example, 12 = 4 + 8 and both 4, 8 are composite numbers. You can output "6 6" or "8 4" as well.In the second example, 15 = 6 + 9. Note that you can't output "1 14" because 1 is not a composite number.
Java 8
standard input
[ "number theory", "math" ]
3ea971165088fae130d866180c6c868b
The only line contains an integer n (12 ≤ n ≤ 106).
800
Output two composite integers x and y (1 &lt; x, y &lt; n) such that x + y = n. If there are multiple solutions, you can output any of them.
standard output
PASSED
6c1d547870a16ddbfff6bd76957b0483
train_001.jsonl
1411918500
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two primes". Let's modify it. How about a statement like that: "each integer no less than 12 can be expressed as the sum of two composite numbers." Not like the Goldbach's conjecture, I can prove this theorem.You are given an integer n no less than 12, express it as a sum of two composite numbers.
256 megabytes
import java.util.*; public class Stringproplm { public static void main(String[] args) { Scanner in=new Scanner(System.in); int n=in.nextInt(); if(n%2==0){ int x=n/2; if(x%2==0){ int y=n/2; int z=n-y; if(y==2){ y+=2; z-=2; } if(z==2){ z+=2; y-=2; } System.out.println(y+" "+z); }else{ int y=x-9; int z=n-y; if(y==2){ y+=2; z-=2; } if(z==2){ z+=2; y-=2; } System.out.println(y+" "+z); } }else{ int x=n-9; int y=n-x; if(x==2){ x+=2; y-=2; } if(y==2){ y+=2; x-=2; } System.out.println(x+" "+y); } } }
Java
["12", "15", "23", "1000000"]
1 second
["4 8", "6 9", "8 15", "500000 500000"]
NoteIn the first example, 12 = 4 + 8 and both 4, 8 are composite numbers. You can output "6 6" or "8 4" as well.In the second example, 15 = 6 + 9. Note that you can't output "1 14" because 1 is not a composite number.
Java 8
standard input
[ "number theory", "math" ]
3ea971165088fae130d866180c6c868b
The only line contains an integer n (12 ≤ n ≤ 106).
800
Output two composite integers x and y (1 &lt; x, y &lt; n) such that x + y = n. If there are multiple solutions, you can output any of them.
standard output
PASSED
accd489cdba8f668446c9efa456b1ccf
train_001.jsonl
1411918500
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two primes". Let's modify it. How about a statement like that: "each integer no less than 12 can be expressed as the sum of two composite numbers." Not like the Goldbach's conjecture, I can prove this theorem.You are given an integer n no less than 12, express it as a sum of two composite numbers.
256 megabytes
import java.util.Scanner; public class DesignTutorialLearnFromMath { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(), x, y; scanner.close(); if (n % 2 == 0) { comp(n / 2, n / 2); } else { x = n / 2; y = x + 1; comp(x, y); } } private static void comp(int x, int y) { int sys = 0, z; if (x % 2 == 0) z = y; else z = x; for (int i = 2; i < x; i++) { if (z % i == 0) { System.out.println(x + " " + y); sys = 1; break; } } if (sys == 0) comp(x - 1, y + 1); } }
Java
["12", "15", "23", "1000000"]
1 second
["4 8", "6 9", "8 15", "500000 500000"]
NoteIn the first example, 12 = 4 + 8 and both 4, 8 are composite numbers. You can output "6 6" or "8 4" as well.In the second example, 15 = 6 + 9. Note that you can't output "1 14" because 1 is not a composite number.
Java 8
standard input
[ "number theory", "math" ]
3ea971165088fae130d866180c6c868b
The only line contains an integer n (12 ≤ n ≤ 106).
800
Output two composite integers x and y (1 &lt; x, y &lt; n) such that x + y = n. If there are multiple solutions, you can output any of them.
standard output
PASSED
34b9ac7611fbf6df03a63db9f456bf35
train_001.jsonl
1411918500
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two primes". Let's modify it. How about a statement like that: "each integer no less than 12 can be expressed as the sum of two composite numbers." Not like the Goldbach's conjecture, I can prove this theorem.You are given an integer n no less than 12, express it as a sum of two composite numbers.
256 megabytes
import java.util.*; public class Matematics{ public static void main(String[] args){ Scanner scan = new Scanner(System.in); int a = scan.nextInt(); //int b = a/2; for(int i=4;i<a;i++){ int b=a-i; if((i%2==0&&b%2==0)||(i%2==0&&b%3==0)||(i%3==0&&b%2==0)||(i%3==0&&b%3==0)){ System.out.println(i+" "+b); break; } } } }
Java
["12", "15", "23", "1000000"]
1 second
["4 8", "6 9", "8 15", "500000 500000"]
NoteIn the first example, 12 = 4 + 8 and both 4, 8 are composite numbers. You can output "6 6" or "8 4" as well.In the second example, 15 = 6 + 9. Note that you can't output "1 14" because 1 is not a composite number.
Java 8
standard input
[ "number theory", "math" ]
3ea971165088fae130d866180c6c868b
The only line contains an integer n (12 ≤ n ≤ 106).
800
Output two composite integers x and y (1 &lt; x, y &lt; n) such that x + y = n. If there are multiple solutions, you can output any of them.
standard output
PASSED
c34fd1179e8291586e1f4b10fb77460c
train_001.jsonl
1454605500
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: G has exactly n vertices, numbered from 1 to n. For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.
256 megabytes
import java.io.InputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.InputMismatchException; import java.util.NoSuchElementException; import java.math.BigInteger; public class Main{ static PrintWriter out; static InputReader ir; static void solve(){ int n=ir.nextInt(); int m=ir.nextInt(); G g=new G(n,true); boolean[][] es=new boolean[n][n]; for(int i=0;i<m;i++){ int u=ir.nextInt()-1; int v=ir.nextInt()-1; es[u][v]=es[v][u]=true; } for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ if(!es[i][j]) g.addEdge(i,j); } } int[] col=new int[n]; for(int i=0;i<n;i++){ if(g.size(i)!=0&&col[i]==0){ if(!dfs(i,1,g,col)){ out.println("No"); return; } } } for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ if(es[i][j]&&col[i]*col[j]==-1){ out.println("No"); return; } } } out.println("Yes"); for(int i=0;i<n;i++){ if(col[i]==1) out.print("a"); else if(col[i]==0) out.print("b"); else out.print("c"); } out.println(); } public static boolean dfs(int v,int c,G g,int[] col){ col[v]=c; for(int i=0;i<g.size(v);i++){ int to=g.to(v,i); if(col[to]==c) return false; if(col[to]==0&&!dfs(to,-c,g,col)) return false; } return true; } static class G{ AL[] g,rg; private int V; private boolean ndir; public G(int V,boolean ndir){ this.V=V; this.ndir=ndir; g=new AL[V]; for(int i=0;i<V;i++) g[i]=new AL(); } public void addEdge(int u,int v,int t){ g[u].add(new int[]{v,t}); if(this.ndir) g[v].add(new int[]{u,t}); } public void addEdge(int u,int v){ addEdge(u,v,0); } public int to(int from,int ind){return g[from].get(ind)[0];} public int cost(int from,int ind){return g[from].get(ind)[1];} public int size(int from){return g[from].size();} public int[] dijkstra(int s){ int[] dist=new int[this.V]; java.util.PriorityQueue<int[]> pque=new java.util.PriorityQueue<int[]>(11,new Comparator<int[]>(){ public int compare(int[] a,int[] b){ return Integer.compare(a[0],b[0]); } }); Arrays.fill(dist,1<<26); dist[s]=0; pque.offer(new int[]{0,s}); while(!pque.isEmpty()){ int[] p=pque.poll(); int v=p[1]; if(dist[v]<p[0]) continue; for(int i=0;i<g[v].size();i++){ int to=to(v,i),cost=cost(v,i); if(dist[to]>dist[v]+cost){ dist[to]=dist[v]+cost; pque.offer(new int[]{dist[to],to}); } } } return dist; } public int[] tporder(){ boolean[] vis=new boolean[V]; ArrayList<Integer> ord=new ArrayList<>(); for(int i=0;i<V;i++) if(!vis[i]) ts(i,vis,ord); int[] ret=new int[V]; for(int i=ord.size()-1;i>=0;i--) ret[ord.size()-1-i]=ord.get(i); return ret; } public int[] scc(){ rg=new AL[V]; for(int i=0;i<V;i++) rg[i]=new AL(); int from,to; for(int i=0;i<V;i++){ for(int j=0;j<g[i].size();j++){ to=i; from=to(i,j); rg[from].add(new int[]{to,0}); } } int[] ord=tporder(); int k=0; boolean[] vis=new boolean[V]; int[] ret=new int[V+1]; for(int i=0;i<V;i++) if(!vis[i]) rs(ord[i],vis,ret,k++); ret[V]=k; return ret; } private void ts(int now,boolean[] vis,ArrayList<Integer> ord){ vis[now]=true; int to; for(int i=0;i<g[now].size();i++){ to=to(now,i); if(!vis[to]) ts(to,vis,ord); } ord.add(now); } private void rs(int now,boolean[] vis,int[] ret,int k){ vis[now]=true; ret[now]=k; int to; for(int i=0;i<rg[now].size();i++){ to=rg[now].get(i)[0]; if(!vis[to]) rs(to,vis,ret,k); } } static class AL extends ArrayList<int[]>{}; } public static void main(String[] args) throws Exception{ ir=new InputReader(System.in); out=new PrintWriter(System.out); solve(); out.flush(); } static class InputReader { private InputStream in; private byte[] buffer=new byte[1024]; private int curbuf; private int lenbuf; public InputReader(InputStream in) {this.in=in; this.curbuf=this.lenbuf=0;} public boolean hasNextByte() { if(curbuf>=lenbuf){ curbuf= 0; try{ lenbuf=in.read(buffer); }catch(IOException e) { throw new InputMismatchException(); } if(lenbuf<=0) return false; } return true; } private int readByte(){if(hasNextByte()) return buffer[curbuf++]; else return -1;} private boolean isSpaceChar(int c){return !(c>=33&&c<=126);} private void skip(){while(hasNextByte()&&isSpaceChar(buffer[curbuf])) curbuf++;} public boolean hasNext(){skip(); return hasNextByte();} public String next(){ if(!hasNext()) throw new NoSuchElementException(); StringBuilder sb=new StringBuilder(); int b=readByte(); while(!isSpaceChar(b)){ sb.appendCodePoint(b); b=readByte(); } return sb.toString(); } public int nextInt() { if(!hasNext()) throw new NoSuchElementException(); int c=readByte(); while (isSpaceChar(c)) c=readByte(); boolean minus=false; if (c=='-') { minus=true; c=readByte(); } int res=0; do{ if(c<'0'||c>'9') throw new InputMismatchException(); res=res*10+c-'0'; c=readByte(); }while(!isSpaceChar(c)); return (minus)?-res:res; } public long nextLong() { if(!hasNext()) throw new NoSuchElementException(); int c=readByte(); while (isSpaceChar(c)) c=readByte(); boolean minus=false; if (c=='-') { minus=true; c=readByte(); } long res = 0; do{ if(c<'0'||c>'9') throw new InputMismatchException(); res=res*10+c-'0'; c=readByte(); }while(!isSpaceChar(c)); return (minus)?-res:res; } public double nextDouble(){return Double.parseDouble(next());} public int[] nextIntArray(int n){ int[] a=new int[n]; for(int i=0;i<n;i++) a[i]=nextInt(); return a; } public long[] nextLongArray(int n){ long[] a=new long[n]; for(int i=0;i<n;i++) a[i]=nextLong(); return a; } public char[][] nextCharMap(int n,int m){ char[][] map=new char[n][m]; for(int i=0;i<n;i++) map[i]=next().toCharArray(); return map; } } }
Java
["2 1\n1 2", "4 3\n1 2\n1 3\n1 4"]
2 seconds
["Yes\naa", "No"]
NoteIn the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "graphs" ]
e71640f715f353e49745eac5f72e682a
The first line of the input contains two integers n and m  — the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.
1,800
In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.
standard output