exec_outcome
stringclasses
1 value
code_uid
stringlengths
32
32
file_name
stringclasses
111 values
prob_desc_created_at
stringlengths
10
10
prob_desc_description
stringlengths
63
3.8k
prob_desc_memory_limit
stringclasses
18 values
source_code
stringlengths
117
65.5k
lang_cluster
stringclasses
1 value
prob_desc_sample_inputs
stringlengths
2
802
prob_desc_time_limit
stringclasses
27 values
prob_desc_sample_outputs
stringlengths
2
796
prob_desc_notes
stringlengths
4
3k
lang
stringclasses
5 values
prob_desc_input_from
stringclasses
3 values
tags
sequencelengths
0
11
src_uid
stringlengths
32
32
prob_desc_input_spec
stringlengths
28
2.37k
difficulty
int64
-1
3.5k
prob_desc_output_spec
stringlengths
17
1.47k
prob_desc_output_to
stringclasses
3 values
hidden_unit_tests
stringclasses
1 value
PASSED
75ff866beed3666b6d2cf4307a9e8ffc
train_000.jsonl
1484235300
It's the turn of the year, so Bash wants to send presents to his friends. There are n cities in the Himalayan region and they are connected by m bidirectional roads. Bash is living in city s. Bash has exactly one friend in each of the other cities. Since Bash wants to surprise his friends, he decides to send a Pikachu to each of them. Since there may be some cities which are not reachable from Bash's city, he only sends a Pikachu to those friends who live in a city reachable from his own city. He also wants to send it to them as soon as possible.He finds out the minimum time for each of his Pikachus to reach its destination city. Since he is a perfectionist, he informs all his friends with the time their gift will reach them. A Pikachu travels at a speed of 1 meters per second. His friends were excited to hear this and would be unhappy if their presents got delayed. Unfortunately Team Rocket is on the loose and they came to know of Bash's plan. They want to maximize the number of friends who are unhappy with Bash.They do this by destroying exactly one of the other n - 1 cities. This implies that the friend residing in that city dies, so he is unhappy as well.Note that if a city is destroyed, all the roads directly connected to the city are also destroyed and the Pikachu may be forced to take a longer alternate route.Please also note that only friends that are waiting for a gift count as unhappy, even if they die.Since Bash is already a legend, can you help Team Rocket this time and find out the maximum number of Bash's friends who can be made unhappy by destroying exactly one city.
512 megabytes
import java.io.*; import java.util.*; public class F { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; int n; int root; List<Edge>[] g; static class Edge { int to, cost; public Edge(int to, int cost) { this.to = to; this.cost = cost; } @Override public String toString() { return "(" + to + ", " + cost + ")"; } } static class Distance implements Comparable<Distance> { int v; long dist; public Distance(int v, long dist) { this.v = v; this.dist = dist; } @Override public int compareTo(Distance o) { return Long.compare(dist, o.dist); } } static final long INF = Long.MAX_VALUE / 10; long[] shortestPaths(int from, int killed) { long[] d = new long[n]; Arrays.fill(d, INF); d[from] = 0; PriorityQueue<Distance> pq = new PriorityQueue<>(); pq.add(new Distance(from, 0)); while (!pq.isEmpty()) { Distance tmp = pq.poll(); int v = tmp.v; long dist = tmp.dist; if (d[v] != dist) { continue; } for (Edge e : g[v]) { if (e.to != killed && d[e.to] > d[v] + e.cost) { d[e.to] = d[v] + e.cost; pq.add(new Distance(e.to, d[e.to])); } } } return d; } int brute() { long[] d = shortestPaths(root, -1); int ret = 0; for (int i = 0; i < n; i++) { if (i == root) { continue; } long[] d2 = shortestPaths(root, i); int cur = 0; for (int j = 0; j < n; j++) { if (d[j] != d2[j]) { cur++; } } ret = Math.max(ret, cur); } return ret; } int[] depth; static final int LOG = 18; boolean[] vis; int[] order; int ptr; void dfs(int v, int par, long[] dist) { // System.err.println(v + " " + par); vis[v] = true; for (Edge e : g[v]) { if (!vis[e.to] && dist[e.to] == dist[v] + e.cost) { dfs(e.to, v, dist); } } order[ptr++] = v; } int solve() { long[] d = shortestPaths(root, -1); vis = new boolean[n]; order = new int[n]; ptr = 0; dfs(root, root, d); for (int i = 0, j = ptr - 1; i < j; i++, j--) { int tmp = order[i]; order[i] = order[j]; order[j] = tmp; } int ret = 0; // System.err.println(Arrays.toString(order)); int[] color = new int[n]; int cnt = 0; int[] byColor = new int[n]; for (int i = 1; i < ptr; i++) { int v = order[i]; int cur = -1; for (Edge e : g[v]) { if (d[e.to] + e.cost == d[v]) { if (e.to == root) { cur = cnt++; break; } if (cur == -1) { cur = color[e.to]; } if (cur != color[e.to]) { cur = cnt++; break; } } } color[v] = cur; byColor[cur]++; ret = Math.max(ret, byColor[cur]); } return ret; } void submit() throws IOException { n = nextInt(); int m = nextInt(); root = nextInt() - 1; g = new List[n]; for (int i = 0; i < n; i++) { g[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int v = nextInt() - 1; int u = nextInt() - 1; int len = nextInt(); g[v].add(new Edge(u, len)); g[u].add(new Edge(v, len)); } out.println(solve()); // out.println(brute()); } static final Random rng = new Random(); void stress(int maxN, int num, int denom, int bound) { for (int tst = 0; tst < Integer.MAX_VALUE; tst++) { n = rng.nextInt(maxN) + 1; g = new List[n]; for (int i = 0; i < n; i++) { g[i] = new ArrayList<>(); } for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) { if (rng.nextInt(denom) < num) { int len = rng.nextInt(bound) + 1; g[i].add(new Edge(j, len)); g[j].add(new Edge(i, len)); } } if (solve() != brute()) { System.err.println(n); System.err.println(Arrays.toString(g)); break; } System.err.println(tst); } } F() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); // stress(10, 1, 2, 10); submit(); out.close(); } public static void main(String[] args) throws IOException { new F(); } 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
["4 4 3\n1 2 1\n2 3 1\n2 4 1\n3 1 1", "7 11 2\n1 2 5\n1 3 5\n2 4 2\n2 5 2\n3 6 3\n3 7 3\n4 6 2\n3 4 2\n6 7 3\n4 5 7\n4 7 7"]
2.5 seconds
["2", "4"]
NoteIn the first sample, on destroying the city 2, the length of shortest distance between pairs of cities (3, 2) and (3, 4) will change. Hence the answer is 2.
Java 8
standard input
[ "data structures", "graphs", "shortest paths" ]
c47d0c9a429030c4b5d6f5605be36c75
The first line contains three space separated integers n, m and s (2 ≤ n ≤ 2·105, , 1 ≤ s ≤ n) — the number of cities and the number of roads in the Himalayan region and the city Bash lives in. Each of the next m lines contain three space-separated integers u, v and w (1 ≤ u, v ≤ n, u ≠ v, 1 ≤ w ≤ 109) denoting that there exists a road between city u and city v of length w meters. It is guaranteed that no road connects a city to itself and there are no two roads that connect the same pair of cities.
2,800
Print a single integer, the answer to the problem.
standard output
PASSED
ad2b57f4e51dd77cd7fadc22ed006f64
train_000.jsonl
1337182200
Berland has managed to repel the flatlanders' attack and is now starting the counter attack.Flatland has n cities, numbered from 1 to n, and some pairs of them are connected by bidirectional roads. The Flatlandian maps show roads between cities if and only if there is in fact no road between this pair of cities (we do not know whether is it a clever spy-proof strategy or just saving ink). In other words, if two cities are connected by a road on a flatland map, then there is in fact no road between them. The opposite situation is also true: if two cities are not connected by a road on a flatland map, then in fact, there is a road between them.The berlanders got hold of a flatland map. Now Vasya the Corporal is commissioned by General Touristov to find all such groups of flatland cities, that in each group of cities you can get from any city to any other one, moving along the actual roads. Also the cities from different groups are unreachable from each other, moving along the actual roads. Indeed, destroying such groups one by one is much easier than surrounding all Flatland at once!Help the corporal complete this task and finally become a sergeant! Don't forget that a flatland map shows a road between cities if and only if there is in fact no road between them.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskE solver = new TaskE(); solver.solve(in, out); out.close(); } } class TaskE { private List<List<Integer>> result = new ArrayList<>(); int [][] graph; int [][] edges; int [] degree; public void solve(InputReader in, OutputWriter out) { int n = in.nextInt(); int m = in.nextInt(); prepareGraph(in, n, m); calculateNumberOfComponents(n); out.printLine(result.size()); for(List<Integer> list : result) { out.print(list.size()+" "); for(int element : list) { out.print((element+1) + " "); } out.printLine(); } } private void prepareGraph(InputReader in, int n, int m) { graph = new int[n][]; degree = new int[n]; edges = new int[m][2]; int from, to; for(int i=0;i<m;i++) { from = in.nextInt() - 1; to = in.nextInt() - 1; degree[from]++; degree[to]++; edges[i][0] = from; edges[i][1] = to; } for(int i=0;i<n;i++) { graph[i] = new int[degree[i]]; degree[i] = 0; } for(int i=0;i<m;i++) { from = edges[i][0]; to = edges[i][1]; graph[from][degree[from]++] = to; graph[to][degree[to]++] = from; } } private void calculateNumberOfComponents(int n) { Set<Integer> remaining = new HashSet<>(); for (int i = 0; i < n; i++) { remaining.add(i); } Queue<Integer> queue = new ArrayDeque<>(); Set<Integer> newlyAdded; List<Integer> partialResult; int vertex; for(int i=0;i<n;i++) { if(!remaining.contains(i)) continue; partialResult = new ArrayList<>(); remaining.remove(i); queue.add(i); while(!queue.isEmpty()) { vertex = queue.remove(); partialResult.add(vertex); newlyAdded = new HashSet<>(); for(int neighbour : graph[vertex]) { if(remaining.contains(neighbour)) { newlyAdded.add(neighbour); remaining.remove(neighbour); } } for(int v : remaining) queue.add(v); remaining.clear(); remaining.addAll(newlyAdded); } result.add(partialResult); } } } 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 boolean hasNext() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { String line = reader.readLine(); if ( line == null ) { return false; } tokenizer = new StringTokenizer(line); } catch (IOException e) { throw new RuntimeException(e); } } return true; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next());} } 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(); } }
Java
["4 4\n1 2\n1 3\n4 2\n4 3", "3 1\n1 2"]
3 seconds
["2\n2 1 4 \n2 2 3", "1\n3 1 2 3"]
NoteIn the first sample there are roads only between pairs of cities 1-4 and 2-3.In the second sample there is no road between cities 1 and 2, but still you can get from one city to the other one through city number 3.
Java 8
standard input
[ "hashing", "graphs", "dsu", "sortings", "data structures" ]
72394a06a9d9dffb61c6c92c4bbd2f3a
The first line contains two space-separated integers n and m (1 ≤ n ≤ 5·105, 0 ≤ m ≤ 106) — the number of cities and the number of roads marked on the flatland map, correspondingly. Next m lines contain descriptions of the cities on the map. The i-th line contains two integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — the numbers of cities that are connected by the i-th road on the flatland map. It is guaranteed that each pair of cities occurs in the input no more than once.
2,100
On the first line print number k — the number of groups of cities in Flatland, such that in each group you can get from any city to any other one by flatland roads. At the same time, the cities from different groups should be unreachable by flatland roads. On each of the following k lines first print ti (1 ≤ ti ≤ n) — the number of vertexes in the i-th group. Then print space-separated numbers of cities in the i-th group. The order of printing groups and the order of printing numbers in the groups does not matter. The total sum ti for all k groups must equal n.
standard output
PASSED
fbccaa26153b84bdbf26214e5bdb741d
train_000.jsonl
1337182200
Berland has managed to repel the flatlanders' attack and is now starting the counter attack.Flatland has n cities, numbered from 1 to n, and some pairs of them are connected by bidirectional roads. The Flatlandian maps show roads between cities if and only if there is in fact no road between this pair of cities (we do not know whether is it a clever spy-proof strategy or just saving ink). In other words, if two cities are connected by a road on a flatland map, then there is in fact no road between them. The opposite situation is also true: if two cities are not connected by a road on a flatland map, then in fact, there is a road between them.The berlanders got hold of a flatland map. Now Vasya the Corporal is commissioned by General Touristov to find all such groups of flatland cities, that in each group of cities you can get from any city to any other one, moving along the actual roads. Also the cities from different groups are unreachable from each other, moving along the actual roads. Indeed, destroying such groups one by one is much easier than surrounding all Flatland at once!Help the corporal complete this task and finally become a sergeant! Don't forget that a flatland map shows a road between cities if and only if there is in fact no road between them.
256 megabytes
import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; public class Task2 { public static void main(String[] args) throws IOException { new Task2().solve(); } int mod = 1000000007; PrintWriter out; int n; int m; ArrayList<Integer>[] g; void solve() throws IOException { //Reader in = new Reader("in.txt"); //out = new PrintWriter( new BufferedWriter(new FileWriter("output.txt")) ); Reader in = new Reader(); PrintWriter out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out)) ); //BufferedReader br = new BufferedReader( new FileReader("in.txt") ); //BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) ); int n = in.nextInt(); int m = in.nextInt(); Pair[] edge = new Pair[m]; int[] inDeg = new int[n]; for (int i = 0; i < m; i++) { int x = in.nextInt()-1; int y = in.nextInt()-1; edge[i] = new Pair(x, y); inDeg[x]++; inDeg[y]++; } ArrayList<Integer> need = new ArrayList<>(); boolean[] isNeed = new boolean[n]; int minV = 0; for (int i = 0; i < n; i++) if (inDeg[i] < inDeg[minV]) minV = i; HashSet<Integer>[] g = new HashSet[n]; for (int i = 0; i < n; i++) { g[i] = new HashSet<>(); } for (int i = 0; i < m; i++) { if (edge[i].a == minV) { need.add(edge[i].b); isNeed[edge[i].b] = true; } if (edge[i].b == minV) { need.add(edge[i].a); isNeed[edge[i].a] = true; } } int[] sz = new int[n]; int[] ver = new int[n]; for (int i = 0; i < need.size(); i++) ver[need.get(i)] = i; int[][] a = new int[need.size()][need.size()]; for (int i = 0; i < m; i++) { int v = edge[i].a; int u = edge[i].b; if (isNeed[v] && isNeed[u]) { a[ver[v]][ver[u]] = 1; a[ver[u]][ver[v]] = 1; } else if (isNeed[u]) { sz[u]++; } else if (isNeed[v]) { sz[v]++; } } DSU dsu = new DSU(n); int cntNotNeed = 0; for (int i = 0; i < n; i++) if (!isNeed[i]) { cntNotNeed++; dsu.union(minV, i); } for (int v : need) { if (sz[v] < cntNotNeed) dsu.union(v, minV); for (int i : need) if (a[ver[v]][ver[i]] == 0) dsu.union(v, i); } ArrayList<Integer>[] tans = new ArrayList[n]; for (int i = 0; i < n; i++) tans[i] = new ArrayList<>(); for (int i = 0; i < n; i++) { int x = dsu.get(i); tans[x].add(i+1); } int acnt = 0; for (int i = 0; i < n; i++) if (tans[i].size() > 0) acnt++; out.println(acnt); for (int i = 0; i < n; i++) { if (tans[i].size() == 0) continue; out.print(tans[i].size() + " "); for (int u : tans[i]) out.print(u+" "); out.println(); } out.flush(); out.close(); } class DSU { int[] set; int[] size; DSU(int n) { set = new int[n]; size = new int[n]; for (int i = 0; i < n; i++) { set[i] = i; size[i] = 1; } } int get(int a) { if (set[a] == a) return a; return set[a] = get(set[a]); } void union(int a, int b) { a = get(a); b = get(b); if (a == b) return; if (size[a] >= size[b]) { set[b] = a; size[a] += size[b]; } else { set[a] = b; size[b] += size[a]; } } boolean compare(int a, int b) { return get(a) == get(b); } } class Pair implements Comparable<Pair>{ int a; int b; Pair(int a, int b) { this.a = a; this.b = b; } public int compareTo(Pair p) { if (b < p.b) return 1; if (b > p.b) return -1; return 0; } // @Override // public boolean equals(Object o) { // Pair p = (Pair) o; // return a == p.a && b == p.b; // } // // @Override // public int hashCode() { // return Integer.valueOf(a).hashCode() + Integer.valueOf(b).hashCode(); // } } class Reader { BufferedReader br; StringTokenizer tok; Reader(String file) throws IOException { br = new BufferedReader( new FileReader(file) ); } Reader() throws IOException { br = new BufferedReader( new InputStreamReader(System.in) ); } String next() throws IOException { while (tok == null || !tok.hasMoreElements()) tok = new StringTokenizer(br.readLine()); return tok.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.valueOf(next()); } long nextLong() throws NumberFormatException, IOException { return Long.valueOf(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.valueOf(next()); } String nextLine() throws IOException { return br.readLine(); } } }
Java
["4 4\n1 2\n1 3\n4 2\n4 3", "3 1\n1 2"]
3 seconds
["2\n2 1 4 \n2 2 3", "1\n3 1 2 3"]
NoteIn the first sample there are roads only between pairs of cities 1-4 and 2-3.In the second sample there is no road between cities 1 and 2, but still you can get from one city to the other one through city number 3.
Java 8
standard input
[ "hashing", "graphs", "dsu", "sortings", "data structures" ]
72394a06a9d9dffb61c6c92c4bbd2f3a
The first line contains two space-separated integers n and m (1 ≤ n ≤ 5·105, 0 ≤ m ≤ 106) — the number of cities and the number of roads marked on the flatland map, correspondingly. Next m lines contain descriptions of the cities on the map. The i-th line contains two integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — the numbers of cities that are connected by the i-th road on the flatland map. It is guaranteed that each pair of cities occurs in the input no more than once.
2,100
On the first line print number k — the number of groups of cities in Flatland, such that in each group you can get from any city to any other one by flatland roads. At the same time, the cities from different groups should be unreachable by flatland roads. On each of the following k lines first print ti (1 ≤ ti ≤ n) — the number of vertexes in the i-th group. Then print space-separated numbers of cities in the i-th group. The order of printing groups and the order of printing numbers in the groups does not matter. The total sum ti for all k groups must equal n.
standard output
PASSED
60ea9cb1d4682f1dc911efaf7945e3e3
train_000.jsonl
1337182200
Berland has managed to repel the flatlanders' attack and is now starting the counter attack.Flatland has n cities, numbered from 1 to n, and some pairs of them are connected by bidirectional roads. The Flatlandian maps show roads between cities if and only if there is in fact no road between this pair of cities (we do not know whether is it a clever spy-proof strategy or just saving ink). In other words, if two cities are connected by a road on a flatland map, then there is in fact no road between them. The opposite situation is also true: if two cities are not connected by a road on a flatland map, then in fact, there is a road between them.The berlanders got hold of a flatland map. Now Vasya the Corporal is commissioned by General Touristov to find all such groups of flatland cities, that in each group of cities you can get from any city to any other one, moving along the actual roads. Also the cities from different groups are unreachable from each other, moving along the actual roads. Indeed, destroying such groups one by one is much easier than surrounding all Flatland at once!Help the corporal complete this task and finally become a sergeant! Don't forget that a flatland map shows a road between cities if and only if there is in fact no road between them.
256 megabytes
import java.io.*; import java.util.*; public class Main { static FastReader in; static PrintWriter out; static int g [][]; static int deg []; static int edges [][]; static ArrayList<ArrayList<Integer>> answer = new ArrayList<ArrayList<Integer>>(); public static void solve () { int n = in.nextInt(); int m = in.nextInt(); g = new int [n][]; deg = new int [n]; edges = new int [m][2]; for (int i = 0; i < m; i++) { int v1 = in.nextInt() - 1; int v2 = in.nextInt() - 1; deg[v1]++; deg[v2]++; edges[i][0] = v1; edges[i][1] = v2; } for (int i = 0; i < n; i++) { g [i] = new int [deg[i]]; deg[i] = 0; } for (int i = 0; i < m; i++) { int v1 = edges[i][0]; int v2 = edges[i][1]; g[v1][deg[v1]++] = v2; g[v2][deg[v2]++] = v1; } HashSet<Integer> set = new HashSet<Integer>(); for (int i = 0; i < n; i++) { set.add(i); } LinkedList<Integer> q = new LinkedList<Integer>(); for (int i = 0; i < n; i++) { if (set.contains(i)) { q.add(i); ArrayList<Integer> list = new ArrayList<Integer>(); set.remove(i); while (!q.isEmpty()) { int v = q.pollFirst(); list.add(v + 1); HashSet<Integer> removeSet = new HashSet<Integer>(); for (int j = 0; j < g[v].length; j++) { int to = g[v][j]; if (set.contains(to)) { removeSet.add(to); set.remove(to); } } for (int to : set) { q.add(to); } if (set.size() > 0) { set.clear(); } for (int rmv : removeSet) { set.add(rmv); } } answer.add(list); } } out.println(answer.size()); for (int i = 0; i < answer.size(); i++) { ArrayList<Integer> list = answer.get(i); out.print(list.size()); for (int v : list) { out.print(" "+v); } out.println(); } } public static void main(String[] args) { in = new FastReader(System.in); // in = new FastReader(new FileInputStream("input.txt")); out = new PrintWriter(System.out); // out = new PrintWriter(new FileOutputStream("output.txt")); int t = 1; while (t-- > 0) solve(); out.close(); } static class FastReader { BufferedReader br; StringTokenizer st; FastReader(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } Integer nextInt() { return Integer.parseInt(next()); } Long nextLong() { return Long.parseLong(next()); } Double nextDouble() { return Double.parseDouble(next()); } String next() { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(nextLine()); } return st.nextToken(); } String nextLine() { String s = ""; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return s; } } }
Java
["4 4\n1 2\n1 3\n4 2\n4 3", "3 1\n1 2"]
3 seconds
["2\n2 1 4 \n2 2 3", "1\n3 1 2 3"]
NoteIn the first sample there are roads only between pairs of cities 1-4 and 2-3.In the second sample there is no road between cities 1 and 2, but still you can get from one city to the other one through city number 3.
Java 8
standard input
[ "hashing", "graphs", "dsu", "sortings", "data structures" ]
72394a06a9d9dffb61c6c92c4bbd2f3a
The first line contains two space-separated integers n and m (1 ≤ n ≤ 5·105, 0 ≤ m ≤ 106) — the number of cities and the number of roads marked on the flatland map, correspondingly. Next m lines contain descriptions of the cities on the map. The i-th line contains two integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — the numbers of cities that are connected by the i-th road on the flatland map. It is guaranteed that each pair of cities occurs in the input no more than once.
2,100
On the first line print number k — the number of groups of cities in Flatland, such that in each group you can get from any city to any other one by flatland roads. At the same time, the cities from different groups should be unreachable by flatland roads. On each of the following k lines first print ti (1 ≤ ti ≤ n) — the number of vertexes in the i-th group. Then print space-separated numbers of cities in the i-th group. The order of printing groups and the order of printing numbers in the groups does not matter. The total sum ti for all k groups must equal n.
standard output
PASSED
da09428ce9658c85471c0284d5fe64e0
train_000.jsonl
1337182200
Berland has managed to repel the flatlanders' attack and is now starting the counter attack.Flatland has n cities, numbered from 1 to n, and some pairs of them are connected by bidirectional roads. The Flatlandian maps show roads between cities if and only if there is in fact no road between this pair of cities (we do not know whether is it a clever spy-proof strategy or just saving ink). In other words, if two cities are connected by a road on a flatland map, then there is in fact no road between them. The opposite situation is also true: if two cities are not connected by a road on a flatland map, then in fact, there is a road between them.The berlanders got hold of a flatland map. Now Vasya the Corporal is commissioned by General Touristov to find all such groups of flatland cities, that in each group of cities you can get from any city to any other one, moving along the actual roads. Also the cities from different groups are unreachable from each other, moving along the actual roads. Indeed, destroying such groups one by one is much easier than surrounding all Flatland at once!Help the corporal complete this task and finally become a sergeant! Don't forget that a flatland map shows a road between cities if and only if there is in fact no road between them.
256 megabytes
import java.io.*; import java.util.*; public class Main { static FastReader in; static PrintWriter out; static int n, m; static int[][] edges; static int[] deg; static int[][] g; static HashSet<Integer> s; static LinkedList<Integer> q; static ArrayList<ArrayList<Integer>> ans; static void solve() { n = in.nextInt(); m = in.nextInt(); edges = new int[m][2]; deg = new int[n]; for (int i = 0; i < m; i++) { int v = in.nextInt() - 1; int u = in.nextInt() - 1; edges[i][0] = v; edges[i][1] = u; deg[v]++; deg[u]++; } g = new int[n][]; for (int i = 0; i < n; i++) { g[i] = new int[deg[i]]; deg[i] = 0; } for (int i = 0; i < m; i++) { int v = edges[i][0]; int u = edges[i][1]; g[v][deg[v]++] = u; g[u][deg[u]++] = v; } ans = new ArrayList<>(); s = new HashSet<>(); for (int i = 0; i < n; i++) { s.add(i); } q = new LinkedList<>(); for (int i = 0; i < n; i++) { if (s.contains(i)) { ArrayList<Integer> ansi = new ArrayList<>(); q.add(i); s.remove(i); while (!q.isEmpty()) { int v = q.poll(); ansi.add(v); HashSet<Integer> temp = new HashSet<>(); for (int u : g[v]) { if (s.contains(u)) { temp.add(u); s.remove(u); } } for (int u : s) { q.add(u); } s = temp; } ans.add(ansi); } } out.println(ans.size()); for (ArrayList<Integer> ansi : ans) { out.print(ansi.size()); for (int v : ansi) { out.print(" " + (v + 1)); } out.print('\n'); } } public static void main(String[] args) { in = new FastReader(System.in); // in = new FastReader(new FileInputStream("input.txt")); out = new PrintWriter(System.out); // out = new PrintWriter(new FileOutputStream("output.txt")); int t = 1; while (t-- > 0) solve(); out.close(); } static class FastReader { BufferedReader br; StringTokenizer st; FastReader(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } Integer nextInt() { return Integer.parseInt(next()); } Long nextLong() { return Long.parseLong(next()); } Double nextDouble() { return Double.parseDouble(next()); } String next() { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(nextLine()); } return st.nextToken(); } String nextLine() { String s = ""; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return s; } } }
Java
["4 4\n1 2\n1 3\n4 2\n4 3", "3 1\n1 2"]
3 seconds
["2\n2 1 4 \n2 2 3", "1\n3 1 2 3"]
NoteIn the first sample there are roads only between pairs of cities 1-4 and 2-3.In the second sample there is no road between cities 1 and 2, but still you can get from one city to the other one through city number 3.
Java 8
standard input
[ "hashing", "graphs", "dsu", "sortings", "data structures" ]
72394a06a9d9dffb61c6c92c4bbd2f3a
The first line contains two space-separated integers n and m (1 ≤ n ≤ 5·105, 0 ≤ m ≤ 106) — the number of cities and the number of roads marked on the flatland map, correspondingly. Next m lines contain descriptions of the cities on the map. The i-th line contains two integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — the numbers of cities that are connected by the i-th road on the flatland map. It is guaranteed that each pair of cities occurs in the input no more than once.
2,100
On the first line print number k — the number of groups of cities in Flatland, such that in each group you can get from any city to any other one by flatland roads. At the same time, the cities from different groups should be unreachable by flatland roads. On each of the following k lines first print ti (1 ≤ ti ≤ n) — the number of vertexes in the i-th group. Then print space-separated numbers of cities in the i-th group. The order of printing groups and the order of printing numbers in the groups does not matter. The total sum ti for all k groups must equal n.
standard output
PASSED
c1da0687e699f7b87c344eea3ee73185
train_000.jsonl
1337182200
Berland has managed to repel the flatlanders' attack and is now starting the counter attack.Flatland has n cities, numbered from 1 to n, and some pairs of them are connected by bidirectional roads. The Flatlandian maps show roads between cities if and only if there is in fact no road between this pair of cities (we do not know whether is it a clever spy-proof strategy or just saving ink). In other words, if two cities are connected by a road on a flatland map, then there is in fact no road between them. The opposite situation is also true: if two cities are not connected by a road on a flatland map, then in fact, there is a road between them.The berlanders got hold of a flatland map. Now Vasya the Corporal is commissioned by General Touristov to find all such groups of flatland cities, that in each group of cities you can get from any city to any other one, moving along the actual roads. Also the cities from different groups are unreachable from each other, moving along the actual roads. Indeed, destroying such groups one by one is much easier than surrounding all Flatland at once!Help the corporal complete this task and finally become a sergeant! Don't forget that a flatland map shows a road between cities if and only if there is in fact no road between them.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.awt.geom.*; import static java.lang.Math.*; public class Solution implements Runnable { int g [][]; int deg []; int edges [][]; ArrayList<ArrayList<Integer>> answer = new ArrayList<ArrayList<Integer>>(); public void solve () throws Exception { int n = nextInt(); int m = nextInt(); g = new int [n][]; deg = new int [n]; edges = new int [m][2]; for (int i = 0; i < m; i++) { int v1 = nextInt() - 1; int v2 = nextInt() - 1; deg[v1]++; deg[v2]++; edges[i][0] = v1; edges[i][1] = v2; } for (int i = 0; i < n; i++) { g [i] = new int [deg[i]]; deg[i] = 0; } for (int i = 0; i < m; i++) { int v1 = edges[i][0]; int v2 = edges[i][1]; g[v1][deg[v1]++] = v2; g[v2][deg[v2]++] = v1; } HashSet<Integer> set = new HashSet<Integer>(); for (int i = 0; i < n; i++) { set.add(i); } LinkedList<Integer> q = new LinkedList<Integer>(); for (int i = 0; i < n; i++) { if (set.contains(i)) { q.add(i); ArrayList<Integer> list = new ArrayList<Integer>(); set.remove(i); while (!q.isEmpty()) { int v = q.pollFirst(); list.add(v + 1); HashSet<Integer> removeSet = new HashSet<Integer>(); for (int j = 0; j < g[v].length; j++) { int to = g[v][j]; if (set.contains(to)) { removeSet.add(to); set.remove(to); } } for (int to : set) { q.add(to); } if (set.size() > 0) { set.clear(); } for (int rmv : removeSet) { set.add(rmv); } } answer.add(list); } } out.println(answer.size()); for (int i = 0; i < answer.size(); i++) { ArrayList<Integer> list = answer.get(i); out.print(list.size()); for (int v : list) { out.print(" "+v); } out.println(); } } static final String fname = ""; static long stime = 0; BufferedReader in; PrintWriter out; StringTokenizer st; private String nextToken () throws Exception { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } private int nextInt () throws Exception { return Integer.parseInt(nextToken()); } private long nextLong () throws Exception { return Long.parseLong(nextToken()); } private double nextDouble () throws Exception { return Double.parseDouble(nextToken()); } @Override public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve (); } catch (Exception e) { throw new RuntimeException(e); } finally { out.close(); } } public static void main(String[] args) { new Thread(null, new Solution(), "", 1<<26).start(); } }
Java
["4 4\n1 2\n1 3\n4 2\n4 3", "3 1\n1 2"]
3 seconds
["2\n2 1 4 \n2 2 3", "1\n3 1 2 3"]
NoteIn the first sample there are roads only between pairs of cities 1-4 and 2-3.In the second sample there is no road between cities 1 and 2, but still you can get from one city to the other one through city number 3.
Java 8
standard input
[ "hashing", "graphs", "dsu", "sortings", "data structures" ]
72394a06a9d9dffb61c6c92c4bbd2f3a
The first line contains two space-separated integers n and m (1 ≤ n ≤ 5·105, 0 ≤ m ≤ 106) — the number of cities and the number of roads marked on the flatland map, correspondingly. Next m lines contain descriptions of the cities on the map. The i-th line contains two integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — the numbers of cities that are connected by the i-th road on the flatland map. It is guaranteed that each pair of cities occurs in the input no more than once.
2,100
On the first line print number k — the number of groups of cities in Flatland, such that in each group you can get from any city to any other one by flatland roads. At the same time, the cities from different groups should be unreachable by flatland roads. On each of the following k lines first print ti (1 ≤ ti ≤ n) — the number of vertexes in the i-th group. Then print space-separated numbers of cities in the i-th group. The order of printing groups and the order of printing numbers in the groups does not matter. The total sum ti for all k groups must equal n.
standard output
PASSED
cd3bb97d73f115845893f17ca3601e68
train_000.jsonl
1266580800
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23. Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.
64 megabytes
import java.util.ArrayList; import java.util.Scanner; public class cf1b { public static String xclToRow(String input){ String result; int j=0; ArrayList<Integer> letterValues = new ArrayList<>(); while(!Character.isDigit(input.charAt(j))){ letterValues.add(input.charAt(j) - 'A' + 1); j++; } int row=0; int counter=1; for(int i=letterValues.size()-1;i>=0;i--){ row+=letterValues.get(i)*counter; counter*=26; } int col=Integer.valueOf(input.substring(j)); result="R"+col+"C"+row; return result; } public static String rowToXcl(String input,int mid){ String result=""; int row=Integer.valueOf(input.substring(1,mid-1)); int col=Integer.valueOf(input.substring(mid)); ArrayList<Character> letterValues = new ArrayList<>(); while(col>0){ if(col%26!=0){ letterValues.add((char)('A' + (col % 26 - 1))); }else{ col--; letterValues.add((char)('A' + (col % 26))); } col/=26; } for(int i=letterValues.size()-1;i>=0;i--){ result+=letterValues.get(i); } result += row; return result; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int numTests = in.nextInt(); String testString; for(int i=0;i<numTests;i++){ testString=in.next(); if(testString.charAt(0)=='R' && Character.isDigit(testString.charAt(1))){ int j=1; while(j<testString.length() && testString.charAt(j)!='C'){ j++; } if(j!=testString.length()){ System.out.println(rowToXcl(testString,j+1)); }else{ System.out.println(xclToRow(testString)); } }else{ System.out.println(xclToRow(testString)); } } in.close(); } }
Java
["2\nR23C55\nBC23"]
10 seconds
["BC23\nR23C55"]
null
Java 8
standard input
[ "implementation", "math" ]
910c0e650d48af22fa51ab05e8123709
The first line of the input contains integer number n (1 ≤ n ≤ 105), the number of coordinates in the test. Then there follow n lines, each of them contains coordinates. All the coordinates are correct, there are no cells with the column and/or the row numbers larger than 106 .
1,600
Write n lines, each line should contain a cell coordinates in the other numeration system.
standard output
PASSED
2644a81d00bd1feb93d81b502063c2ea
train_000.jsonl
1266580800
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23. Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.
64 megabytes
// package CodeForces; import java.io.*; import java.util.*; public class Problem_1B { public static StringBuilder add(StringBuilder s) { if(s.toString().equals("Z")) return new StringBuilder("AA"); char c=s.charAt(s.length()-1); c++; // System.out.println(c); if(c>'Z') { return add(s.replace(s.length()-1, s.length(), "")).append("A"); } return s.replace(s.length()-1, s.length(), c+""); } public static void sol(StringBuilder s,int c) { if(c>100) return; // for(int i=(int)'A';i<=(int)'Z';i++) // { // System.out.println(s.toString()+(char)i+" "+c); // hm.put(s.toString()+(char)i, c); // hm2.put(c-1, s.toString()+(char)i); // c++; // } // sol(add(s),c); } static HashMap<String, String>hm; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(); PrintWriter pw = new PrintWriter(System.out); hm=new HashMap<>(3000000); // int[]cint=new int[1000001]; // String[]cstr=new String[1000001]; // ArrayList<String>cstr=new ArrayList<>(1000001); // cstr.add("Yahia"); // sol(new StringBuilder(),1); // StringBuilder sb= new StringBuilder("A"); // int c=1; //// System.out.println(add(new StringBuilder("ZZZ")).toString()); // while(c<=1000000) // { //// if(c<100) //// System.out.println(sb.toString()+" "+c); //// cstr.add(sb.toString()); // hm.put(sb.toString(),""+ c); // hm.put(""+c, sb.toString()); // sb=add(sb); // c++; // } // System.out.println(hm.size()); // displayMemory(); // System.out.println(conv(28)); int n=sc.nextInt(); while(n-->0) { StringBuilder s=new StringBuilder(sc.nextLine()); { int i=0,ii=0,C=0; boolean f=false,inv=false; for(;i<s.length();i++) { if(s.charAt(i)>='0' && s.charAt(i)<='9') { if(!f) ii=i; f=true; } else if(f) { inv=true; C=i; break; } } if(inv) { String row=s.substring(1,C); String column=s.substring(C+1); // pw.println(hm.get(column)+row); pw.println(conv(Integer.parseInt(column))+row); } else { String letters=s.substring(0,ii); // pw.println("R"+s.substring(ii)+"C"+hm.get(letters)); pw.println("R"+s.substring(ii)+"C"+conv(letters)); } } } pw.close(); } public static String conv(int x) { StringBuilder ans=new StringBuilder(""); // x--; // while(x>0) // { // int r=x%26; //// r--; // r+=65; // char c=(char)r; // x/=26; // ans.append(c+""); // } while(x>0) { int r=x%26; char c=(char)(r+64); boolean flag=false; if(r==0) { if(x==26) return "Z"+ans.reverse().toString(); else { c='Z'; flag=true; } } ans.append(c); x/=26; if(flag) x--; flag=false; } return ans.reverse().toString(); } public static int conv(String s) { int i=s.length()-1,j=0;int letter;int ans=0; while(i>=0) { letter=s.charAt(i)-'A'+1; ans+=Math.pow(26, j)*letter; j++; i--; } return ans; } public static void displayMemory() { Runtime r=Runtime.getRuntime(); r.gc(); r.gc(); // YES, you NEED 2! System.out.println("Memory Used="+(r.totalMemory()-r.freeMemory())); } static class Pair { int r,c; public Pair(int r,int c) { this.r=r;this.c=c; } } static class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException { return br.readLine(); } boolean hasnext() throws IOException { return br.ready(); } } }
Java
["2\nR23C55\nBC23"]
10 seconds
["BC23\nR23C55"]
null
Java 8
standard input
[ "implementation", "math" ]
910c0e650d48af22fa51ab05e8123709
The first line of the input contains integer number n (1 ≤ n ≤ 105), the number of coordinates in the test. Then there follow n lines, each of them contains coordinates. All the coordinates are correct, there are no cells with the column and/or the row numbers larger than 106 .
1,600
Write n lines, each line should contain a cell coordinates in the other numeration system.
standard output
PASSED
85aa0e881c333dcd410a2a2240d53a90
train_000.jsonl
1266580800
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23. Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.
64 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Z1B { static char[] digits = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); StringBuilder result = new StringBuilder(); String input; while (n-- > 0) { input = br.readLine(); if (input.charAt(0) == 'R' && input.indexOf('C') >= 0 && Character.isDigit(input.charAt(input.indexOf('C') - 1))) { int cIndex = input.indexOf('C'); int row = Integer.parseInt(input.substring(1, cIndex)); int col = Integer.parseInt(input.substring(cIndex + 1)); result.append(getRadix(col)).append(row); } else { int rowIndex = 0; while (!Character.isDigit(input.charAt(rowIndex))) { rowIndex++; } String colS = input.substring(0, rowIndex); int row = Integer.parseInt(input.substring(rowIndex)); int col = 0; while (colS.length() > 0) { col = col * 26; col = col + colS.charAt(0) - 'A' + 1; colS = colS.substring(1); } result.append("R").append(row).append("C").append(col); } result.append("\n"); } System.out.println(result.toString()); } private static String getRadix(int i) { StringBuilder sb = new StringBuilder(); while (i > 0) { sb.insert(0, digits[(i - 1) % 26]); i = (i - 1) / 26; } return sb.toString().toUpperCase(); } }
Java
["2\nR23C55\nBC23"]
10 seconds
["BC23\nR23C55"]
null
Java 8
standard input
[ "implementation", "math" ]
910c0e650d48af22fa51ab05e8123709
The first line of the input contains integer number n (1 ≤ n ≤ 105), the number of coordinates in the test. Then there follow n lines, each of them contains coordinates. All the coordinates are correct, there are no cells with the column and/or the row numbers larger than 106 .
1,600
Write n lines, each line should contain a cell coordinates in the other numeration system.
standard output
PASSED
e9d205ad35c6173dbc51b3bd28ee5586
train_000.jsonl
1266580800
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23. Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.
64 megabytes
import java.util.*; import java.io.*; public class spreadsheet { public static void main(String[] args) { @SuppressWarnings("resource") Scanner sc=new Scanner(System.in); PrintWriter out=new PrintWriter(System.out); int tc=sc.nextInt(); while(tc-->0) { String s=sc.next(); if(s.charAt(0)=='R'&&Character.isDigit(s.charAt(1))&&s.contains("C")) out.println(first(s)); else out.println(second(s)); } out.flush(); out.close(); } public static String first(String s) { String res=""; int index=0; for(int i=0;s.length()>i;i++) if(s.charAt(i)=='C') index=i; int row; row=Integer.parseInt(s.substring(1, index)); int col=Integer.parseInt(s.substring(index+1,s.length())); while(col>0) { int k=col%26; if(k==0) { col-=26; k=26; } char c=(char)('A'+k-1); col=col/26; res=c+res; } return res+row; } public static String second(String s) { String res=""; int index=0; for(int i=0;s.length()>i;i++) { if(Character.isDigit(s.charAt(i))) { index=i; break; } } int l=s.substring(0,index).length(); String s1=s.substring(0,index); int row=Integer.parseInt(s.substring(index,s.length())); int col=0; for(int i=0;s1.length()>i;i++) { int k=(int)(s1.charAt(i)-'A')+1; l--; col+=k*Math.pow(26,l ); } res+="R"+row+"C"+col; return res; } }
Java
["2\nR23C55\nBC23"]
10 seconds
["BC23\nR23C55"]
null
Java 8
standard input
[ "implementation", "math" ]
910c0e650d48af22fa51ab05e8123709
The first line of the input contains integer number n (1 ≤ n ≤ 105), the number of coordinates in the test. Then there follow n lines, each of them contains coordinates. All the coordinates are correct, there are no cells with the column and/or the row numbers larger than 106 .
1,600
Write n lines, each line should contain a cell coordinates in the other numeration system.
standard output
PASSED
183beead68a0b340f21f3558e9cd5f18
train_000.jsonl
1266580800
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23. Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.
64 megabytes
import java.util.Scanner; import java.util.StringTokenizer; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); while(n-- > 0) { String line = sc.next(); if(line.charAt(0) == 'R' && line.charAt(1) >= '0' && line.charAt(1) <= '9' && line.contains("C")) { StringTokenizer st = new StringTokenizer(line,"C"); int r = Integer.parseInt(st.nextToken().substring(1)); int c = Integer.parseInt(st.nextToken()); String cc = ""; while(c > 0) { int rem = c%26; if(rem==0) { c -= 26; rem = 26; } c /= 26; cc = (char)('A'+rem-1)+cc; } System.out.println(cc+r); } else { int i; for(i = 0; !(line.charAt(i) >= '0' && line.charAt(i) <= '9'); i++); String c = line.substring(0,i); int cc = 0; for(int j = 0; j < c.length(); j++) cc += (c.charAt(j) - 'A' + 1)* Math.pow(26, c.length() - j - 1); System.out.println("R"+line.substring(i)+"C"+cc); } } } }
Java
["2\nR23C55\nBC23"]
10 seconds
["BC23\nR23C55"]
null
Java 8
standard input
[ "implementation", "math" ]
910c0e650d48af22fa51ab05e8123709
The first line of the input contains integer number n (1 ≤ n ≤ 105), the number of coordinates in the test. Then there follow n lines, each of them contains coordinates. All the coordinates are correct, there are no cells with the column and/or the row numbers larger than 106 .
1,600
Write n lines, each line should contain a cell coordinates in the other numeration system.
standard output
PASSED
1a916f97f0d145677e2ee141b63af40d
train_000.jsonl
1266580800
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23. Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.
64 megabytes
import java.util.Scanner; import java.util.regex.Pattern; public class Puzzle1B { public static Pattern ROW_NUM_COL_NUM = Pattern.compile("R[0-9]+C[0-9]+"); public static Pattern COL_ROW = Pattern.compile("[A-Z]+[0-9]+"); public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int numInputs = scanner.nextInt(); for (int i = 0; i < numInputs; i++) { String input = scanner.next(); if (ROW_NUM_COL_NUM.matcher(input).matches()) { int row = Integer.parseInt(input.split("C")[0].substring(1)); int col = Integer.parseInt(input.split("C")[1]); String res = ""; while (col >= 26) { if (col % 26 != 0) { res = (char) (col % 26 + 64) + res; col /= 26; } else { res = "Z" + res; col /= 26; col--; } } if (col != 0) res = (char) (col % 26 + 64) + res; System.out.println(res + row); } else if (COL_ROW.matcher(input).matches()) { char[] chars = input.toCharArray(); int col = 0; int c = 0; for (; c < chars.length; c++) { if (Character.isDigit(chars[c])) break; col *= 26; col += chars[c] - 64; } System.out.println("R" + input.substring(c) + "C" + col); } else { System.out.println("ERROR: " + input); break; } } scanner.close(); } }
Java
["2\nR23C55\nBC23"]
10 seconds
["BC23\nR23C55"]
null
Java 8
standard input
[ "implementation", "math" ]
910c0e650d48af22fa51ab05e8123709
The first line of the input contains integer number n (1 ≤ n ≤ 105), the number of coordinates in the test. Then there follow n lines, each of them contains coordinates. All the coordinates are correct, there are no cells with the column and/or the row numbers larger than 106 .
1,600
Write n lines, each line should contain a cell coordinates in the other numeration system.
standard output
PASSED
f73a788a8f0ab4b437fd8f84a55a6a2c
train_000.jsonl
1266580800
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23. Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.
64 megabytes
import java.io.*; import java.util.Arrays; public class Codeforces { public static PrintWriter out; public static void main(String[] args) throws IOException{ Reader sc = new Reader(); out = new PrintWriter(new BufferedOutputStream(System.out)); int n = sc.nextInt(); for(int i=0; i<=n; i++){ String str = sc.readLine(); String regex = "[^A-Z0-9]+|(?<=[A-Z])(?=[0-9])|(?<=[0-9])(?=[A-Z])"; String[] atoms = str.split(regex); System.out.println(convert(atoms)); out.flush(); } out.close(); } public static String convert(String[] atoms){ StringBuffer sol = new StringBuffer(); if(atoms.length == 2){ sol.append("R"); sol.append(atoms[1]); sol.append("C"); long col = 0; for(int i=0; i<atoms[0].length(); i++){ if(i==0) col += (((int)atoms[0].charAt(atoms[0].length()-i-1))-64); else col += (((long)atoms[0].charAt(atoms[0].length()-i-1))-64) * Math.pow(26, i); } sol.append(col); }else if(atoms.length == 4){ long col = Long.parseLong(atoms[3]); while(col > 0) { char tmp = (char)(col%26+64); if(tmp == '@'){ tmp = 'Z'; sol.insert(0, tmp); col = col/26 - 1; }else{ sol.insert(0, tmp); col /= 26; } } sol.append(atoms[1]); } return sol.toString(); } 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 = 41; 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\nR23C55\nBC23"]
10 seconds
["BC23\nR23C55"]
null
Java 8
standard input
[ "implementation", "math" ]
910c0e650d48af22fa51ab05e8123709
The first line of the input contains integer number n (1 ≤ n ≤ 105), the number of coordinates in the test. Then there follow n lines, each of them contains coordinates. All the coordinates are correct, there are no cells with the column and/or the row numbers larger than 106 .
1,600
Write n lines, each line should contain a cell coordinates in the other numeration system.
standard output
PASSED
9efe9ca73f7f4b5b1ed20e3d218fc357
train_000.jsonl
1266580800
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23. Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.
64 megabytes
//package main; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class Test { public static int[] pows = new int[6]; public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); //BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("input"))); pows[0] = 1;pows[1] = 26; for(int i = 2; i < 6; i++) { pows[i] = (int)Math.pow(26, i) + pows[i-1]; } int n = Integer.parseInt(reader.readLine().trim()); List<String> data = new ArrayList<String>(); for(int i = 0; i < n; i++) { char[] line = reader.readLine().toCharArray(); data.clear(); String word = ""; char prev = line[0]; word += prev; for(int c = 1; c < line.length; c++) { char curr = line[c]; if( (Character.isDigit(prev) && Character.isLetter(curr)) || (Character.isDigit(curr) && Character.isLetter(prev)) ) { data.add(word); word = String.valueOf(curr); } else { word += curr; } prev = line[c]; } data.add(word); if(data.size() == 2) { char[] col = data.get(0).toCharArray(); int row = Integer.parseInt(data.get(1)); int cols = 0; for(int j = 0; j < col.length - 1; j++) { int p = (col.length - 1) - j; cols += Math.pow(26, p) + ((col[j] - 'A') * Math.pow(26, p)); } cols += (col[col.length - 1] - 'A') + 1; System.out.println("R" + row + "C" + cols); } else { int col = Integer.parseInt(data.get(3)); if(col < 27) { System.out.println((char)('A' + (col-1))+data.get(1)); continue; } int size = 1; int sump = 0; while(sump + Math.pow((double)26, (double)size) < col) { sump += Math.pow((double)26, (double)size); size++; } size--; String colS = ""; col -= pows[size]; while(size > 0) { int pv = (int)Math.pow(26, size); int ind = col / pv; if(col % pv == 0) { if(ind - 1 == 26 || ind == 0)colS += 'Z'; else colS += (char)((int)'A' + (ind - 1)); } else { if(ind == 26)colS += 'Z'; else colS += (char)((int)'A' + (ind)); } col -= (pv * ind); size--; } if(col == 0)colS += 'Z'; else colS += (char)((int)'A' + (col - 1)); System.out.println(colS+data.get(1)); } } reader.close(); } }
Java
["2\nR23C55\nBC23"]
10 seconds
["BC23\nR23C55"]
null
Java 8
standard input
[ "implementation", "math" ]
910c0e650d48af22fa51ab05e8123709
The first line of the input contains integer number n (1 ≤ n ≤ 105), the number of coordinates in the test. Then there follow n lines, each of them contains coordinates. All the coordinates are correct, there are no cells with the column and/or the row numbers larger than 106 .
1,600
Write n lines, each line should contain a cell coordinates in the other numeration system.
standard output
PASSED
14f53c15214eb0044e7f9d6df34ac7d9
train_000.jsonl
1266580800
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23. Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.
64 megabytes
import java.io.*; import java.util.StringTokenizer; public class Problem2 { public static void main(String[]args) throws IOException { Scanner reader = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int tests = reader.nextInt(); for(int test=0; test<tests; test++){ String input = reader.next(); try{out.println(second(input));} catch(Exception e){out.println(first(input));} } out.flush(); out.close(); reader.br.close(); } public static String first(String input){ String col = ""; int row = 0; for(int i=0; i<input.length(); i++){ char temp = input.charAt(i); if(temp < 'A' || temp > 'Z'){ col = input.substring(0,i); row = Integer.parseInt(input.substring(i)); break; } } int column = 0; int length = col.length(); for(int i=0; i<col.length(); i++){ int temp = col.charAt(i)-64; column += temp*Math.pow(26, length-(i+1)); } return ("R"+row+"C"+column); } public static String second(String input){ StringTokenizer st = new StringTokenizer(input, "RC"); int r = Integer.parseInt(st.nextToken()); int c = Integer.parseInt(st.nextToken()); String col = ""; boolean carry = false; while(c != 0){ char temp = (char) (c%26); if(temp == 0) { col = 'Z' + col; carry = true; c -= 1; } else col = (char)(64+temp)+col; c /= 26; } return(col+r); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if(x.charAt(0) == '-') { neg = true; start++; } for(int i = start; i < x.length(); i++) if(x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if(dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg?-1:1); } public boolean ready() throws IOException {return br.ready();} } }
Java
["2\nR23C55\nBC23"]
10 seconds
["BC23\nR23C55"]
null
Java 8
standard input
[ "implementation", "math" ]
910c0e650d48af22fa51ab05e8123709
The first line of the input contains integer number n (1 ≤ n ≤ 105), the number of coordinates in the test. Then there follow n lines, each of them contains coordinates. All the coordinates are correct, there are no cells with the column and/or the row numbers larger than 106 .
1,600
Write n lines, each line should contain a cell coordinates in the other numeration system.
standard output
PASSED
5d95b4bef2fd4d7394bab22f795daebf
train_000.jsonl
1401895800
Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother. As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the maximum value of his brother's array b. Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.
256 megabytes
import javafx.util.*; import java.util.*; import java.io.*; public class JavaApplication1 { static long x, y, z; static ArrayList<Integer>arr1 = new ArrayList<Integer>(); static ArrayList<Integer>arr2 = new ArrayList<Integer>(); public static void main(String[] args) throws IOException { Scanner scan = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); x = scan.nextLong(); y = scan.nextLong(); for(int i = 0; i < x; i++){ z = scan.nextLong(); arr1.add((int)z); } for(int i = 0; i < y; i++){ z = scan.nextLong(); arr2.add((int)z); } arr1.sort((x, y) -> (y - x)); arr2.sort((x, y) -> (y - x)); long ans = rec(arr1.get(0)); int s = 1, ss = 1000000000, mid1, mid2; for(int i = 0; i < 300; i++){ mid1 = s + (ss - s) / 3; mid2 = s + 2 * (ss - s) / 3; long r1 = rec(mid1), r2 = rec(mid2); ans = Math.min(ans, Math.min(r1, r2)); if (r1 < r2){ ss = mid2; } else{ s = mid1; } } if(ss < s){ out.println(0); } else{ out.printf("%d\n", ans); } out.close(); } public static long rec(long val){ long sum = 0; for (int i = 0; i < x; i++){ sum += Math.max(0, val - arr1.get(i)); } for (int i = 0; i < y; i++){ sum += Math.max(arr2.get(i) - val, 0); } return sum; } //public static int GCD(int a, int b) { return b == 0 ? a : GCD(b, a % b); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if(x.charAt(0) == '-') { neg = true; start++; } for(int i = start; i < x.length(); i++) if(x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if(dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg?-1:1); } public boolean ready() throws IOException {return br.ready();} } }
Java
["2 2\n2 3\n3 5", "3 2\n1 2 3\n3 4", "3 2\n4 5 6\n1 2"]
1 second
["3", "4", "0"]
NoteIn example 1, you can increase a1 by 1 and decrease b2 by 1 and then again decrease b2 by 1. Now array a will be [3; 3] and array b will also be [3; 3]. Here minimum element of a is at least as large as maximum element of b. So minimum number of operations needed to satisfy Devu's condition are 3.In example 3, you don't need to do any operation, Devu's condition is already satisfied.
Java 8
standard input
[ "two pointers", "binary search", "sortings", "ternary search" ]
e0b5169945909cd2809482b7fd7178c2
The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105). The second line will contain n space-separated integers representing content of the array a (1 ≤ ai ≤ 109). The third line will contain m space-separated integers representing content of the array b (1 ≤ bi ≤ 109).
1,700
You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.
standard output
PASSED
d643c3108e935c581e93bdfa4a9f81eb
train_000.jsonl
1401895800
Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother. As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the maximum value of his brother's array b. Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.
256 megabytes
import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; /** * Created by vikas.k on 26/12/16. */ public class CF251D { public static void main(String[] args){ CF251D gv = new CF251D(); gv.solve(); } private int n,m; private List<Long> lst1,lst2; private void solve(){ MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); n = sc.nextInt(); m = sc.nextInt(); lst1 = new ArrayList<>(); lst2 = new ArrayList<>(); for(int i=0;i<n;i++){ lst1.add(sc.nextLong()); } for(int i=0;i<m;i++){ lst2.add(sc.nextLong()); } out.println(doTernary(0,1000000001)); out.close(); } private long doTernary(long lo,long hi){ while(hi-lo > 2){ long lt = lo + (hi-lo)/3; long rt = lo + 2*((hi-lo)/3); if(doCheck(lt) < doCheck(rt)) hi = rt; else lo = lt; } long vl = doCheck(lo); for(long i = lo+1;i<=hi;i++){ long tmp = doCheck(i); if(vl > tmp){ vl = tmp; } } return vl; } private long doCheck(long x){ long cnt = 0; for(long i: lst1){ if(i<x) cnt+= Math.abs(x-i); } for(long i: lst2){ if(i>x) cnt+= Math.abs(x-i); } return cnt; } public static PrintWriter out; private static class MyScanner{ BufferedReader bufferedReader; StringTokenizer stringTokenizer; private MyScanner(){ bufferedReader = new BufferedReader(new InputStreamReader(System.in)); } private String next(){ if(stringTokenizer == null || !stringTokenizer.hasMoreElements()){ try { stringTokenizer = new StringTokenizer(bufferedReader.readLine()); } catch (IOException e) { e.printStackTrace(); } } return stringTokenizer.nextToken(); } private int nextInt(){ return Integer.parseInt(next()); } private long nextLong(){ return Long.parseLong(next()); } private String nextLine(){ String ret= ""; try { ret= bufferedReader.readLine(); } catch (IOException e) { e.printStackTrace(); } return ret; } } }
Java
["2 2\n2 3\n3 5", "3 2\n1 2 3\n3 4", "3 2\n4 5 6\n1 2"]
1 second
["3", "4", "0"]
NoteIn example 1, you can increase a1 by 1 and decrease b2 by 1 and then again decrease b2 by 1. Now array a will be [3; 3] and array b will also be [3; 3]. Here minimum element of a is at least as large as maximum element of b. So minimum number of operations needed to satisfy Devu's condition are 3.In example 3, you don't need to do any operation, Devu's condition is already satisfied.
Java 8
standard input
[ "two pointers", "binary search", "sortings", "ternary search" ]
e0b5169945909cd2809482b7fd7178c2
The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105). The second line will contain n space-separated integers representing content of the array a (1 ≤ ai ≤ 109). The third line will contain m space-separated integers representing content of the array b (1 ≤ bi ≤ 109).
1,700
You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.
standard output
PASSED
e7e99c14a63a7cba604961c4856f3c7e
train_000.jsonl
1401895800
Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother. As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the maximum value of his brother's array b. Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.Random; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { int[] a; int[] b; long[] bita; long[] bitb; public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); a = in.readIntArray(n); b = in.readIntArray(m); ArrayUtils.shuffle(a); Arrays.sort(a); ArrayUtils.shuffle(b); Arrays.sort(b); if (a[0] >= b[b.length - 1]) { out.println(0); return; } bita = new long[a.length]; bita[0] = a[0]; for (int i = 1; i < a.length; i++) { bita[i] = a[i] + bita[i - 1]; } bitb = new long[b.length]; bitb[b.length - 1] = b[b.length - 1]; for (int i = b.length - 2; i >= 0; i--) { bitb[i] = b[i] + bitb[i + 1]; } int l = 0; int r = 1000000001; for (int i = 0; i < 100; i++) { int m1 = l + (r - l) / 3; int m2 = r - (r - l) / 3; if (f(m1) > f(m2)) l = m1; else r = m2; } long minVal = Long.MAX_VALUE; for (int i = l; i <= r; i++) { minVal = Math.min(minVal, f(i)); } out.println(minVal); } long f(int v) { long p1 = ArrayUtils.firstGreatThan(a, v); long s1; if (p1 == 0) { s1 = 0; } else { s1 = bita[(int) p1 - 1]; s1 = (long) v * p1 - s1; } long p2 = ArrayUtils.firstGreatThan(b, v); long s2; if (p2 == b.length) { s2 = 0; } else { s2 = bitb[(int) p2]; s2 = s2 - (long) v * (b.length - p2); } return s1 + s2; } } static class InputReader { StringTokenizer st; BufferedReader br; public InputReader(InputStream is) { BufferedReader br = new BufferedReader(new InputStreamReader(is)); this.br = br; } public String next() { if (st == null || !st.hasMoreTokens()) { String nextLine = null; try { nextLine = br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } if (nextLine == null) return null; st = new StringTokenizer(nextLine); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public int[] readIntArray(int n) { int[] ar = new int[n]; for (int i = 0; i < n; i++) { ar[i] = nextInt(); } return ar; } } static final class ArrayUtils { static Random rnd = new Random(); public static void shuffle(int[] ar) { for (int i = ar.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); int a = ar[index]; ar[index] = ar[i]; ar[i] = a; } } public static int firstGreatThan(int[] ar, int v) { int l = -1; int r = ar.length; while (r - l > 1) { int m = (l + r) / 2; if (ar[m] <= v) l = m; else r = m; } return r; } } }
Java
["2 2\n2 3\n3 5", "3 2\n1 2 3\n3 4", "3 2\n4 5 6\n1 2"]
1 second
["3", "4", "0"]
NoteIn example 1, you can increase a1 by 1 and decrease b2 by 1 and then again decrease b2 by 1. Now array a will be [3; 3] and array b will also be [3; 3]. Here minimum element of a is at least as large as maximum element of b. So minimum number of operations needed to satisfy Devu's condition are 3.In example 3, you don't need to do any operation, Devu's condition is already satisfied.
Java 8
standard input
[ "two pointers", "binary search", "sortings", "ternary search" ]
e0b5169945909cd2809482b7fd7178c2
The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105). The second line will contain n space-separated integers representing content of the array a (1 ≤ ai ≤ 109). The third line will contain m space-separated integers representing content of the array b (1 ≤ bi ≤ 109).
1,700
You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.
standard output
PASSED
af87de09c78e1066e068d5e17aa91e19
train_000.jsonl
1401895800
Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother. As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the maximum value of his brother's array b. Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.Random; import java.io.IOException; import java.io.InputStreamReader; import java.util.function.Function; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { int[] a; int[] b; FenwickTree bita; FenwickTree bitb; public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); a = in.readIntArray(n); b = in.readIntArray(m); ArrayUtils.shuffle(a); Arrays.sort(a); ArrayUtils.shuffle(b); Arrays.sort(b); if (a[0] >= b[b.length - 1]) { out.println(0); return; } bita = new FenwickTree(a.length + 1); for (int i = 0; i < a.length; i++) bita.inc(i, a[i]); bitb = new FenwickTree(b.length + 1); for (int i = 0; i < b.length; i++) bitb.inc(i, b[i]); int ans = Algorithms.ternarySearchMin(0, 1000000001, 1000, this::f); out.println(f(ans)); } long f(int v) { long p1 = ArrayUtils.firstGreatThan(a, v); long s1; if (p1 == 0) { s1 = 0; } else { s1 = bita.sum(0, (int) (p1 - 1)); s1 = (long) v * p1 - s1; } long p2 = ArrayUtils.firstGreatThan(b, v); long s2; if (p2 == b.length) { s2 = 0; } else { s2 = bitb.sum((int) p2, b.length - 1); s2 = s2 - (long) v * (b.length - p2); } return s1 + s2; } } static class Algorithms { public static int ternarySearchMin(int l, int r, int iter, Function<Integer, Long> f) { for (int i = 0; i < iter; i++) { int m1 = l + (r - l) / 3; int m2 = r - (r - l) / 3; if (f.apply(m1) > f.apply(m2)) l = m1; else r = m2; } long minVal = Long.MAX_VALUE; int ans = -1; for (int i = l; i <= r; i++) { long t = f.apply(i); if (minVal > t) { minVal = t; ans = i; } } return ans; } } static final class ArrayUtils { static Random rnd = new Random(); public static void shuffle(int[] ar) { for (int i = ar.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); int a = ar[index]; ar[index] = ar[i]; ar[i] = a; } } public static int firstGreatThan(int[] ar, int v) { int l = -1; int r = ar.length; while (r - l > 1) { int m = (l + r) / 2; if (ar[m] <= v) l = m; else r = m; } return r; } } static class FenwickTree { long[] t; int n; public FenwickTree(int n) { this.n = n; t = new long[n]; } private long sum(int r) { long result = 0; for (; r >= 0; r = (r & (r + 1)) - 1) result += t[r]; return result; } public void inc(int i, long delta) { for (; i < n; i = (i | (i + 1))) t[i] += delta; } public long sum(int l, int r) { return sum(r) - sum(l - 1); } } static class InputReader { StringTokenizer st; BufferedReader br; public InputReader(InputStream is) { BufferedReader br = new BufferedReader(new InputStreamReader(is)); this.br = br; } public String next() { if (st == null || !st.hasMoreTokens()) { String nextLine = null; try { nextLine = br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } if (nextLine == null) return null; st = new StringTokenizer(nextLine); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public int[] readIntArray(int n) { int[] ar = new int[n]; for (int i = 0; i < n; i++) { ar[i] = nextInt(); } return ar; } } }
Java
["2 2\n2 3\n3 5", "3 2\n1 2 3\n3 4", "3 2\n4 5 6\n1 2"]
1 second
["3", "4", "0"]
NoteIn example 1, you can increase a1 by 1 and decrease b2 by 1 and then again decrease b2 by 1. Now array a will be [3; 3] and array b will also be [3; 3]. Here minimum element of a is at least as large as maximum element of b. So minimum number of operations needed to satisfy Devu's condition are 3.In example 3, you don't need to do any operation, Devu's condition is already satisfied.
Java 8
standard input
[ "two pointers", "binary search", "sortings", "ternary search" ]
e0b5169945909cd2809482b7fd7178c2
The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105). The second line will contain n space-separated integers representing content of the array a (1 ≤ ai ≤ 109). The third line will contain m space-separated integers representing content of the array b (1 ≤ bi ≤ 109).
1,700
You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.
standard output
PASSED
6d12a28fbcf8dda07236e05ee3b33dbe
train_000.jsonl
1401895800
Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother. As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the maximum value of his brother's array b. Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.Random; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { int[] a; int[] b; FenwickTree bita; FenwickTree bitb; public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); a = in.readIntArray(n); b = in.readIntArray(m); ArrayUtils.shuffle(a); Arrays.sort(a); ArrayUtils.shuffle(b); Arrays.sort(b); if (a[0] >= b[b.length - 1]) { out.println(0); return; } bita = new FenwickTree(a.length + 1); for (int i = 0; i < a.length; i++) bita.inc(i, a[i]); bitb = new FenwickTree(b.length + 1); for (int i = 0; i < b.length; i++) bitb.inc(i, b[i]); int l = 0; int r = 1000000001; for (int i = 0; i < 1000; i++) { int m1 = l + (r - l) / 3; int m2 = r - (r - l) / 3; if (f(m1) > f(m2)) l = m1; else r = m2; } long minVal = Long.MAX_VALUE; for (int i = l; i <= r; i++) { minVal = Math.min(minVal, f(i)); } out.println(minVal); } long f(int v) { long p1 = ArrayUtils.firstGreatThan(a, v); long s1; if (p1 == 0) { s1 = 0; } else { s1 = bita.sum(0, (int) (p1 - 1)); s1 = (long) v * p1 - s1; } long p2 = ArrayUtils.firstGreatThan(b, v); long s2; if (p2 == b.length) { s2 = 0; } else { s2 = bitb.sum((int) p2, b.length - 1); s2 = s2 - (long) v * (b.length - p2); } return s1 + s2; } } static final class ArrayUtils { static Random rnd = new Random(); public static void shuffle(int[] ar) { for (int i = ar.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); int a = ar[index]; ar[index] = ar[i]; ar[i] = a; } } public static int firstGreatThan(int[] ar, int v) { int l = -1; int r = ar.length; while (r - l > 1) { int m = (l + r) / 2; if (ar[m] <= v) l = m; else r = m; } return r; } } static class FenwickTree { long[] t; int n; public FenwickTree(int n) { this.n = n; t = new long[n]; } private long sum(int r) { long result = 0; for (; r >= 0; r = (r & (r + 1)) - 1) result += t[r]; return result; } public void inc(int i, long delta) { for (; i < n; i = (i | (i + 1))) t[i] += delta; } public long sum(int l, int r) { return sum(r) - sum(l - 1); } } static class InputReader { StringTokenizer st; BufferedReader br; public InputReader(InputStream is) { BufferedReader br = new BufferedReader(new InputStreamReader(is)); this.br = br; } public String next() { if (st == null || !st.hasMoreTokens()) { String nextLine = null; try { nextLine = br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } if (nextLine == null) return null; st = new StringTokenizer(nextLine); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public int[] readIntArray(int n) { int[] ar = new int[n]; for (int i = 0; i < n; i++) { ar[i] = nextInt(); } return ar; } } }
Java
["2 2\n2 3\n3 5", "3 2\n1 2 3\n3 4", "3 2\n4 5 6\n1 2"]
1 second
["3", "4", "0"]
NoteIn example 1, you can increase a1 by 1 and decrease b2 by 1 and then again decrease b2 by 1. Now array a will be [3; 3] and array b will also be [3; 3]. Here minimum element of a is at least as large as maximum element of b. So minimum number of operations needed to satisfy Devu's condition are 3.In example 3, you don't need to do any operation, Devu's condition is already satisfied.
Java 8
standard input
[ "two pointers", "binary search", "sortings", "ternary search" ]
e0b5169945909cd2809482b7fd7178c2
The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105). The second line will contain n space-separated integers representing content of the array a (1 ≤ ai ≤ 109). The third line will contain m space-separated integers representing content of the array b (1 ≤ bi ≤ 109).
1,700
You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.
standard output
PASSED
6a848dce605ce0a432520055e8405b2d
train_000.jsonl
1401895800
Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother. As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the maximum value of his brother's array b. Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.StringTokenizer; public class Task2 { static ArrayList<Long> arr1 , arr2; static int n , m; public static long f(long num) { long ans = 0; for(int i =0 ; i < n ; ++i) { if(arr1.get(i) >=num) continue; else ans += Math.abs(num - arr1.get(i)); } for(int i =0 ; i < m ; ++i) { if(arr2.get(i) <=num) continue; else ans += Math.abs(num - arr2.get(i)); } return ans; } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); n = sc.nextInt(); m = sc.nextInt(); arr1 = new ArrayList<Long>();arr2 = new ArrayList<Long>(); for(int i = 0 ; i < n ; ++i) arr1.add(sc.nextLong()); for(int i = 0 ; i < m ; ++i) arr2.add(sc.nextLong()); Collections.sort(arr1);Collections.sort(arr2); long left = arr1.get(0) , right = arr2.get(m-1); while(right - left > 3) { long g = left + (right-left)/3 , h = left + 2*(right - left) /3; if(f(g)<f(h)) right = h; else left = g; } long ans = f(left); for(long i = left +1 ; i <= right ; ++i) if(f(i)<ans) ans = f(i); System.out.println(ans); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public Scanner(FileReader r){ br = new BufferedReader(r);} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if(x.charAt(0) == '-') { neg = true; start++; } for(int i = start; i < x.length(); i++) if(x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if(dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg?-1:1); } public boolean ready() throws IOException {return br.ready();} } }
Java
["2 2\n2 3\n3 5", "3 2\n1 2 3\n3 4", "3 2\n4 5 6\n1 2"]
1 second
["3", "4", "0"]
NoteIn example 1, you can increase a1 by 1 and decrease b2 by 1 and then again decrease b2 by 1. Now array a will be [3; 3] and array b will also be [3; 3]. Here minimum element of a is at least as large as maximum element of b. So minimum number of operations needed to satisfy Devu's condition are 3.In example 3, you don't need to do any operation, Devu's condition is already satisfied.
Java 8
standard input
[ "two pointers", "binary search", "sortings", "ternary search" ]
e0b5169945909cd2809482b7fd7178c2
The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105). The second line will contain n space-separated integers representing content of the array a (1 ≤ ai ≤ 109). The third line will contain m space-separated integers representing content of the array b (1 ≤ bi ≤ 109).
1,700
You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.
standard output
PASSED
ac04c065d8363ad062cfaf124d37fc17
train_000.jsonl
1401895800
Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother. As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the maximum value of his brother's array b. Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class Task2 { static long []arr1 , arr2; static int n , m; public static long f(long num) { long ans = 0; for(int i =0 ; i < n ; ++i) { if(arr1[i] >=num) continue; else ans += Math.abs(num - arr1[i]); } for(int i =0 ; i < m ; ++i) { if(arr2[i] <=num) continue; else ans += Math.abs(num - arr2[i]); } return ans; } static void shuffle(long[] a) { int n = a.length; for(int i = 0; i < n; i++) { int r = i + (int)(Math.random() * (n - i)); long tmp = a[i]; a[i] = a[r]; a[r] = tmp; } } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); n = sc.nextInt(); m = sc.nextInt(); arr1 = new long[n]; arr2 = new long[m]; for(int i = 0 ; i < n ; ++i) arr1[i] =sc.nextLong(); for(int i = 0 ; i < m ; ++i) arr2[i] =sc.nextLong(); shuffle(arr1);shuffle(arr2); Arrays.sort(arr1);Arrays.sort(arr2); long left = arr1[0] , right = arr2[m-1]; while(right - left > 3) { long g = left + (right-left)/3 , h = left + 2*(right - left) /3; if(f(g)<f(h)) right = h; else left = g; } long ans = f(left); for(long i = left +1 ; i <= right ; ++i) if(f(i)<ans) ans = f(i); System.out.println(ans); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public Scanner(FileReader r){ br = new BufferedReader(r);} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if(x.charAt(0) == '-') { neg = true; start++; } for(int i = start; i < x.length(); i++) if(x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if(dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg?-1:1); } public boolean ready() throws IOException {return br.ready();} } }
Java
["2 2\n2 3\n3 5", "3 2\n1 2 3\n3 4", "3 2\n4 5 6\n1 2"]
1 second
["3", "4", "0"]
NoteIn example 1, you can increase a1 by 1 and decrease b2 by 1 and then again decrease b2 by 1. Now array a will be [3; 3] and array b will also be [3; 3]. Here minimum element of a is at least as large as maximum element of b. So minimum number of operations needed to satisfy Devu's condition are 3.In example 3, you don't need to do any operation, Devu's condition is already satisfied.
Java 8
standard input
[ "two pointers", "binary search", "sortings", "ternary search" ]
e0b5169945909cd2809482b7fd7178c2
The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105). The second line will contain n space-separated integers representing content of the array a (1 ≤ ai ≤ 109). The third line will contain m space-separated integers representing content of the array b (1 ≤ bi ≤ 109).
1,700
You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.
standard output
PASSED
3cf56a2ce06178b50466d88d76a416f0
train_000.jsonl
1401895800
Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother. As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the maximum value of his brother's array b. Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.
256 megabytes
import java.io.*; import java.util.*; import java.util.Random; import java.util.StringTokenizer; public class Main { long b = 31; String fileName = ""; ////////////////////// SOLUTION SOLUTION SOLUTION ////////////////////////////// long INF = Long.MAX_VALUE / 10000; int MODULO = 1000*1000*1000+7; ArrayList<Edge>[] graph; class Edge{ int to, dist; Edge(int to, int dist){ this.dist = dist; this.to = to; } } void solve() throws IOException { int n = readInt(); int m = readInt(); Long[] a = new Long[n]; Long[] b = new Long[m]; for (int i=0; i<n; ++i) a[i] = readLong(); for (int i=0; i<m; ++i) b[i] = readLong(); Arrays.sort(a); Arrays.sort(b); long[] prefA = new long[n+1]; long[] prefB = new long[m+1]; for (int i=1; i<=n; ++i) prefA[i] = prefA[i-1] + a[i-1]; for (int i=1; i<=m; ++i) prefB[i] = prefB[i-1] + b[i-1]; int p1 = 1; int p2 = 1; long ans = Long.MAX_VALUE; while(p1<=n && p2<=m){ if (b[p2-1]<=a[p1-1]) p2++; else{ ans = Math.min(ans, (a[p1-1]*p1)-prefA[p1] + (prefB[m] - prefB[p2-1]) - a[p1-1]*(m - p2 + 1)); p1++; } } p1 = n; p2 = m; while(p1>=1 && p2>=1){ if (b[p2-1]<=a[p1-1]) p1--; else{ ans = Math.min(ans, (b[p2-1]*p1)-prefA[p1] + (prefB[m] - prefB[p2-1]) - b[p2-1]*(m - p2 + 1)); p2--; } } out.println(ans!=Long.MAX_VALUE?ans:0); } class Vertex implements Comparable<Vertex>{ int dist, from; Vertex(int b, int c){ this.dist = c; this.from = b; } @Override public int compareTo(Vertex o) { return this.dist-o.dist; } } /////////////////////////////////////////////////////////////////////////////////////////// class SparseTable{ int[][] rmq; int[] logTable; int n; SparseTable(int[] a){ n = a.length; logTable = new int[n+1]; for(int i = 2; i <= n; ++i){ logTable[i] = logTable[i >> 1] + 1; } rmq = new int[logTable[n] + 1][n]; for(int i=0; i<n; ++i){ rmq[0][i] = a[i]; } for(int k=1; (1 << k) < n; ++k){ for(int i=0; i + (1 << k) <= n; ++i){ int max1 = rmq[k - 1][i]; int max2 = rmq[k-1][i + (1 << (k-1))]; rmq[k][i] = Math.max(max1, max2); } } } int max(int l, int r){ int k = logTable[r - l]; int max1 = rmq[k][l]; int max2 = rmq[k][r - (1 << k) + 1]; return Math.max(max1, max2); } } long checkBit(long mask, int bit){ return (mask >> bit) & 1; } class Dsu{ int[] parent; int countSets; Dsu(int n){ countSets = n; parent = new int[n]; for(int i=0; i<n; ++i){ parent[i] = i; } } int findSet(int a){ if(parent[a] == a) return a; parent[a] = findSet(parent[a]); return parent[a]; } void unionSets(int a, int b){ a = findSet(a); b = findSet(b); if(a!=b){ countSets--; parent[a] = b; } } } static int checkBit(int mask, int bit) { return (mask >> bit) & 1; } boolean isLower(char c){ return c >= 'a' && c <= 'z'; } //////////////////////////////////////////////////////////// class SegmentTree{ int[] t; int n; SegmentTree(int n){ t = new int[4*n]; build(new int[n+1], 1, 1, n); } void build (int a[], int v, int tl, int tr) { if (tl == tr) t[v] = a[tl]; else { int tm = (tl + tr) / 2; build (a, v*2, tl, tm); build (a, v*2+1, tm+1, tr); } } void update (int v, int tl, int tr, int l, int r, int add) { if (l > r) return; if (l == tl && tr == r) t[v] += add; else { int tm = (tl + tr) / 2; update (v*2, tl, tm, l, Math.min(r,tm), add); update (v*2+1, tm+1, tr, Math.max(l,tm+1), r, add); } } int get (int v, int tl, int tr, int pos) { if (tl == tr) return t[v]; int tm = (tl + tr) / 2; if (pos <= tm) return t[v] + get (v*2, tl, tm, pos); else return t[v] + get (v*2+1, tm+1, tr, pos); } } class Fenwik { long[] t; int length; Fenwik(int[] a) { length = a.length + 100; t = new long[length]; for (int i = 0; i < a.length; ++i) { inc(i, a[i]); } } void inc(int ind, int delta) { for (; ind < length; ind = ind | (ind + 1)) { t[ind] += delta; } } long getSum(int r) { long sum = 0; for (; r >= 0; r = (r & (r + 1)) - 1) { sum += t[r]; } return sum; } } int gcd(int a, int b){ return b == 0 ? a : gcd(b, a%b); } long gcd(long a, long b){ return b == 0 ? a : gcd(b, a%b); } long binPow(long a, long b, long m) { if (b == 0) { return 1; } if (b % 2 == 1) { return ((a % m) * (binPow(a, b - 1, m) % m)) % m; } else { long c = binPow(a, b / 2, m); return (c * c) % m; } } int minInt(int... values) { int min = Integer.MAX_VALUE; for (int value : values) min = Math.min(min, value); return min; } int maxInt(int... values) { int max = Integer.MIN_VALUE; for (int value : values) max = Math.max(max, value); return max; } public static void main(String[] args) throws NumberFormatException, IOException { // TODO Auto-generated method stub new Main().run(); } void run() throws NumberFormatException, IOException { solve(); out.close(); }; BufferedReader in; PrintWriter out; StringTokenizer tok; String delim = " "; Random rnd = new Random(); Main() throws FileNotFoundException { try { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } catch (Exception e) { if (fileName.isEmpty()) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader(fileName + ".in")); out = new PrintWriter(fileName + ".out"); } } tok = new StringTokenizer(""); } String readLine() throws IOException { return in.readLine(); } String readString() throws IOException { while (!tok.hasMoreTokens()) { String nextLine = readLine(); if (null == nextLine) { return null; } tok = new StringTokenizer(nextLine); } return tok.nextToken(); } int readInt() throws NumberFormatException, IOException { return Integer.parseInt(readString()); } byte readByte() throws NumberFormatException, IOException { return Byte.parseByte(readString()); } int[] readIntArray (int n) throws NumberFormatException, IOException { int[] a = new int[n]; for(int i=0; i<n; ++i){ a[i] = readInt(); } return a; } Integer[] readIntegerArray (int n) throws NumberFormatException, IOException { Integer[] a = new Integer[n]; for(int i=0; i<n; ++i){ a[i] = readInt(); } return a; } long readLong() throws NumberFormatException, IOException { return Long.parseLong(readString()); } double readDouble() throws NumberFormatException, IOException { return Double.parseDouble(readString()); } }
Java
["2 2\n2 3\n3 5", "3 2\n1 2 3\n3 4", "3 2\n4 5 6\n1 2"]
1 second
["3", "4", "0"]
NoteIn example 1, you can increase a1 by 1 and decrease b2 by 1 and then again decrease b2 by 1. Now array a will be [3; 3] and array b will also be [3; 3]. Here minimum element of a is at least as large as maximum element of b. So minimum number of operations needed to satisfy Devu's condition are 3.In example 3, you don't need to do any operation, Devu's condition is already satisfied.
Java 8
standard input
[ "two pointers", "binary search", "sortings", "ternary search" ]
e0b5169945909cd2809482b7fd7178c2
The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105). The second line will contain n space-separated integers representing content of the array a (1 ≤ ai ≤ 109). The third line will contain m space-separated integers representing content of the array b (1 ≤ bi ≤ 109).
1,700
You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.
standard output
PASSED
6d632358882030a490ef46b3716edd06
train_000.jsonl
1401895800
Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother. As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the maximum value of his brother's array b. Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } Integer[] b = new Integer[m]; for (int i = 0; i < m; i++) { b[i] = in.nextInt(); } Arrays.sort(a); Arrays.sort(b, (Integer f, Integer s) -> s - f); long ans = 0; int end = Math.min(n, m); for (int i = 0; i < end; i++) { if (a[i] >= b[i]) { break; } ans += b[i]; ans -= a[i]; } out.println(ans); } } static class InputReader { private BufferedReader reader; private StringTokenizer stt; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { return null; } } public String next() { while (stt == null || !stt.hasMoreTokens()) { stt = new StringTokenizer(nextLine()); } return stt.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["2 2\n2 3\n3 5", "3 2\n1 2 3\n3 4", "3 2\n4 5 6\n1 2"]
1 second
["3", "4", "0"]
NoteIn example 1, you can increase a1 by 1 and decrease b2 by 1 and then again decrease b2 by 1. Now array a will be [3; 3] and array b will also be [3; 3]. Here minimum element of a is at least as large as maximum element of b. So minimum number of operations needed to satisfy Devu's condition are 3.In example 3, you don't need to do any operation, Devu's condition is already satisfied.
Java 8
standard input
[ "two pointers", "binary search", "sortings", "ternary search" ]
e0b5169945909cd2809482b7fd7178c2
The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105). The second line will contain n space-separated integers representing content of the array a (1 ≤ ai ≤ 109). The third line will contain m space-separated integers representing content of the array b (1 ≤ bi ≤ 109).
1,700
You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.
standard output
PASSED
8a241e311e00abcd11aa372d8ce23c3c
train_000.jsonl
1401895800
Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother. As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the maximum value of his brother's array b. Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.
256 megabytes
import java.util.*; import java.io.*; public class Main { static int a[]; static int b[]; static long find(long mid){ long temp = 0; for(int i = 0;i < a.length;i++){ if(mid >= a[i]) temp += mid - a[i]; } for(int i = 0;i < b.length;i++){ if(mid < b[i]) temp += b[i] - mid; } return temp; } public static void main(String [] args)throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); a = new int[n]; b = new int[m]; 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()); long low = 0; long high = Integer.MAX_VALUE; while(low < high){ long mid = (low + high)/2; long t = find(mid); long t1 = find(mid + 1); long t0 = find(mid - 1); if(t0 > t && t > t1)low = mid + 1; else high = mid; } long ans = 0; for(int i = 0;i < n;i++){ if(a[i] >= low)continue; ans += low - a[i]; } for(int i = 0;i < m;i++){ if(b[i] <= low)continue; ans += b[i] - low; } System.out.print(ans); } }
Java
["2 2\n2 3\n3 5", "3 2\n1 2 3\n3 4", "3 2\n4 5 6\n1 2"]
1 second
["3", "4", "0"]
NoteIn example 1, you can increase a1 by 1 and decrease b2 by 1 and then again decrease b2 by 1. Now array a will be [3; 3] and array b will also be [3; 3]. Here minimum element of a is at least as large as maximum element of b. So minimum number of operations needed to satisfy Devu's condition are 3.In example 3, you don't need to do any operation, Devu's condition is already satisfied.
Java 8
standard input
[ "two pointers", "binary search", "sortings", "ternary search" ]
e0b5169945909cd2809482b7fd7178c2
The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105). The second line will contain n space-separated integers representing content of the array a (1 ≤ ai ≤ 109). The third line will contain m space-separated integers representing content of the array b (1 ≤ bi ≤ 109).
1,700
You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.
standard output
PASSED
02c6fe12ce7766acbac520acda71a7d6
train_000.jsonl
1401895800
Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother. As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the maximum value of his brother's array b. Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; 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); Task solver = new TaskD(); solver.solve(1, in, out); out.close(); } } interface Task { public void solve(int testNumber, InputReader in, OutputWriter out); } class TaskA implements Task { public void solve(int testNumber, InputReader in, OutputWriter out) { int n=in.readInt(), d=in.readInt(), ret=0, total=0; while (n-->0) { total+=in.readInt(); if (n>0) { total+=10; ret+=2; } } while (total+5<=d) { total+=5; ret++; } out.printLine(total<=d?ret:-1); } } class TaskB implements Task { public void solve(int testNumber, InputReader in, OutputWriter out) { int n=in.readInt(), x=in.readInt(); long ret=0L; int[] arr=IOUtils.readIntArray(in, n); Arrays.sort(arr); for (int i: arr) { ret+=1L*i*x; if (x>1) x--; } out.printLine(ret); } } class TaskC implements Task { LinkedList<Integer> par=new LinkedList<Integer>(), impar=new LinkedList<Integer>(); ArrayList<ArrayList<Integer>> arr=new ArrayList<ArrayList<Integer>>(); public void solve(int testNumber, InputReader in, OutputWriter out) { int n=in.readInt(), k=in.readInt(), p=in.readInt(); for (int i=0; i<n; i++) { int x=in.readInt(); if (x%2==0) par.addLast(x); else impar.addLast(x); } for (int i=0; i<k; i++) arr.add(new ArrayList<Integer>()); for (int i=p; i<k; i++) if (!impar.isEmpty()) arr.get(i).add(impar.removeFirst()); for (int i=0; i<p; i++) { if (!impar.isEmpty()) arr.get(i).add(impar.removeFirst()); if (!impar.isEmpty()) arr.get(i).add(impar.removeFirst()); } while (!impar.isEmpty()) arr.get(0).add(impar.removeFirst()); for (int i=0; i<k; i++) if (arr.get(i).isEmpty() && !par.isEmpty()) arr.get(i).add(par.removeFirst()); while (!par.isEmpty()) arr.get(0).add(par.removeFirst()); boolean val=true; for (int i=0; i<k; i++) { int x=0; for (int j: arr.get(i)) x+=j; val&=(i<p?x%2==0:x%2==1); val&=!arr.get(i).isEmpty(); } if (val) { out.printLine("YES"); for (int i=0; i<k; i++) { out.print(arr.get(i).size()); for (int j: arr.get(i)) out.print("", j); out.printLine(); } } else out.printLine("NO"); } } class TaskD implements Task { int[] a, b; public void solve(int testNumber, InputReader in, OutputWriter out) { int n=in.readInt(), m=in.readInt(); a=IOUtils.readIntArray(in, n); b=IOUtils.readIntArray(in, m); // f(search(1, 1000000000)); out.printLine(f(search(1, 1000000000))); } int search(int ini, int fim) { while (ini<fim) { if (fim<ini+3) { long min=1000000000000000000L; int ret=-1; for (int i=ini; i<=fim; i++) { long x=f(i); if (x<min) { min=x; ret=i; } } return ret; } int x1=(int)((2L*ini+fim)/3L), x2=(int)((ini+2L*fim)/3L); if (f(x1)>f(x2)) ini=x1; else fim=x2; } return -1; } long f(int x) { long ret=0L; for (int i: a) if (i<x) ret+=x-i; for (int i: b) if (i>x) ret+=i-x; return ret; } } class TaskE implements Task { public void solve(int testNumber, InputReader in, OutputWriter out) { } } class GeometryUtils { public static double epsilon = 1e-5; public static double fastHypot(double... x) { if (x.length == 0) return 0; else if (x.length == 1) return Math.abs(x[0]); else { double sumSquares = 0; for (double value : x) sumSquares += value * value; return Math.sqrt(sumSquares); } } public static double fastHypot(double x, double y) { return Math.sqrt(x * x + y * y); } public static double fastHypot(double[] x, double[] y) { if (x.length == 0) return 0; else if (x.length == 1) return Math.abs(x[0] - y[0]); else { double sumSquares = 0; for (int i = 0; i < x.length; i++) { double diff = x[i] - y[i]; sumSquares += diff * diff; } return Math.sqrt(sumSquares); } } public static double fastHypot(int[] x, int[] y) { if (x.length == 0) return 0; else if (x.length == 1) return Math.abs(x[0] - y[0]); else { double sumSquares = 0; for (int i = 0; i < x.length; i++) { double diff = x[i] - y[i]; sumSquares += diff * diff; } return Math.sqrt(sumSquares); } } public static double missileTrajectoryLength(double v, double angle, double g) { return (v * v * Math.sin(2 * angle)) / g; } public static double sphereVolume(double radius) { return 4 * Math.PI * radius * radius * radius / 3; } public static double triangleSquare(double first, double second, double third) { double p = (first + second + third) / 2; return Math.sqrt(p * (p - first) * (p - second) * (p - third)); } public static double canonicalAngle(double angle) { while (angle > Math.PI) angle -= 2 * Math.PI; while (angle < -Math.PI) angle += 2 * Math.PI; return angle; } public static double positiveAngle(double angle) { while (angle > 2 * Math.PI - GeometryUtils.epsilon) angle -= 2 * Math.PI; while (angle < -GeometryUtils.epsilon) angle += 2 * Math.PI; return angle; } } 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(char[] array) { writer.print(array); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void print(int[] array) { for (int i = 0; i < array.length; i++) { if (i != 0) writer.print(' '); writer.print(array[i]); } } public void print(long[] array) { for (int i = 0; i < array.length; i++) { if (i != 0) writer.print(' '); writer.print(array[i]); } } public void print(Collection<Integer> collection) { boolean first = true; for (Integer iterator : collection) { if (first) first = false; else writer.print(' '); writer.print(iterator); } } public void printLine(int[] array) { print(array); writer.println(); } public void printLine(long[] array) { print(array); writer.println(); } public void printLine(Collection<Integer> collection) { print(collection); writer.println(); } public void printLine() { writer.println(); } public void printLine(Object... objects) { print(objects); writer.println(); } public void print(char i) { writer.print(i); } public void printLine(char i) { writer.println(i); } public void printLine(char[] array) { writer.println(array); } public void printFormat(String format, Object... objects) { writer.printf(format, objects); } public void close() { writer.close(); } public void flush() { writer.flush(); } public void print(long i) { writer.print(i); } public void printLine(long i) { writer.println(i); } public void print(int i) { writer.print(i); } public void printLine(int i) { writer.println(i); } } 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 peek() { if (numChars == -1) return -1; if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { return -1; } if (numChars <= 0) return -1; } return buf[curChar]; } public int 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(); StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0() { StringBuilder buf = new StringBuilder(); int c = read(); while (c != '\n' && c != -1) { if (c != '\r') buf.appendCodePoint(c); c = read(); } return buf.toString(); } public String readLine() { String s = readLine0(); while (s.trim().length() == 0) s = readLine0(); return s; } public String readLine(boolean ignoreEmptyLines) { if (ignoreEmptyLines) return readLine(); else return readLine0(); } public BigInteger readBigInteger() { try { return new BigInteger(readString()); } catch (NumberFormatException e) { throw new InputMismatchException(); } } public char readCharacter() { int c = read(); while (isSpaceChar(c)) c = read(); return (char) c; } public double readDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, readInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, readInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public boolean isExhausted() { int value; while (isSpaceChar(value = peek()) && value != -1) read(); return value == -1; } public String next() { return readString(); } public SpaceCharFilter getFilter() { return filter; } public void setFilter(SpaceCharFilter filter) { this.filter = filter; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } class IOUtils { public static Pair<Integer, Integer> readIntPair(InputReader in) { int first = in.readInt(); int second = in.readInt(); return Pair.makePair(first, second); } public static Pair<Long, Long> readLongPair(InputReader in) { long first = in.readLong(); long second = in.readLong(); return Pair.makePair(first, second); } 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 double[] readDoubleArray(InputReader in, int size) { double[] array = new double[size]; for (int i = 0; i < size; i++) array[i] = in.readDouble(); return array; } public static String[] readStringArray(InputReader in, int size) { String[] array = new String[size]; for (int i = 0; i < size; i++) array[i] = in.readString(); return array; } public static char[] readCharArray(InputReader in, int size) { char[] array = new char[size]; for (int i = 0; i < size; i++) array[i] = in.readCharacter(); return array; } public static Pair<Integer, Integer>[] readIntPairArray(InputReader in, int size) { @SuppressWarnings({ "unchecked" }) Pair<Integer, Integer>[] result = new Pair[size]; for (int i = 0; i < size; i++) result[i] = readIntPair(in); return result; } public static Pair<Long, Long>[] readLongPairArray(InputReader in, int size) { @SuppressWarnings({ "unchecked" }) Pair<Long, Long>[] result = new Pair[size]; for (int i = 0; i < size; i++) result[i] = readLongPair(in); return result; } public static void readIntArrays(InputReader in, int[]... arrays) { for (int i = 0; i < arrays[0].length; i++) { for (int j = 0; j < arrays.length; j++) arrays[j][i] = in.readInt(); } } public static void readLongArrays(InputReader in, long[]... arrays) { for (int i = 0; i < arrays[0].length; i++) { for (int j = 0; j < arrays.length; j++) arrays[j][i] = in.readLong(); } } public static void readDoubleArrays(InputReader in, double[]... arrays) { for (int i = 0; i < arrays[0].length; i++) { for (int j = 0; j < arrays.length; j++) arrays[j][i] = in.readDouble(); } } public static char[][] readTable(InputReader in, int rowCount, int columnCount) { char[][] table = new char[rowCount][]; for (int i = 0; i < rowCount; i++) table[i] = readCharArray(in, columnCount); return table; } 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 double[][] readDoubleTable(InputReader in, int rowCount, int columnCount) { double[][] table = new double[rowCount][]; for (int i = 0; i < rowCount; i++) table[i] = readDoubleArray(in, columnCount); return table; } public static long[][] readLongTable(InputReader in, int rowCount, int columnCount) { long[][] table = new long[rowCount][]; for (int i = 0; i < rowCount; i++) table[i] = readLongArray(in, columnCount); return table; } public static String[][] readStringTable(InputReader in, int rowCount, int columnCount) { String[][] table = new String[rowCount][]; for (int i = 0; i < rowCount; i++) table[i] = readStringArray(in, columnCount); return table; } public static String readText(InputReader in) { StringBuilder result = new StringBuilder(); while (true) { int character = in.read(); if (character == '\r') continue; if (character == -1) break; result.append((char) character); } return result.toString(); } public static void readStringArrays(InputReader in, String[]... arrays) { for (int i = 0; i < arrays[0].length; i++) { for (int j = 0; j < arrays.length; j++) arrays[j][i] = in.readString(); } } public static void printTable(OutputWriter out, char[][] table) { for (char[] row : table) out.printLine(new String(row)); } } 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); } private Pair(U first, V second) { this.first = first; this.second = second; } @Override 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); } @Override public int hashCode() { int result = first != null ? first.hashCode() : 0; result = 31 * result + (second != null ? second.hashCode() : 0); return result; } public Pair<V, U> swap() { return makePair(second, first); } @Override public String toString() { return "(" + first + "," + second + ")"; } @SuppressWarnings({ "unchecked" }) 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 BidirectionalGraph extends Graph { public int[] transposedEdge; public BidirectionalGraph(int vertexCount) { this(vertexCount, vertexCount); } public BidirectionalGraph(int vertexCount, int edgeCapacity) { super(vertexCount, 2 * edgeCapacity); transposedEdge = new int[2 * edgeCapacity]; } public static BidirectionalGraph createGraph(int vertexCount, int[] from, int[] to) { BidirectionalGraph graph = new BidirectionalGraph(vertexCount, from.length); for (int i = 0; i < from.length; i++) graph.addSimpleEdge(from[i], to[i]); return graph; } public static BidirectionalGraph createWeightedGraph(int vertexCount, int[] from, int[] to, long[] weight) { BidirectionalGraph graph = new BidirectionalGraph(vertexCount, from.length); for (int i = 0; i < from.length; i++) graph.addWeightedEdge(from[i], to[i], weight[i]); return graph; } public static BidirectionalGraph createFlowGraph(int vertexCount, int[] from, int[] to, long[] capacity) { BidirectionalGraph graph = new BidirectionalGraph(vertexCount, from.length * 2); for (int i = 0; i < from.length; i++) graph.addFlowEdge(from[i], to[i], capacity[i]); return graph; } public static BidirectionalGraph createFlowWeightedGraph(int vertexCount, int[] from, int[] to, long[] weight, long[] capacity) { BidirectionalGraph graph = new BidirectionalGraph(vertexCount, from.length * 2); for (int i = 0; i < from.length; i++) graph.addFlowWeightedEdge(from[i], to[i], weight[i], capacity[i]); return graph; } @Override public int addEdge(int fromID, int toID, long weight, long capacity, int reverseEdge) { int lastEdgeCount = edgeCount; super.addEdge(fromID, toID, weight, capacity, reverseEdge); super.addEdge(toID, fromID, weight, capacity, reverseEdge == -1 ? -1 : reverseEdge + 1); this.transposedEdge[lastEdgeCount] = lastEdgeCount + 1; this.transposedEdge[lastEdgeCount + 1] = lastEdgeCount; return lastEdgeCount; } @Override protected int entriesPerEdge() { return 2; } @Override public final int transposed(int id) { return transposedEdge[id]; } @Override protected void ensureEdgeCapacity(int size) { if (size > edgeCapacity()) { super.ensureEdgeCapacity(size); transposedEdge = resize(transposedEdge, edgeCapacity()); } } } class Graph { public static final int REMOVED_BIT = 0; protected int vertexCount; protected int edgeCount; private int[] firstOutbound; private int[] firstInbound; private Edge[] edges; private int[] nextInbound; private int[] nextOutbound; private int[] from; private int[] to; private long[] weight; private long[] capacity; private int[] reverseEdge; private int[] flags; public Graph(int vertexCount) { this(vertexCount, vertexCount); } public Graph(int vertexCount, int edgeCapacity) { this.vertexCount = vertexCount; firstOutbound = new int[vertexCount]; Arrays.fill(firstOutbound, -1); from = new int[edgeCapacity]; to = new int[edgeCapacity]; nextOutbound = new int[edgeCapacity]; flags = new int[edgeCapacity]; } public static Graph createGraph(int vertexCount, int[] from, int[] to) { Graph graph = new Graph(vertexCount, from.length); for (int i = 0; i < from.length; i++) graph.addSimpleEdge(from[i], to[i]); return graph; } public static Graph createWeightedGraph(int vertexCount, int[] from, int[] to, long[] weight) { Graph graph = new Graph(vertexCount, from.length); for (int i = 0; i < from.length; i++) graph.addWeightedEdge(from[i], to[i], weight[i]); return graph; } public static Graph createFlowGraph(int vertexCount, int[] from, int[] to, long[] capacity) { Graph graph = new Graph(vertexCount, from.length * 2); for (int i = 0; i < from.length; i++) graph.addFlowEdge(from[i], to[i], capacity[i]); return graph; } public static Graph createFlowWeightedGraph(int vertexCount, int[] from, int[] to, long[] weight, long[] capacity) { Graph graph = new Graph(vertexCount, from.length * 2); for (int i = 0; i < from.length; i++) graph.addFlowWeightedEdge(from[i], to[i], weight[i], capacity[i]); return graph; } public static Graph createTree(int[] parent) { Graph graph = new Graph(parent.length + 1, parent.length); for (int i = 0; i < parent.length; i++) graph.addSimpleEdge(parent[i], i + 1); return graph; } public int addEdge(int fromID, int toID, long weight, long capacity, int reverseEdge) { ensureEdgeCapacity(edgeCount + 1); if (firstOutbound[fromID] != -1) nextOutbound[edgeCount] = firstOutbound[fromID]; else nextOutbound[edgeCount] = -1; firstOutbound[fromID] = edgeCount; if (firstInbound != null) { if (firstInbound[toID] != -1) nextInbound[edgeCount] = firstInbound[toID]; else nextInbound[edgeCount] = -1; firstInbound[toID] = edgeCount; } this.from[edgeCount] = fromID; this.to[edgeCount] = toID; if (capacity != 0) { if (this.capacity == null) this.capacity = new long[from.length]; this.capacity[edgeCount] = capacity; } if (weight != 0) { if (this.weight == null) this.weight = new long[from.length]; this.weight[edgeCount] = weight; } if (reverseEdge != -1) { if (this.reverseEdge == null) { this.reverseEdge = new int[from.length]; Arrays.fill(this.reverseEdge, 0, edgeCount, -1); } this.reverseEdge[edgeCount] = reverseEdge; } if (edges != null) edges[edgeCount] = createEdge(edgeCount); return edgeCount++; } protected final GraphEdge createEdge(int id) { return new GraphEdge(id); } public final int addFlowWeightedEdge(int from, int to, long weight, long capacity) { if (capacity == 0) { return addEdge(from, to, weight, 0, -1); } else { int lastEdgeCount = edgeCount; addEdge(to, from, -weight, 0, lastEdgeCount + entriesPerEdge()); return addEdge(from, to, weight, capacity, lastEdgeCount); } } protected int entriesPerEdge() { return 1; } public final int addFlowEdge(int from, int to, long capacity) { return addFlowWeightedEdge(from, to, 0, capacity); } public final int addWeightedEdge(int from, int to, long weight) { return addFlowWeightedEdge(from, to, weight, 0); } public final int addSimpleEdge(int from, int to) { return addWeightedEdge(from, to, 0); } public final int vertexCount() { return vertexCount; } public final int edgeCount() { return edgeCount; } protected final int edgeCapacity() { return from.length; } public final Edge edge(int id) { initEdges(); return edges[id]; } public final int firstOutbound(int vertex) { int id = firstOutbound[vertex]; while (id != -1 && isRemoved(id)) id = nextOutbound[id]; return id; } public final int nextOutbound(int id) { id = nextOutbound[id]; while (id != -1 && isRemoved(id)) id = nextOutbound[id]; return id; } public final int firstInbound(int vertex) { initInbound(); int id = firstInbound[vertex]; while (id != -1 && isRemoved(id)) id = nextInbound[id]; return id; } public final int nextInbound(int id) { initInbound(); id = nextInbound[id]; while (id != -1 && isRemoved(id)) id = nextInbound[id]; return id; } public final int source(int id) { return from[id]; } public final int destination(int id) { return to[id]; } public final long weight(int id) { if (weight == null) return 0; return weight[id]; } public final long capacity(int id) { if (capacity == null) return 0; return capacity[id]; } public final long flow(int id) { if (reverseEdge == null) return 0; return capacity[reverseEdge[id]]; } public final void pushFlow(int id, long flow) { if (flow == 0) return; if (flow > 0) { if (capacity(id) < flow) throw new IllegalArgumentException("Not enough capacity"); } else { if (flow(id) < -flow) throw new IllegalArgumentException("Not enough capacity"); } capacity[id] -= flow; capacity[reverseEdge[id]] += flow; } public int transposed(int id) { return -1; } public final int reverse(int id) { if (reverseEdge == null) return -1; return reverseEdge[id]; } public final void addVertices(int count) { ensureVertexCapacity(vertexCount + count); Arrays.fill(firstOutbound, vertexCount, vertexCount + count, -1); if (firstInbound != null) Arrays.fill(firstInbound, vertexCount, vertexCount + count, -1); vertexCount += count; } protected final void initEdges() { if (edges == null) { edges = new Edge[from.length]; for (int i = 0; i < edgeCount; i++) edges[i] = createEdge(i); } } public final void removeVertex(int vertex) { int id = firstOutbound[vertex]; while (id != -1) { removeEdge(id); id = nextOutbound[id]; } initInbound(); id = firstInbound[vertex]; while (id != -1) { removeEdge(id); id = nextInbound[id]; } } private void initInbound() { if (firstInbound == null) { firstInbound = new int[firstOutbound.length]; Arrays.fill(firstInbound, 0, vertexCount, -1); nextInbound = new int[from.length]; for (int i = 0; i < edgeCount; i++) { nextInbound[i] = firstInbound[to[i]]; firstInbound[to[i]] = i; } } } public final boolean flag(int id, int bit) { return (flags[id] >> bit & 1) != 0; } public final void setFlag(int id, int bit) { flags[id] |= 1 << bit; } public final void removeFlag(int id, int bit) { flags[id] &= -1 - (1 << bit); } public final void removeEdge(int id) { setFlag(id, REMOVED_BIT); } public final void restoreEdge(int id) { removeFlag(id, REMOVED_BIT); } public final boolean isRemoved(int id) { return flag(id, REMOVED_BIT); } public final Iterable<Edge> outbound(final int id) { initEdges(); return new Iterable<Edge>() { public Iterator<Edge> iterator() { return new EdgeIterator(id, firstOutbound, nextOutbound); } }; } public final Iterable<Edge> inbound(final int id) { initEdges(); initInbound(); return new Iterable<Edge>() { public Iterator<Edge> iterator() { return new EdgeIterator(id, firstInbound, nextInbound); } }; } protected void ensureEdgeCapacity(int size) { if (from.length < size) { int newSize = Math.max(size, 2 * from.length); if (edges != null) edges = resize(edges, newSize); from = resize(from, newSize); to = resize(to, newSize); nextOutbound = resize(nextOutbound, newSize); if (nextInbound != null) nextInbound = resize(nextInbound, newSize); if (weight != null) weight = resize(weight, newSize); if (capacity != null) capacity = resize(capacity, newSize); if (reverseEdge != null) reverseEdge = resize(reverseEdge, newSize); flags = resize(flags, newSize); } } private void ensureVertexCapacity(int size) { if (firstOutbound.length < size) { int newSize = Math.max(size, 2 * from.length); firstOutbound = resize(firstOutbound, newSize); if (firstInbound != null) firstInbound = resize(firstInbound, newSize); } } protected final int[] resize(int[] array, int size) { int[] newArray = new int[size]; System.arraycopy(array, 0, newArray, 0, array.length); return newArray; } private long[] resize(long[] array, int size) { long[] newArray = new long[size]; System.arraycopy(array, 0, newArray, 0, array.length); return newArray; } private Edge[] resize(Edge[] array, int size) { Edge[] newArray = new Edge[size]; System.arraycopy(array, 0, newArray, 0, array.length); return newArray; } public final boolean isSparse() { return vertexCount == 0 || edgeCount * 20 / vertexCount <= vertexCount; } protected class GraphEdge implements Edge { protected int id; protected GraphEdge(int id) { this.id = id; } public int getSource() { return source(id); } public int getDestination() { return destination(id); } public long getWeight() { return weight(id); } public long getCapacity() { return capacity(id); } public long getFlow() { return flow(id); } public void pushFlow(long flow) { Graph.this.pushFlow(id, flow); } public boolean getFlag(int bit) { return flag(id, bit); } public void setFlag(int bit) { Graph.this.setFlag(id, bit); } public void removeFlag(int bit) { Graph.this.removeFlag(id, bit); } public int getTransposedID() { return transposed(id); } public Edge getTransposedEdge() { int reverseID = getTransposedID(); if (reverseID == -1) return null; initEdges(); return edge(reverseID); } public int getReverseID() { return reverse(id); } public Edge getReverseEdge() { int reverseID = getReverseID(); if (reverseID == -1) return null; initEdges(); return edge(reverseID); } public int getID() { return id; } public void remove() { removeEdge(id); } public void restore() { restoreEdge(id); } } public class EdgeIterator implements Iterator<Edge> { private int edgeID; private final int[] next; private int lastID = -1; public EdgeIterator(int id, int[] first, int[] next) { this.next = next; edgeID = nextEdge(first[id]); } private int nextEdge(int id) { while (id != -1 && isRemoved(id)) id = next[id]; return id; } public boolean hasNext() { return edgeID != -1; } public Edge next() { if (edgeID == -1) throw new NoSuchElementException(); lastID = edgeID; edgeID = nextEdge(next[lastID]); return edges[lastID]; } public void remove() { if (lastID == -1) throw new IllegalStateException(); removeEdge(lastID); lastID = -1; } } } interface Edge { public int getSource(); public int getDestination(); public long getWeight(); public long getCapacity(); public long getFlow(); public void pushFlow(long flow); public boolean getFlag(int bit); public void setFlag(int bit); public void removeFlag(int bit); public int getTransposedID(); public Edge getTransposedEdge(); public int getReverseID(); public Edge getReverseEdge(); public int getID(); public void remove(); public void restore(); } class MiscUtils { public static final int[] DX4 = { 1, 0, -1, 0 }; public static final int[] DY4 = { 0, -1, 0, 1 }; public static final int[] DX8 = { 1, 1, 1, 0, -1, -1, -1, 0 }; public static final int[] DY8 = { -1, 0, 1, 1, 1, 0, -1, -1 }; public static final int[] DX_KNIGHT = { 2, 1, -1, -2, -2, -1, 1, 2 }; public static final int[] DY_KNIGHT = { 1, 2, 2, 1, -1, -2, -2, -1 }; private static final String[] ROMAN_TOKENS = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" }; private static final int[] ROMAN_VALUES = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }; public static long josephProblem(long n, int k) { if (n == 1) return 0; if (k == 1) return n - 1; if (k > n) return (josephProblem(n - 1, k) + k) % n; long count = n / k; long result = josephProblem(n - count, k); result -= n % k; if (result < 0) result += n; else result += result / (k - 1); return result; } public static boolean isValidCell(int row, int column, int rowCount, int columnCount) { return row >= 0 && row < rowCount && column >= 0 && column < columnCount; } public static List<Integer> getPath(int[] last, int destination) { List<Integer> path = new ArrayList<Integer>(); while (destination != -1) { path.add(destination); destination = last[destination]; } Collections.reverse(path); return path; } public static List<Integer> getPath(int[][] lastIndex, int[][] lastPathNumber, int destination, int pathNumber) { List<Integer> path = new ArrayList<Integer>(); while (destination != -1 || pathNumber != 0) { path.add(destination); int nextDestination = lastIndex[destination][pathNumber]; pathNumber = lastPathNumber[destination][pathNumber]; destination = nextDestination; } Collections.reverse(path); return path; } public static long maximalRectangleSum(long[][] array) { int n = array.length; int m = array[0].length; long[][] partialSums = new long[n + 1][m + 1]; for (int i = 0; i < n; i++) { long rowSum = 0; for (int j = 0; j < m; j++) { rowSum += array[i][j]; partialSums[i + 1][j + 1] = partialSums[i][j + 1] + rowSum; } } long result = Long.MIN_VALUE; for (int i = 0; i < m; i++) { for (int j = i; j < m; j++) { long minPartialSum = 0; for (int k = 1; k <= n; k++) { long current = partialSums[k][j + 1] - partialSums[k][i]; result = Math.max(result, current - minPartialSum); minPartialSum = Math.min(minPartialSum, current); } } } return result; } public static int parseIP(String ip) { String[] components = ip.split("[.]"); int result = 0; for (int i = 0; i < 4; i++) result += (1 << (24 - 8 * i)) * Integer.parseInt(components[i]); return result; } public static String buildIP(int mask) { StringBuilder result = new StringBuilder(); for (int i = 0; i < 4; i++) { if (i != 0) result.append('.'); result.append(mask >> (24 - 8 * i) & 255); } return result.toString(); } public static long binarySearch(long from, long to, Function<Long, Boolean> function) { while (from < to) { long argument = from + (to - from) / 2; if (function.value(argument)) to = argument; else from = argument + 1; } return from; } public static <T> boolean equals(T first, T second) { return first == null && second == null || first != null && first.equals(second); } public static boolean isVowel(char ch) { ch = Character.toUpperCase(ch); return ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U' || ch == 'Y'; } public static boolean isStrictVowel(char ch) { ch = Character.toUpperCase(ch); return ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U'; } public static String convertToRoman(int number) { StringBuilder result = new StringBuilder(); for (int i = 0; i < ROMAN_TOKENS.length; i++) { while (number >= ROMAN_VALUES[i]) { number -= ROMAN_VALUES[i]; result.append(ROMAN_TOKENS[i]); } } return result.toString(); } public static int convertFromRoman(String number) { int result = 0; for (int i = 0; i < ROMAN_TOKENS.length; i++) { while (number.startsWith(ROMAN_TOKENS[i])) { number = number.substring(ROMAN_TOKENS[i].length()); result += ROMAN_VALUES[i]; } } return result; } public static int distance(int x1, int y1, int x2, int y2) { int dx = x1 - x2; int dy = y1 - y2; return dx * dx + dy * dy; } public static <T extends Comparable<T>> T min(T first, T second) { if (first.compareTo(second) <= 0) return first; return second; } public static <T extends Comparable<T>> T max(T first, T second) { if (first.compareTo(second) <= 0) return second; return first; } public static void decreaseByOne(int[]... arrays) { for (int[] array : arrays) { for (int i = 0; i < array.length; i++) array[i]--; } } public static int[] getIntArray(String s) { String[] tokens = s.split(" "); int[] result = new int[tokens.length]; for (int i = 0; i < result.length; i++) result[i] = Integer.parseInt(tokens[i]); return result; } } interface Function<A, V> { public abstract V value(A argument); } interface IntComparator { public static final IntComparator DEFAULT = new IntComparator() { public int compare(int first, int second) { if (first < second) return -1; if (first > second) return 1; return 0; } }; public static final IntComparator REVERSE = new IntComparator() { public int compare(int first, int second) { if (first < second) return 1; if (first > second) return -1; return 0; } }; public int compare(int first, int second); } class DFSOrder { public final int[] position; public final int[] end; public DFSOrder(Graph graph) { this(graph, 0); } public DFSOrder(Graph graph, int root) { int count = graph.vertexCount(); position = new int[count]; end = new int[count]; int[] edge = new int[count]; int[] stack = new int[count]; for (int i = 0; i < count; i++) edge[i] = graph.firstOutbound(i); stack[0] = root; int size = 1; position[root] = 0; int index = 0; while (size > 0) { int current = stack[size - 1]; if (edge[current] == -1) { end[current] = index; size--; } else { int next = graph.destination(edge[current]); edge[current] = graph.nextOutbound(edge[current]); position[next] = ++index; stack[size++] = next; } } } public DFSOrder(BidirectionalGraph graph) { this(graph, 0); } public DFSOrder(BidirectionalGraph graph, int root) { int count = graph.vertexCount(); position = new int[count]; end = new int[count]; int[] edge = new int[count]; int[] stack = new int[count]; int[] last = new int[count]; for (int i = 0; i < count; i++) edge[i] = graph.firstOutbound(i); stack[0] = root; last[root] = -1; int size = 1; position[root] = 0; int index = 0; while (size > 0) { int current = stack[size - 1]; if (edge[current] == -1) { end[current] = index; size--; } else { int next = graph.destination(edge[current]); if (next == last[current]) { edge[current] = graph.nextOutbound(edge[current]); continue; } edge[current] = graph.nextOutbound(edge[current]); position[next] = ++index; last[next] = current; stack[size++] = next; } } } } abstract class IntervalTree { protected int size; protected IntervalTree(int size) { this(size, true); } public IntervalTree(int size, boolean shouldInit) { this.size = size; int nodeCount = Math.max(1, Integer.highestOneBit(size) << 2); initData(size, nodeCount); if (shouldInit) init(); } protected abstract void initData(int size, int nodeCount); protected abstract void initAfter(int root, int left, int right, int middle); protected abstract void initBefore(int root, int left, int right, int middle); protected abstract void initLeaf(int root, int index); protected abstract void updatePostProcess(int root, int left, int right, int from, int to, long delta, int middle); protected abstract void updatePreProcess(int root, int left, int right, int from, int to, long delta, int middle); protected abstract void updateFull(int root, int left, int right, int from, int to, long delta); protected abstract long queryPostProcess(int root, int left, int right, int from, int to, int middle, long leftResult, long rightResult); protected abstract void queryPreProcess(int root, int left, int right, int from, int to, int middle); protected abstract long queryFull(int root, int left, int right, int from, int to); protected abstract long emptySegmentResult(); public void init() { if (size == 0) return; init(0, 0, size - 1); } private void init(int root, int left, int right) { if (left == right) { initLeaf(root, left); } else { int middle = (left + right) >> 1; initBefore(root, left, right, middle); init(2 * root + 1, left, middle); init(2 * root + 2, middle + 1, right); initAfter(root, left, right, middle); } } public void update(int from, int to, long delta) { update(0, 0, size - 1, from, to, delta); } protected void update(int root, int left, int right, int from, int to, long delta) { if (left > to || right < from) return; if (left >= from && right <= to) { updateFull(root, left, right, from, to, delta); return; } int middle = (left + right) >> 1; updatePreProcess(root, left, right, from, to, delta, middle); update(2 * root + 1, left, middle, from, to, delta); update(2 * root + 2, middle + 1, right, from, to, delta); updatePostProcess(root, left, right, from, to, delta, middle); } public long query(int from, int to) { return query(0, 0, size - 1, from, to); } protected long query(int root, int left, int right, int from, int to) { if (left > to || right < from) return emptySegmentResult(); if (left >= from && right <= to) return queryFull(root, left, right, from, to); int middle = (left + right) >> 1; queryPreProcess(root, left, right, from, to, middle); long leftResult = query(2 * root + 1, left, middle, from, to); long rightResult = query(2 * root + 2, middle + 1, right, from, to); return queryPostProcess(root, left, right, from, to, middle, leftResult, rightResult); } } class LCA { private final long[] order; private final int[] position; private final IntervalTree lcaTree; private final int[] level; public LCA(Graph graph) { this(graph, 0); } public LCA(Graph graph, int root) { order = new long[2 * graph.vertexCount() - 1]; position = new int[graph.vertexCount()]; level = new int[graph.vertexCount()]; int[] index = new int[graph.vertexCount()]; for (int i = 0; i < index.length; i++) index[i] = graph.firstOutbound(i); int[] last = new int[graph.vertexCount()]; int[] stack = new int[graph.vertexCount()]; stack[0] = root; int size = 1; int j = 0; last[root] = -1; Arrays.fill(position, -1); while (size > 0) { int vertex = stack[--size]; if (position[vertex] == -1) position[vertex] = j; order[j++] = vertex; if (last[vertex] != -1) level[vertex] = level[last[vertex]] + 1; while (index[vertex] != -1 && last[vertex] == graph.destination(index[vertex])) index[vertex] = graph.nextOutbound(index[vertex]); if (index[vertex] != -1) { stack[size++] = vertex; stack[size++] = graph.destination(index[vertex]); last[graph.destination(index[vertex])] = vertex; index[vertex] = graph.nextOutbound(index[vertex]); } } lcaTree = new ReadOnlyIntervalTree(order) { @Override protected long joinValue(long left, long right) { if (left == -1) return right; if (right == -1) return left; if (level[((int) left)] < level[((int) right)]) return left; return right; } @Override protected long neutralValue() { return -1; } }; lcaTree.init(); } public int getPosition(int vertex) { return position[vertex]; } public int getLCA(int first, int second) { return (int) lcaTree.query(Math.min(position[first], position[second]), Math.max(position[first], position[second])); } public int getLevel(int vertex) { return level[vertex]; } public int getPathLength(int first, int second) { return level[first] + level[second] - 2 * level[getLCA(first, second)]; } } abstract class LongIntervalTree extends IntervalTree { protected long[] value; protected long[] delta; protected LongIntervalTree(int size) { this(size, true); } public LongIntervalTree(int size, boolean shouldInit) { super(size, shouldInit); } @Override protected void initData(int size, int nodeCount) { value = new long[nodeCount]; delta = new long[nodeCount]; } protected abstract long joinValue(long left, long right); protected abstract long joinDelta(long was, long delta); protected abstract long accumulate(long value, long delta, int length); protected abstract long neutralValue(); protected abstract long neutralDelta(); protected long initValue(int index) { return neutralValue(); } @Override protected void initAfter(int root, int left, int right, int middle) { value[root] = joinValue(value[2 * root + 1], value[2 * root + 2]); delta[root] = neutralDelta(); } @Override protected void initBefore(int root, int left, int right, int middle) { } @Override protected void initLeaf(int root, int index) { value[root] = initValue(index); delta[root] = neutralDelta(); } @Override protected void updatePostProcess(int root, int left, int right, int from, int to, long delta, int middle) { value[root] = joinValue(value[2 * root + 1], value[2 * root + 2]); } @Override protected void updatePreProcess(int root, int left, int right, int from, int to, long delta, int middle) { pushDown(root, left, middle, right); } protected void pushDown(int root, int left, int middle, int right) { value[2 * root + 1] = accumulate(value[2 * root + 1], delta[root], middle - left + 1); value[2 * root + 2] = accumulate(value[2 * root + 2], delta[root], right - middle); delta[2 * root + 1] = joinDelta(delta[2 * root + 1], delta[root]); delta[2 * root + 2] = joinDelta(delta[2 * root + 2], delta[root]); delta[root] = neutralDelta(); } @Override protected void updateFull(int root, int left, int right, int from, int to, long delta) { value[root] = accumulate(value[root], delta, right - left + 1); this.delta[root] = joinDelta(this.delta[root], delta); } @Override protected long queryPostProcess(int root, int left, int right, int from, int to, int middle, long leftResult, long rightResult) { return joinValue(leftResult, rightResult); } @Override protected void queryPreProcess(int root, int left, int right, int from, int to, int middle) { pushDown(root, left, middle, right); } @Override protected long queryFull(int root, int left, int right, int from, int to) { return value[root]; } @Override protected long emptySegmentResult() { return neutralValue(); } } class SumIntervalTree extends LongIntervalTree { public SumIntervalTree(int size) { super(size); } @Override protected long joinValue(long left, long right) { return left + right; } @Override protected long joinDelta(long was, long delta) { return was + delta; } @Override protected long accumulate(long value, long delta, int length) { return value + delta * length; } @Override protected long neutralValue() { return 0; } @Override protected long neutralDelta() { return 0; } } abstract class ReadOnlyIntervalTree extends IntervalTree { protected long[] value; protected long[] array; protected ReadOnlyIntervalTree(long[] array) { super(array.length, false); this.array = array; init(); } @Override protected void initData(int size, int nodeCount) { value = new long[nodeCount]; } @Override protected void initAfter(int root, int left, int right, int middle) { value[root] = joinValue(value[2 * root + 1], value[2 * root + 2]); } @Override protected void initBefore(int root, int left, int right, int middle) { } @Override protected void initLeaf(int root, int index) { value[root] = array[index]; } @Override protected void updatePostProcess(int root, int left, int right, int from, int to, long delta, int middle) { throw new UnsupportedOperationException(); } @Override protected void updatePreProcess(int root, int left, int right, int from, int to, long delta, int middle) { throw new UnsupportedOperationException(); } @Override protected void updateFull(int root, int left, int right, int from, int to, long delta) { throw new UnsupportedOperationException(); } @Override protected long queryPostProcess(int root, int left, int right, int from, int to, int middle, long leftResult, long rightResult) { return joinValue(leftResult, rightResult); } @Override protected void queryPreProcess(int root, int left, int right, int from, int to, int middle) { } @Override protected long queryFull(int root, int left, int right, int from, int to) { return value[root]; } @Override protected long emptySegmentResult() { return neutralValue(); } @Override public void update(int from, int to, long delta) { throw new UnsupportedOperationException(); } @Override protected void update(int root, int left, int right, int from, int to, long delta) { throw new UnsupportedOperationException(); } protected abstract long neutralValue(); protected abstract long joinValue(long left, long right); }
Java
["2 2\n2 3\n3 5", "3 2\n1 2 3\n3 4", "3 2\n4 5 6\n1 2"]
1 second
["3", "4", "0"]
NoteIn example 1, you can increase a1 by 1 and decrease b2 by 1 and then again decrease b2 by 1. Now array a will be [3; 3] and array b will also be [3; 3]. Here minimum element of a is at least as large as maximum element of b. So minimum number of operations needed to satisfy Devu's condition are 3.In example 3, you don't need to do any operation, Devu's condition is already satisfied.
Java 8
standard input
[ "two pointers", "binary search", "sortings", "ternary search" ]
e0b5169945909cd2809482b7fd7178c2
The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105). The second line will contain n space-separated integers representing content of the array a (1 ≤ ai ≤ 109). The third line will contain m space-separated integers representing content of the array b (1 ≤ bi ≤ 109).
1,700
You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.
standard output
PASSED
296fea11340cc46e127a94115b7805a4
train_000.jsonl
1401895800
Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother. As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the maximum value of his brother's array b. Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.
256 megabytes
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Random; import java.util.Scanner; import java.io.*; public class Main { public static void main(String[] args) throws FileNotFoundException { // Scanner read = new Scanner(new FileInputStream(new // File("input.txt"))); // PrintWriter out = new PrintWriter(new File("output.txt")); Scanner read = new Scanner(System.in); int n = read.nextInt(), m = read.nextInt(); long a[] = new long[n], b[] = new long[m], min = 100000, min2 = 100000, max = -1, max2 = -1; for (int i = 0; i < n; i++) { a[i] = read.nextLong(); if (a[i] < min) min = a[i]; if (a[i] > max) max = a[i]; } for (int i = 0; i < m; i++) { b[i] = read.nextLong(); if (b[i] < min2) min2 = b[i]; if (b[i] > max2) max2 = b[i]; } if (min > max2) System.out.println("0"); else { long left = 0, right = 1000L * 1000 * 1000 + 7, mid1 = 0, mid2 = 0, part = 0, ans = Long.MAX_VALUE; while (right - left > 10) { part = (right - left) / 3; mid1 = left + part; mid2 = right - part; long x = fun(mid1, a, b), y = fun(mid2, a, b); if (x < y) right = mid2; else left = mid1; ans = Math.min(ans, Math.min(x, y)); } for (long i = left; i <= right; i++) { ans = Math.min(ans, fun(i, a, b)); } System.out.println(ans); } } private static long fun(long x, long[] a, long[] b) { long c = 0; for (int i = 0; i < a.length; i++) { c += Math.max(x - a[i], 0); } for (int i = 0; i < b.length; i++) { c += Math.max(b[i] - x, 0); } return c; } }
Java
["2 2\n2 3\n3 5", "3 2\n1 2 3\n3 4", "3 2\n4 5 6\n1 2"]
1 second
["3", "4", "0"]
NoteIn example 1, you can increase a1 by 1 and decrease b2 by 1 and then again decrease b2 by 1. Now array a will be [3; 3] and array b will also be [3; 3]. Here minimum element of a is at least as large as maximum element of b. So minimum number of operations needed to satisfy Devu's condition are 3.In example 3, you don't need to do any operation, Devu's condition is already satisfied.
Java 8
standard input
[ "two pointers", "binary search", "sortings", "ternary search" ]
e0b5169945909cd2809482b7fd7178c2
The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105). The second line will contain n space-separated integers representing content of the array a (1 ≤ ai ≤ 109). The third line will contain m space-separated integers representing content of the array b (1 ≤ bi ≤ 109).
1,700
You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.
standard output
PASSED
685c9c7c81a729143a4d3f67899adcae
train_000.jsonl
1401895800
Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother. As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the maximum value of his brother's array b. Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.TreeSet; import java.util.TreeMap; import java.util.Map; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.Collections; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Alex */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(), m = in.readInt(); int[] a = IOUtils.readIntArray(in, n); int[] b = IOUtils.readIntArray(in, m); TreeMap<Integer, Integer> acount = new TreeMap<>(); for (int val : a) acount.merge(val, 1, Integer::sum); TreeMap<Integer, Integer> bcount = new TreeMap<>(); for (int val : b) bcount.merge(val, 1, Integer::sum); TreeSet<Integer> both = new TreeSet<>(); for (int val : a) both.add(val); for (int val : b) both.add(val); TreeMap<Integer, Long> mem = new TreeMap<>(); int aprev = 0; int aoccur = 0; long asum = 0; for (int key : both) { asum += (long) (key - aprev) * aoccur; mem.merge(key, asum, Long::sum); aprev = key; aoccur += acount.getOrDefault(key, 0); } int bprev = 0; int boccur = 0; long bsum = 0; for (int key : both.descendingSet()) { bsum += (long) (bprev - key) * boccur; mem.merge(key, bsum, Long::sum); bprev = key; boccur += bcount.getOrDefault(key, 0); } out.printLine(Collections.min(mem.values())); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void printLine(long i) { writer.println(i); } } static class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = in.readInt(); return array; } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["2 2\n2 3\n3 5", "3 2\n1 2 3\n3 4", "3 2\n4 5 6\n1 2"]
1 second
["3", "4", "0"]
NoteIn example 1, you can increase a1 by 1 and decrease b2 by 1 and then again decrease b2 by 1. Now array a will be [3; 3] and array b will also be [3; 3]. Here minimum element of a is at least as large as maximum element of b. So minimum number of operations needed to satisfy Devu's condition are 3.In example 3, you don't need to do any operation, Devu's condition is already satisfied.
Java 8
standard input
[ "two pointers", "binary search", "sortings", "ternary search" ]
e0b5169945909cd2809482b7fd7178c2
The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105). The second line will contain n space-separated integers representing content of the array a (1 ≤ ai ≤ 109). The third line will contain m space-separated integers representing content of the array b (1 ≤ bi ≤ 109).
1,700
You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.
standard output
PASSED
3d0cdb6b6694203334c22ef9033d0ea1
train_000.jsonl
1401895800
Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother. As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the maximum value of his brother's array b. Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.util.Set; import java.util.InputMismatchException; import java.io.IOException; import java.util.TreeSet; import java.util.TreeMap; import java.util.Map; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Alex */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(), m = in.readInt(); int[] a = IOUtils.readIntArray(in, n); int[] b = IOUtils.readIntArray(in, m); TreeMap<Integer, Integer> acount = new TreeMap<>(); for (int val : a) acount.merge(val, 1, Integer::sum); TreeMap<Integer, Integer> bcount = new TreeMap<>(); for (int val : b) bcount.merge(val, 1, Integer::sum); TreeSet<Integer> both = new TreeSet<>(); for (int val : a) both.add(val); for (int val : b) both.add(val); TreeMap<Integer, Long> mem = new TreeMap<>(); { int aprev = acount.firstKey(); int aoccur = 0; long asum = 0; for (int key : both) { asum += (long) (key - aprev) * aoccur; mem.merge(key, asum, Long::sum); aprev = key; aoccur += acount.getOrDefault(key, 0); } } { int bprev = bcount.lastKey(); int boccur = 0; long bsum = 0; bcount.keySet().toArray(); for (int key : both.descendingSet()) { bsum += (long) (bprev - key) * boccur; mem.merge(key, bsum, Long::sum); bprev = key; boccur += bcount.getOrDefault(key, 0); } } long res = Long.MAX_VALUE; for (long val : mem.values()) res = Math.min(res, val); out.printLine(res); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void printLine(long i) { writer.println(i); } } static class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = in.readInt(); return array; } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["2 2\n2 3\n3 5", "3 2\n1 2 3\n3 4", "3 2\n4 5 6\n1 2"]
1 second
["3", "4", "0"]
NoteIn example 1, you can increase a1 by 1 and decrease b2 by 1 and then again decrease b2 by 1. Now array a will be [3; 3] and array b will also be [3; 3]. Here minimum element of a is at least as large as maximum element of b. So minimum number of operations needed to satisfy Devu's condition are 3.In example 3, you don't need to do any operation, Devu's condition is already satisfied.
Java 8
standard input
[ "two pointers", "binary search", "sortings", "ternary search" ]
e0b5169945909cd2809482b7fd7178c2
The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105). The second line will contain n space-separated integers representing content of the array a (1 ≤ ai ≤ 109). The third line will contain m space-separated integers representing content of the array b (1 ≤ bi ≤ 109).
1,700
You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.
standard output
PASSED
db040f2a0eaaad7f1821e69afa804f34
train_000.jsonl
1401895800
Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother. As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the maximum value of his brother's array b. Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.util.HashMap; import java.util.InputMismatchException; import java.io.IOException; import java.util.TreeSet; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Alex */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(), m = in.readInt(); int[] a = IOUtils.readIntArray(in, n); int[] b = IOUtils.readIntArray(in, m); HashMap<Integer, Integer> acount = new HashMap<>(); for (int val : a) acount.merge(val, 1, Integer::sum); HashMap<Integer, Integer> bcount = new HashMap<>(); for (int val : b) bcount.merge(val, 1, Integer::sum); TreeSet<Integer> both = new TreeSet<>(); for (int val : a) both.add(val); for (int val : b) both.add(val); HashMap<Integer, Long> mem = new HashMap<>(); { int aprev = 0; int aoccur = 0; long asum = 0; for (int key : both) { asum += (long) (key - aprev) * aoccur; mem.merge(key, asum, Long::sum); aprev = key; aoccur += acount.getOrDefault(key, 0); } } { int bprev = 0; int boccur = 0; long bsum = 0; for (int key : both.descendingSet()) { bsum += (long) (bprev - key) * boccur; mem.merge(key, bsum, Long::sum); bprev = key; boccur += bcount.getOrDefault(key, 0); } } long res = Long.MAX_VALUE; for (long val : mem.values()) res = Math.min(res, val); out.printLine(res); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void printLine(long i) { writer.println(i); } } static class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = in.readInt(); return array; } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["2 2\n2 3\n3 5", "3 2\n1 2 3\n3 4", "3 2\n4 5 6\n1 2"]
1 second
["3", "4", "0"]
NoteIn example 1, you can increase a1 by 1 and decrease b2 by 1 and then again decrease b2 by 1. Now array a will be [3; 3] and array b will also be [3; 3]. Here minimum element of a is at least as large as maximum element of b. So minimum number of operations needed to satisfy Devu's condition are 3.In example 3, you don't need to do any operation, Devu's condition is already satisfied.
Java 8
standard input
[ "two pointers", "binary search", "sortings", "ternary search" ]
e0b5169945909cd2809482b7fd7178c2
The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105). The second line will contain n space-separated integers representing content of the array a (1 ≤ ai ≤ 109). The third line will contain m space-separated integers representing content of the array b (1 ≤ bi ≤ 109).
1,700
You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.
standard output
PASSED
b151604db5354678073026a9f33a6516
train_000.jsonl
1401895800
Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother. As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the maximum value of his brother's array b. Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.TreeSet; import java.util.TreeMap; import java.util.Map; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.Collections; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Alex */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(), m = in.readInt(); int[] a = IOUtils.readIntArray(in, n); int[] b = IOUtils.readIntArray(in, m); TreeMap<Integer, Integer> acount = new TreeMap<>(); for (int val : a) acount.merge(val, 1, Integer::sum); TreeMap<Integer, Integer> bcount = new TreeMap<>(); for (int val : b) bcount.merge(val, 1, Integer::sum); TreeSet<Integer> both = new TreeSet<>(); for (int val : a) both.add(val); for (int val : b) both.add(val); TreeMap<Integer, Long> mem = new TreeMap<>(); { int aprev = 0; int aoccur = 0; long asum = 0; for (int key : both) { asum += (long) (key - aprev) * aoccur; mem.merge(key, asum, Long::sum); aprev = key; aoccur += acount.getOrDefault(key, 0); } } { int bprev = 0; int boccur = 0; long bsum = 0; for (int key : both.descendingSet()) { bsum += (long) (bprev - key) * boccur; mem.merge(key, bsum, Long::sum); bprev = key; boccur += bcount.getOrDefault(key, 0); } } out.printLine(Collections.min(mem.values())); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void printLine(long i) { writer.println(i); } } static class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = in.readInt(); return array; } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["2 2\n2 3\n3 5", "3 2\n1 2 3\n3 4", "3 2\n4 5 6\n1 2"]
1 second
["3", "4", "0"]
NoteIn example 1, you can increase a1 by 1 and decrease b2 by 1 and then again decrease b2 by 1. Now array a will be [3; 3] and array b will also be [3; 3]. Here minimum element of a is at least as large as maximum element of b. So minimum number of operations needed to satisfy Devu's condition are 3.In example 3, you don't need to do any operation, Devu's condition is already satisfied.
Java 8
standard input
[ "two pointers", "binary search", "sortings", "ternary search" ]
e0b5169945909cd2809482b7fd7178c2
The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105). The second line will contain n space-separated integers representing content of the array a (1 ≤ ai ≤ 109). The third line will contain m space-separated integers representing content of the array b (1 ≤ bi ≤ 109).
1,700
You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.
standard output
PASSED
9334815dd5d2e026321e53c8e92afeca
train_000.jsonl
1401895800
Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother. As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the maximum value of his brother's array b. Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Collection; import java.util.Locale; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { new Thread(null, new Runnable() { public void run() { try { long prevTime = System.currentTimeMillis(); new Main().run(); System.err.println("Total time: " + (System.currentTimeMillis() - prevTime) + " ms"); System.err.println("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); Object o = solve(); if (o != null) out.println(o); out.close(); in.close(); } private Object solve() throws IOException { int n = ni(); int m = ni(); Integer[] a = new Integer[n]; for(int i =0;i<n;i++) a[i]= ni(); Arrays.sort(a); Integer[] b = new Integer[m]; for(int i =0;i<m;i++) b[i]= ni(); Arrays.sort(b); long[] acum = new long[m+1]; for(int j = m-1;j>=0;j--) acum[j] =acum[j+1]+b[j]; int[] important = union(a,b); int i =0; int j =0; long sum =0; long ret = Long.MAX_VALUE; for(long check : important){ while(i<n && a[i]<= check){ sum+= a[i]; i++; } long up = check * i - sum; while(j<m && b[j]<= check) j++; long down= acum[j] - (m-j) * check; ret = Math.min(ret, up+down); } return ret; } private int[] union(Integer[] arr1, Integer[] arr2) { int n1 = arr1.length; int n2 = arr2.length; int[] aux = new int[n1+n2]; int i =0; int j =0; int index=0; while(i<n1 && j<n2){ while(i+1<n1 && arr1[i]==arr1[i+1]) i++; while(j+1<n2 && arr2[j]==arr2[j+1]) j++; if(arr1[i]==arr2[j]){ aux[index++]=arr1[i]; i++; j++; }else if( arr1[i]<arr2[j]){ aux[index++]=arr1[i]; i++; }else{ aux[index++]=arr2[j]; j++; } } while(i<n1){ aux[index++]=arr1[i]; while(i<n1 && arr1[i]==aux[index-1]) i++; } while(j<n2){ aux[index++]=arr2[j]; while(j<n2 && arr2[j]==aux[index-1]) j++; } int[] ret = new int[index]; System.arraycopy(aux, 0, ret, 0, index); return ret; } BufferedReader in; PrintWriter out; StringTokenizer strTok = new StringTokenizer(""); String nextToken() throws IOException { while (!strTok.hasMoreTokens()) strTok = new StringTokenizer(in.readLine()); return strTok.nextToken(); } int ni() throws IOException { return Integer.parseInt(nextToken()); } long nl() throws IOException { return Long.parseLong(nextToken()); } double nd() throws IOException { return Double.parseDouble(nextToken()); } int[] nia(int size) throws IOException { int[] ret = new int[size]; for (int i = 0; i < size; i++) ret[i] = ni(); return ret; } long[] nla(int size) throws IOException { long[] ret = new long[size]; for (int i = 0; i < size; i++) ret[i] = nl(); return ret; } double[] nda(int size) throws IOException { double[] ret = new double[size]; for (int i = 0; i < size; i++) ret[i] = nd(); return ret; } String nextLine() throws IOException { strTok = new StringTokenizer(""); return in.readLine(); } boolean EOF() throws IOException { while (!strTok.hasMoreTokens()) { String s = in.readLine(); if (s == null) return true; strTok = new StringTokenizer(s); } return false; } void printRepeat(String s, int count) { for (int i = 0; i < count; i++) out.print(s); } void printArray(int[] array) { for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(long[] array) { for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(double[] array) { 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) { 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) { 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) { boolean blank = false; for (Object x : collection) { if (blank) out.print(' '); else blank = true; out.print(x); } out.println(); } static String memoryStatus() { return (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory() >> 20) + "/" + (Runtime.getRuntime().totalMemory() >> 20) + " MB"; } public void pln() { out.println(); } public void pln(int arg) { out.println(arg); } public void pln(long arg) { out.println(arg); } public void pln(double arg) { out.println(arg); } public void pln(String arg) { out.println(arg); } public void pln(boolean arg) { out.println(arg); } public void pln(char arg) { out.println(arg); } public void pln(float arg) { out.println(arg); } public void pln(Object arg) { out.println(arg); } public void p(int arg) { out.print(arg); } public void p(long arg) { out.print(arg); } public void p(double arg) { out.print(arg); } public void p(String arg) { out.print(arg); } public void p(boolean arg) { out.print(arg); } public void p(char arg) { out.print(arg); } public void p(float arg) { out.print(arg); } public void p(Object arg) { out.print(arg); } }
Java
["2 2\n2 3\n3 5", "3 2\n1 2 3\n3 4", "3 2\n4 5 6\n1 2"]
1 second
["3", "4", "0"]
NoteIn example 1, you can increase a1 by 1 and decrease b2 by 1 and then again decrease b2 by 1. Now array a will be [3; 3] and array b will also be [3; 3]. Here minimum element of a is at least as large as maximum element of b. So minimum number of operations needed to satisfy Devu's condition are 3.In example 3, you don't need to do any operation, Devu's condition is already satisfied.
Java 8
standard input
[ "two pointers", "binary search", "sortings", "ternary search" ]
e0b5169945909cd2809482b7fd7178c2
The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105). The second line will contain n space-separated integers representing content of the array a (1 ≤ ai ≤ 109). The third line will contain m space-separated integers representing content of the array b (1 ≤ bi ≤ 109).
1,700
You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.
standard output
PASSED
4e1448bae404b1caa4f7b614ec42daae
train_000.jsonl
1401895800
Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother. As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the maximum value of his brother's array b. Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; public class P439D { public static void main(String[] args) { FastScanner scan = new FastScanner(); int n = scan.nextInt(); int m = scan.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = scan.nextInt(); int[] b = new int[m]; for (int i = 0; i < m; i++) b[i] = scan.nextInt(); int lo = 1, hi = 1_000_000_000; while (lo+1 < hi) { int m1 = lo + (hi-lo+1)/3; int m2 = hi - (hi-lo+1)/3; long t1 = totalMoves(a, b, m1); long t2 = totalMoves(a, b, m2); if (t1 < t2) hi = m2; else lo = m1; } long min = Long.MAX_VALUE; for (int i = -10; i <= 10; i++) min = Math.min(min, totalMoves(a, b, lo+i)); System.out.println(min); } private static long totalMoves(int[] a, int[] b, int mid) { long t = 0; for (int i = 0; i < a.length; i++) { if (a[i] < mid) t += mid-a[i]; } for (int i = 0; i < b.length; i++) { if (b[i] > mid) t += b[i]-mid; } return t; } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { try { br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } } public String next() { if (st.hasMoreTokens()) return st.nextToken(); try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public String nextLine() { String line = ""; try { line = br.readLine(); } catch (Exception e) { e.printStackTrace(); } return line; } } }
Java
["2 2\n2 3\n3 5", "3 2\n1 2 3\n3 4", "3 2\n4 5 6\n1 2"]
1 second
["3", "4", "0"]
NoteIn example 1, you can increase a1 by 1 and decrease b2 by 1 and then again decrease b2 by 1. Now array a will be [3; 3] and array b will also be [3; 3]. Here minimum element of a is at least as large as maximum element of b. So minimum number of operations needed to satisfy Devu's condition are 3.In example 3, you don't need to do any operation, Devu's condition is already satisfied.
Java 8
standard input
[ "two pointers", "binary search", "sortings", "ternary search" ]
e0b5169945909cd2809482b7fd7178c2
The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105). The second line will contain n space-separated integers representing content of the array a (1 ≤ ai ≤ 109). The third line will contain m space-separated integers representing content of the array b (1 ≤ bi ≤ 109).
1,700
You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.
standard output
PASSED
40c1120288f66cc6b15bc529c50b536c
train_000.jsonl
1401895800
Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother. As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the maximum value of his brother's array b. Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.
256 megabytes
import java.io.*; import java.util.*; public class Solution { static Scanner sc=new Scanner(System.in); static PrintWriter out=new PrintWriter(System.out); //Main static int n,m; static long a[],b[]; static long check(long x) { long res=0; for(int i=0;i<n;i++) res+=Math.max(0, x-a[i]); for(int i=0;i<m;i++) res+=Math.max(0, b[i]-x); return res; } public static void main(String args[]) { int test=1; //test=sc.nextInt(); while(test-->0) { //Focus n=sc.nextInt();m=sc.nextInt();a=new long[n];b=new long[m]; for(int i=0;i<n;i++) a[i]=sc.nextLong(); for(int i=0;i<m;i++) b[i]=sc.nextLong(); long l=0,r=(long)1e9+1; while(r-l>=3) { long m1=l+(r-l)/3,m2=r-(r-l)/3; long f1=check(m1),f2=check(m2); if(f2<f1) l=m1; else r=m2; } long ans=Long.MAX_VALUE; for(;l<=r;l++) ans=Math.min(ans,check(l)); out.println(ans); } out.flush(); out.close(); } }
Java
["2 2\n2 3\n3 5", "3 2\n1 2 3\n3 4", "3 2\n4 5 6\n1 2"]
1 second
["3", "4", "0"]
NoteIn example 1, you can increase a1 by 1 and decrease b2 by 1 and then again decrease b2 by 1. Now array a will be [3; 3] and array b will also be [3; 3]. Here minimum element of a is at least as large as maximum element of b. So minimum number of operations needed to satisfy Devu's condition are 3.In example 3, you don't need to do any operation, Devu's condition is already satisfied.
Java 8
standard input
[ "two pointers", "binary search", "sortings", "ternary search" ]
e0b5169945909cd2809482b7fd7178c2
The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105). The second line will contain n space-separated integers representing content of the array a (1 ≤ ai ≤ 109). The third line will contain m space-separated integers representing content of the array b (1 ≤ bi ≤ 109).
1,700
You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.
standard output
PASSED
8b48792482d1358bf320d17b3f9dda28
train_000.jsonl
1401895800
Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother. As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the maximum value of his brother's array b. Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class Main { int n, m; int[] aa, bb; public long f(int k){ long res = 0; for(int i = 0; i < n; i++){ res += Math.max(k - aa[i], 0); } for(int i = 0; i < m; i++){ res += Math.max(bb[i] - k, 0); } return res; } public void solve() throws IOException{ n = in.nextInt(); m = in.nextInt(); aa = new int[n]; bb = new int[m]; for(int i = 0; i < n; i++){ aa[i] = in.nextInt(); } for(int i = 0; i < m; i++){ bb[i] = in.nextInt(); } int l = 0, r = 1000000001; long res = Long.MAX_VALUE; for(int i = 0; i < 100; i++){ int m1 = l + (r - l) / 3; int m2 = r - (r - l) / 3; long v1 = f(m1); long v2 = f(m2); res = Math.min(res, v1); res = Math.min(res, v2); if(v1 > v2){ l = m1; }else{ r = m2; } } out.println(res); } public BigInteger gcdBigInt(BigInteger a, BigInteger b){ if(a.compareTo(BigInteger.valueOf(0L)) == 0){ return b; }else{ return gcdBigInt(b.mod(a), a); } } FastScanner in; PrintWriter out; static class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = null; } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { if (st == null || !st.hasMoreTokens()) return br.readLine(); StringBuilder result = new StringBuilder(st.nextToken()); while (st.hasMoreTokens()) { result.append(" "); result.append(st.nextToken()); } return result.toString(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } } void run() throws IOException { in = new FastScanner(System.in); out = new PrintWriter(System.out, false); solve(); out.close(); } public static void main(String[] args) throws IOException{ new Main().run(); } public void printArr(int[] arr){ for(int i = 0; i < arr.length; i++){ out.print(arr[i] + " "); } out.println(); } public long gcd(long a, long b){ if(a == 0) return b; return gcd(b % a, a); } public boolean isPrime(long num){ if(num == 0 || num == 1){ return false; } for(int i = 2; i * i <= num; i++){ if(num % i == 0){ return false; } } return true; } public class Pair<A, B>{ public A x; public B y; Pair(A x, B 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; if (!x.equals(pair.x)) return false; return y.equals(pair.y); } @Override public int hashCode() { int result = x.hashCode(); result = 31 * result + y.hashCode(); return result; } } class Tuple{ int x; int y; int z; Tuple(int ix, int iy, int iz){ x = ix; y = iy; z = iz; } } }
Java
["2 2\n2 3\n3 5", "3 2\n1 2 3\n3 4", "3 2\n4 5 6\n1 2"]
1 second
["3", "4", "0"]
NoteIn example 1, you can increase a1 by 1 and decrease b2 by 1 and then again decrease b2 by 1. Now array a will be [3; 3] and array b will also be [3; 3]. Here minimum element of a is at least as large as maximum element of b. So minimum number of operations needed to satisfy Devu's condition are 3.In example 3, you don't need to do any operation, Devu's condition is already satisfied.
Java 8
standard input
[ "two pointers", "binary search", "sortings", "ternary search" ]
e0b5169945909cd2809482b7fd7178c2
The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105). The second line will contain n space-separated integers representing content of the array a (1 ≤ ai ≤ 109). The third line will contain m space-separated integers representing content of the array b (1 ≤ bi ≤ 109).
1,700
You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.
standard output
PASSED
f399a6fc88c3e513fa00811f05b2e6ba
train_000.jsonl
1401895800
Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother. As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the maximum value of his brother's array b. Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class DevuandhisBrother { static long[] a, b; static boolean hat(long x) { long y = x + 1; long res1 = 0; long res2 = 0; for (int i = 0; i < a.length; i++) { if (x > a[i]) res1 += x - a[i]; if (y > a[i]) res2 += y - a[i]; } for (int i = b.length - 1; i > -1; i--) { if (b[i] > x) res1 += b[i] - x; if (b[i] > y) res2 += b[i] - y; } return res1 > res2; } static long get(long x) { long res = 0; for (int i = 0; i < a.length; i++) { if (x > a[i]) res += x - a[i]; } for (int i = 0; i < b.length; i++) { if (x < b[i]) res += b[i] - x; } return res; } public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); sc = new StringTokenizer(""); int n = nxtInt(); int m = nxtInt(); a = nxtLngArr(n); b = nxtLngArr(m); // Arrays.sort(a); // Arrays.sort(b); // long lo = a[0]; // long hi = b[m - 1]; // while (lo < hi) { // long mid = (lo + hi) / 2; // if (hat(mid)) // lo = mid + 1; // else // hi = mid; // } // long res = 0; // for (int i = 0; i < a.length && lo > a[i]; i++) // res += lo - a[i]; // for (int i = b.length - 1; i > -1 && b[i] > lo; i--) // res += b[i] - lo; // out.println(res); long lo = 0; long hi = 1000000007; while (lo < hi) { long mid1 = lo + (hi - lo) / 3; long mid2 = lo + 2 * (hi - lo) / 3; long res1 = get(mid1); long res2 = get(mid2); if (res1 > res2) { lo = mid1 + 1; } else { hi = mid2; } } out.println(Math.min(get(lo), get(hi))); br.close(); out.close(); } static BufferedReader br; static StringTokenizer sc; static PrintWriter out; static String nxtTok() throws IOException { while (!sc.hasMoreTokens()) { String s = br.readLine(); if (s == null) return null; sc = new StringTokenizer(s.trim()); } return sc.nextToken(); } static int nxtInt() throws IOException { return Integer.parseInt(nxtTok()); } static long nxtLng() throws IOException { return Long.parseLong(nxtTok()); } static double nxtDbl() throws IOException { return Double.parseDouble(nxtTok()); } static int[] nxtIntArr(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nxtInt(); return a; } static long[] nxtLngArr(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nxtLng(); return a; } static char[] nxtCharArr() throws IOException { return nxtTok().toCharArray(); } }
Java
["2 2\n2 3\n3 5", "3 2\n1 2 3\n3 4", "3 2\n4 5 6\n1 2"]
1 second
["3", "4", "0"]
NoteIn example 1, you can increase a1 by 1 and decrease b2 by 1 and then again decrease b2 by 1. Now array a will be [3; 3] and array b will also be [3; 3]. Here minimum element of a is at least as large as maximum element of b. So minimum number of operations needed to satisfy Devu's condition are 3.In example 3, you don't need to do any operation, Devu's condition is already satisfied.
Java 8
standard input
[ "two pointers", "binary search", "sortings", "ternary search" ]
e0b5169945909cd2809482b7fd7178c2
The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105). The second line will contain n space-separated integers representing content of the array a (1 ≤ ai ≤ 109). The third line will contain m space-separated integers representing content of the array b (1 ≤ bi ≤ 109).
1,700
You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.
standard output
PASSED
4cc13276b4eccaceeee12e2e3782a928
train_000.jsonl
1401895800
Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother. As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the maximum value of his brother's array b. Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; public class Main { long[]a; long[]b; long min = (long) Math.pow(20, 9); long max = 0; public static void main(String[] args) { // TODO Auto-generated method stub Main t = new Main(); try{ InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); String[]input; input = (br.readLine()).split(" "); int n = Integer.parseInt(input[0]); int m = Integer.parseInt(input[1]); t.a = new long[n]; t.b = new long[m]; input = (br.readLine()).split(" "); long temp; for (int i = 0; i < input.length; i++) { temp = Long.parseLong(input[i]); t.a[i] = temp; if(temp < t.min){ t.min = temp; } } input = (br.readLine()).split(" "); for (int i = 0; i < input.length; i++) { temp = Long.parseLong(input[i]); t.b[i] = temp; if(temp > t.max){ t.max = temp; } } if(t.min < t.max){ System.out.printf("%d\n", t.minStep()); }else{ System.out.println("0"); } }catch(Exception e){ } } long minStep(){ long low = min - 10; long high = max + 10; double min = Math.pow(Math.E, -9); long t1; long t2; long steps1 = 0; long steps2 = 0; while(high - low > 0 ) { t1 = low + ((high - low) / 3); t2 = low + (2* (high - low) / 3); steps1 = numberSteps(t1); steps2= numberSteps(t2); if(steps1 > steps2){ low = t1+1; }else{ high = t2; } } return steps1; } long numberSteps(long num){ long steps = 0; for (int i = 0; i < a.length; i++) { if(a[i] < num){ steps = steps + num - a[i]; } } for (int i = b.length-1; i >= 0 ; i--) { if(b[i] > num){ steps = steps + b[i] - num; } } return steps; } }
Java
["2 2\n2 3\n3 5", "3 2\n1 2 3\n3 4", "3 2\n4 5 6\n1 2"]
1 second
["3", "4", "0"]
NoteIn example 1, you can increase a1 by 1 and decrease b2 by 1 and then again decrease b2 by 1. Now array a will be [3; 3] and array b will also be [3; 3]. Here minimum element of a is at least as large as maximum element of b. So minimum number of operations needed to satisfy Devu's condition are 3.In example 3, you don't need to do any operation, Devu's condition is already satisfied.
Java 8
standard input
[ "two pointers", "binary search", "sortings", "ternary search" ]
e0b5169945909cd2809482b7fd7178c2
The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105). The second line will contain n space-separated integers representing content of the array a (1 ≤ ai ≤ 109). The third line will contain m space-separated integers representing content of the array b (1 ≤ bi ≤ 109).
1,700
You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.
standard output
PASSED
db86b99c41d4ada8c574b6a5880090cf
train_000.jsonl
1401895800
Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother. As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the maximum value of his brother's array b. Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public final class devu_bro { static BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); static FastScanner sc=new FastScanner(br); static PrintWriter out=new PrintWriter(System.out); static Random rnd=new Random(); static long[] a,b; static int n,m; static long f(long mid) { long ret=0; for(int i=0;i<m;i++) { if(b[i]>mid) { ret+=(b[i]-mid); } } for(int i=0;i<n;i++) { if(a[i]<mid) { ret+=(mid-a[i]); } } return ret; } static void shuffle(long[] a) { for(int i=0;i<a.length;i++) { int next=rnd.nextInt(a.length); long temp=a[i];a[i]=a[next];a[next]=temp; } } public static void main(String args[]) throws Exception { n=sc.nextInt();m=sc.nextInt();a=new long[n];b=new long[m]; for(int i=0;i<n;i++) { a[i]=sc.nextInt(); } for(int i=0;i<m;i++) { b[i]=sc.nextInt(); } long low=1,high=(long)(2e9); while(high-low>1) { long mid=(low+high)>>1; if(f(mid)<f(mid+1)) { high=mid; } else { low=mid; } } out.println(Math.min(f(low),f(high)));out.close(); } } class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() throws Exception { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } public String next() throws Exception { return nextToken().toString(); } public int nextInt() throws Exception { return Integer.parseInt(nextToken()); } public long nextLong() throws Exception { return Long.parseLong(nextToken()); } public double nextDouble() throws Exception { return Double.parseDouble(nextToken()); } }
Java
["2 2\n2 3\n3 5", "3 2\n1 2 3\n3 4", "3 2\n4 5 6\n1 2"]
1 second
["3", "4", "0"]
NoteIn example 1, you can increase a1 by 1 and decrease b2 by 1 and then again decrease b2 by 1. Now array a will be [3; 3] and array b will also be [3; 3]. Here minimum element of a is at least as large as maximum element of b. So minimum number of operations needed to satisfy Devu's condition are 3.In example 3, you don't need to do any operation, Devu's condition is already satisfied.
Java 8
standard input
[ "two pointers", "binary search", "sortings", "ternary search" ]
e0b5169945909cd2809482b7fd7178c2
The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105). The second line will contain n space-separated integers representing content of the array a (1 ≤ ai ≤ 109). The third line will contain m space-separated integers representing content of the array b (1 ≤ bi ≤ 109).
1,700
You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.
standard output
PASSED
95893efe21e8be9ac5fe91e3018a0b51
train_000.jsonl
1401895800
Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother. As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the maximum value of his brother's array b. Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.
256 megabytes
import java.io.*; import java.util.*; public class MainClass { public static void main(String[] args)throws IOException { Reader in = new Reader(); int n = in.nextInt(); int m = in.nextInt(); long[] A = new long[n]; long[] B = new long[m]; for (int i=0;i<n;i++) A[i] = in.nextLong(); for (int i=0;i<m;i++) B[i] = in.nextLong(); long sum = 0L; new MergeSortLong().sort(A, 0, n - 1); new MergeSortLong().sort(B, 0, m - 1); for (int i=0;i<m/2;i++) { long temp = B[i]; B[i] = B[m - 1 - i]; B[m - 1 - i] = temp; } for (int i=0;i<Math.min(n, m);i++) { if (A[i] < B[i]) { sum += B[i] - A[i]; } else break; } System.out.println(sum); } } 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(); } } class MergeSortLong { // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] void merge(long arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ long L[] = new long[n1]; long R[] = new long[n2]; /*Copy data to temp arrays*/ for (int i = 0; i < n1; ++i) L[i] = arr[l + i]; for (int j = 0; j < n2; ++j) R[j] = arr[m + 1 + j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } // Main function that sorts arr[l..r] using // merge() void sort(long arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l + r) / 2; // Sort first and second halves sort(arr, l, m); sort(arr, m + 1, r); // Merge the sorted halves merge(arr, l, m, r); } } }
Java
["2 2\n2 3\n3 5", "3 2\n1 2 3\n3 4", "3 2\n4 5 6\n1 2"]
1 second
["3", "4", "0"]
NoteIn example 1, you can increase a1 by 1 and decrease b2 by 1 and then again decrease b2 by 1. Now array a will be [3; 3] and array b will also be [3; 3]. Here minimum element of a is at least as large as maximum element of b. So minimum number of operations needed to satisfy Devu's condition are 3.In example 3, you don't need to do any operation, Devu's condition is already satisfied.
Java 8
standard input
[ "two pointers", "binary search", "sortings", "ternary search" ]
e0b5169945909cd2809482b7fd7178c2
The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105). The second line will contain n space-separated integers representing content of the array a (1 ≤ ai ≤ 109). The third line will contain m space-separated integers representing content of the array b (1 ≤ bi ≤ 109).
1,700
You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.
standard output
PASSED
64492d57c6498ff8924b37dae4f454be
train_000.jsonl
1401895800
Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother. As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the maximum value of his brother's array b. Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.
256 megabytes
import java.awt.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class CandidateCode { static int a[],b[],n,m; public static void main(String[] args) throws IOException { FastReader sc = new FastReader(); n=sc.nextInt();m= sc.nextInt(); a=new int[n];b=new int[m]; for (int i=0;i<n;i++)a[i]=sc.nextInt(); for (int i=0;i<m;i++)b[i]=sc.nextInt(); System.out.println(ternary()); } /* Ternary Search: is used when a function f is (strictly) increases first then (strictly) decreases (Concave function) Or when f (strictly) decreases first and then (strictly) increases(Convex) in interval [l,r] to find maximum and minimum point respectively . For Convexity (2nd Derivative) f″(x)>=0 For Concave function:(Concave function = - Convex Function) choose two point m1 and m2 such that l<m1<m2<r if f(m1)<f(m2) then ans belongs to [m1,r] else if f(m1)>f(m2) then ans belongs to [l,m2] else if f(m1)==f(m2) then ans belongs to [m1,m2](this condition can be merged with previous ones) */ static long ternary(){ int lo=1,hi=1000000000; long ans=(long)1e18; long val=1; for (int it=0;it<100;it++){// use iterations to avoid infinite loop int m1=lo+(hi-lo)/3; int m2=hi-(hi-lo)/3; if (f(m1)<ans){ ans=f(m1); val=m1; } if (f(m2)<ans){ ans=f(m2); val=m2; } if (f(m1)>=f(m2)){// to find minimum func. in convex func. lo=m1; }else { hi=m2; } // if (f(m1)<=f(m2)){ // to find maximum point in concave func. // lo=m1; // }else { // hi=m2; // } } return ans; } static long f(int k){ long ans=0; for (int i=0;i<n;i++){ if (a[i]<k)ans+=k-a[i]; } for (int i=0;i<m;i++){ if (b[i]>k)ans+=b[i]-k; } return ans; } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int 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 2\n2 3\n3 5", "3 2\n1 2 3\n3 4", "3 2\n4 5 6\n1 2"]
1 second
["3", "4", "0"]
NoteIn example 1, you can increase a1 by 1 and decrease b2 by 1 and then again decrease b2 by 1. Now array a will be [3; 3] and array b will also be [3; 3]. Here minimum element of a is at least as large as maximum element of b. So minimum number of operations needed to satisfy Devu's condition are 3.In example 3, you don't need to do any operation, Devu's condition is already satisfied.
Java 8
standard input
[ "two pointers", "binary search", "sortings", "ternary search" ]
e0b5169945909cd2809482b7fd7178c2
The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105). The second line will contain n space-separated integers representing content of the array a (1 ≤ ai ≤ 109). The third line will contain m space-separated integers representing content of the array b (1 ≤ bi ≤ 109).
1,700
You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.
standard output
PASSED
86e6a42d29bb3f643ebe36176c2c3ded
train_000.jsonl
1401895800
Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother. As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the maximum value of his brother's array b. Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.
256 megabytes
import java.io.*; import java.lang.*; import java.util.*; import java.text.*; public class Main { public static void main(String[] args) throws IOException { //BufferedReader cin = new BufferedReader(new FileReader("test.txt")); BufferedReader cin = new BufferedReader(new InputStreamReader(System.in)); String line; StringTokenizer st; line = cin.readLine(); st = new StringTokenizer(line); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); //int b = Integer.parseInt(st.nextToken()); ArrayList<Integer> a = new ArrayList<Integer>(n); ArrayList<Integer> b = new ArrayList<Integer>(n); line = cin.readLine(); st = new StringTokenizer(line); int t; for(int i=0;i<n;i++){ t=Integer.parseInt(st.nextToken()); a.add(t); } line = cin.readLine(); st = new StringTokenizer(line); //int t; for(int i=0;i<m;i++){ t=Integer.parseInt(st.nextToken()); b.add(t); } Collections.sort(a); Collections.sort(b,Collections.reverseOrder()); long count=0; for(int i=0;i<Math.min(n,m);i++){ if(b.get(i)>a.get(i))count+=(long)b.get(i)-a.get(i); else break; } System.out.println(count); cin.close(); } }
Java
["2 2\n2 3\n3 5", "3 2\n1 2 3\n3 4", "3 2\n4 5 6\n1 2"]
1 second
["3", "4", "0"]
NoteIn example 1, you can increase a1 by 1 and decrease b2 by 1 and then again decrease b2 by 1. Now array a will be [3; 3] and array b will also be [3; 3]. Here minimum element of a is at least as large as maximum element of b. So minimum number of operations needed to satisfy Devu's condition are 3.In example 3, you don't need to do any operation, Devu's condition is already satisfied.
Java 8
standard input
[ "two pointers", "binary search", "sortings", "ternary search" ]
e0b5169945909cd2809482b7fd7178c2
The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105). The second line will contain n space-separated integers representing content of the array a (1 ≤ ai ≤ 109). The third line will contain m space-separated integers representing content of the array b (1 ≤ bi ≤ 109).
1,700
You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.
standard output
PASSED
681771e7dffc3d5abf14c4cdc193cb35
train_000.jsonl
1401895800
Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother. As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the maximum value of his brother's array b. Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.
256 megabytes
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class Main { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(), m = ni(); int[] a = na(n); int[] b = na(m); long mina = Long.MAX_VALUE; long maxb = Long.MIN_VALUE; for(int i = 0; i < n; i++) { mina = Math.min(mina, a[i]); } for(int i = 0; i < m; i++) { maxb = Math.max(maxb, b[i]); } if(mina >= maxb) { out.println(0); return; } long low = 0, high = 1000000007; long ans = ternarySearch(low, high, a, b); out.println(ans); } public long f(long x, int[] a, int[] b) { long ret = 0; for(int v : a) { if(v < x) ret += x - v; } for(int v : b) { if(v > x) ret += v - x; } return ret; } public long ternarySearch(long low, long high, int[] a, int[] b) { while(low <= high) { if(low == high) break; long mid1 = low + (high - low) / 3; long mid2 = high + (low - high) / 3; long vl = f(mid1, a, b); long vh = f(mid2, a, b); if(vl > vh) { low = mid1 + 1; } else { high = mid2 - 1; } } return f(low, a, b); } 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 Main().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } private double nd() { return Double.parseDouble(ns()); } private float nf() { return Float.parseFloat(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 2\n2 3\n3 5", "3 2\n1 2 3\n3 4", "3 2\n4 5 6\n1 2"]
1 second
["3", "4", "0"]
NoteIn example 1, you can increase a1 by 1 and decrease b2 by 1 and then again decrease b2 by 1. Now array a will be [3; 3] and array b will also be [3; 3]. Here minimum element of a is at least as large as maximum element of b. So minimum number of operations needed to satisfy Devu's condition are 3.In example 3, you don't need to do any operation, Devu's condition is already satisfied.
Java 8
standard input
[ "two pointers", "binary search", "sortings", "ternary search" ]
e0b5169945909cd2809482b7fd7178c2
The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105). The second line will contain n space-separated integers representing content of the array a (1 ≤ ai ≤ 109). The third line will contain m space-separated integers representing content of the array b (1 ≤ bi ≤ 109).
1,700
You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.
standard output
PASSED
8eb8022771a630865b15c26b28b1d748
train_000.jsonl
1401895800
Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother. As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the maximum value of his brother's array b. Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); Integer[] a = new Integer[n]; Integer[] b = new Integer[m]; for (int i = 0; i < n; i++) a[i] = in.nextInt(); for (int i = 0; i < m; i++) b[i] = in.nextInt(); Arrays.sort(a); Arrays.sort(b); long cnt = 0; long diff = b[m - 1] - a[0]; // diff is positive if brother has more int l = 1; int r = 1; while (diff > 0) { if (l < r) { if (l == n) { cnt += l * diff; diff = 0; } else { long next = Math.min(a[l] - a[l - 1], diff); cnt += next * l; diff -= next; l++; } } else { if (r == m) { cnt += r * diff; diff = 0; } else { long next = Math.min(b[m - r] - b[m - r - 1], diff); cnt += next * r; diff -= next; r++; } } } out.println(cnt); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["2 2\n2 3\n3 5", "3 2\n1 2 3\n3 4", "3 2\n4 5 6\n1 2"]
1 second
["3", "4", "0"]
NoteIn example 1, you can increase a1 by 1 and decrease b2 by 1 and then again decrease b2 by 1. Now array a will be [3; 3] and array b will also be [3; 3]. Here minimum element of a is at least as large as maximum element of b. So minimum number of operations needed to satisfy Devu's condition are 3.In example 3, you don't need to do any operation, Devu's condition is already satisfied.
Java 8
standard input
[ "two pointers", "binary search", "sortings", "ternary search" ]
e0b5169945909cd2809482b7fd7178c2
The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105). The second line will contain n space-separated integers representing content of the array a (1 ≤ ai ≤ 109). The third line will contain m space-separated integers representing content of the array b (1 ≤ bi ≤ 109).
1,700
You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.
standard output
PASSED
e107e73ffd09760dc6d29788cdd593d6
train_000.jsonl
1401895800
Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother. As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the maximum value of his brother's array b. Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.
256 megabytes
import java.io.*; import java.util.Arrays; import java.util.Collections; public class D { public static void main(String[] args) throws Exception{ Integer[] first = IO.nextIntArray(2, " "); Integer[] d1 = IO.nextIntArray(first[0], " "); Integer[] d2 = IO.nextIntArray(first[1], " "); Arrays.sort(d1); Arrays.sort(d2, Collections.reverseOrder()); int upto = Math.min(d1.length, d2.length); long diff=0; for(int i=0;i<upto;++i){ if(d1[i]>=d2[i])break; // IO.println("d1[i] = "+d1[i]+" d2[i] = "+d2[i]); diff+=Math.abs(d1[i]-d2[i]); } IO.println(diff); } static class IO { static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public static Integer[] nextIntArray(int nInts, String seperator) throws IOException { String ints = br.readLine(); String[] sArray = ints.split(seperator); Integer[] array = new Integer[nInts]; for (int i = 0; i < nInts; ++i) { array[i] = Integer.parseInt(sArray[i]); } return array; } public static long[] nextLongArray(int nLongs, String seperator) throws IOException { String longs = br.readLine(); String[] sArray = longs.split(seperator); long[] array = new long[nLongs + 1]; for (int i = 1; i <= nLongs; ++i) { array[i] = Long.parseLong(sArray[i - 1]); } return array; } public static double[] nextDoubleArray(int nDoubles, String seperator) throws IOException { String doubles = br.readLine(); String[] sArray = doubles.split(seperator); double[] array = new double[nDoubles + 1]; for (int i = 1; i <= nDoubles; ++i) { array[i] = Double.parseDouble(sArray[i - 1]); } return array; } public static char[] nextCharArray(int nChars, String seperator) throws IOException { String chars = br.readLine(); String[] sArray = chars.split(seperator); char[] array = new char[nChars + 1]; for (int i = 1; i <= nChars; ++i) { array[i] = sArray[i - 1].charAt(0); } return array; } public static int nextInt() throws IOException { String in = br.readLine(); return Integer.parseInt(in); } public static double nextDouble() throws IOException { String in = br.readLine(); return Double.parseDouble(in); } public static long nextLong() throws IOException { String in = br.readLine(); return Long.parseLong(in); } public static int nextChar() throws IOException { String in = br.readLine(); return in.charAt(0); } public static String nextString() throws IOException { return br.readLine(); } public static void print(Object... o) { for (Object os : o) { System.out.print(os); } } public static void println(Object... o) { for (Object os : o) { System.out.print(os); } System.out.print("\n"); } public static void printlnSeperate(String seperator, Object... o) { StringBuilder sb = new StringBuilder(); sb.delete(sb.length() - seperator.length(), sb.length()); System.out.println(sb); } } }
Java
["2 2\n2 3\n3 5", "3 2\n1 2 3\n3 4", "3 2\n4 5 6\n1 2"]
1 second
["3", "4", "0"]
NoteIn example 1, you can increase a1 by 1 and decrease b2 by 1 and then again decrease b2 by 1. Now array a will be [3; 3] and array b will also be [3; 3]. Here minimum element of a is at least as large as maximum element of b. So minimum number of operations needed to satisfy Devu's condition are 3.In example 3, you don't need to do any operation, Devu's condition is already satisfied.
Java 8
standard input
[ "two pointers", "binary search", "sortings", "ternary search" ]
e0b5169945909cd2809482b7fd7178c2
The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105). The second line will contain n space-separated integers representing content of the array a (1 ≤ ai ≤ 109). The third line will contain m space-separated integers representing content of the array b (1 ≤ bi ≤ 109).
1,700
You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.
standard output
PASSED
e4e126ad51cd870673dae8c5c54a43f7
train_000.jsonl
1401895800
Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother. As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the maximum value of his brother's array b. Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.
256 megabytes
import java.util.*; import java.io.*; public class b{ static void shuffle(int [] a){ Random rn=new Random(); for(int i=a.length-1;i>0;i--){ int ind=rn.nextInt(i); int temp=a[ind]; a[ind]=a[i]; a[i]=temp; } Arrays.sort(a); } static long f(int [] a,int [] b,long k){ long ans=0; for(int i : a)if(i<=k)ans+=(long)(k-(long)i); for(int i: b)if(i>=k)ans+=(long)((long)i-k); return ans; } public static void main(String [] args) throws IOException{ FastScanner sc=new FastScanner(); PrintWriter out=new PrintWriter(System.out); int n=sc.nextInt(); int m=sc.nextInt(); int [] a=sc.nextIntArray(n); int [] b=sc.nextIntArray(m); shuffle(a); shuffle(b); if(a[0]>=b[m-1]){ out.println(0); out.close(); return; } long l=(long)(1),r=(long)(1e9); long ans=(long)(1e18); int i=0; while(l<=r && i<=100){ long mid1=l+(r-l)/3; long mid2=r-(r-l)/3; long amid1=f(a,b,mid1); long amid2=f(a,b,mid2); if(amid2<=amid1){ ans=Math.min(ans,amid2); l=mid1; } else{ ans=Math.min(ans,amid1); r=mid2; } i++; } out.println(ans); out.close(); } } class FastScanner{ private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public FastScanner() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public FastScanner( String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public String next() throws IOException{ byte c = read(); while(Character.isWhitespace(c)){ c = read(); } StringBuilder builder = new StringBuilder(); builder.append((char)c); c = read(); while(!Character.isWhitespace(c)){ builder.append((char)c); c = read(); } return builder.toString(); } public 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 int[] nextIntArray( int n) throws IOException { int arr[] = new int[n]; for(int i = 0; i < n; i++){ arr[i] = nextInt(); } return arr; } 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 long[] nextLongArray( int n) throws IOException { long arr[] = new long[n]; for(int i = 0; i < n; i++){ arr[i] = nextLong(); } return arr; } public char nextChar() throws IOException{ byte c = read(); while(Character.isWhitespace(c)){ c = read(); } return (char) c; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } public double[] nextDoubleArray( int n) throws IOException { double arr[] = new double[n]; for(int i = 0; i < n; i++){ arr[i] = nextDouble(); } return arr; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } }
Java
["2 2\n2 3\n3 5", "3 2\n1 2 3\n3 4", "3 2\n4 5 6\n1 2"]
1 second
["3", "4", "0"]
NoteIn example 1, you can increase a1 by 1 and decrease b2 by 1 and then again decrease b2 by 1. Now array a will be [3; 3] and array b will also be [3; 3]. Here minimum element of a is at least as large as maximum element of b. So minimum number of operations needed to satisfy Devu's condition are 3.In example 3, you don't need to do any operation, Devu's condition is already satisfied.
Java 8
standard input
[ "two pointers", "binary search", "sortings", "ternary search" ]
e0b5169945909cd2809482b7fd7178c2
The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105). The second line will contain n space-separated integers representing content of the array a (1 ≤ ai ≤ 109). The third line will contain m space-separated integers representing content of the array b (1 ≤ bi ≤ 109).
1,700
You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.
standard output
PASSED
686c5283ab645d2fab7ba33432e7e2a5
train_000.jsonl
1401895800
Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother. As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the maximum value of his brother's array b. Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.
256 megabytes
import java.util.*; import java.io.*; public class b{ static void shuffle(int [] a){ Random rn=new Random(); for(int i=a.length-1;i>0;i--){ int ind=rn.nextInt(i); int temp=a[ind]; a[ind]=a[i]; a[i]=temp; } Arrays.sort(a); } static long f(int [] a,int [] b,long k){ long ans=0; for(int i : a)if(i<=k)ans+=(long)(k-(long)i); for(int i: b)if(i>=k)ans+=(long)((long)i-k); return ans; } public static void main(String [] args) throws IOException{ FastScanner sc=new FastScanner(); PrintWriter out=new PrintWriter(System.out); int n=sc.nextInt(); int m=sc.nextInt(); int [] a=sc.nextIntArray(n); int [] b=sc.nextIntArray(m); shuffle(a); shuffle(b); if(a[0]>=b[m-1]){ out.println(0); out.close(); return; } long l=(long)(1),r=(long)(1e9); long ans=(long)(1e18); int i=0; while(l<=r && i<=200){ long mid1=l+(r-l)/3; long mid2=r-(r-l)/3; long amid1=f(a,b,mid1); long amid2=f(a,b,mid2); if(amid2<=amid1){ ans=Math.min(ans,amid2); l=mid1; } else{ ans=Math.min(ans,amid1); r=mid2; } i++; } out.println(ans); out.close(); } } class FastScanner{ private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public FastScanner() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public FastScanner( String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public String next() throws IOException{ byte c = read(); while(Character.isWhitespace(c)){ c = read(); } StringBuilder builder = new StringBuilder(); builder.append((char)c); c = read(); while(!Character.isWhitespace(c)){ builder.append((char)c); c = read(); } return builder.toString(); } public 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 int[] nextIntArray( int n) throws IOException { int arr[] = new int[n]; for(int i = 0; i < n; i++){ arr[i] = nextInt(); } return arr; } 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 long[] nextLongArray( int n) throws IOException { long arr[] = new long[n]; for(int i = 0; i < n; i++){ arr[i] = nextLong(); } return arr; } public char nextChar() throws IOException{ byte c = read(); while(Character.isWhitespace(c)){ c = read(); } return (char) c; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } public double[] nextDoubleArray( int n) throws IOException { double arr[] = new double[n]; for(int i = 0; i < n; i++){ arr[i] = nextDouble(); } return arr; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } }
Java
["2 2\n2 3\n3 5", "3 2\n1 2 3\n3 4", "3 2\n4 5 6\n1 2"]
1 second
["3", "4", "0"]
NoteIn example 1, you can increase a1 by 1 and decrease b2 by 1 and then again decrease b2 by 1. Now array a will be [3; 3] and array b will also be [3; 3]. Here minimum element of a is at least as large as maximum element of b. So minimum number of operations needed to satisfy Devu's condition are 3.In example 3, you don't need to do any operation, Devu's condition is already satisfied.
Java 8
standard input
[ "two pointers", "binary search", "sortings", "ternary search" ]
e0b5169945909cd2809482b7fd7178c2
The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105). The second line will contain n space-separated integers representing content of the array a (1 ≤ ai ≤ 109). The third line will contain m space-separated integers representing content of the array b (1 ≤ bi ≤ 109).
1,700
You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.
standard output
PASSED
9b1a46b76b8e10eef4d02a351356632f
train_000.jsonl
1401895800
Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother. As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the maximum value of his brother's array b. Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.
256 megabytes
import java.util.*; import java.io.*; import java.text.*; public class T{ static final long mod = (long)163577857, root = 23; static int MAX = (int)2e5+1, A = 26; static FastReader in; public static void main(String[] args) throws Exception{ in = new FastReader(); int n = ni(), m = ni(); long[] a = la(n), b = la(m); long lo = 0, hi = (long)1e10; long ans = (long)1e18; while(lo<=hi){ long c1 = lo+(hi-lo)/3, c2 = hi-(hi-lo)/3; if(c1==lo && c2==hi)break; long o1 = 0, o2 = 0; for(int i = 0; i< n; i++){ o1+=Math.max(0,c1-a[i]); o2+=Math.max(0,c2-a[i]); } for(int i = 0; i< m; i++){ o1+=Math.max(0,b[i]-c1); o2+=Math.max(0,b[i]-c2); } ans = Math.min(ans, Math.min(o1,o2)); if(o1<o2)hi = c2; else lo = c1; } for(long x = lo; x<=hi; x++){ long op = 0; for(int i = 0; i< n; i++){ op+=Math.max(0,x-a[i]); } for(int i = 0; i< m; i++){ op+=Math.max(0,b[i]-x); } ans = Math.min(ans, op); } pn(ans); } static long[] la(int n){ long[] t = new long[n]; for(int i = 0; i< n; i++)t[i] = nl(); return t; } static void p(Object o){ System.out.print(o); } static void pn(Object o){ System.out.println(o); } static String n(){ return in.next(); } static String nln(){ return in.nextLine(); } static int ni(){ return Integer.parseInt(in.next()); } static long nl(){ return Long.parseLong(in.next()); } static double nd(){ return Double.parseDouble(in.next()); } static class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws Exception{ br = new BufferedReader(new FileReader(s)); } 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; } } }
Java
["2 2\n2 3\n3 5", "3 2\n1 2 3\n3 4", "3 2\n4 5 6\n1 2"]
1 second
["3", "4", "0"]
NoteIn example 1, you can increase a1 by 1 and decrease b2 by 1 and then again decrease b2 by 1. Now array a will be [3; 3] and array b will also be [3; 3]. Here minimum element of a is at least as large as maximum element of b. So minimum number of operations needed to satisfy Devu's condition are 3.In example 3, you don't need to do any operation, Devu's condition is already satisfied.
Java 8
standard input
[ "two pointers", "binary search", "sortings", "ternary search" ]
e0b5169945909cd2809482b7fd7178c2
The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105). The second line will contain n space-separated integers representing content of the array a (1 ≤ ai ≤ 109). The third line will contain m space-separated integers representing content of the array b (1 ≤ bi ≤ 109).
1,700
You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.
standard output
PASSED
0adbaf403c84904eed33ab5a80b6e00e
train_000.jsonl
1401895800
Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother. As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the maximum value of his brother's array b. Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.
256 megabytes
import java.io.*; import java.util.*; public class CF439Dpt2 { public static void main (String[]args) throws IOException { //BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out)); //Scanner in = new Scanner(System.in); //String line1[] = br.readLine().split(" "); //String line2[] = br.readLine().split(" "); //String line3[] = br.readLine().split(" "); //int n = Integer.parseInt(line1[0]); //int m = Integer.parseInt(line1[1]); FastScanner sc = new FastScanner(); int n = sc.nextInt(); int m = sc.nextInt(); int[] arrA = new int[n]; int[] arrB = new int[m]; int min = -1; int max = 0; for (int i = 0; i < n; i++) { // arrA[i] = Integer.parseInt(line2[i]); arrA[i] = sc.nextInt(); if (min == -1 || arrA[i] < min) min = arrA[i]; if (arrA[i] > max) max = arrA[i]; } for (int i = 0; i < m; i++) { // arrB[i] = Integer.parseInt(line3[i]); arrB[i] = sc.nextInt(); if (arrB[i] < min) min = arrB[i]; if (arrB[i] > max) max = arrB[i]; } //Arrays.sort(arrA); //Arrays.sort(arrB); //min = arrA[0]; //max = arrA[n-1]; //if (arrB[0] < min) // min = arrB[0]; //if (arrB[m-1] > max) // max = arrB[m-1]; //System.out.println(max + " " + min); while (max - min > 1) { int M = min + (max - min)/2; int M1 = M + 1; long f1 = 0; long f2 = 0; for (int i = 0; i < n; i++) { int m11 = M - arrA[i]; int m21 = M1 - arrA[i]; if (m11 > 0) f1 += m11; if (m21 > 0) f2 += m21; } for (int i = m-1; i >= 0; i--) { int m12 = arrB[i] - M; int m22 = arrB[i] - M1; if (m22 > 0) f2 += m22; if (m12 > 0) f1 += m12; } if (f1 < f2) max = M; else min = M; //System.out.println(max + " " + min); } long f1 = 0; long f2 = 0; for (int i = 0; i < n; i++) { int m11 = min - arrA[i]; int m21 = max - arrA[i]; if (m11 > 0) f1 += m11; if (m21 > 0) f2 += m21; } for (int i = m-1; i >= 0; i--) { int m12 = arrB[i] - min; int m22 = arrB[i] - max; if (m22 > 0) f2 += m22; if (m12 > 0) f1 += m12; } long ans = Math.min(f1, f2); //pw.println(ans); //pw.close(); System.out.println(ans); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { try { br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } } public String next() { if (st.hasMoreTokens()) return st.nextToken(); try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public String nextLine() { String line = ""; try { line = br.readLine(); } catch (Exception e) { e.printStackTrace(); } return line; } } }
Java
["2 2\n2 3\n3 5", "3 2\n1 2 3\n3 4", "3 2\n4 5 6\n1 2"]
1 second
["3", "4", "0"]
NoteIn example 1, you can increase a1 by 1 and decrease b2 by 1 and then again decrease b2 by 1. Now array a will be [3; 3] and array b will also be [3; 3]. Here minimum element of a is at least as large as maximum element of b. So minimum number of operations needed to satisfy Devu's condition are 3.In example 3, you don't need to do any operation, Devu's condition is already satisfied.
Java 8
standard input
[ "two pointers", "binary search", "sortings", "ternary search" ]
e0b5169945909cd2809482b7fd7178c2
The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105). The second line will contain n space-separated integers representing content of the array a (1 ≤ ai ≤ 109). The third line will contain m space-separated integers representing content of the array b (1 ≤ bi ≤ 109).
1,700
You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.
standard output
PASSED
8f0ee9d3f6069722e0928e5f5968978d
train_000.jsonl
1405774800
Jzzhu is the president of country A. There are n cities numbered from 1 to n in his country. City 1 is the capital of A. Also there are m roads connecting the cities. One can go from city ui to vi (and vise versa) using the i-th road, the length of this road is xi. Finally, there are k train routes in the country. One can use the i-th train route to go from capital of the country to city si (and vise versa), the length of this route is yi.Jzzhu doesn't want to waste the money of the country, so he is going to close some of the train routes. Please tell Jzzhu the maximum number of the train routes which can be closed under the following condition: the length of the shortest path from every city to the capital mustn't change.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.PriorityQueue; public class JzzhuandCities { public static class node implements Comparable<node> { int node; long val; node(int n, long v) { node = n; val = v; } @Override public int compareTo(node o) { if (o.val < val) return 1; else return -1; } } public static ArrayList<node> graph[]; public static ArrayList<node> t; public static long train[]; public static long dp[]; public static int ans; public static int n; public static boolean vis[]; public static void dig() { // Arrays.fill(dp, Integer.MAX_VALUE); boolean ch[] = new boolean[300005]; dp[1] = 0; PriorityQueue<node> q = new PriorityQueue<>(); q.add(new node(1, 0)); while (!q.isEmpty()) { node e = q.poll(); int node = e.node; if (ch[node]) continue; ch[node] = true; for (int i = 0; i < graph[node].size(); i++) { int node2 = graph[node].get(i).node; long val = graph[node].get(i).val; long min = dp[node] + val; if (node == 1) { min = Math.min(train[node2], min); } if (dp[node2] > min) { dp[node2] = min; q.add(new node(node2, dp[node2])); } } if (node == 1) { for (int i = 0; i < t.size(); i++) { int v = t.get(i).node; if (dp[v] > t.get(i).val) { dp[v] = t.get(i).val; q.add(new node(v, dp[v])); } } } } } public static class point { int x; int y; long val; point(int x, int y, long v) { val = v; this.x = x; this.y = y; } } public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringBuilder q = new StringBuilder(); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); String y[] = in.readLine().split(" "); n = Integer.parseInt(y[0]); int m = Integer.parseInt(y[1]); int k = Integer.parseInt(y[2]); ans = 0; graph = new ArrayList[n + 1]; vis = new boolean[n + 1]; t = new ArrayList(); train = new long[n + 1]; dp = new long[n + 1]; for (int i = 0; i < n + 1; i++) { train[i] = Integer.MAX_VALUE; graph[i] = new ArrayList(); dp[i] = train[i]; } for (int i = 0; i < m; i++) { y = in.readLine().split(" "); int one = Integer.parseInt(y[0]); int two = Integer.parseInt(y[1]); long val = Long.parseLong(y[2]); graph[one].add(new node(two, val)); graph[two].add(new node(one, val)); } for (int i = 0; i < k; i++) { y = in.readLine().split(" "); int one = Integer.parseInt(y[0]); long v = Long.parseLong(y[1]); train[one] = v; t.add(new node(one, v)); } dig(); for (int i = 0; i < k; i++) { int node = t.get(i).node; long val = t.get(i).val; if (vis[node]) { ans++; } if (!vis[node]) { if (dp[node] < val) { // System.out.println(node+" "+dp[node]); ans++; } else { vis[node] = true; for (int j = 0; j < graph[node].size(); j++) { int node2 = graph[node].get(j).node; long val2 = graph[node].get(j).val; if (dp[node2] + val2 == dp[node]) { // System.out.println(node + " " + dp[node]); ans++; break; } } } } } out.println(ans); out.close(); } }
Java
["5 5 3\n1 2 1\n2 3 2\n1 3 3\n3 4 4\n1 5 5\n3 5\n4 5\n5 5", "2 2 3\n1 2 2\n2 1 3\n2 1\n2 2\n2 3"]
2 seconds
["2", "2"]
null
Java 7
standard input
[ "graphs", "greedy", "shortest paths" ]
03d6b61be6ca0ac9dd8259458f41da59
The first line contains three integers n, m, k (2 ≤ n ≤ 105; 1 ≤ m ≤ 3·105; 1 ≤ k ≤ 105). Each of the next m lines contains three integers ui, vi, xi (1 ≤ ui, vi ≤ n; ui ≠ vi; 1 ≤ xi ≤ 109). Each of the next k lines contains two integers si and yi (2 ≤ si ≤ n; 1 ≤ yi ≤ 109). It is guaranteed that there is at least one way from every city to the capital. Note, that there can be multiple roads between two cities. Also, there can be multiple routes going to the same city from the capital.
2,000
Output a single integer representing the maximum number of the train routes which can be closed.
standard output
PASSED
7237168685fc2fdcb0c02fa6a08b9048
train_000.jsonl
1405774800
Jzzhu is the president of country A. There are n cities numbered from 1 to n in his country. City 1 is the capital of A. Also there are m roads connecting the cities. One can go from city ui to vi (and vise versa) using the i-th road, the length of this road is xi. Finally, there are k train routes in the country. One can use the i-th train route to go from capital of the country to city si (and vise versa), the length of this route is yi.Jzzhu doesn't want to waste the money of the country, so he is going to close some of the train routes. Please tell Jzzhu the maximum number of the train routes which can be closed under the following condition: the length of the shortest path from every city to the capital mustn't change.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Div2_257_D { static long INFINITY = 1000000000000l; static int nodes; static int edges; static int trains; static long distance[]; static int previous[]; static int sum[]; static int type[]; static Edge3 railways[]; static boolean visited[]; static ArrayList<Edge3>[] graph; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); sc = new StringTokenizer(""); nodes = nxtInt(); edges = nxtInt(); trains = nxtInt(); graph = new ArrayList[nodes]; for (int i = 0; i < nodes; i++) { graph[i] = new ArrayList<Edge3>(); }// end for. for (int i = 0; i < edges; i++) { int from = nxtInt() - 1; int to = nxtInt() - 1; int w = nxtInt(); graph[from].add(new Edge3(from, to, w, 0)); graph[to].add(new Edge3(to, from, w, 0)); }// end for. railways = new Edge3[trains]; sum = new int[nodes]; for (int i = 0; i < trains; i++) { int to = nxtInt() - 1; int w = nxtInt(); graph[0].add(new Edge3(0, to, w, i + 1)); graph[to].add(new Edge3(to, 0, w, i + 1)); sum[to]++; railways[i] = new Edge3(0, to, w, i + 1); }// end for. dijkstra(0); int counter = 0; boolean closed[] = new boolean[trains]; for (int i = 0; i < trains; i++) { int node = railways[i].to; int weight = railways[i].weight; int trainNum = railways[i].trainNumber; if (distance[node] < weight) { closed[i] = true; counter++; // System.out.println(weight+","+distance[node]); } else if (distance[node] == weight) { if (previous[node] != 0) { counter++; // System.out.println(weight+",,"); } else { if (type[node] != trainNum) { counter++; // System.out.println(weight+" ,,,"); } } } }// end for(i). // int counter = 0; // for (int i = 0; i < nodes; i++) { // if (previous[i] > 0) { // counter += sum[i]; // } else { // if (type[i] > 0){ // counter += (sum[i] - 1); // }else{ // counter+=sum[i]; // } // } // }// end for(i). System.out.println(counter); }// end method. public static void dijkstra(int source) { distance = new long[nodes]; previous = new int[nodes]; type = new int[nodes]; visited = new boolean[nodes]; // type=0 ->road. // type !=0 ->train number. for (int i = 0; i < nodes; i++) { distance[i] = INFINITY; } distance[source] = 0; PriorityQueue<Node3> pq = new PriorityQueue<Node3>(); pq.add(new Node3(0, 0)); while (!pq.isEmpty()) { Node3 c = pq.poll(); int node = c.node; if (!visited[node]) { visited[node] = true; for (int i = 0; i < graph[node].size(); i++) { Edge3 e = graph[node].get(i); int to = e.to; int w = e.weight; int t = e.trainNumber; if (distance[node] + w < distance[to]) { distance[to] = distance[node] + w; previous[to] = node; type[to] = t; Node3 toAdd = new Node3(to, distance[to]); pq.add(toAdd); } else if (distance[node] + w == distance[to]) { if (previous[to] < node) { previous[to] = node; type[to] = 0; } if (previous[to] == node) { type[to] = Math.min(type[to], t); } } }// end for. } }// end while. }// end method. static BufferedReader br; static StringTokenizer sc; static PrintWriter out; static String nxtTok() throws IOException { while (!sc.hasMoreTokens()) { String s = br.readLine(); if (s == null) return null; sc = new StringTokenizer(s.trim()); } return sc.nextToken(); } static int nxtInt() throws IOException { return Integer.parseInt(nxtTok()); } static long nxtLng() throws IOException { return Long.parseLong(nxtTok()); } static double nxtDbl() throws IOException { return Double.parseDouble(nxtTok()); } static int[] nxtIntArr(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nxtInt(); return a; } static long[] nxtLngArr(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nxtLng(); return a; } static char[] nxtCharArr() throws IOException { return nxtTok().toCharArray(); } }// end class class Edge3 { int from; int to; int weight; int trainNumber; // 0->road. // !=0 ->trainNumber. public Edge3(int x, int y, int w, int t) { from = x; to = y; weight = w; trainNumber = t; } } class Node3 implements Comparable<Node3> { int node; long key; public Node3(int a, long k) { node = a; key = k; } @Override public int compareTo(Node3 o) { return Long.valueOf(key).compareTo(o.key); } }// end class Node3.
Java
["5 5 3\n1 2 1\n2 3 2\n1 3 3\n3 4 4\n1 5 5\n3 5\n4 5\n5 5", "2 2 3\n1 2 2\n2 1 3\n2 1\n2 2\n2 3"]
2 seconds
["2", "2"]
null
Java 7
standard input
[ "graphs", "greedy", "shortest paths" ]
03d6b61be6ca0ac9dd8259458f41da59
The first line contains three integers n, m, k (2 ≤ n ≤ 105; 1 ≤ m ≤ 3·105; 1 ≤ k ≤ 105). Each of the next m lines contains three integers ui, vi, xi (1 ≤ ui, vi ≤ n; ui ≠ vi; 1 ≤ xi ≤ 109). Each of the next k lines contains two integers si and yi (2 ≤ si ≤ n; 1 ≤ yi ≤ 109). It is guaranteed that there is at least one way from every city to the capital. Note, that there can be multiple roads between two cities. Also, there can be multiple routes going to the same city from the capital.
2,000
Output a single integer representing the maximum number of the train routes which can be closed.
standard output
PASSED
325e7ad073f6f11666527c07b9c15772
train_000.jsonl
1405774800
Jzzhu is the president of country A. There are n cities numbered from 1 to n in his country. City 1 is the capital of A. Also there are m roads connecting the cities. One can go from city ui to vi (and vise versa) using the i-th road, the length of this road is xi. Finally, there are k train routes in the country. One can use the i-th train route to go from capital of the country to city si (and vise versa), the length of this route is yi.Jzzhu doesn't want to waste the money of the country, so he is going to close some of the train routes. Please tell Jzzhu the maximum number of the train routes which can be closed under the following condition: the length of the shortest path from every city to the capital mustn't change.
256 megabytes
import java.util.*; import java.io.*; public class CF257D { class EdgeList extends HashMap<Integer, List<Integer>> {}; // multigraph // src -> (dest -> [costs of edges]) static EdgeList [] graph; static CF257D c; private static void populateEdge (int u, int v, int x) { EdgeList nbrs = graph[u]; if (nbrs == null) { nbrs = c.new EdgeList(); graph[u] = nbrs; } List<Integer> edges = nbrs.get(v); if (edges == null) { edges = new ArrayList<Integer>(); nbrs.put(v, edges); } edges.add(x); } public static void main(String [] args) { c = new CF257D(); class pos implements Comparable<pos>{ public int i; public long j; public pos(int i, long j) { super(); this.i = i; this.j = j; } public String toString() { return "(" + i + "," + j + ")"; } @Override public int compareTo(pos arg0) { return Long.compare(this.j, arg0.j); } } InputReader in = new InputReader(System.in); int n = in.nextInt(); graph = new EdgeList[n+1]; boolean [] visited = new boolean[n+1]; long [] dist = new long[n+1]; for (int i = 2; i <= n ; i++) { dist[i] = Long.MAX_VALUE; } int [] prevVertex = new int[n+1]; boolean [] prevEdgeIsTrain = new boolean[n+1]; int m = in.nextInt(); int k = in.nextInt(); for (int i = 0; i < m; i++) { int u = in.nextInt(); int v = in.nextInt(); int x = in.nextInt(); populateEdge(u, v, x); populateEdge(v, u, x); } // Map<Integer, List<Integer>> capNbrs = graph.get(1); // if (capNbrs == null) { // capNbrs = new HashMap<Integer, List<Integer>>(); // graph.put(1, capNbrs); // } for (int i = 0; i < k; i++) { int s = in.nextInt(); int y = in.nextInt(); // negative cost indicates that this is a train route edge populateEdge(1, s, -y); populateEdge(s, 1, -y); } PriorityQueue<pos> pq = new PriorityQueue<pos>(); pq.add(new pos(1,0)); while(!pq.isEmpty()) { pos next = pq.poll(); int v = next.i; if (visited[v]) continue; visited[v] = true; Map<Integer, List<Integer>> nbrs = graph[v]; for (int w : nbrs.keySet()) { if (visited[w]) continue; for (int e : nbrs.get(w)) { boolean isTrain = (e < 0); if (isTrain) e = -e; // flip cost back to normal if ( ((dist[v] + e) == dist[w] && !isTrain) || (dist[v] + e < dist[w])) { prevVertex[w] = v; // add the signal back prevEdgeIsTrain[w] = isTrain; dist[w] = dist[v] + e; pq.add(new pos(w, dist[w])); } } } } int neccessary = 0; for (int i = 2; i <= n; i++) { if (prevEdgeIsTrain[i]) { neccessary++; } } PrintWriter out = new PrintWriter(System.out); out.println(k-neccessary); out.close(); } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String nextToken() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["5 5 3\n1 2 1\n2 3 2\n1 3 3\n3 4 4\n1 5 5\n3 5\n4 5\n5 5", "2 2 3\n1 2 2\n2 1 3\n2 1\n2 2\n2 3"]
2 seconds
["2", "2"]
null
Java 7
standard input
[ "graphs", "greedy", "shortest paths" ]
03d6b61be6ca0ac9dd8259458f41da59
The first line contains three integers n, m, k (2 ≤ n ≤ 105; 1 ≤ m ≤ 3·105; 1 ≤ k ≤ 105). Each of the next m lines contains three integers ui, vi, xi (1 ≤ ui, vi ≤ n; ui ≠ vi; 1 ≤ xi ≤ 109). Each of the next k lines contains two integers si and yi (2 ≤ si ≤ n; 1 ≤ yi ≤ 109). It is guaranteed that there is at least one way from every city to the capital. Note, that there can be multiple roads between two cities. Also, there can be multiple routes going to the same city from the capital.
2,000
Output a single integer representing the maximum number of the train routes which can be closed.
standard output
PASSED
293f4b98d31c43dca298bdf977c8a033
train_000.jsonl
1405774800
Jzzhu is the president of country A. There are n cities numbered from 1 to n in his country. City 1 is the capital of A. Also there are m roads connecting the cities. One can go from city ui to vi (and vise versa) using the i-th road, the length of this road is xi. Finally, there are k train routes in the country. One can use the i-th train route to go from capital of the country to city si (and vise versa), the length of this route is yi.Jzzhu doesn't want to waste the money of the country, so he is going to close some of the train routes. Please tell Jzzhu the maximum number of the train routes which can be closed under the following condition: the length of the shortest path from every city to the capital mustn't change.
256 megabytes
import java.util.*; import java.io.*; public class B257 { public static void main(String[] args) throws IOException { input.init(System.in); int n = input.nextInt(), m = input.nextInt(), k = input.nextInt(); ArrayList<Edge>[] g = new ArrayList[n]; for(int i = 0; i<n; i++) g[i] = new ArrayList<Edge>(); boolean[] needTrain = new boolean[n]; long[] trainDist = new long[n]; Arrays.fill(trainDist, (long)1e18); trainDist[0] = 0; for(int i = 0; i<m; i++) { int a = input.nextInt()-1, b = input.nextInt()-1, c = input.nextInt(); g[a].add(new Edge(b, c)); g[b].add(new Edge(a, c)); } for(int i = 0; i<k; i++) { int to = input.nextInt()-1; int dist = input.nextInt(); needTrain[to] = true; trainDist[to] = Math.min(trainDist[to], dist); } //System.out.println(Arrays.toString(trainDist)); PriorityQueue<State> pq = new PriorityQueue<State>(); pq.add(new State(0, 0)); for(int i = 1; i<n; i++) if(needTrain[i]) { pq.add(new State(i, trainDist[i])); //System.out.println(i+" "+trainDist[i]); } long[] dist = new long[n]; for(int i = 0; i<n; i++) dist[i] = trainDist[i]; //System.out.println(Arrays.toString(dist)); while(!pq.isEmpty()) { State at = pq.poll(); //System.out.println(at.at+" "+at.dist); //if(at.dist > 1e9) break; if(at.dist > dist[at.at]) continue; for(Edge e: g[at.at]) { long nd = at.dist + e.dist; //System.out.println(at.at+" "+at.dist+" "+e.to+" "+e.dist+" "+nd); if(nd <= trainDist[e.to]) needTrain[e.to] = false; if(nd < dist[e.to]) { dist[e.to] = nd; pq.add(new State(e.to, nd)); } } } int need = 0; for(int i = 1; i<n; i++) if(needTrain[i]) need++; System.out.println(k - need); } static class Edge { int to, dist; public Edge(int tt, int dd) { to = tt; dist = dd; } } static class State implements Comparable<State> { int at; long dist; public State(int aa, long dd) { at = aa; dist = dd; } @Override public int compareTo(State o) { // TODO Auto-generated method stub return (int)Long.signum(dist - o.dist); } } public static class input { static BufferedReader reader; static StringTokenizer tokenizer; /** call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input) ); tokenizer = new StringTokenizer(""); } /** get next word */ static String next() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt( next() ); } static double nextDouble() throws IOException { return Double.parseDouble( next() ); } static long nextLong() throws IOException { return Long.parseLong( next() ); } } }
Java
["5 5 3\n1 2 1\n2 3 2\n1 3 3\n3 4 4\n1 5 5\n3 5\n4 5\n5 5", "2 2 3\n1 2 2\n2 1 3\n2 1\n2 2\n2 3"]
2 seconds
["2", "2"]
null
Java 7
standard input
[ "graphs", "greedy", "shortest paths" ]
03d6b61be6ca0ac9dd8259458f41da59
The first line contains three integers n, m, k (2 ≤ n ≤ 105; 1 ≤ m ≤ 3·105; 1 ≤ k ≤ 105). Each of the next m lines contains three integers ui, vi, xi (1 ≤ ui, vi ≤ n; ui ≠ vi; 1 ≤ xi ≤ 109). Each of the next k lines contains two integers si and yi (2 ≤ si ≤ n; 1 ≤ yi ≤ 109). It is guaranteed that there is at least one way from every city to the capital. Note, that there can be multiple roads between two cities. Also, there can be multiple routes going to the same city from the capital.
2,000
Output a single integer representing the maximum number of the train routes which can be closed.
standard output
PASSED
6cc8504a8f4f5cf23dfa5602339b389a
train_000.jsonl
1405774800
Jzzhu is the president of country A. There are n cities numbered from 1 to n in his country. City 1 is the capital of A. Also there are m roads connecting the cities. One can go from city ui to vi (and vise versa) using the i-th road, the length of this road is xi. Finally, there are k train routes in the country. One can use the i-th train route to go from capital of the country to city si (and vise versa), the length of this route is yi.Jzzhu doesn't want to waste the money of the country, so he is going to close some of the train routes. Please tell Jzzhu the maximum number of the train routes which can be closed under the following condition: the length of the shortest path from every city to the capital mustn't change.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class PD2 { public static void main(String[] args) { MyScanner scanner = new MyScanner(); int n = scanner.nextInt(); int m = scanner.nextInt(); int k = scanner.nextInt(); List<List<Edge>> edges = new ArrayList<List<Edge>>(); for (int i = 0; i < n; ++i) { edges.add(new ArrayList<Edge>()); } for (int i = 0; i < m; ++i) { int u = scanner.nextInt() - 1; int v = scanner.nextInt() - 1; long x = scanner.nextLong(); edges.get(u).add(new Edge(v, x, false)); edges.get(v).add(new Edge(u, x, false)); } for (int i = 0; i < k; ++i) { int s = scanner.nextInt() - 1; long y = scanner.nextLong(); edges.get(0).add(new Edge(s, y, true)); } Deque<Integer> queue = new ArrayDeque<Integer>(); boolean[] inQueue = new boolean[n]; boolean[] fromTrain = new boolean[n]; long[] shortest = new long[n]; Arrays.fill(inQueue, false); Arrays.fill(fromTrain, false); Arrays.fill(shortest, Long.MAX_VALUE / 2); shortest[0] = 0; queue.add(0); inQueue[0] = true; while (queue.size() > 0) { int x = queue.pollFirst(); inQueue[x] = false; for (Edge e : edges.get(x)) { long newDist = shortest[x] + e.dist; if (newDist < shortest[e.city]) { shortest[e.city] = newDist; if (!inQueue[e.city]) { if (!queue.isEmpty() && shortest[queue.getFirst()] > newDist) { queue.addFirst(e.city); } else { queue.addLast(e.city); } inQueue[e.city] = true; } fromTrain[e.city] = e.isTrain; } else if (newDist == shortest[e.city] && !e.isTrain) { fromTrain[e.city] = false; } } } int ans = k; for (int i = 0; i < n; ++i) { if (fromTrain[i]) { ans--; } } System.out.println(ans); } static class Edge { int city; long dist; boolean isTrain; Edge(int c, long d, boolean is) { city = c; dist = d; isTrain = is; } } //-----------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
["5 5 3\n1 2 1\n2 3 2\n1 3 3\n3 4 4\n1 5 5\n3 5\n4 5\n5 5", "2 2 3\n1 2 2\n2 1 3\n2 1\n2 2\n2 3"]
2 seconds
["2", "2"]
null
Java 7
standard input
[ "graphs", "greedy", "shortest paths" ]
03d6b61be6ca0ac9dd8259458f41da59
The first line contains three integers n, m, k (2 ≤ n ≤ 105; 1 ≤ m ≤ 3·105; 1 ≤ k ≤ 105). Each of the next m lines contains three integers ui, vi, xi (1 ≤ ui, vi ≤ n; ui ≠ vi; 1 ≤ xi ≤ 109). Each of the next k lines contains two integers si and yi (2 ≤ si ≤ n; 1 ≤ yi ≤ 109). It is guaranteed that there is at least one way from every city to the capital. Note, that there can be multiple roads between two cities. Also, there can be multiple routes going to the same city from the capital.
2,000
Output a single integer representing the maximum number of the train routes which can be closed.
standard output
PASSED
908880263d5c150004ef8907c36a8c15
train_000.jsonl
1405774800
Jzzhu is the president of country A. There are n cities numbered from 1 to n in his country. City 1 is the capital of A. Also there are m roads connecting the cities. One can go from city ui to vi (and vise versa) using the i-th road, the length of this road is xi. Finally, there are k train routes in the country. One can use the i-th train route to go from capital of the country to city si (and vise versa), the length of this route is yi.Jzzhu doesn't want to waste the money of the country, so he is going to close some of the train routes. Please tell Jzzhu the maximum number of the train routes which can be closed under the following condition: the length of the shortest path from every city to the capital mustn't change.
256 megabytes
import java.io.*; import java.util.*; import java.util.List; public class Main { private static StringTokenizer st; private static BufferedReader br; public static long MOD = 1000000007; public static void print(Object x) { System.out.println(x + ""); } public static String join(List<?> x, String space) { StringBuilder sb = new StringBuilder(); for (Object elt : x) { sb.append(elt); sb.append(space); } return sb.toString(); } public static String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine().trim()); } return st.nextToken(); } public static double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } public static long nextLong() throws IOException { return Long.parseLong(nextToken()); } public static int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public static List<Double> nextDoubles(int n) throws IOException{ List<Double> lst = new ArrayList<Double>(); for (int i = 0; i < n; i++) { lst.add(nextDouble()); } return lst; } public static List<Integer> nextInts(int n) throws IOException{ List<Integer> lst = new ArrayList<Integer>(); for (int i = 0; i < n; i++) { lst.add(nextInt()); } return lst; } public static List<Long> nextLongs(int n) throws IOException{ List<Long> lst = new ArrayList<Long>(); for (int i = 0; i < n; i++) { lst.add(nextLong()); } return lst; } public static List<Integer> emptyList(int n, int val) { List<Integer> lst = new ArrayList<Integer>(); for (int i = 0; i < n; i++) { lst.add(val); } return lst; } public static void dijkstra(List<List<Pair<Integer, Long>>> neighbors, Map<Integer, Long> distances, PriorityQueue<Pair<Integer, Long>> queue) { Set<Integer> processed = new HashSet<Integer>(); while (queue.size() > 0) { Pair<Integer, Long> pair = queue.poll(); Integer cur = pair.first; Long curDist = pair.second; if (processed.contains(cur)) continue; processed.add(cur); for (Pair<Integer, Long> road : neighbors.get(cur)) { int next = road.first; Long length = road.second + curDist; if (!distances.containsKey(next) || length < distances.get(next)) { distances.put(next, length); queue.add(new Pair<Integer, Long>(next, length)); } } } } public static Long getRoad(Integer u2, Integer v2, Map<Pair<Integer, Integer>, Long> roads) { int u = Math.min(u2, v2); int v = Math.max(u2, v2); return roads.get(new Pair<Integer, Integer>(u, v)); } public static String solve(int n, long total, List<List<Pair<Integer, Long>>> neighbors, Map<Integer, Long> trains, Map<Integer, Long> cRoads) { PriorityQueue<Pair<Integer, Long>> queue = new PriorityQueue<Pair<Integer, Long>>(10, new Comparator<Pair<Integer, Long>>() { @Override public int compare(Pair<Integer, Long> o1, Pair<Integer, Long> o2) { return o1.second.compareTo(o2.second); } }); Map<Integer, Long> distances = new HashMap<Integer, Long>(); for (Map.Entry<Integer, Long> road : cRoads.entrySet()) { int v = road.getKey(); long length = road.getValue(); distances.put(v, length); queue.add(new Pair<Integer, Long>(v, length)); } for (Map.Entry<Integer, Long> road : trains.entrySet()) { int v = road.getKey(); long length = road.getValue(); queue.add(new Pair<Integer, Long>(v, length)); } dijkstra(neighbors, distances, queue); for (Map.Entry<Integer, Long> road : trains.entrySet()) { int v = road.getKey(); long length = road.getValue(); if (distances.containsKey(v) && distances.get(v) <= length) { total++; } } return total + ""; } public static class Pair<F, S> { F first; S second; public Pair(F first, S second) { this.first = first; this.second = second; } @Override public boolean equals(Object obj) { if (!(obj instanceof Pair)) return false; Pair o = (Pair) obj; return this.first.equals(o.first) && this.second.equals(o.second); } @Override public int hashCode() { return first.hashCode() * 31 + second.hashCode(); } } public static void main(String[] args) throws Exception { boolean debug = false; InputStream in = System.in; if (debug) { in = new FileInputStream("input.in"); } br = new BufferedReader(new InputStreamReader(in)); int n = nextInt(); int m = nextInt(); int k = nextInt(); List<List<Pair<Integer, Long>>> neighbors = new ArrayList<List<Pair<Integer, Long>>>(); for (int i = 0; i <= n; i++) neighbors.add(new ArrayList<Pair<Integer, Long>>()); Map<Integer, Long> trains = new HashMap<Integer, Long>(); Map<Integer, Long> cRoads = new HashMap<Integer, Long>(); for (int i = 0; i < m; i++) { int u2 = nextInt(); int v2 = nextInt(); int u = Math.min(u2, v2); int v = Math.max(u2, v2); long length = nextLong(); if (u == 1) { if (cRoads.containsKey(v)) { length = Math.min(length, cRoads.get(v)); } cRoads.put(v, length); continue; } neighbors.get(u).add(new Pair<Integer, Long>(v, length)); neighbors.get(v).add(new Pair<Integer, Long>(u, length)); } long killTrains = 0; for (int i = 0; i < k; i++) { int s = nextInt(); long length = nextLong(); if (trains.containsKey(s)) { length = Math.min(length, trains.get(s)); killTrains++; } trains.put(s, length); } print(solve(n, killTrains, neighbors, trains, cRoads)); } }
Java
["5 5 3\n1 2 1\n2 3 2\n1 3 3\n3 4 4\n1 5 5\n3 5\n4 5\n5 5", "2 2 3\n1 2 2\n2 1 3\n2 1\n2 2\n2 3"]
2 seconds
["2", "2"]
null
Java 7
standard input
[ "graphs", "greedy", "shortest paths" ]
03d6b61be6ca0ac9dd8259458f41da59
The first line contains three integers n, m, k (2 ≤ n ≤ 105; 1 ≤ m ≤ 3·105; 1 ≤ k ≤ 105). Each of the next m lines contains three integers ui, vi, xi (1 ≤ ui, vi ≤ n; ui ≠ vi; 1 ≤ xi ≤ 109). Each of the next k lines contains two integers si and yi (2 ≤ si ≤ n; 1 ≤ yi ≤ 109). It is guaranteed that there is at least one way from every city to the capital. Note, that there can be multiple roads between two cities. Also, there can be multiple routes going to the same city from the capital.
2,000
Output a single integer representing the maximum number of the train routes which can be closed.
standard output
PASSED
4824fcc56c417dbb5f85de361dcac3b1
train_000.jsonl
1276700400
In one one-dimensional world there are n platforms. Platform with index k (platforms are numbered from 1) is a segment with coordinates [(k - 1)m, (k - 1)m + l], and l &lt; m. Grasshopper Bob starts to jump along the platforms from point 0, with each jump he moves exactly d units right. Find out the coordinate of the point, where Bob will fall down. The grasshopper falls down, if he finds himself not on the platform, but if he finds himself on the edge of the platform, he doesn't fall down.
64 megabytes
import java.util.*; import java.io.*; public class Main implements Runnable { public void solve() throws IOException { long n = nextLong(); long d = nextLong(); long m = nextLong(); long l = nextLong(); if(l == m - 1){ long ans = (n - 1) * m + l; ans = ans / d; ans = ans * d; ans += d; System.out.println(ans); } else{ long cur = 0; long lastPoint = (n - 1) * m + l; //System.out.println(lastPoint + " lp"); while(cur <= lastPoint && (cur % m) <= l){ cur += d; } System.out.println(cur); } } //----------------------------------------------------------- public static void main(String[] args) { new Main().run(); } public void print1Int(int[] a){ for(int i = 0; i < a.length; i++) System.out.print(a[i] + " "); System.out.println(); } public void print2Int(int[][] a){ for(int i = 0; i < a.length; i++){ for(int j = 0; j < a[0].length; j++){ System.out.print(a[i][j] + " "); } System.out.println(); } } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); tok = null; solve(); in.close(); } catch (IOException e) { System.exit(0); } } public String nextToken() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } BufferedReader in; StringTokenizer tok; }
Java
["2 2 5 3", "5 4 11 8"]
2 seconds
["4", "20"]
null
Java 7
standard input
[ "brute force", "math" ]
ecbc339ad8064681789075f9234c269a
The first input line contains 4 integer numbers n, d, m, l (1 ≤ n, d, m, l ≤ 106, l &lt; m) — respectively: amount of platforms, length of the grasshopper Bob's jump, and numbers m and l needed to find coordinates of the k-th platform: [(k - 1)m, (k - 1)m + l].
1,700
Output the coordinates of the point, where the grosshopper will fall down. Don't forget that if Bob finds himself on the platform edge, he doesn't fall down.
standard output
PASSED
27816d0d0e9f606bb476ca9c83b9c996
train_000.jsonl
1276700400
In one one-dimensional world there are n platforms. Platform with index k (platforms are numbered from 1) is a segment with coordinates [(k - 1)m, (k - 1)m + l], and l &lt; m. Grasshopper Bob starts to jump along the platforms from point 0, with each jump he moves exactly d units right. Find out the coordinate of the point, where Bob will fall down. The grasshopper falls down, if he finds himself not on the platform, but if he finds himself on the edge of the platform, he doesn't fall down.
64 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; public class Task018B { public static void main(String... args) throws NumberFormatException, IOException { Solution.main(System.in, System.out); } static class Scanner { private final BufferedReader br; private String[] cache; private int cacheIndex; Scanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); cache = new String[0]; cacheIndex = 0; } int nextInt() throws IOException { if (cacheIndex >= cache.length) { cache = br.readLine().split(" "); cacheIndex = 0; } return Integer.parseInt(cache[cacheIndex++]); } long nextLong() throws IOException { if (cacheIndex >= cache.length) { cache = br.readLine().split(" "); cacheIndex = 0; } return Long.parseLong(cache[cacheIndex++]); } String next() throws IOException { if (cacheIndex >= cache.length) { cache = br.readLine().split(" "); cacheIndex = 0; } return cache[cacheIndex++]; } void close() throws IOException { br.close(); } } static class Solution { public static void main(InputStream is, OutputStream os) throws NumberFormatException, IOException { PrintWriter pw = new PrintWriter(os); Scanner sc = new Scanner(is); long n = sc.nextLong(); long d = sc.nextLong(); long m = sc.nextLong(); long l = sc.nextLong(); long answer = Long.MAX_VALUE; for (int i = 0; i < m; ++ i) { if (i * d % m > l) { answer = Math.min(answer, i * d); } } answer = Math.min(answer, (((n - 1) * m + l) / d + 1) * d); pw.println(answer); pw.flush(); sc.close(); } } }
Java
["2 2 5 3", "5 4 11 8"]
2 seconds
["4", "20"]
null
Java 7
standard input
[ "brute force", "math" ]
ecbc339ad8064681789075f9234c269a
The first input line contains 4 integer numbers n, d, m, l (1 ≤ n, d, m, l ≤ 106, l &lt; m) — respectively: amount of platforms, length of the grasshopper Bob's jump, and numbers m and l needed to find coordinates of the k-th platform: [(k - 1)m, (k - 1)m + l].
1,700
Output the coordinates of the point, where the grosshopper will fall down. Don't forget that if Bob finds himself on the platform edge, he doesn't fall down.
standard output
PASSED
d9b4fa50e3c50a4931954d6dc9eb85c6
train_000.jsonl
1276700400
In one one-dimensional world there are n platforms. Platform with index k (platforms are numbered from 1) is a segment with coordinates [(k - 1)m, (k - 1)m + l], and l &lt; m. Grasshopper Bob starts to jump along the platforms from point 0, with each jump he moves exactly d units right. Find out the coordinate of the point, where Bob will fall down. The grasshopper falls down, if he finds himself not on the platform, but if he finds himself on the edge of the platform, he doesn't fall down.
64 megabytes
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Scanner; public class B { public static void main(String[] args) throws IOException { File inputFile = new File("entradaB"); if (inputFile.exists()) System.setIn(new FileInputStream(inputFile)); Scanner in = new Scanner(System.in); while (in.hasNext()) { long n = in.nextInt(), d = in.nextInt(), m = in.nextInt(), l = in.nextInt(); long[][] p = new long[(int) n + 2][2]; p[(int) n + 1][0] = p[(int) n + 1][1] = Long.MAX_VALUE; for (int k = 1; k <= n; k++) { p[k][0] = (k - 1) * m; p[k][1] = (k - 1) * m + l; } long x = 0, ans = 0; for (int i = 1; i <= n && ans == 0; i++) { if (x >= p[i][0] && x <= p[i][1]) { long adv = (p[i][1] - x +d) / d; x += adv * d; } if (x > p[i][1] && x < p[i + 1][0]) ans = x; } System.out.println(ans); } } }
Java
["2 2 5 3", "5 4 11 8"]
2 seconds
["4", "20"]
null
Java 7
standard input
[ "brute force", "math" ]
ecbc339ad8064681789075f9234c269a
The first input line contains 4 integer numbers n, d, m, l (1 ≤ n, d, m, l ≤ 106, l &lt; m) — respectively: amount of platforms, length of the grasshopper Bob's jump, and numbers m and l needed to find coordinates of the k-th platform: [(k - 1)m, (k - 1)m + l].
1,700
Output the coordinates of the point, where the grosshopper will fall down. Don't forget that if Bob finds himself on the platform edge, he doesn't fall down.
standard output
PASSED
d3087734cb6cf66d9e9c46fc7f882b1d
train_000.jsonl
1276700400
In one one-dimensional world there are n platforms. Platform with index k (platforms are numbered from 1) is a segment with coordinates [(k - 1)m, (k - 1)m + l], and l &lt; m. Grasshopper Bob starts to jump along the platforms from point 0, with each jump he moves exactly d units right. Find out the coordinate of the point, where Bob will fall down. The grasshopper falls down, if he finds himself not on the platform, but if he finds himself on the edge of the platform, he doesn't fall down.
64 megabytes
import java.util.*; import java.io.*; public class B0018 { public static void main(String args[]) throws Exception { new B0018(); } B0018() throws Exception { PandaScanner sc = null; PrintWriter out = null; try { sc = new PandaScanner(System.in); out = new PrintWriter(System.out); } catch (Exception ignored) { } long n = sc.nextInt(); long d = sc.nextInt(); long m = sc.nextInt(); long l = sc.nextInt(); for (int i = 0; i < n; i++) { long x = i * m; long beforeGap = ((x + l) / d) * d; long nextSpot = beforeGap + d; if (nextSpot < x + m) { out.println(nextSpot); out.close(); System.exit(0); } } out.println((((n - 1) * m + l) / d) * d + d); out.close(); System.exit(0); } //The PandaScanner class, for Panda fast scanning! public class PandaScanner { BufferedReader br; StringTokenizer st; InputStream in; PandaScanner(InputStream in) throws Exception { br = new BufferedReader(new InputStreamReader(this.in = in)); } public String next() throws Exception { if (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine().trim()); return next(); } return st.nextToken(); } public boolean hasNext() throws Exception { return (st != null && st.hasMoreTokens()) || in.available() > 0; } public long nextLong() throws Exception { return Long.parseLong(next()); } public int nextInt() throws Exception { return Integer.parseInt(next()); } } }
Java
["2 2 5 3", "5 4 11 8"]
2 seconds
["4", "20"]
null
Java 7
standard input
[ "brute force", "math" ]
ecbc339ad8064681789075f9234c269a
The first input line contains 4 integer numbers n, d, m, l (1 ≤ n, d, m, l ≤ 106, l &lt; m) — respectively: amount of platforms, length of the grasshopper Bob's jump, and numbers m and l needed to find coordinates of the k-th platform: [(k - 1)m, (k - 1)m + l].
1,700
Output the coordinates of the point, where the grosshopper will fall down. Don't forget that if Bob finds himself on the platform edge, he doesn't fall down.
standard output
PASSED
1c8f4618f5f1a9a09f4d92f26c237aff
train_000.jsonl
1276700400
In one one-dimensional world there are n platforms. Platform with index k (platforms are numbered from 1) is a segment with coordinates [(k - 1)m, (k - 1)m + l], and l &lt; m. Grasshopper Bob starts to jump along the platforms from point 0, with each jump he moves exactly d units right. Find out the coordinate of the point, where Bob will fall down. The grasshopper falls down, if he finds himself not on the platform, but if he finds himself on the edge of the platform, he doesn't fall down.
64 megabytes
import java.io.IOException; import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.NoSuchElementException; import java.io.Writer; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Nguyen Trung Hieu - [email protected] */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { public void solve(int testNumber, InputReader in, OutputWriter out) { long n = in.readInt(); long d = in.readInt(); long m = in.readInt(); long l = in.readInt(); if (l == m - 1) { long ans = (n - 1) * m + l; ans /= d; ans *= d; ans += d; out.printLine(ans); } else { long cur = 0; while (cur <= (n - 1) * m + l && cur % m <= l) cur += d; out.printLine(cur); } } } 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 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(); } }
Java
["2 2 5 3", "5 4 11 8"]
2 seconds
["4", "20"]
null
Java 7
standard input
[ "brute force", "math" ]
ecbc339ad8064681789075f9234c269a
The first input line contains 4 integer numbers n, d, m, l (1 ≤ n, d, m, l ≤ 106, l &lt; m) — respectively: amount of platforms, length of the grasshopper Bob's jump, and numbers m and l needed to find coordinates of the k-th platform: [(k - 1)m, (k - 1)m + l].
1,700
Output the coordinates of the point, where the grosshopper will fall down. Don't forget that if Bob finds himself on the platform edge, he doesn't fall down.
standard output
PASSED
6760e767bca637341ba11e5e6b2f7128
train_000.jsonl
1276700400
In one one-dimensional world there are n platforms. Platform with index k (platforms are numbered from 1) is a segment with coordinates [(k - 1)m, (k - 1)m + l], and l &lt; m. Grasshopper Bob starts to jump along the platforms from point 0, with each jump he moves exactly d units right. Find out the coordinate of the point, where Bob will fall down. The grasshopper falls down, if he finds himself not on the platform, but if he finds himself on the edge of the platform, he doesn't fall down.
64 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.lang.reflect.Constructor; import java.util.Arrays; import java.util.StringTokenizer; public class CodeE { static class Scanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String nextLine() { try { return br.readLine(); } catch(Exception e) { throw(new RuntimeException()); } } public String next() { while(!st.hasMoreTokens()) { String l = nextLine(); if(l == null) return null; st = new StringTokenizer(l); } 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 int[] nextIntArray(int n) { int[] res = new int[n]; for(int i = 0; i < res.length; i++) res[i] = nextInt(); return res; } public long[] nextLongArray(int n) { long[] res = new long[n]; for(int i = 0; i < res.length; i++) res[i] = nextLong(); return res; } public double[] nextDoubleArray(int n) { double[] res = new double[n]; for(int i = 0; i < res.length; i++) res[i] = nextDouble(); return res; } public void sortIntArray(int[] array) { Integer[] vals = new Integer[array.length]; for(int i = 0; i < array.length; i++) vals[i] = array[i]; Arrays.sort(vals); for(int i = 0; i < array.length; i++) array[i] = vals[i]; } public void sortLongArray(long[] array) { Long[] vals = new Long[array.length]; for(int i = 0; i < array.length; i++) vals[i] = array[i]; Arrays.sort(vals); for(int i = 0; i < array.length; i++) array[i] = vals[i]; } public void sortDoubleArray(double[] array) { Double[] vals = new Double[array.length]; for(int i = 0; i < array.length; i++) vals[i] = array[i]; Arrays.sort(vals); for(int i = 0; i < array.length; i++) array[i] = vals[i]; } public String[] nextStringArray(int n) { String[] vals = new String[n]; for(int i = 0; i < n; i++) vals[i] = next(); return vals; } Integer nextInteger() { String s = next(); if(s == null) return null; return Integer.parseInt(s); } int[][] nextIntMatrix(int n, int m) { int[][] ans = new int[n][]; for(int i = 0; i < n; i++) ans[i] = nextIntArray(m); return ans; } static <T> T fill(T arreglo, int val) { if(arreglo instanceof Object[]) { Object[] a = (Object[]) arreglo; for(Object x : a) fill(x, val); } else if(arreglo instanceof int[]) Arrays.fill((int[]) arreglo, val); else if(arreglo instanceof double[]) Arrays.fill((double[]) arreglo, val); else if(arreglo instanceof long[]) Arrays.fill((long[]) arreglo, val); return arreglo; } <T> T[] nextObjectArray(Class <T> clazz, int size) { @SuppressWarnings("unchecked") T[] result = (T[]) java.lang.reflect.Array.newInstance(clazz, size); try { Constructor <T> constructor = clazz.getConstructor(Scanner.class, Integer.TYPE); for(int i = 0; i < result.length; i++) result[i] = constructor.newInstance(this, i); return result; } catch(Exception e) { throw new RuntimeException(e); } } } public static void main(String[] args) { Scanner sc = new Scanner(); int n = sc.nextInt(); long d = sc.nextInt(); long m = sc.nextInt(); long l = sc.nextInt(); long actual = 0; for(int i = 0; i < n; i++) { long izq = i * m; long der = i * m + l; if(actual < izq) break; if(actual > der) continue; long cuanto = (der - actual) / d; actual += d * cuanto; while(actual <= der) actual += d; } System.out.println(actual); } }
Java
["2 2 5 3", "5 4 11 8"]
2 seconds
["4", "20"]
null
Java 7
standard input
[ "brute force", "math" ]
ecbc339ad8064681789075f9234c269a
The first input line contains 4 integer numbers n, d, m, l (1 ≤ n, d, m, l ≤ 106, l &lt; m) — respectively: amount of platforms, length of the grasshopper Bob's jump, and numbers m and l needed to find coordinates of the k-th platform: [(k - 1)m, (k - 1)m + l].
1,700
Output the coordinates of the point, where the grosshopper will fall down. Don't forget that if Bob finds himself on the platform edge, he doesn't fall down.
standard output
PASSED
8f0c7ac97b4d8a01f1d8032fe5fc9757
train_000.jsonl
1276700400
In one one-dimensional world there are n platforms. Platform with index k (platforms are numbered from 1) is a segment with coordinates [(k - 1)m, (k - 1)m + l], and l &lt; m. Grasshopper Bob starts to jump along the platforms from point 0, with each jump he moves exactly d units right. Find out the coordinate of the point, where Bob will fall down. The grasshopper falls down, if he finds himself not on the platform, but if he finds himself on the edge of the platform, he doesn't fall down.
64 megabytes
import java.io.*; import java.util.*; import java.math.*; public class B implements Runnable { BufferedReader in; PrintWriter out; StringTokenizer st; Random rnd; void solve() throws IOException { long total = nextInt(), oneJump = nextInt(), m = nextInt(), l = nextInt(); long current = 0; while(true) { current += oneJump; long jumped = (current / m) + 1; long pos = current % m; //out.println(current + " " + jumped + " " + remain); if(pos > l || jumped > total) { // current -= oneJump; break; } long remain = l - pos; long k = remain / oneJump; current += oneJump * k; } out.println(current); } public static void main(String[] args) { final boolean oldChecker = false; if(oldChecker) { new Thread(null, new B(), "yarrr", 1 << 24).start(); } else { new B().run(); } } public void run() { try { final String className = this.getClass().getName().toLowerCase(); try { in = new BufferedReader(new FileReader(className + ".in")); out = new PrintWriter(new FileWriter(className + ".out")); } catch (FileNotFoundException e) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } rnd = new Random(); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); System.exit(42); } } String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { String line = in.readLine(); if (line == null) { return null; } st = new StringTokenizer(line); } 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()); } }
Java
["2 2 5 3", "5 4 11 8"]
2 seconds
["4", "20"]
null
Java 7
standard input
[ "brute force", "math" ]
ecbc339ad8064681789075f9234c269a
The first input line contains 4 integer numbers n, d, m, l (1 ≤ n, d, m, l ≤ 106, l &lt; m) — respectively: amount of platforms, length of the grasshopper Bob's jump, and numbers m and l needed to find coordinates of the k-th platform: [(k - 1)m, (k - 1)m + l].
1,700
Output the coordinates of the point, where the grosshopper will fall down. Don't forget that if Bob finds himself on the platform edge, he doesn't fall down.
standard output
PASSED
99b30e9f485109da62ff477478f50c29
train_000.jsonl
1276700400
In one one-dimensional world there are n platforms. Platform with index k (platforms are numbered from 1) is a segment with coordinates [(k - 1)m, (k - 1)m + l], and l &lt; m. Grasshopper Bob starts to jump along the platforms from point 0, with each jump he moves exactly d units right. Find out the coordinate of the point, where Bob will fall down. The grasshopper falls down, if he finds himself not on the platform, but if he finds himself on the edge of the platform, he doesn't fall down.
64 megabytes
import java.io.*; import java.util.*; public class Platforms { public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(f.readLine()); long n = Long.parseLong(st.nextToken()); long d = Long.parseLong(st.nextToken()); long m = Long.parseLong(st.nextToken()); long l = Long.parseLong(st.nextToken()); long x = 0; while (x < n*m && (x%m) <= l) x += d*((l-x%m)/d+1); System.out.println(x); } }
Java
["2 2 5 3", "5 4 11 8"]
2 seconds
["4", "20"]
null
Java 7
standard input
[ "brute force", "math" ]
ecbc339ad8064681789075f9234c269a
The first input line contains 4 integer numbers n, d, m, l (1 ≤ n, d, m, l ≤ 106, l &lt; m) — respectively: amount of platforms, length of the grasshopper Bob's jump, and numbers m and l needed to find coordinates of the k-th platform: [(k - 1)m, (k - 1)m + l].
1,700
Output the coordinates of the point, where the grosshopper will fall down. Don't forget that if Bob finds himself on the platform edge, he doesn't fall down.
standard output
PASSED
93b4191fb3d00e31104483834e85056c
train_000.jsonl
1276700400
In one one-dimensional world there are n platforms. Platform with index k (platforms are numbered from 1) is a segment with coordinates [(k - 1)m, (k - 1)m + l], and l &lt; m. Grasshopper Bob starts to jump along the platforms from point 0, with each jump he moves exactly d units right. Find out the coordinate of the point, where Bob will fall down. The grasshopper falls down, if he finds himself not on the platform, but if he finds himself on the edge of the platform, he doesn't fall down.
64 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int jump = in.nextInt(); int m = in.nextInt(); int len = in.nextInt(); int delta = jump % m; boolean[] pos = new boolean[m]; pos[0] = true; int x = 0, i = 0; while (true) { ++i; x += delta; x %= m; if (pos[x]) { long y = ((long)m * n - 1) / jump; System.out.print((y + 1) * jump); System.exit(0); } else if (x <= len) pos[x] = true; else { long value = 1; System.out.println((long) i * jump); System.exit(0); } } } }
Java
["2 2 5 3", "5 4 11 8"]
2 seconds
["4", "20"]
null
Java 7
standard input
[ "brute force", "math" ]
ecbc339ad8064681789075f9234c269a
The first input line contains 4 integer numbers n, d, m, l (1 ≤ n, d, m, l ≤ 106, l &lt; m) — respectively: amount of platforms, length of the grasshopper Bob's jump, and numbers m and l needed to find coordinates of the k-th platform: [(k - 1)m, (k - 1)m + l].
1,700
Output the coordinates of the point, where the grosshopper will fall down. Don't forget that if Bob finds himself on the platform edge, he doesn't fall down.
standard output
PASSED
25f9ad06968f23dc3248b7dd0742c3db
train_000.jsonl
1276700400
In one one-dimensional world there are n platforms. Platform with index k (platforms are numbered from 1) is a segment with coordinates [(k - 1)m, (k - 1)m + l], and l &lt; m. Grasshopper Bob starts to jump along the platforms from point 0, with each jump he moves exactly d units right. Find out the coordinate of the point, where Bob will fall down. The grasshopper falls down, if he finds himself not on the platform, but if he finds himself on the edge of the platform, he doesn't fall down.
64 megabytes
import java.io.*; import java.util.*; public class Codeforces { public static void main(String[] args) throws IOException { Reader.init(System.in); long n = Reader.nextInt(), d = Reader.nextInt(), m = Reader.nextInt(), l = Reader.nextInt(); long arr[][] = new long[2][(int)n]; int c = 0; long a = 0, b = l; for(long i = d; ;){ while(c < n && i > b){ c++; a = (long)c * m; b = a + l; } if(c == n || i < a){ System.out.println(i); return; } else { long x = ((b - i)/d) * d; i += x > 0 ? x : d; } } } } 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 byte nextByte() throws IOException { return Byte.parseByte(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } }
Java
["2 2 5 3", "5 4 11 8"]
2 seconds
["4", "20"]
null
Java 7
standard input
[ "brute force", "math" ]
ecbc339ad8064681789075f9234c269a
The first input line contains 4 integer numbers n, d, m, l (1 ≤ n, d, m, l ≤ 106, l &lt; m) — respectively: amount of platforms, length of the grasshopper Bob's jump, and numbers m and l needed to find coordinates of the k-th platform: [(k - 1)m, (k - 1)m + l].
1,700
Output the coordinates of the point, where the grosshopper will fall down. Don't forget that if Bob finds himself on the platform edge, he doesn't fall down.
standard output
PASSED
993773a660dfb62d7bb390a8daaba70d
train_000.jsonl
1276700400
In one one-dimensional world there are n platforms. Platform with index k (platforms are numbered from 1) is a segment with coordinates [(k - 1)m, (k - 1)m + l], and l &lt; m. Grasshopper Bob starts to jump along the platforms from point 0, with each jump he moves exactly d units right. Find out the coordinate of the point, where Bob will fall down. The grasshopper falls down, if he finds himself not on the platform, but if he finds himself on the edge of the platform, he doesn't fall down.
64 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class _18B { public static void main(String arg[]) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s[] = br.readLine().split(" "); long n = Integer.parseInt(s[0]); long d = Integer.parseInt(s[1]); long m = Integer.parseInt(s[2]); long l = Integer.parseInt(s[3]); boolean fall = false; long cod=-1; for(int i=0;i<n-1;i++){ long start = i*m+l; long end = (i+1)*m; long steps = start/d; //System.out.println(start+" "+end+" "+steps); if((start<(steps+1)*d)&&((steps+1)*d<end)){ //System.out.println("here"+start+" "+end+" "+steps); fall = true; cod = (steps+1)*d; break; } } if(fall==false){ long steps = ((n-1)*m+l)/d; cod = (steps+1)*d; } System.out.println(cod); } }
Java
["2 2 5 3", "5 4 11 8"]
2 seconds
["4", "20"]
null
Java 7
standard input
[ "brute force", "math" ]
ecbc339ad8064681789075f9234c269a
The first input line contains 4 integer numbers n, d, m, l (1 ≤ n, d, m, l ≤ 106, l &lt; m) — respectively: amount of platforms, length of the grasshopper Bob's jump, and numbers m and l needed to find coordinates of the k-th platform: [(k - 1)m, (k - 1)m + l].
1,700
Output the coordinates of the point, where the grosshopper will fall down. Don't forget that if Bob finds himself on the platform edge, he doesn't fall down.
standard output
PASSED
732b8b63f09c3010e47db8712e168cec
train_000.jsonl
1276700400
In one one-dimensional world there are n platforms. Platform with index k (platforms are numbered from 1) is a segment with coordinates [(k - 1)m, (k - 1)m + l], and l &lt; m. Grasshopper Bob starts to jump along the platforms from point 0, with each jump he moves exactly d units right. Find out the coordinate of the point, where Bob will fall down. The grasshopper falls down, if he finds himself not on the platform, but if he finds himself on the edge of the platform, he doesn't fall down.
64 megabytes
import java.util.ArrayList; import java.io.InputStream; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.IOException; import java.util.StringTokenizer; /** * Built using CHelper plug-in * Actual solution is at the top * @author nasko */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { public void solve(int testNumber, InputReader in, PrintWriter out) { StringTokenizer st = new StringTokenizer(in.nextLine()); long n = Long.parseLong(st.nextToken()); long d = Long.parseLong(st.nextToken()); long m = Long.parseLong(st.nextToken()); long l = Long.parseLong(st.nextToken()); ArrayList<Position> ar = new ArrayList<Position>(); for(long i = 1; i <= n; ++i) { ar.add(new Position((i-1)*m,(i-1)*m + l)); } long start = 0; int i = 0; while(i < n) { if(start < ar.get(i).left) break; if(start <= ar.get(i).right) { start = d*(ar.get(i).right / d + 1); } ++i; } out.println(start); } } class Position { long left; long right; public Position(long _left,long _right) { left = _left; right = _right; } } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String nextLine() { String s = null; try { s = reader.readLine(); } catch (IOException e) { e.printStackTrace(); } return s; } }
Java
["2 2 5 3", "5 4 11 8"]
2 seconds
["4", "20"]
null
Java 7
standard input
[ "brute force", "math" ]
ecbc339ad8064681789075f9234c269a
The first input line contains 4 integer numbers n, d, m, l (1 ≤ n, d, m, l ≤ 106, l &lt; m) — respectively: amount of platforms, length of the grasshopper Bob's jump, and numbers m and l needed to find coordinates of the k-th platform: [(k - 1)m, (k - 1)m + l].
1,700
Output the coordinates of the point, where the grosshopper will fall down. Don't forget that if Bob finds himself on the platform edge, he doesn't fall down.
standard output
PASSED
81ffd2ad7d4e19b0b3631a9a12e1fd13
train_000.jsonl
1276700400
In one one-dimensional world there are n platforms. Platform with index k (platforms are numbered from 1) is a segment with coordinates [(k - 1)m, (k - 1)m + l], and l &lt; m. Grasshopper Bob starts to jump along the platforms from point 0, with each jump he moves exactly d units right. Find out the coordinate of the point, where Bob will fall down. The grasshopper falls down, if he finds himself not on the platform, but if he finds himself on the edge of the platform, he doesn't fall down.
64 megabytes
import java.io.BufferedReader; import java.io.OutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author nasko */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { public void solve(int testNumber, InputReader in, PrintWriter out) { long n = in.nextInt(); long d = in.nextInt(); long m = in.nextInt(); long l = in.nextInt(); long ans = 0; if(l == m - 1) { ans = ( n - 1) * m + l; ans /= d; ans *= d; ans += d; out.println(ans); } else { long last = ( n - 1) * m + l; while(ans <= last && ( ans % m <= l)) ans += d; out.println(ans); } } } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["2 2 5 3", "5 4 11 8"]
2 seconds
["4", "20"]
null
Java 7
standard input
[ "brute force", "math" ]
ecbc339ad8064681789075f9234c269a
The first input line contains 4 integer numbers n, d, m, l (1 ≤ n, d, m, l ≤ 106, l &lt; m) — respectively: amount of platforms, length of the grasshopper Bob's jump, and numbers m and l needed to find coordinates of the k-th platform: [(k - 1)m, (k - 1)m + l].
1,700
Output the coordinates of the point, where the grosshopper will fall down. Don't forget that if Bob finds himself on the platform edge, he doesn't fall down.
standard output
PASSED
00e900f874b854b65c3413084679a96c
train_000.jsonl
1276700400
In one one-dimensional world there are n platforms. Platform with index k (platforms are numbered from 1) is a segment with coordinates [(k - 1)m, (k - 1)m + l], and l &lt; m. Grasshopper Bob starts to jump along the platforms from point 0, with each jump he moves exactly d units right. Find out the coordinate of the point, where Bob will fall down. The grasshopper falls down, if he finds himself not on the platform, but if he finds himself on the edge of the platform, he doesn't fall down.
64 megabytes
import java.util.Scanner; public class Platforms { public static void main(String[] args) { Scanner in = new Scanner(System.in); long n = in.nextLong(); long d = in.nextLong(); long m = in.nextLong(); long l = in.nextLong(); in.close(); long x = 0; for (long i = 0; i < n; i++) { long endPlatform = i * m + l; long beginNextPlatform = (i + 1) * m; x = (endPlatform / d) * d + d; if (i == n - 1 || x < beginNextPlatform) { System.out.println(x); return; } } System.out.println(x + d); } }
Java
["2 2 5 3", "5 4 11 8"]
2 seconds
["4", "20"]
null
Java 7
standard input
[ "brute force", "math" ]
ecbc339ad8064681789075f9234c269a
The first input line contains 4 integer numbers n, d, m, l (1 ≤ n, d, m, l ≤ 106, l &lt; m) — respectively: amount of platforms, length of the grasshopper Bob's jump, and numbers m and l needed to find coordinates of the k-th platform: [(k - 1)m, (k - 1)m + l].
1,700
Output the coordinates of the point, where the grosshopper will fall down. Don't forget that if Bob finds himself on the platform edge, he doesn't fall down.
standard output
PASSED
586f43d293a85061f71926370d0d3521
train_000.jsonl
1482165300
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k.
256 megabytes
import java.util.Scanner; public class CodeForce { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int w=0; int x = 0; if(n%2==0) { System.out.println(n/2); while(n/2>x) { System.out.print(2+" "); x++; } } else { x = 0; w = n - 3; w = w/2; System.out.println(w+1); while(w>=x) { if(w>x) { System.out.print(2+" "); } else { System.out.print(3); } x++; } } } }
Java
["5", "6"]
1 second
["2\n2 3", "3\n2 2 2"]
null
Java 11
standard input
[ "implementation", "number theory", "greedy", "math" ]
98fd00d3c83d4b3f0511d8afa6fdb27b
The only line of the input contains a single integer n (2 ≤ n ≤ 100 000).
800
The first line of the output contains a single integer k — maximum possible number of primes in representation. The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.
standard output
PASSED
a4f74cb598fb01c874996b3718f91ae9
train_000.jsonl
1482165300
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k.
256 megabytes
import java.util.Scanner; public class A{ public static void main(String args[]){ Scanner sc = new Scanner(System.in); int t ,n; n=sc.nextInt(); if(n%2!=0) { System.out.println(1+(n-3)/2); System.out.print(3+" "); for(int i=1;i<=(n-3)/2;i++) System.out.print(2+" "); } else{ System.out.println(n/2); // System.out.println(); for(int i=1;i<=n/2;i++){ System.out.print(2+" "); } } } }
Java
["5", "6"]
1 second
["2\n2 3", "3\n2 2 2"]
null
Java 11
standard input
[ "implementation", "number theory", "greedy", "math" ]
98fd00d3c83d4b3f0511d8afa6fdb27b
The only line of the input contains a single integer n (2 ≤ n ≤ 100 000).
800
The first line of the output contains a single integer k — maximum possible number of primes in representation. The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.
standard output
PASSED
c7334d47b787a1a5e3cd862b019fd48f
train_000.jsonl
1482165300
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k.
256 megabytes
import java.util.Scanner; public class A749 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); if(t%2==0){ System.out.println(t/2); while(t > 0){ System.out.print("2 "); t-=2; } }else{ int pr = 1 + (t-3)/2; System.out.println(pr); System.out.print("3 "); t -= 3; while(t > 0){ System.out.print("2 "); t-=2; } } } }
Java
["5", "6"]
1 second
["2\n2 3", "3\n2 2 2"]
null
Java 11
standard input
[ "implementation", "number theory", "greedy", "math" ]
98fd00d3c83d4b3f0511d8afa6fdb27b
The only line of the input contains a single integer n (2 ≤ n ≤ 100 000).
800
The first line of the output contains a single integer k — maximum possible number of primes in representation. The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.
standard output
PASSED
a6bbfd15fa2e0b88e47c0ab565975e3c
train_000.jsonl
1482165300
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k.
256 megabytes
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ import java.util.Scanner; /** * * @author yashvi1902 */ public class bachgold { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); System.out.println(n/2); if (n%2==1){ System.out.print("3 "); n -= 3; } while(n>0){ System.out.print("2 "); n -= 2; } } }
Java
["5", "6"]
1 second
["2\n2 3", "3\n2 2 2"]
null
Java 11
standard input
[ "implementation", "number theory", "greedy", "math" ]
98fd00d3c83d4b3f0511d8afa6fdb27b
The only line of the input contains a single integer n (2 ≤ n ≤ 100 000).
800
The first line of the output contains a single integer k — maximum possible number of primes in representation. The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.
standard output
PASSED
bbba891c2dd293eaceb28f5bf49815de
train_000.jsonl
1482165300
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k.
256 megabytes
import java.util.Scanner; public class P749A { static void printAsMaximalPrimeSum(int n) { int cont2=0, cont3=0, cont=0; if (n % 2 == 1) { cont++; cont3++; n =n-3; } while (n>0) { cont++; cont2++; n =n-2; } System.out.println(cont); for (int i = 0; i < cont2; i++) { System.out.print("2 "); } for (int i = 0; i < cont3; i++) { System.out.println("3 "); } } public static void main (String[] args) { Scanner entrada = new Scanner(System.in); int n=entrada.nextInt(); printAsMaximalPrimeSum(n); } }
Java
["5", "6"]
1 second
["2\n2 3", "3\n2 2 2"]
null
Java 11
standard input
[ "implementation", "number theory", "greedy", "math" ]
98fd00d3c83d4b3f0511d8afa6fdb27b
The only line of the input contains a single integer n (2 ≤ n ≤ 100 000).
800
The first line of the output contains a single integer k — maximum possible number of primes in representation. The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.
standard output
PASSED
bb659e6cfba304215074caa02fb02385
train_000.jsonl
1482165300
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k.
256 megabytes
import java.util.*; public class solution { public static void main(String[] args) { Scanner s=new Scanner(System.in); int t=s.nextInt(); if(t%2==0) { int n=t/2; System.out.println(n); for(int i=0;i<n;i++) { System.out.print(2+" "); } } else { t=t-3; int n=t/2; System.out.println(n+1); System.out.print(3+" "); for(int i=0;i<n;i++){ System.out.print(2+" "); } } s.close(); } }
Java
["5", "6"]
1 second
["2\n2 3", "3\n2 2 2"]
null
Java 11
standard input
[ "implementation", "number theory", "greedy", "math" ]
98fd00d3c83d4b3f0511d8afa6fdb27b
The only line of the input contains a single integer n (2 ≤ n ≤ 100 000).
800
The first line of the output contains a single integer k — maximum possible number of primes in representation. The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.
standard output
PASSED
7e8bc26e37be39fcbd02ff38a0941d44
train_000.jsonl
1482165300
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k.
256 megabytes
import java.util.*; public class solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt() ; System.out.println(n/2); while (n > 3){ System.out.print(2 + " "); n -= 2 ; } System.out.println(n); } }
Java
["5", "6"]
1 second
["2\n2 3", "3\n2 2 2"]
null
Java 11
standard input
[ "implementation", "number theory", "greedy", "math" ]
98fd00d3c83d4b3f0511d8afa6fdb27b
The only line of the input contains a single integer n (2 ≤ n ≤ 100 000).
800
The first line of the output contains a single integer k — maximum possible number of primes in representation. The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.
standard output
PASSED
86001d83ab9acef755f38c21ee90bc8f
train_000.jsonl
1482165300
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k.
256 megabytes
import java.util.Scanner; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author ASUS */ public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); System.out.println(n/2); if(n%2==1){ System.out.print("3 "); n-=3; } while(n>0){ System.out.print("2 "); n=n-2; } } }
Java
["5", "6"]
1 second
["2\n2 3", "3\n2 2 2"]
null
Java 11
standard input
[ "implementation", "number theory", "greedy", "math" ]
98fd00d3c83d4b3f0511d8afa6fdb27b
The only line of the input contains a single integer n (2 ≤ n ≤ 100 000).
800
The first line of the output contains a single integer k — maximum possible number of primes in representation. The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.
standard output
PASSED
b85123ee1382809cadb7dfdcc395c7d1
train_000.jsonl
1482165300
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class SolutionA extends Thread { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } } private static final FastReader scanner = new FastReader(); private static final PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { new Thread(null, new SolutionA(), "Main", 1 << 26).start(); } public void run() { int t = 1; for (int i = 0; i < t; i++) { solve(); } out.close(); } private static void solve() { int n = scanner.nextInt(); if (n % 2 == 0) { out.println(n/2); for (int i = 0; i < n / 2; i++) { out.print("2 "); } out.println(); } else { out.println(n/2); for (int i = 0; i < n / 2 - 1; i++) { out.print("2 "); } out.println("3"); } } }
Java
["5", "6"]
1 second
["2\n2 3", "3\n2 2 2"]
null
Java 11
standard input
[ "implementation", "number theory", "greedy", "math" ]
98fd00d3c83d4b3f0511d8afa6fdb27b
The only line of the input contains a single integer n (2 ≤ n ≤ 100 000).
800
The first line of the output contains a single integer k — maximum possible number of primes in representation. The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.
standard output
PASSED
6ab3b576be00c3b01f1b33c843b24433
train_000.jsonl
1482165300
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k.
256 megabytes
//package hiougyf; import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) throws IOException { Scanner sc =new Scanner(System.in); int n=sc.nextInt(); int x=n/2; System.out.println(x); if(n%2==0) { while(x-->0) System.out.print(2+" "); } else { x-=1; while(x-->0) { System.out.print(2+" "); } System.out.print(3); } } public static int floorSqrt(int x) { // Base Cases if (x == 0 || x == 1) return x; // Do Binary Search for floor(sqrt(x)) int start = 1, end = x, ans=0; while (start <= end) { int mid = (start + end) / 2; // If x is a perfect square if (mid*mid == x) return mid; // Since we need floor, we update answer when mid*mid is // smaller than x, and move closer to sqrt(x) if (mid*mid < x) { start = mid + 1; ans = mid; } else // If mid*mid is greater than x end = mid-1; } return ans; } static int div(int n,int b) { int g=-1; for(int i=2;i<=Math.sqrt(n);i++) { if(n%i==0&&i!=b) { g=i; break; } } return g; } public static int gcd(int a, int b) { if (a == 0) return b; return gcd(b%a, a); } public static int lcm(int a, int b) { return (a*b)/gcd(a, b); } public static boolean isPrime1(int n) { if (n <= 1) { return false; } if (n == 2) { return true; } for (int i = 2; i <= Math.sqrt(n) + 1; i++) { if (n % i == 0) { return false; } } return true; } public static boolean isPrime(int n) { if (n <= 1) { return false; } if (n == 2) { return true; } if (n % 2 == 0) { return false; } for (int i = 3; i <= Math.sqrt(n) + 1; i = i + 2) { if (n % i == 0) { return false; } } return true; } }
Java
["5", "6"]
1 second
["2\n2 3", "3\n2 2 2"]
null
Java 11
standard input
[ "implementation", "number theory", "greedy", "math" ]
98fd00d3c83d4b3f0511d8afa6fdb27b
The only line of the input contains a single integer n (2 ≤ n ≤ 100 000).
800
The first line of the output contains a single integer k — maximum possible number of primes in representation. The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.
standard output
PASSED
c73117f83bb41ed425c9d0bf179145d0
train_000.jsonl
1482165300
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k.
256 megabytes
import java.util.*; import java.io.*; public class BachgoldProblem { public static void main (String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); if (n%2==0) { System.out.print(n/2); System.out.println(" "); for (int i=0; i<(n/2); i++) { System.out.print("2" + " "); } } else { int temp = n; int count = -1; while (temp>=1) { temp = temp - 2; count++; } System.out.print(count); System.out.println(" "); for (int i=0; i<(count-1); i++) { System.out.print("2" + " "); } System.out.print("3"); } } }
Java
["5", "6"]
1 second
["2\n2 3", "3\n2 2 2"]
null
Java 11
standard input
[ "implementation", "number theory", "greedy", "math" ]
98fd00d3c83d4b3f0511d8afa6fdb27b
The only line of the input contains a single integer n (2 ≤ n ≤ 100 000).
800
The first line of the output contains a single integer k — maximum possible number of primes in representation. The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.
standard output
PASSED
cc629c6ff50023bbb9037ed94b06438e
train_000.jsonl
1482165300
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k.
256 megabytes
import java.util.*; public class Solution{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); if(n == 2){ System.out.println("1"); System.out.println("2"); } else if(n == 3){ System.out.println("1"); System.out.println("3"); } else{ if(n%2 == 0){ System.out.println(n/2); for(int i=0; i < n/2 - 1; i++){ System.out.print("2 "); } System.out.println("2"); } else{ System.out.println(n/2); for(int i=0; i<n/2-1; i++){ System.out.print("2 "); } System.out.println("3"); } } } }
Java
["5", "6"]
1 second
["2\n2 3", "3\n2 2 2"]
null
Java 11
standard input
[ "implementation", "number theory", "greedy", "math" ]
98fd00d3c83d4b3f0511d8afa6fdb27b
The only line of the input contains a single integer n (2 ≤ n ≤ 100 000).
800
The first line of the output contains a single integer k — maximum possible number of primes in representation. The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.
standard output
PASSED
7893e8b9e92e4764df63de8c566ad192
train_000.jsonl
1482165300
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.String; import java.util.*; public class Main { 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) { Scanner input = new Scanner(System.in); FastReader f=new FastReader(); int n=f.nextInt(); int k=n/2; System.out.println(k); if (n%2==0){ for (int i=0;i<k;i++){ System.out.print("2 "); } } else { int rem=n%2; for (int i=0;i<k-1;i++){ System.out.print("2 "); } System.out.print("3 "); } } }
Java
["5", "6"]
1 second
["2\n2 3", "3\n2 2 2"]
null
Java 11
standard input
[ "implementation", "number theory", "greedy", "math" ]
98fd00d3c83d4b3f0511d8afa6fdb27b
The only line of the input contains a single integer n (2 ≤ n ≤ 100 000).
800
The first line of the output contains a single integer k — maximum possible number of primes in representation. The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.
standard output
PASSED
6aa20efadc34b26bebf0a8864c733c8e
train_000.jsonl
1482165300
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int count = 0; int sumEven = 0; if (n % 2 == 0) { while (sumEven != n) { sumEven += 2; count++; } System.out.println(count); sumEven = 0; while (sumEven != n) { sumEven += 2; System.out.println(2); } }else{ sumEven=3; while (sumEven!=n){ sumEven+=2; count++; } System.out.println(count+1); System.out.println(3); sumEven=3; while (sumEven!=n){ sumEven+=2; System.out.println(2); } } } }
Java
["5", "6"]
1 second
["2\n2 3", "3\n2 2 2"]
null
Java 11
standard input
[ "implementation", "number theory", "greedy", "math" ]
98fd00d3c83d4b3f0511d8afa6fdb27b
The only line of the input contains a single integer n (2 ≤ n ≤ 100 000).
800
The first line of the output contains a single integer k — maximum possible number of primes in representation. The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.
standard output
PASSED
9eee968fad5cdd1b7c576b09a0c9982b
train_000.jsonl
1482165300
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner akash = new Scanner(System.in); int number = akash.nextInt(); if(number%2==0){ System.out.println(number/2); for(int i=0;i<number/2;i++){ System.out.print(2 +" "); } System.out.println(); } else{ System.out.println(number/2); for(int j=0;j<(number/2)-1;j++){ System.out.print(2 +" "); } System.out.println(3); } akash.close(); } }
Java
["5", "6"]
1 second
["2\n2 3", "3\n2 2 2"]
null
Java 11
standard input
[ "implementation", "number theory", "greedy", "math" ]
98fd00d3c83d4b3f0511d8afa6fdb27b
The only line of the input contains a single integer n (2 ≤ n ≤ 100 000).
800
The first line of the output contains a single integer k — maximum possible number of primes in representation. The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.
standard output
PASSED
41ea5878d74d39883072832dabba898e
train_000.jsonl
1482165300
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner akash = new Scanner(System.in); int number = akash.nextInt(); if(number%2==0){ System.out.println(number/2); for(int i=0;i<number/2;i++){ System.out.print(2+" "); } System.out.println(); } else{ System.out.println(number/2); for(int j=0;j<(number/2)-1;j++){ System.out.print(2+" "); } System.out.println(3); } akash.close(); } }
Java
["5", "6"]
1 second
["2\n2 3", "3\n2 2 2"]
null
Java 11
standard input
[ "implementation", "number theory", "greedy", "math" ]
98fd00d3c83d4b3f0511d8afa6fdb27b
The only line of the input contains a single integer n (2 ≤ n ≤ 100 000).
800
The first line of the output contains a single integer k — maximum possible number of primes in representation. The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.
standard output
PASSED
9fb3e365e9b0d3e3031fb00e564acb64
train_000.jsonl
1482165300
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k.
256 megabytes
import java.util.Scanner; public class competitive8 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int ans=(int)(n/2); System.out.println(ans); for(int i=0;i<(int)(n/2);i++){ if(i!=((int)(n/2)-1)) { System.out.print("2 "); } if(n%2==0 && i==((int)(n/2)-1)){ System.out.print("2"); } if(n%2!=0 && i==((int)(n/2)-1)){ System.out.print("3"); } } } }
Java
["5", "6"]
1 second
["2\n2 3", "3\n2 2 2"]
null
Java 11
standard input
[ "implementation", "number theory", "greedy", "math" ]
98fd00d3c83d4b3f0511d8afa6fdb27b
The only line of the input contains a single integer n (2 ≤ n ≤ 100 000).
800
The first line of the output contains a single integer k — maximum possible number of primes in representation. The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.
standard output
PASSED
a449133a313fb5a8f20319a54e144a54
train_000.jsonl
1482165300
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k.
256 megabytes
import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; public class CF749A { public static ArrayList<Integer> primes=new ArrayList<>(); public static void sieve(){ int[] prime=new int[100000]; for(int i=3;i<prime.length;i+=2){ prime[i]=1; } prime[2]=1; for(int i=3;i*i<prime.length;i+=2){ if(prime[i]==1){ for(int j=i*i;j<prime.length;j+=i){ prime[j]=0; } } } for(int i=0;i<prime.length;i++){ if(prime[i]==1) { primes.add(i); } } } public static void main(String[] args) { Scanner s=new Scanner(System.in); sieve(); int num=s.nextInt(); if(num%2==0){ System.out.println(num/2); for(int i=0;i<num/2;i++){ System.out.print(2+" "); } } else{ int idx=0; while(true){ if(primes.get(idx)==num){ System.out.println(1); System.out.println(primes.get(idx)); break; } if((num-primes.get(idx))%2==0){ int count=1+((num-primes.get(idx))/2); System.out.println(count); System.out.print(primes.get(idx)+" "); int iter=(num-primes.get(idx))/2; for(int i=0;i<iter;i++){ System.out.print(2+" "); } break; } idx++; } } } }
Java
["5", "6"]
1 second
["2\n2 3", "3\n2 2 2"]
null
Java 11
standard input
[ "implementation", "number theory", "greedy", "math" ]
98fd00d3c83d4b3f0511d8afa6fdb27b
The only line of the input contains a single integer n (2 ≤ n ≤ 100 000).
800
The first line of the output contains a single integer k — maximum possible number of primes in representation. The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.
standard output
PASSED
f2d001eb7699d133a7bd4488a80f58a1
train_000.jsonl
1482165300
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k.
256 megabytes
import java.util.Scanner; public class Main{ public static void main(String [] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int count=0; if(n%2==0) { for(int i=2;i<=n;i=i+2) { count++; } System.out.print(count); System.out.println(); for(int j=1;j<=count;j++) { System.out.print(2+" "); } }else { for(int i=2;i<=n-3;i=i+2) { count++; } count=count+1; System.out.print(count); System.out.println(); for(int j=1;j<=count-1;j++) { System.out.print(2+" "); } System.out.print(3); } } }
Java
["5", "6"]
1 second
["2\n2 3", "3\n2 2 2"]
null
Java 11
standard input
[ "implementation", "number theory", "greedy", "math" ]
98fd00d3c83d4b3f0511d8afa6fdb27b
The only line of the input contains a single integer n (2 ≤ n ≤ 100 000).
800
The first line of the output contains a single integer k — maximum possible number of primes in representation. The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.
standard output
PASSED
32e68b1cb53a5b26613933c298b42621
train_000.jsonl
1482165300
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k.
256 megabytes
import java.util.Scanner; public class BachgoldProblem { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int count = 0; if (n % 2 == 0) { count = n / 2; System.out.println(count); for (int i = 0; i < count; i++) { System.out.print(2 + " "); } } else { n = n - 3; count = n / 2 + 1; System.out.println(count); for (int i = 0; i < count - 1; i++) { System.out.print(2 + " "); } System.out.print(3); } } }
Java
["5", "6"]
1 second
["2\n2 3", "3\n2 2 2"]
null
Java 11
standard input
[ "implementation", "number theory", "greedy", "math" ]
98fd00d3c83d4b3f0511d8afa6fdb27b
The only line of the input contains a single integer n (2 ≤ n ≤ 100 000).
800
The first line of the output contains a single integer k — maximum possible number of primes in representation. The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.
standard output
PASSED
8598b0f558a815ef76c7cc1faff5d6c7
train_000.jsonl
1482165300
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k.
256 megabytes
import java.util.Scanner; public class BachgoldProblem { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int count = 0; if (n % 2 == 0) { count = n / 2; System.out.println(count); for (int i = 0; i < count; i++) { System.out.print(2 + " "); } } else { while (n >= 3) { n -= 2; count++; if (n == 3) { count++; break; } } System.out.println(count); for (int i = 0; i < count - 1; i++) { System.out.print(2 + " "); } System.out.print(3); } } }
Java
["5", "6"]
1 second
["2\n2 3", "3\n2 2 2"]
null
Java 11
standard input
[ "implementation", "number theory", "greedy", "math" ]
98fd00d3c83d4b3f0511d8afa6fdb27b
The only line of the input contains a single integer n (2 ≤ n ≤ 100 000).
800
The first line of the output contains a single integer k — maximum possible number of primes in representation. The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.
standard output
PASSED
0c30004253a7be8166c4bc069f2852e1
train_000.jsonl
1482165300
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k.
256 megabytes
import java .util.Scanner ; import java.util.*; public class cf2{ public static void main(String[] args ){ Scanner s =new Scanner (System.in); int n =s.nextInt(); int count=0; System.out.println(n/2); while(n>0){ //System.out.println(n/2); if(n>=2 && n%2==0){ System.out.print("2"+" "); n=n-2; } else if( n>1 && n%2==1){ System.out.print("3"+" "); n=n-3; if(n>=2 && n%2==0){ //System.out.print(" "); System.out.print("2"+" "); n=n-2; } } } System.exit(0); } }
Java
["5", "6"]
1 second
["2\n2 3", "3\n2 2 2"]
null
Java 11
standard input
[ "implementation", "number theory", "greedy", "math" ]
98fd00d3c83d4b3f0511d8afa6fdb27b
The only line of the input contains a single integer n (2 ≤ n ≤ 100 000).
800
The first line of the output contains a single integer k — maximum possible number of primes in representation. The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.
standard output
PASSED
49ceb9b4d04b06e64819beb7d3f22d8b
train_000.jsonl
1482165300
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k.
256 megabytes
import java.util.*; public class BachgoldProblem { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); if(n==3) { System.out.println(1); System.out.println(3); } else if(n%2==0) { System.out.println(n/2); for(int i=0;i<n/2;i++) { System.out.print(2+" "); } } else { System.out.println(n/2); System.out.print(3+" "); for(int i=1;i<n/2;i++) { System.out.print(2+" "); } } } }
Java
["5", "6"]
1 second
["2\n2 3", "3\n2 2 2"]
null
Java 11
standard input
[ "implementation", "number theory", "greedy", "math" ]
98fd00d3c83d4b3f0511d8afa6fdb27b
The only line of the input contains a single integer n (2 ≤ n ≤ 100 000).
800
The first line of the output contains a single integer k — maximum possible number of primes in representation. The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.
standard output
PASSED
579bd66f2b308e0742a3c39682a6104e
train_000.jsonl
1482165300
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k.
256 megabytes
import java.util.Scanner; public class BachgoldProblem { public static void main(String [] args) { Scanner sc = new Scanner(System.in); int n,two,three=0;n=sc.nextInt(); if(n%2==0) two=n/2; else { three=1; n=n-3; two=n/2; } System.out.println(two+three); for(int i=1;i<=two;i++) System.out.print(2+" "); if(three==1) System.out.println(3); else System.out.println(); sc.close(); } }
Java
["5", "6"]
1 second
["2\n2 3", "3\n2 2 2"]
null
Java 11
standard input
[ "implementation", "number theory", "greedy", "math" ]
98fd00d3c83d4b3f0511d8afa6fdb27b
The only line of the input contains a single integer n (2 ≤ n ≤ 100 000).
800
The first line of the output contains a single integer k — maximum possible number of primes in representation. The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.
standard output
PASSED
b6a7b0f8bbb0e569f77e0be877e5079e
train_000.jsonl
1482165300
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k.
256 megabytes
import java.util.*; public class file { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); if(n%2==0) { System.out.println(n/2); for(int i = 0 ; i< n/2 ; i++) { System.out.print(2 + " "); } }else if(n%2==1) { n=n-3; System.out.println((n/2)+1); for(int j = 0 ; j< n/2 ; j++) { System.out.print(2 + " "); } System.out.print(3); } } }
Java
["5", "6"]
1 second
["2\n2 3", "3\n2 2 2"]
null
Java 11
standard input
[ "implementation", "number theory", "greedy", "math" ]
98fd00d3c83d4b3f0511d8afa6fdb27b
The only line of the input contains a single integer n (2 ≤ n ≤ 100 000).
800
The first line of the output contains a single integer k — maximum possible number of primes in representation. The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.
standard output
PASSED
4fcdc0edb8f152a49654550a21c74250
train_000.jsonl
1482165300
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k.
256 megabytes
import java.util.Scanner; public class BachgoldProblem { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); System.out.println(n/2); if(n % 2 == 0) { for(int i = 1; i <= n/2 - 1; i++) { System.out.print("2 "); } System.out.println("2"); } else { for(int i = 1; i <= n/2 - 1; i++) { System.out.print("2 "); } System.out.println("3"); } } }
Java
["5", "6"]
1 second
["2\n2 3", "3\n2 2 2"]
null
Java 11
standard input
[ "implementation", "number theory", "greedy", "math" ]
98fd00d3c83d4b3f0511d8afa6fdb27b
The only line of the input contains a single integer n (2 ≤ n ≤ 100 000).
800
The first line of the output contains a single integer k — maximum possible number of primes in representation. The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.
standard output
PASSED
6dd7c3d342487a985e0d124aa90a6add
train_000.jsonl
1482165300
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int sum=0; if(n%2==0) { System.out.println(n/2); for(int i=0;i<n/2;i++) System.out.print(2+" "); }else { System.out.println(n/2); for(int i=0;i<n/2-1;i++) System.out.print(2+" "); System.out.print(3); } } }
Java
["5", "6"]
1 second
["2\n2 3", "3\n2 2 2"]
null
Java 11
standard input
[ "implementation", "number theory", "greedy", "math" ]
98fd00d3c83d4b3f0511d8afa6fdb27b
The only line of the input contains a single integer n (2 ≤ n ≤ 100 000).
800
The first line of the output contains a single integer k — maximum possible number of primes in representation. The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.
standard output
PASSED
24e8a5e6513a4119899abe83a258c8f6
train_000.jsonl
1482165300
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k.
256 megabytes
import java.util.Scanner; public class BachgoldProblem { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int n = sc.nextInt(); System.out.println( n / 2); System.out.print((n % 2) != 0 ? 3 : 2); for (int i = n - 2; i >= 2; i -= 2){ System.out.print(" 2"); } System.out.print("\n"); } }
Java
["5", "6"]
1 second
["2\n2 3", "3\n2 2 2"]
null
Java 11
standard input
[ "implementation", "number theory", "greedy", "math" ]
98fd00d3c83d4b3f0511d8afa6fdb27b
The only line of the input contains a single integer n (2 ≤ n ≤ 100 000).
800
The first line of the output contains a single integer k — maximum possible number of primes in representation. The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.
standard output
PASSED
c1affbba9b30116c7c35b77e2b9d55ce
train_000.jsonl
1482165300
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k.
256 megabytes
// Codeforces 749A import java.util.Scanner; public class CF749A { static final Scanner SC = new Scanner(System.in); public static void main(String[] args) { int number = SC.nextInt(); printPrimeDistribution(number); } // Prints the given number as a sum of prime numbers such that the constituent primes are maximum in number static void printPrimeDistribution(int number) { // Maximum constituents => Smaller constituents should be preferred. Use as many 2s as possible, and if the number is odd - then use a 3 instead of one 2. int primes = number/2; // Number of prime constituents System.out.println(primes); if ((number & 1) == 1) System.out.print(3 + " "); else System.out.print(2 + " "); for (int p = 1; p < primes; ++p) System.out.print(2 + " "); } }
Java
["5", "6"]
1 second
["2\n2 3", "3\n2 2 2"]
null
Java 11
standard input
[ "implementation", "number theory", "greedy", "math" ]
98fd00d3c83d4b3f0511d8afa6fdb27b
The only line of the input contains a single integer n (2 ≤ n ≤ 100 000).
800
The first line of the output contains a single integer k — maximum possible number of primes in representation. The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.
standard output
PASSED
fc076904929ff67400f916c48e6e6f15
train_000.jsonl
1482165300
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ // QAQAQYSYIOIWIN // outputCopy // 4 // inputCopy // QAQQQZZYNOIWIN // outputCopy // 3 public class Main { static PrintWriter out; static class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br=new BufferedReader(new InputStreamReader(System.in)); out=new PrintWriter(System.out); } 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; } } // SHIVAM GUPTA : // ASCII = 48 + i ; // SHIVAM GUPTA : public static int min(int a ,int b , int c, int d) { int[] arr = new int[4] ; arr[0] = a; arr[1] = b ; arr[2] = c; arr[3] = d; Arrays.sort(arr) ; return arr[0]; } public static int max(int a ,int b , int c, int d) { int[] arr = new int[4] ; arr[0] = a; arr[1] = b ; arr[2] = c; arr[3] = d; Arrays.sort(arr) ; return arr[3]; } static int sieve = 1000000 ; static boolean[] prime = new boolean[sieve + 1] ; public static void sieveOfEratosthenes() { // TRUE == prime // FALSE == COMPOSITE // FALSE== 1 for(int i=0;i< sieve + 1;i++) prime[i] = true; for(int p = 2; p*p <= sieve; p++) { if(prime[p] == true) { for(int i = p*p; i <= sieve; i += p) prime[i] = false; } } } public static String reverse(String input) { String op = "" ; for(int i = 0; i < input.length() ; i++ ) { op = input.charAt(i)+ op ; } return op ; } public static int[] sortI(int[] arr) { Arrays.sort(arr) ; return arr ; } public static int[] sortD(int[] arr) { Arrays.sort(arr) ; int i =0 ; int j = arr.length -1 ; while( i < j) { int temp = arr[i] ; arr[i] =arr[j] ; arr[j] = temp ; i++ ; j-- ; } return arr ; } public static boolean isPossibleTriangle(int a ,int b , int c) { if( a + b > c && c+b > a && a +c > b) { return true ; } return false ; } public static int gcd(int a, int b ) { if(b==0)return a ; else return gcd(b,a%b) ; } public static int lcm(int a, int b ,int c , int d ) { int temp = lcm(a,b , c) ; int ans = lcm(temp ,d ) ; return ans ; } public static int lcm(int a, int b ,int c ) { int temp = lcm(a,b) ; int ans = lcm(temp ,c) ; return ans ; } public static int lcm(int a , int b ) { int gc = gcd(a,b); return (a*b)/gc ; } static boolean isPrime(int n) { if(n==1) { return false ; } boolean ans = true ; for(int i = 2; i*i <= n ;i++) { if(n% i ==0) { ans = false ;break ; } } return ans ; } static boolean isPowerOfTwo(int n) { if(n==0) return false; if(((n ) & (n-1)) == 0 ) return true ; else return false ; } public static int countDigit(long n) { return (int)Math.floor(Math.log10(n) + 1); } static final int MAXN = 100001; static int spf[] = new int[MAXN]; 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; } } } // The above code works well for n upto the order of 10^7. // Beyond this we will face memory issues. // Time Complexity: The precomputation for smallest prime factor is done in O(n log log n) // using sieve. // Where as in the calculation step we are dividing the number every time by // the smallest prime number till it becomes 1. // So, let’s consider a worst case in which every time the SPF is 2 . // Therefore will have log n division steps. // Hence, We can say that our Time Complexity will be O(log n) in worst case. static Vector<Integer> getFactorization(int x) { Vector<Integer> ret = new Vector<>(); while (x != 1) { ret.add(spf[x]); x = x / spf[x]; } return ret; } public static void main (String[] args) throws java.lang.Exception { FastReader scn = new FastReader() ; // int t = scn.nextInt() ; // for(int i1 = 1; i1<= t ; i1++) // { // int x = scn.nextInt() ;int y = scn.nextInt() ; int n = scn.nextInt() ; // int ans = 0 ; // if( n % x == 0) // { // ans = n+y-x ; // } // else{ // ans = (n/x)*x + y ; // } // out.println(ans) ; // } // } int n ; n = scn.nextInt() ; out.println(n/2) ; if(n%2 == 0) { for(int k = 1; k <= n/2 ; k++)out.print(2+" ") ; } else{ for(int k = 1; k < n/2 ; k++)out.print(2+" ") ; out.print(3+" ") ; } out.println() ; out.flush() ; } }
Java
["5", "6"]
1 second
["2\n2 3", "3\n2 2 2"]
null
Java 11
standard input
[ "implementation", "number theory", "greedy", "math" ]
98fd00d3c83d4b3f0511d8afa6fdb27b
The only line of the input contains a single integer n (2 ≤ n ≤ 100 000).
800
The first line of the output contains a single integer k — maximum possible number of primes in representation. The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.
standard output
PASSED
f155cd74be670c6cf90f3c718cde7981
train_000.jsonl
1482165300
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k.
256 megabytes
import java.util.*; import java.io.*; public class sumofprimeequalton{ static int n,k; static StringBuilder ans; static HashMap<Integer,Integer> map=new HashMap<>(); public static void main(String[] args) throws IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); ans=new StringBuilder(); PrintWriter out=new PrintWriter(System.out); int t=Integer.parseInt(br.readLine().trim()); if(t%2==0){ int sum=0; ans.append(t/2+"\n"); while(sum!=t){ ans.append(2+" "); sum+=2; } } else{ int sum=0; ans.append(((t-3)/2)+1+"\n"); while(sum+3!=t){ ans.append(2+" "); sum+=2; } ans.append(3+" "); } out.println(ans); out.close(); } }
Java
["5", "6"]
1 second
["2\n2 3", "3\n2 2 2"]
null
Java 11
standard input
[ "implementation", "number theory", "greedy", "math" ]
98fd00d3c83d4b3f0511d8afa6fdb27b
The only line of the input contains a single integer n (2 ≤ n ≤ 100 000).
800
The first line of the output contains a single integer k — maximum possible number of primes in representation. The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.
standard output
PASSED
adc55086ccd58499cd537de92f295937
train_000.jsonl
1482165300
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k.
256 megabytes
import java.util.Scanner; public class BachgoldProblem { public static void main(String[] args) { // TODO Auto-generated method stub Scanner s=new Scanner(System.in); int n=s.nextInt(); if(n%2==0){ int v=n/2; System.out.println(n/2); while(v--!=0){ System.out.print("2 "); } }else{ int v=n/2-1; System.out.println(n/2); while(v--!=0){ System.out.print("2 "); } System.out.print("3 "); } } }
Java
["5", "6"]
1 second
["2\n2 3", "3\n2 2 2"]
null
Java 11
standard input
[ "implementation", "number theory", "greedy", "math" ]
98fd00d3c83d4b3f0511d8afa6fdb27b
The only line of the input contains a single integer n (2 ≤ n ≤ 100 000).
800
The first line of the output contains a single integer k — maximum possible number of primes in representation. The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.
standard output