exec_outcome
stringclasses
1 value
code_uid
stringlengths
32
32
file_name
stringclasses
111 values
prob_desc_created_at
stringlengths
10
10
prob_desc_description
stringlengths
63
3.8k
prob_desc_memory_limit
stringclasses
18 values
source_code
stringlengths
117
65.5k
lang_cluster
stringclasses
1 value
prob_desc_sample_inputs
stringlengths
2
802
prob_desc_time_limit
stringclasses
27 values
prob_desc_sample_outputs
stringlengths
2
796
prob_desc_notes
stringlengths
4
3k
lang
stringclasses
5 values
prob_desc_input_from
stringclasses
3 values
tags
listlengths
0
11
src_uid
stringlengths
32
32
prob_desc_input_spec
stringlengths
28
2.37k
difficulty
int64
-1
3.5k
prob_desc_output_spec
stringlengths
17
1.47k
prob_desc_output_to
stringclasses
3 values
hidden_unit_tests
stringclasses
1 value
PASSED
78109ca4523912c692bb0676e83fe354
train_110.jsonl
1613658900
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
512 megabytes
import java.io.*; import java.util.*; public class CF703E { static final int N = (int)(2e5 + 11), INF = (int)(1e9 + 11); static int n, m, v, u, w; static ArrayList< int[] > g[] = new ArrayList[N]; static int[][] d; static PriorityQueue<Node> pq; public static void main (String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); StringTokenizer st = new StringTokenizer(br.readLine()); n = Integer.parseInt(st.nextToken()); m = Integer.parseInt(st.nextToken()); for (int i = 0; i < n; ++i) g[i] = new ArrayList<>(); while (m-- > 0) { st = new StringTokenizer(br.readLine()); v = Integer.parseInt(st.nextToken()); u = Integer.parseInt(st.nextToken()); w = Integer.parseInt(st.nextToken()); --v; --u; g[v].add(new int[] {u, w}); g[u].add(new int[] {v, w}); } d = new int[n][]; for (int i = 0; i < n; ++i) { d[i] = new int[51]; for (int j = 0; j < 51; ++j) d[i][j] = INF; } d[0][0] = 0; Node V; pq = new PriorityQueue<Node>(); pq.add(new Node(0, 0, d[0][0])); while (pq.size() > 0) { V = pq.remove(); int v = V.v; int lvl = V.lvl; int cost = V.cost; if (d[v][lvl] != cost) continue; for (int[] u : g[v]) { int to = u[0], w = u[1], lvl1; if (lvl == 0) { lvl1 = w; w = w*w; } else { lvl1 = 0; w = w*w + 2*lvl*w; } if (d[to][lvl1] > w + d[v][lvl]) { d[to][lvl1] = w + d[v][lvl]; pq.add(new Node(to, lvl1, d[to][lvl1])); } } } for (int i = 0; i < n; ++i) if (d[i][0] == INF) System.out.print("-1 "); else System.out.print(d[i][0] + " "); } static class Node implements Comparable<Node> { public int v, lvl, cost; Node (int v1, int lvl1, int cost1) { v = v1; lvl = lvl1; cost = cost1; } @Override public int compareTo (Node a) { return Integer.compare(cost, a.cost); } } }
Java
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
4 seconds
["0 98 49 25 114", "0 -1 9"]
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
Java 11
standard input
[ "binary search", "brute force", "constructive algorithms", "dp", "flows", "graphs", "shortest paths" ]
abee4d188bb59d82fcf4579c7416a343
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
2,200
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
standard output
PASSED
1c757c8938c07973d351c374dcfde071
train_110.jsonl
1613658900
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
512 megabytes
import java.io.*; import java.util.*; public class CF703E { static final int N = (int)(2e5 + 11), INF = (int)(1e9 + 11); static int n, m, v, u, w; static ArrayList< int[] > g[] = new ArrayList[N]; static int[][] d; static PriorityQueue<Node> pq; public static void main (String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); StringTokenizer st = new StringTokenizer(br.readLine()); n = Integer.parseInt(st.nextToken()); m = Integer.parseInt(st.nextToken()); for (int i = 0; i < n; ++i) g[i] = new ArrayList<>(); while (m-- > 0) { st = new StringTokenizer(br.readLine()); v = Integer.parseInt(st.nextToken()); u = Integer.parseInt(st.nextToken()); w = Integer.parseInt(st.nextToken()); --v; --u; // bw.write(v + " " + u + " " + w + "\n"); g[v].add(new int[] {u, w}); g[u].add(new int[] {v, w}); } d = new int[n][]; for (int i = 0; i < n; ++i) { d[i] = new int[51]; for (int j = 0; j < 51; ++j) d[i][j] = INF; } d[0][0] = 0; Node V; pq = new PriorityQueue<Node>(); pq.add(new Node(0, 0, d[0][0])); while (pq.size() > 0) { V = pq.remove(); int v = V.v; int lvl = V.lvl; int cost = V.cost; if (d[v][lvl] != cost) continue; for (int[] u : g[v]) { int to = u[0], w = u[1], lvl1; if (lvl == 0) { lvl1 = w; w = w*w; } else { lvl1 = 0; w = w*w + 2*lvl*w; } if (d[to][lvl1] > w + d[v][lvl]) { d[to][lvl1] = w + d[v][lvl]; pq.add(new Node(to, lvl1, d[to][lvl1])); } } } for (int i = 0; i < n; ++i) if (d[i][0] == INF) bw.write(-1 + " "); else bw.write(d[i][0] + " "); bw.close(); } static class Node implements Comparable<Node> { public int v, lvl, cost; Node (int v1, int lvl1, int cost1) { v = v1; lvl = lvl1; cost = cost1; } @Override public int compareTo (Node a) { return Integer.compare(cost, a.cost); } } }
Java
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
4 seconds
["0 98 49 25 114", "0 -1 9"]
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
Java 11
standard input
[ "binary search", "brute force", "constructive algorithms", "dp", "flows", "graphs", "shortest paths" ]
abee4d188bb59d82fcf4579c7416a343
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
2,200
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
standard output
PASSED
e72a9215c56667a4c15855b299f365f8
train_110.jsonl
1613658900
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class problemE { static class Solution { Node[] nodes; void solve() { int n = fs.nextInt(), m = fs.nextInt(); nodes = new Node[n+1]; for (int i = 1; i <= n; i ++) nodes[i] = new Node(i); for (int i = 0 ; i < m ; i ++ ) { int u = fs.nextInt(), v = fs.nextInt(), w = fs.nextInt(); nodes[u].edges.addLast(new Edge(v, w)); nodes[v].edges.addLast(new Edge(u, w)); } PriorityQueue<Item> pQ = new PriorityQueue<>(); pQ.add(new Item(0, 0, 1)); nodes[1].D[0] = 0; while (!pQ.isEmpty()) { Item top = pQ.poll(); int dist = top.dist, ind = top.ind, node = top.node; if (nodes[node].D[ind] < dist) continue; nodes[node].D[ind] = dist; for (Edge edge : nodes[node].edges) { if (ind == 0) { if (nodes[edge.v].D[edge.w] > nodes[node].D[ind]) { pQ.add(new Item(nodes[node].D[ind], edge.w, edge.v)); nodes[edge.v].D[edge.w] = nodes[node].D[ind]; } } else { int newDist = nodes[node].D[ind] + square((ind+edge.w)); if (nodes[edge.v].D[0] > newDist) { pQ.add(new Item(newDist, 0, edge.v)); nodes[edge.v].D[0] = newDist; } } } } for (int i = 1; i <= n ; i ++ ) { int dist = nodes[i].D[0]; out.print(dist == Integer.MAX_VALUE ? -1 : dist); out.print(' '); } out.println(); } int square(int x) { return x * x ; } class Item implements Comparable<Item> { int dist; int ind; int node; Item(int dist, int ind, int node) { this.dist = dist; this.ind = ind; this.node = node; } @Override public int compareTo(Item other) { if (this.dist == other.dist) return Integer.compare(this.node, other.node); return Integer.compare(this.dist, other.dist); } } class Node { int ind; int[] D = new int[51]; LinkedList<Edge> edges = new LinkedList<>(); Node(int ind) { this.ind = ind; Arrays.fill(this.D, Integer.MAX_VALUE); } } class Edge { int v, w; Edge(int v, int w) { this.v = v; this.w = w; } } } public static void main(String[] args) throws Exception { int T = 1; Solution solution = new Solution(); for (int t = 0; t < T; t++) solution.solve(); out.close(); } static void debug(Object... O) { System.err.println("DEBUG: " + Arrays.deepToString(O)); } private static FastScanner fs = new FastScanner(); private static PrintWriter out = new PrintWriter(System.out); static class FastScanner { // Thanks SecondThread. BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } ArrayList<Integer> readArrayList(int n) { ArrayList<Integer> a = new ArrayList<>(n); for (int i = 0 ; i < n; i ++ ) a.add(fs.nextInt()); return a; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextString() { return next(); } } }
Java
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
4 seconds
["0 98 49 25 114", "0 -1 9"]
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
Java 11
standard input
[ "binary search", "brute force", "constructive algorithms", "dp", "flows", "graphs", "shortest paths" ]
abee4d188bb59d82fcf4579c7416a343
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
2,200
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
standard output
PASSED
07744b018585c9f3429d217801539386
train_110.jsonl
1613658900
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
512 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Codechef { static class Pair { Integer v; int w; Pair(Integer v, Integer w) { this.v = v; this.w = w; } } static class Group { Integer distance; Pair pair; Group(int distance, Pair pair) { this.distance = distance; this.pair = pair; } } static int N = 100005, W = 51; static int[][] dist = new int[N][W]; static boolean[][] visited = new boolean[N][W]; public static void main(String[] args) throws java.lang.Exception { out = new PrintWriter(new BufferedOutputStream(System.out)); sc = new FastReader(); int test = 1; for (int t = 0; t < test; t++) { int n = sc.nextInt(); int m = sc.nextInt(); Map<Integer, List<Pair>> map = new HashMap<>(); for (int i = 1; i <= n; i++) { map.put(i, new ArrayList<>()); } for (int i = 0; i < m; i++) { int u = sc.nextInt(); int v = sc.nextInt(); int w = sc.nextInt(); map.get(u).add(new Pair(v, w)); map.get(v).add(new Pair(u, w)); } PriorityQueue<Group> pq = new PriorityQueue<>(new Comparator<Group>() { @Override public int compare(Group o1, Group o2) { return o2.distance - o1.distance; } }); pq.add(new Group(1, new Pair(1, 0))); for (int i = 0; i < dist.length; i++) { for (int j = 0; j < dist[0].length; j++) { dist[i][j] = -1; visited[i][j] = false; } } dist[1][0] = 0; while (!pq.isEmpty()) { Pair p = pq.peek().pair; pq.poll(); if (visited[p.v][p.w]) { continue; } visited[p.v][p.w] = true; if (p.w == 0) { for(Pair adj : map.get(p.v)) { if (dist[adj.v][adj.w] == -1 || dist[adj.v][adj.w] > dist[p.v][p.w] + adj.w * adj.w) { dist[adj.v][adj.w] = dist[p.v][p.w] + adj.w * adj.w; pq.add(new Group(-dist[adj.v][adj.w], new Pair(adj.v, adj.w))); } } }else { for(Pair adj : map.get(p.v)) { if (dist[adj.v][0] == -1 || dist[adj.v][0] > dist[p.v][p.w] + adj.w * adj.w + 2 * p.w * adj.w) { dist[adj.v][0] = dist[p.v][p.w] + adj.w * adj.w + 2 * p.w * adj.w; pq.add(new Group(-dist[adj.v][0], new Pair(adj.v, 0))); } } } } for (int v = 1; v <= n; v++) { out.print(dist[v][0] + " "); } out.println(); } out.close(); } public static FastReader sc; public static PrintWriter out; static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
4 seconds
["0 98 49 25 114", "0 -1 9"]
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
Java 11
standard input
[ "binary search", "brute force", "constructive algorithms", "dp", "flows", "graphs", "shortest paths" ]
abee4d188bb59d82fcf4579c7416a343
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
2,200
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
standard output
PASSED
5dc52f0434ef749c2d7262ff15a717ac
train_110.jsonl
1613658900
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.PriorityQueue; import java.util.Random; import java.util.StringTokenizer; public final class E { public static void main(String[] args) { final FastScanner fs = new FastScanner(); final int n = fs.nextInt(); final int m = fs.nextInt(); final List<List<int[]>> g = new ArrayList<>(); for (int i = 0; i < n; i++) { g.add(new ArrayList<>()); } for (int i = 0; i < m; i++) { final int u = fs.nextInt() - 1; final int v = fs.nextInt() - 1; final int w = fs.nextInt(); g.get(u).add(new int[] { v, w }); g.get(v).add(new int[] { u, w }); } final int[][] d = new int[n][55]; final int inf = (int) 2e9; for (int i = 0; i < n; i++) { for (int j = 0; j <= 50; j++) { d[i][j] = inf; } } d[0][0] = 0; final PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(val -> val[0])); pq.offer(new int[] { 0, 0, 0 }); while (!pq.isEmpty()) { final int[] curr = pq.remove(); final int u = curr[1]; final int w = curr[2]; if (curr[0] > d[u][w]) { continue; } for (int[] next : g.get(u)) { final int v = next[0]; final int w1 = next[1]; int nw = 0; final int total; if (w == 0) { nw = w1; total = d[u][0]; } else { total = d[u][w] + (w1 + w) * (w1 + w); } if (total < d[v][nw]) { d[v][nw] = total; pq.offer(new int[] { total, v, nw }); } } } final StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) { sb.append(d[i][0] == inf ? -1 : d[i][0]); sb.append(' '); } System.out.println(sb); } static final class Utils { public static void shuffleSort(int[] x) { shuffle(x); Arrays.sort(x); } public static void shuffleSort(long[] x) { shuffle(x); Arrays.sort(x); } public static void shuffle(int[] x) { final Random r = new Random(); for (int i = 0; i <= x.length - 2; i++) { final int j = i + r.nextInt(x.length - i); swap(x, i, j); } } public static void shuffle(long[] x) { final Random r = new Random(); for (int i = 0; i <= x.length - 2; i++) { final int j = i + r.nextInt(x.length - i); swap(x, i, j); } } public static void swap(int[] x, int i, int j) { final int t = x[i]; x[i] = x[j]; x[j] = t; } public static void swap(long[] x, int i, int j) { final long t = x[i]; x[i] = x[j]; x[j] = t; } private Utils() {} } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); private String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { //noinspection CallToPrintStackTrace e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } int[] nextIntArray(int n) { final int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } long[] nextLongArray(int n) { final long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } } }
Java
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
4 seconds
["0 98 49 25 114", "0 -1 9"]
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
Java 11
standard input
[ "binary search", "brute force", "constructive algorithms", "dp", "flows", "graphs", "shortest paths" ]
abee4d188bb59d82fcf4579c7416a343
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
2,200
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
standard output
PASSED
52aa06a5855487dc57d3c00fcc772b16
train_110.jsonl
1613658900
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
512 megabytes
import java.util.*; public class pairedPaymentCF { public static void main (String[]args) { Scanner scan = new Scanner (System.in); int nodeNumber = scan.nextInt(); int edgeNumber = scan.nextInt(); Hashtable <Integer, ArrayList<edge>> weightedGraph = new Hashtable <Integer, ArrayList<edge>>(); for (int i = 0; i < nodeNumber; i++) { weightedGraph.put(i, new ArrayList<edge>()); } for (int i = 0; i < edgeNumber; i++) { int firstNode = scan.nextInt(); int secondNode = scan.nextInt(); int edgeCost = scan.nextInt(); firstNode--; secondNode--; ArrayList<edge> temp = weightedGraph.get(firstNode); edge addingEdge = new edge (secondNode, edgeCost); temp.add(addingEdge); weightedGraph.put(firstNode, temp); ArrayList<edge> tempTwo = weightedGraph.get(secondNode); addingEdge = new edge (firstNode, edgeCost); tempTwo.add(addingEdge); weightedGraph.put(secondNode, tempTwo); } // Dp table represents the shortest distance from node 1 to node i and being on the ith step and hav int [][][] dp = new int [nodeNumber][2][55]; // Initialization for (int i = 0; i < nodeNumber; i++) { for (int j = 0; j < 2; j++) { Arrays.fill(dp[i][j], Integer.MAX_VALUE); } } // Base Case dp[0][0][0] = 0; pqPair startingPair = new pqPair (0, 0, 0, 0); PriorityQueue <pqPair> pq = new PriorityQueue <pqPair>(); pq.add(startingPair); while (pq.isEmpty() == false) { pqPair curPair = pq.poll(); int curNode = curPair.node; int curStep = curPair.stepNumber; int firstEdgeWeight = curPair.edgeWeight; int curDist = curPair.distanceFromStart; ArrayList<edge> neighbors = weightedGraph.get(curNode); for (int i = 0; i < neighbors.size(); i++) { int neighborNode = neighbors.get(i).secondNode; int nextEdgeWeight = neighbors.get(i).edgeCost; if (curStep == 0) { if (dp[neighborNode][1][nextEdgeWeight] > dp[curNode][0][0]) { dp[neighborNode][1][nextEdgeWeight] = dp[curNode][0][0]; pqPair addingPair = new pqPair (neighborNode, 1, nextEdgeWeight, dp[neighborNode][1][nextEdgeWeight]); pq.add(addingPair); } } else { int nextAdd = (firstEdgeWeight + nextEdgeWeight) * (firstEdgeWeight + nextEdgeWeight); if (dp[neighborNode][0][0] > dp[curNode][1][firstEdgeWeight] + nextAdd) { dp[neighborNode][0][0] = dp[curNode][1][firstEdgeWeight] + nextAdd; pqPair addingPair = new pqPair (neighborNode, 0, 0, dp[neighborNode][0][0]); pq.add(addingPair); } } } } for (int i = 0; i < nodeNumber; i++) { int curAnswer = Integer.MAX_VALUE; for (int j = 0; j < 55; j++) { curAnswer = Math.min(dp[i][0][j], curAnswer); } if (curAnswer == Integer.MAX_VALUE) { curAnswer = -1; } System.out.print(curAnswer + " "); } } private static class pqPair implements Comparable<pqPair> { int node; int stepNumber; int edgeWeight; int distanceFromStart; public pqPair (int node, int stepNumber, int edgeWeight, int distanceFromStart) { this.node = node; this.stepNumber = stepNumber; this.edgeWeight = edgeWeight; this.distanceFromStart = distanceFromStart; } public int compareTo (pqPair p) { return (distanceFromStart - p.distanceFromStart); } } private static class edge { int secondNode; int edgeCost; public edge (int secondNode, int edgeCost) { this.secondNode = secondNode; this.edgeCost = edgeCost; } } }
Java
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
4 seconds
["0 98 49 25 114", "0 -1 9"]
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
Java 11
standard input
[ "binary search", "brute force", "constructive algorithms", "dp", "flows", "graphs", "shortest paths" ]
abee4d188bb59d82fcf4579c7416a343
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
2,200
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
standard output
PASSED
4faec1b2cf8209a05573113abb324209
train_110.jsonl
1613658900
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
512 megabytes
import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import java.io.*; import java.util.*; public class A { static int n, m; static int[] arr; static char[] s; static List<int[]>[] adj; public static void main(String[] args) throws IOException { f = new Flash(); out = new PrintWriter(System.out); int T = 1; //ni(); for(int tc = 1; tc <= T; tc++){ n = ni(); m = ni(); adj = new ArrayList[n]; for(int i = 0; i < n; i++) adj[i] = new ArrayList<>(); for(int i = 1; i <= m; i++) { int u = ni()-1, v = ni()-1, w = ni(); adj[u].add(new int[] {v, w}); adj[v].add(new int[] {u, w}); } fn(); } out.flush(); out.close(); } static void fn() { long[][] dp = new long[n][51]; boolean[][] vis = new boolean[n][51]; for(int i = 0; i < n; i++) Arrays.fill(dp[i], inf); dp[0][0] = 0L; PriorityQueue<Node> pq = new PriorityQueue<>(); pq.add(new Node(0, 0, 0L)); while(!pq.isEmpty()) { Node cur = pq.poll(); if(vis[cur.u][cur.tag]) continue; vis[cur.u][cur.tag] = true; for(int[] vw : adj[cur.u]) { int v = vw[0], w = vw[1]; if(cur.tag == 0) { if(dp[v][w] > cur.dist) { dp[v][w] = cur.dist; pq.add(new Node(v, w, cur.dist)); } } else { long cost = (cur.tag+w) * (cur.tag+w); if(dp[v][0] > cur.dist+cost) { dp[v][0] = cur.dist+cost; pq.add(new Node(v, 0, cur.dist+cost)); } } } } long[] ans = new long[n]; for(int i = 0; i < n; i++) { if(dp[i][0] == inf) dp[i][0] = -1; ans[i] = dp[i][0]; } print(ans); } static class Node implements Comparable<Node>{ int u, tag; long dist; Node(int i, int t, long d){ u = i; tag = t; dist = d; } public int compareTo(Node n2) { return Long.compare(this.dist, n2.dist); } } static Flash f; static PrintWriter out; static final long mod = (long)1e9+7; static final long inf = Long.MAX_VALUE; static final int _inf = Integer.MAX_VALUE; static final int maxN = (int)5e5+5; static long[] fact, inv; static void sort(int[] a){ List<Integer> A = new ArrayList<>(); for(int i : a) A.add(i); Collections.sort(A); for(int i = 0; i < A.size(); i++) a[i] = A.get(i); } static void sort(long[] a){ List<Long> A = new ArrayList<>(); for(long i : a) A.add(i); Collections.sort(A); for(int i = 0; i < A.size(); i++) a[i] = A.get(i); } static void print(int[] a){ StringBuilder sb = new StringBuilder(); for(int i = 0; i < a.length; i++) sb.append(a[i] + " "); sop(sb); } static void print(long[] a){ StringBuilder sb = new StringBuilder(); for(int i = 0; i < a.length; i++) sb.append(a[i] + " "); sop(sb); } static int swap(int itself, int dummy){return itself;} static long swap(long itself, long dummy){return itself;} static void sop(Object o){out.println(o);} static int ni(){return f.ni();} static long nl(){return f.nl();} static double nd(){return f.nd();} static String next(){return f.next();} static String ns(){return f.ns();} static char[] nc(){return f.nc();} static int[] arr(int len){return f.arr(len);} static int gcd(int a, int b){if(b == 0) return a; return gcd(b, a%b);} static long gcd(long a, long b){if(b == 0) return a; return gcd(b, a%b);} static int lcm(int a, int b){return (a*b)/gcd(a, b);} static long lcm(long a, long b){return (a*b)/gcd(a, b);} static class Flash { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next(){ while(!st.hasMoreTokens()){ try{ st = new StringTokenizer(br.readLine()); }catch(IOException e){ e.printStackTrace(); } } return st.nextToken(); } String ns(){ String s = new String(); try{ s = br.readLine().trim(); }catch(IOException e){ e.printStackTrace(); } return s; } int[] arr(int n){ int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = ni(); return a; } char[] nc(){return ns().toCharArray();} int ni(){return Integer.parseInt(next());} long nl(){return Long.parseLong(next());} double nd(){return Double.parseDouble(next());} } }
Java
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
4 seconds
["0 98 49 25 114", "0 -1 9"]
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
Java 11
standard input
[ "binary search", "brute force", "constructive algorithms", "dp", "flows", "graphs", "shortest paths" ]
abee4d188bb59d82fcf4579c7416a343
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
2,200
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
standard output
PASSED
6565506ffd13d61b557d556fb4b2c419
train_110.jsonl
1613658900
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
512 megabytes
import java.io.*; import java.util.*; public class CF1486E extends PrintWriter { CF1486E() { super(System.out, true); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1486E o = new CF1486E(); o.main(); o.flush(); } static final int W = 51, INF = 0x3f3f3f3f; int[] eo; int[][] ej; byte[][] ew; void append(int i, int j, byte w) { int o = eo[i]++; if (o >= 2 && (o & o - 1) == 0) { ej[i] = Arrays.copyOf(ej[i], o << 1); ew[i] = Arrays.copyOf(ew[i], o << 1); } ej[i][o] = j; ew[i][o] = w; } int[] dd, pq, iq; int cnt; boolean lt(int i, int j) { return dd[i] < dd[j]; } int p2(int p) { return (p *= 2) > cnt ? 0 : p < cnt && lt(iq[p + 1], iq[p]) ? p + 1 : p; } void pq_up(int i) { int j, p, q; for (p = pq[i]; (q = p / 2) > 0 && lt(i, j = iq[q]); p = q) iq[pq[j] = p] = j; iq[pq[i] = p] = i; } void pq_dn(int i) { int j, p, q; for (p = pq[i]; (q = p2(p)) > 0 && lt(j = iq[q], i); p = q) iq[pq[j] = p] = j; iq[pq[i] = p] = i; } void pq_add_last(int i) { iq[pq[i] = ++cnt] = i; } int pq_remove_first() { int i = iq[1], j = iq[cnt--]; if (j != i) pq[j] = 1; pq_dn(j); pq[i] = 0; return i; } void main() { int n = sc.nextInt(); int m = sc.nextInt(); eo = new int[n]; ej = new int[n][2]; ew = new byte[n][2]; while (m-- > 0) { int i = sc.nextInt() - 1; int j = sc.nextInt() - 1; byte w = (byte) sc.nextInt(); append(i, j, w); append(j, i, w); } dd = new int[n * W]; Arrays.fill(dd, INF); pq = new int[n * W]; iq = new int[1 + n * W]; dd[0] = 0; pq_add_last(0); while (cnt > 0) { int iw = pq_remove_first(); int i = iw / W, u = iw % W, d = dd[iw]; for (int o = eo[i]; o-- > 0; ) { int j = ej[i][o], v = ew[i][o], jv, d_; if (u == 0) { jv = j * W + v; d_ = d; } else { jv = j * W; d_ = d + (u + v) * (u + v); } if (dd[jv] > d_) { if (dd[jv] == INF) pq_add_last(jv); dd[jv] = d_; pq_up(jv); } } } for (int i = 0; i < n; i++) { int d = dd[i * W]; if (d == INF) d = -1; print(d + " "); } println(); } }
Java
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
4 seconds
["0 98 49 25 114", "0 -1 9"]
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
Java 11
standard input
[ "binary search", "brute force", "constructive algorithms", "dp", "flows", "graphs", "shortest paths" ]
abee4d188bb59d82fcf4579c7416a343
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
2,200
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
standard output
PASSED
65ffe17c8db041cf40ca517d92853b31
train_110.jsonl
1613658900
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
512 megabytes
import java.io.*; import java.text.CollationElementIterator; import java.util.*; public class Main { static final long INF = (long) 1e18; static ArrayList<Edge> adjList[]; static int n; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); n = sc.nextInt(); int m = sc.nextInt(); adjList = new ArrayList[n]; for (int i = 0; i < n; i++) adjList[i] = new ArrayList<>(); while (m-- > 0) { int u = sc.nextInt() - 1, v = sc.nextInt() - 1, w = sc.nextInt(); adjList[u].add(new Edge(v, w)); adjList[v].add(new Edge(u, w)); } long[] dist = new long[n]; Arrays.fill(dist, INF); PriorityQueue<Edge> pq = new PriorityQueue<>(); pq.add(new Edge(0, 0)); dist[0] = 0; while (!pq.isEmpty()) { Edge cur = pq.remove(); int u = cur.u; long cost = cur.w; if (dist[u] < cost) continue; for (Edge a : adjList[u]) for (Edge b : adjList[a.u]) { long next = cost + sq(a.w + b.w); if (next < dist[b.u]) pq.add(new Edge(b.u, dist[b.u] = next)); } } for (long d : dist) if (d == INF) out.print(-1 + " "); else out.print(d + " "); out.flush(); out.close(); } static long sq(long x) { return x * x; } static class Edge implements Comparable<Edge> { int u; long w; public Edge(int u, long w) { this.u = u; this.w = w; } @Override public int compareTo(Edge o) { return Long.compare(w, o.w); } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public Scanner(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public int[] nextIntArray(int n) throws IOException { int[] ans = new int[n]; for (int i = 0; i < n; i++) ans[i] = nextInt(); return ans; } public long[] nextLongArray(int n) throws IOException { long[] ans = new long[n]; for (int i = 0; i < n; i++) ans[i] = nextLong(); return ans; } public Integer[] nextIntegerArray(int n) throws IOException { Integer[] ans = new Integer[n]; for (int i = 0; i < n; i++) ans[i] = nextInt(); return ans; } public char nextChar() throws IOException { return next().charAt(0); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
4 seconds
["0 98 49 25 114", "0 -1 9"]
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
Java 11
standard input
[ "binary search", "brute force", "constructive algorithms", "dp", "flows", "graphs", "shortest paths" ]
abee4d188bb59d82fcf4579c7416a343
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
2,200
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
standard output
PASSED
819b59784e2ee73d1dc61c8523512284
train_110.jsonl
1613658900
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
512 megabytes
//package round703; import java.io.*; import java.util.ArrayDeque; import java.util.Arrays; import java.util.InputMismatchException; import java.util.Queue; public class E { InputStream is; FastWriter out; String INPUT = ""; void solve() { int n = ni(), m = ni(); int[] from = new int[m]; int[] to = new int[m]; int[] ws = new int[m]; for(int i = 0;i < m;i++){ from[i] = ni()-1; to[i] = ni()-1; ws[i] = ni(); } int[][][] g = packWU(n, from, to, ws); long[] ptns = new long[n]; for(int i = 0;i < n;i++){ for(int[] e : g[i]){ ptns[i] |= 1L<<e[1]; } } long[] td = new long[n*51]; Arrays.fill(td, Long.MAX_VALUE / 2); MinHeapL q = new MinHeapL(n*51); q.add(0, 0); td[0] = 0; while(q.size() > 0){ int cur = q.argmin(); q.remove(cur); if(cur < n){ for(int[] e : g[cur]){ int next = e[0]; for(long i = ptns[next];i != 0;i &= i-1){ int o = Long.numberOfTrailingZeros(i); long nd = td[cur] + (long)(e[1] + o) * (e[1] + o); int ne = next + o * n; if(nd < td[ne]){ td[ne] = nd; q.update(ne, nd); } } } }else{ int ww = cur / n; for(int[] e : g[cur%n]){ if(e[1] == ww){ if(td[cur] < td[e[0]]){ td[e[0]] = td[cur]; q.update(e[0], td[e[0]]); } } } } } for(int i = 0;i < n;i++){ out.print(td[i] >= Long.MAX_VALUE / 3 ? -1 : td[i]).print(" "); } out.println(); } public static class MinHeapL { public long[] a; public int[] map; public int[] imap; public int n; public int pos; public static long INF = Long.MAX_VALUE; public MinHeapL(int m) { n = Integer.highestOneBit((m+1)<<1); a = new long[n]; map = new int[n]; imap = new int[n]; Arrays.fill(a, INF); Arrays.fill(map, -1); Arrays.fill(imap, -1); pos = 1; } public long add(int ind, long x) { int ret = imap[ind]; if(imap[ind] < 0){ a[pos] = x; map[pos] = ind; imap[ind] = pos; pos++; up(pos-1); } return ret != -1 ? a[ret] : x; } public long update(int ind, long x) { int ret = imap[ind]; if(imap[ind] < 0){ a[pos] = x; map[pos] = ind; imap[ind] = pos; pos++; up(pos-1); }else{ a[ret] = x; up(ret); down(ret); } return x; } public long remove(int ind) { if(pos == 1)return INF; if(imap[ind] == -1)return INF; pos--; int rem = imap[ind]; long ret = a[rem]; map[rem] = map[pos]; imap[map[pos]] = rem; imap[ind] = -1; a[rem] = a[pos]; a[pos] = INF; map[pos] = -1; up(rem); down(rem); return ret; } public long min() { return a[1]; } public int argmin() { return map[1]; } public int size() { return pos-1; } private void up(int cur) { for(int c = cur, p = c>>>1;p >= 1 && a[p] > a[c];c>>>=1, p>>>=1){ long d = a[p]; a[p] = a[c]; a[c] = d; int e = imap[map[p]]; imap[map[p]] = imap[map[c]]; imap[map[c]] = e; e = map[p]; map[p] = map[c]; map[c] = e; } } private void down(int cur) { for(int c = cur;2*c < pos;){ int b = a[2*c] < a[2*c+1] ? 2*c : 2*c+1; if(a[b] < a[c]){ long d = a[c]; a[c] = a[b]; a[b] = d; int e = imap[map[c]]; imap[map[c]] = imap[map[b]]; imap[map[b]] = e; e = map[c]; map[c] = map[b]; map[b] = e; c = b; }else{ break; } } } } public static int[][][] packWU(int n, int[] from, int[] to, int[] w) { return packWU(n, from, to, w, from.length); } public static int[][][] packWU(int n, int[] from, int[] to, int[] w, int sup) { int[][][] g = new int[n][][]; int[] p = new int[n]; for (int i = 0; i < sup; i++) p[from[i]]++; for (int i = 0; i < sup; i++) p[to[i]]++; for (int i = 0; i < n; i++) g[i] = new int[p[i]][2]; for (int i = 0; i < sup; i++) { --p[from[i]]; g[from[i]][p[from[i]]][0] = to[i]; g[from[i]][p[from[i]]][1] = w[i]; --p[to[i]]; g[to[i]][p[to[i]]][0] = from[i]; g[to[i]][p[to[i]]][1] = w[i]; } return g; } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new FastWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new E().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private long[] nal(int n) { long[] a = new long[n]; for(int i = 0;i < n;i++)a[i] = nl(); return a; } 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[][] nmi(int n, int m) { int[][] map = new int[n][]; for(int i = 0;i < n;i++)map[i] = na(m); return map; } private int ni() { return (int)nl(); } 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(); } } public static class FastWriter { private static final int BUF_SIZE = 1<<13; private final byte[] buf = new byte[BUF_SIZE]; private final OutputStream out; private int ptr = 0; private FastWriter(){out = null;} public FastWriter(OutputStream os) { this.out = os; } public FastWriter(String path) { try { this.out = new FileOutputStream(path); } catch (FileNotFoundException e) { throw new RuntimeException("FastWriter"); } } public FastWriter write(byte b) { buf[ptr++] = b; if(ptr == BUF_SIZE)innerflush(); return this; } public FastWriter write(char c) { return write((byte)c); } public FastWriter write(char[] s) { for(char c : s){ buf[ptr++] = (byte)c; if(ptr == BUF_SIZE)innerflush(); } return this; } public FastWriter write(String s) { s.chars().forEach(c -> { buf[ptr++] = (byte)c; if(ptr == BUF_SIZE)innerflush(); }); return this; } private static int countDigits(int l) { if (l >= 1000000000) return 10; if (l >= 100000000) return 9; if (l >= 10000000) return 8; if (l >= 1000000) return 7; if (l >= 100000) return 6; if (l >= 10000) return 5; if (l >= 1000) return 4; if (l >= 100) return 3; if (l >= 10) return 2; return 1; } public FastWriter write(int x) { if(x == Integer.MIN_VALUE){ return write((long)x); } if(ptr + 12 >= BUF_SIZE)innerflush(); if(x < 0){ write((byte)'-'); x = -x; } int d = countDigits(x); for(int i = ptr + d - 1;i >= ptr;i--){ buf[i] = (byte)('0'+x%10); x /= 10; } ptr += d; return this; } private static int countDigits(long l) { if (l >= 1000000000000000000L) return 19; if (l >= 100000000000000000L) return 18; if (l >= 10000000000000000L) return 17; if (l >= 1000000000000000L) return 16; if (l >= 100000000000000L) return 15; if (l >= 10000000000000L) return 14; if (l >= 1000000000000L) return 13; if (l >= 100000000000L) return 12; if (l >= 10000000000L) return 11; if (l >= 1000000000L) return 10; if (l >= 100000000L) return 9; if (l >= 10000000L) return 8; if (l >= 1000000L) return 7; if (l >= 100000L) return 6; if (l >= 10000L) return 5; if (l >= 1000L) return 4; if (l >= 100L) return 3; if (l >= 10L) return 2; return 1; } public FastWriter write(long x) { if(x == Long.MIN_VALUE){ return write("" + x); } if(ptr + 21 >= BUF_SIZE)innerflush(); if(x < 0){ write((byte)'-'); x = -x; } int d = countDigits(x); for(int i = ptr + d - 1;i >= ptr;i--){ buf[i] = (byte)('0'+x%10); x /= 10; } ptr += d; return this; } public FastWriter write(double x, int precision) { if(x < 0){ write('-'); x = -x; } x += Math.pow(10, -precision)/2; // if(x < 0){ x = 0; } write((long)x).write("."); x -= (long)x; for(int i = 0;i < precision;i++){ x *= 10; write((char)('0'+(int)x)); x -= (int)x; } return this; } public FastWriter writeln(char c){ return write(c).writeln(); } public FastWriter writeln(int x){ return write(x).writeln(); } public FastWriter writeln(long x){ return write(x).writeln(); } public FastWriter writeln(double x, int precision){ return write(x, precision).writeln(); } public FastWriter write(int... xs) { boolean first = true; for(int x : xs) { if (!first) write(' '); first = false; write(x); } return this; } public FastWriter write(long... xs) { boolean first = true; for(long x : xs) { if (!first) write(' '); first = false; write(x); } return this; } public FastWriter writeln() { return write((byte)'\n'); } public FastWriter writeln(int... xs) { return write(xs).writeln(); } public FastWriter writeln(long... xs) { return write(xs).writeln(); } public FastWriter writeln(char[] line) { return write(line).writeln(); } public FastWriter writeln(char[]... map) { for(char[] line : map)write(line).writeln(); return this; } public FastWriter writeln(String s) { return write(s).writeln(); } private void innerflush() { try { out.write(buf, 0, ptr); ptr = 0; } catch (IOException e) { throw new RuntimeException("innerflush"); } } public void flush() { innerflush(); try { out.flush(); } catch (IOException e) { throw new RuntimeException("flush"); } } public FastWriter print(byte b) { return write(b); } public FastWriter print(char c) { return write(c); } public FastWriter print(char[] s) { return write(s); } public FastWriter print(String s) { return write(s); } public FastWriter print(int x) { return write(x); } public FastWriter print(long x) { return write(x); } public FastWriter print(double x, int precision) { return write(x, precision); } public FastWriter println(char c){ return writeln(c); } public FastWriter println(int x){ return writeln(x); } public FastWriter println(long x){ return writeln(x); } public FastWriter println(double x, int precision){ return writeln(x, precision); } public FastWriter print(int... xs) { return write(xs); } public FastWriter print(long... xs) { return write(xs); } public FastWriter println(int... xs) { return writeln(xs); } public FastWriter println(long... xs) { return writeln(xs); } public FastWriter println(char[] line) { return writeln(line); } public FastWriter println(char[]... map) { return writeln(map); } public FastWriter println(String s) { return writeln(s); } public FastWriter println() { return writeln(); } } public void trnz(int... o) { for(int i = 0;i < o.length;i++)if(o[i] != 0)System.out.print(i+":"+o[i]+" "); System.out.println(); } // print ids which are 1 public void trt(long... o) { Queue<Integer> stands = new ArrayDeque<>(); for(int i = 0;i < o.length;i++){ for(long x = o[i];x != 0;x &= x-1)stands.add(i<<6|Long.numberOfTrailingZeros(x)); } System.out.println(stands); } public void tf(boolean... r) { for(boolean x : r)System.out.print(x?'#':'.'); System.out.println(); } public void tf(boolean[]... b) { for(boolean[] r : b) { for(boolean x : r)System.out.print(x?'#':'.'); System.out.println(); } System.out.println(); } public void tf(long[]... b) { if(INPUT.length() != 0) { for (long[] r : b) { for (long x : r) { for (int i = 0; i < 64; i++) { System.out.print(x << ~i < 0 ? '#' : '.'); } } System.out.println(); } System.out.println(); } } public void tf(long... b) { if(INPUT.length() != 0) { for (long x : b) { for (int i = 0; i < 64; i++) { System.out.print(x << ~i < 0 ? '#' : '.'); } } System.out.println(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
4 seconds
["0 98 49 25 114", "0 -1 9"]
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
Java 11
standard input
[ "binary search", "brute force", "constructive algorithms", "dp", "flows", "graphs", "shortest paths" ]
abee4d188bb59d82fcf4579c7416a343
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
2,200
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
standard output
PASSED
f8259770784fd3f0c3900d7d2f7aec42
train_110.jsonl
1613658900
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
512 megabytes
import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.regex.*; public class C { 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()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } double nextDouble() { return Double.parseDouble(next()); } } static boolean Vist[]; static List<List<node>> Ady; static PriorityQueue<node> Q; static long Dist[]; static long INF = Long.MAX_VALUE; static class node implements Comparable<node> { int node; long weight; public node(int node, long weight) { this.node = node; this.weight = weight; } public int compareTo(node o) { return (weight - o.weight < 0) ? -1 : (weight - o.weight == 0) ? 0 : 1; } } static void relax(int actual, int ady, long peso) { if (Dist[actual] + peso < Dist[ady]) { Dist[ady] = Dist[actual] + peso; Q.add(new node(ady, Dist[ady])); } } static void dijkstra(int ini) { Q.add(new node(ini, 0)); Dist[ini] = 0; int actual, Tady; long peso; while (!Q.isEmpty()) { actual = Q.poll().node; if (Vist[actual]) { continue; } Vist[actual] = true; for (int i = 0; i < Ady.get(actual).size(); i++) { List<node> adyActual = Ady.get(Ady.get(actual).get(i).node); long w1 = Ady.get(actual).get(i).weight; for (int j = 0; j < adyActual.size(); j++) { Tady = adyActual.get(j).node; if(Tady == actual) continue; long w2 = adyActual.get(j).weight; peso = (w1+w2)*(w1+w2); if (!Vist[Tady]) { relax(actual, Tady, peso); } } } } } static void ini(int n) { Vist = new boolean[n]; Ady = new ArrayList<List<node>>(); Dist = new long[n]; Q = new PriorityQueue<node>(); Arrays.fill(Dist, INF); for (int i = 0; i < n; i++) { Ady.add(new ArrayList<node>()); } }//END DYKSTRA public static void main(String[] args) throws IOException { FastReader fr = new FastReader(); PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out)); int n, m; n = fr.nextInt(); m = fr.nextInt(); ini(n); for (int i = 0; i < m; i++) { int f, t, w; f = fr.nextInt() - 1; t = fr.nextInt() - 1; w = fr.nextInt(); Ady.get(f).add(new node(t, w)); Ady.get(t).add(new node(f, w)); } dijkstra(0); for (int i = 0; i < Dist.length; i++) { if(Dist[i] == Long.MAX_VALUE){ pw.print("-1 "); }else{ pw.print(Dist[i]+" "); } } pw.println(); pw.flush(); } }
Java
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
4 seconds
["0 98 49 25 114", "0 -1 9"]
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
Java 11
standard input
[ "binary search", "brute force", "constructive algorithms", "dp", "flows", "graphs", "shortest paths" ]
abee4d188bb59d82fcf4579c7416a343
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
2,200
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
standard output
PASSED
c1536ab63dbb6dab93a804e8a12075ad
train_110.jsonl
1613658900
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
512 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String args[]) {new Main().run();} FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); void run() { work(); out.flush(); } long mod=1000000007; long gcd(long a,long b) { return a==0?b:gcd(b%a,a); } long inf=Long.MAX_VALUE/3; ArrayList<int[]>[] graph; void work() { int n=ni(),m=ni(); graph=new ArrayList[n]; for(int i=0;i<n;i++){ graph[i]=new ArrayList<>(); } for(int i=0;i<m;i++){ int s=ni()-1,e=ni()-1,w=ni(); graph[s].add(new int[]{e,w}); graph[e].add(new int[]{s,w}); } int[][] vis=new int[n][51]; for(int[] d:vis){ Arrays.fill(d,Integer.MAX_VALUE); } PriorityQueue<int[]> pq=new PriorityQueue<>((a1,a2)->a1[1]-a2[1]); pq.add(new int[]{0,0,0});//node,dis,state vis[0][0]=0; while(pq.size()>0){ int[] q = pq.poll(); int node=q[0],dis=q[1],state=q[2]; if(vis[node][state]<dis)continue; for(int[] nn:graph[node]){ int n1=nn[0],w=nn[1]; if(state==0){ int d=dis+w*w; if(d<vis[n1][w]){ vis[n1][w]=d; pq.add(new int[]{n1,d,w}); } }else{ int d=dis+2*w*state+w*w; if(d<vis[n1][0]){ vis[n1][0]=d; pq.add(new int[]{n1,d,0}); } } } } for(int i=0;i<n;i++){ out.print((vis[i][0]==Integer.MAX_VALUE?-1:vis[i][0])+" "); } } @SuppressWarnings("unused") private ArrayList<Integer>[] ng(int n, int m) { ArrayList<Integer>[] graph=(ArrayList<Integer>[])new ArrayList[n]; for(int i=0;i<n;i++) { graph[i]=new ArrayList<>(); } for(int i=1;i<=m;i++) { int s=in.nextInt()-1,e=in.nextInt()-1; graph[s].add(e); graph[e].add(s); } return graph; } private ArrayList<long[]>[] ngw(int n, int m) { ArrayList<long[]>[] graph=(ArrayList<long[]>[])new ArrayList[n]; for(int i=0;i<n;i++) { graph[i]=new ArrayList<>(); } for(int i=1;i<=m;i++) { long s=in.nextLong()-1,e=in.nextLong()-1,w=in.nextLong(); graph[(int)s].add(new long[] {e,w}); graph[(int)e].add(new long[] {s,w}); } return graph; } private int ni() { return in.nextInt(); } private long nl() { return in.nextLong(); } private double nd() { return in.nextDouble(); } private String ns() { return in.next(); } private long[] na(int n) { long[] A=new long[n]; for(int i=0;i<n;i++) { A[i]=in.nextLong(); } return A; } private int[] nia(int n) { int[] A=new int[n]; for(int i=0;i<n;i++) { A[i]=in.nextInt(); } return A; } } class FastReader { BufferedReader br; StringTokenizer st; InputStreamReader input;//no buffer public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } public FastReader(boolean isBuffer) { if(!isBuffer){ input=new InputStreamReader(System.in); }else{ br=new BufferedReader(new InputStreamReader(System.in)); } } public boolean hasNext(){ try{ String s=br.readLine(); if(s==null){ return false; } st=new StringTokenizer(s); }catch(IOException e){ e.printStackTrace(); } return true; } public String next() { if(input!=null){ try { StringBuilder sb=new StringBuilder(); int ch=input.read(); while(ch=='\n'||ch=='\r'||ch==32){ ch=input.read(); } while(ch!='\n'&&ch!='\r'&&ch!=32){ sb.append((char)ch); ch=input.read(); } return sb.toString(); }catch (Exception e){ e.printStackTrace(); } } while(st==null || !st.hasMoreElements())//回车,空行情况 { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return (int)nextLong(); } public long nextLong() { try { if(input!=null){ long ret=0; int b=input.read(); while(b<'0'||b>'9'){ b=input.read(); } while(b>='0'&&b<='9'){ ret=ret*10+(b-'0'); b=input.read(); } return ret; } }catch (Exception e){ e.printStackTrace(); } return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } }
Java
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
4 seconds
["0 98 49 25 114", "0 -1 9"]
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "dp", "flows", "graphs", "shortest paths" ]
abee4d188bb59d82fcf4579c7416a343
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
2,200
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
standard output
PASSED
a1b471273b6f74ec548908da6721de2f
train_110.jsonl
1613658900
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
512 megabytes
// Don't place your source in a package import java.lang.reflect.Array; import java.text.DecimalFormat; import java.util.*; import java.lang.*; import java.io.*; import java.math.*; import java.util.stream.Stream; // Please name your class Main public class Main { static FastScanner fs=new FastScanner(); static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); public String next() { while (!st.hasMoreElements()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int Int() { return Integer.parseInt(next()); } long Long() { return Long.parseLong(next()); } String Str(){ return next(); } } public static void main (String[] args) throws java.lang.Exception { PrintWriter out = new PrintWriter(System.out); int T=1; for(int t=0;t<T;t++){ int n=Int();int m=Int(); List<int[]>g[]=new ArrayList[n]; for(int i=0;i<g.length;i++){ g[i]=new ArrayList<>(); } for(int i=0;i<m;i++){ int u=Int()-1,v=Int()-1,w=Int(); g[u].add(new int[]{v,w}); g[v].add(new int[]{u,w}); } Solution sol=new Solution(); sol.solution(out,g); } out.flush(); } public static int Int(){ return fs.Int(); } public static long Long(){ return fs.Long(); } public static String Str(){ return fs.Str(); } } class Solution{ public void solution(PrintWriter out,List<int[]>g[]){ int n=g.length; int dis[][][]=new int[51][n][2]; for(int i=0;i<dis.length;i++){ for(int j=0;j<dis[0].length;j++){ Arrays.fill(dis[i][j],Integer.MAX_VALUE); } } PriorityQueue<int[]>q=new PriorityQueue<>((a,b)->{ return a[3]-b[3]; }); q.add(new int[]{0,0,0,0}); dis[0][0][0]=0; while(q.size()>0){ int top[]=q.poll(); int pre=top[0],root=top[1],level=top[2]; level%=2; if(top[3]!=dis[pre][root][level])continue; for(int p[]:g[root]){ int next=p[0],w=p[1]; int mn=Integer.MAX_VALUE; if(level%2==0){ mn=Math.min(mn,dis[pre][root][level]); } else{ mn=Math.min(mn,dis[pre][root][level]+(pre+w)*(pre+w)); } if(mn!=Integer.MAX_VALUE && dis[w][next][(level+1)%2]>mn){ dis[w][next][(level+1)%2]=mn; q.add(new int[]{w,next,(level+1)%2,mn}); } } } for(int i=0;i<dis[0].length;i++){ int mn=Integer.MAX_VALUE; for(int j=0;j<dis.length;j++){ mn=Math.min(mn,dis[j][i][0]); } if(mn==Integer.MAX_VALUE)out.print("-1 "); else out.print(mn+" "); } } }
Java
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
4 seconds
["0 98 49 25 114", "0 -1 9"]
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "dp", "flows", "graphs", "shortest paths" ]
abee4d188bb59d82fcf4579c7416a343
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
2,200
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
standard output
PASSED
2a32d3e07bc3d97f674d9379a16c16f9
train_110.jsonl
1613658900
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
512 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { public static void main(String[] args) throws IOException { InputStream inputStream = System.in; OutputStream outputStream = System.out; PrintWriter out = new PrintWriter(outputStream); InputReader in = new InputReader(inputStream); // for(int i=4;i<=4;i++) { // InputStream uinputStream = new FileInputStream("timeline.in"); //String f = i+".in"; //InputStream uinputStream = new FileInputStream(f); // InputReader in = new InputReader(uinputStream); // PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("timeline.out"))); // } Task t = new Task(); t.solve(in, out); out.close(); } static class Task{ public void solve(InputReader in, PrintWriter out) throws IOException { int n = in.nextInt(); int m = in.nextInt(); ArrayList<edge>[] g = new ArrayList[n]; for(int i=0;i<n;i++) g[i] = new ArrayList<edge>(); for(int i=0;i<m;i++) { int f = in.nextInt()-1; int t = in.nextInt()-1; int l = in.nextInt(); g[f].add(new edge(f,t,l,i,0)); g[t].add(new edge(t,f,l,i,0)); } int dist[][] = dijkstra(g,n); for(int i=0;i<n;i++) { if(dist[i][0]==999999999) out.print(-1+" "); else out.print(dist[i][0]+" "); } out.println(); } int[][] dijkstra(ArrayList<edge>[] g, int n) { boolean vis[][] = new boolean[n][101]; int dist[][] = new int[n][101]; PriorityQueue<edge> pq = new PriorityQueue<edge>(); vis[0][0] = true; for(int i=0;i<n;i++) Arrays.fill(dist[i], 999999999); dist[0][0] = 0; for(edge e:g[0]) { pq.add(new edge(e.f,e.t,e.len,1,e.len)); } while(!pq.isEmpty()) { edge e = pq.poll(); if(e.id==0&&vis[e.t][0]) continue; if(e.id==1&&vis[e.t][e.short_len]) continue; if(e.id==0) { dist[e.t][0] = e.len; vis[e.t][0] = true; }else { dist[e.t][e.short_len] = e.len; vis[e.t][e.short_len] = true; } for(edge nxt:g[e.t]) { int cost = nxt.len; if(e.id==1) cost = (e.short_len+nxt.len)*(e.short_len+nxt.len); if(e.id==0) { if(dist[nxt.t][cost] > dist[nxt.f][0]+cost) { dist[nxt.t][cost] = dist[nxt.f][0]+cost; pq.add(new edge(nxt.f,nxt.t,dist[nxt.t][cost],1,cost)); } }else { if(dist[nxt.t][0] > dist[e.f][0]+cost) { dist[nxt.t][0] = dist[e.f][0]+cost; pq.add(new edge(nxt.f,nxt.t,dist[nxt.t][0],0,nxt.len)); } } } } return dist; } private static int combx(int n, int k) { int comb[][] = new int[n+1][n+1]; for(int i = 0; i <=n; i ++){ comb[i][0] = comb[i][i] = 1; for(int j = 1; j < i; j++){ comb[i][j] = comb[i-1][j] + comb[i-1][j-1]; comb[i][j] %= 1000000007; } } return comb[n][k]; } class trie_node{ boolean end; int val; int lvl; trie_node zero; trie_node one; public trie_node() { zero = null; one = null; end = false; val = -1; lvl = -1; } } class trie{ trie_node root = new trie_node(); public void build(int x, int sz) { trie_node cur = root; for(int i=sz;i>=0;i--) { int v = (x&(1<<i))==0?0:1; if(v==0&&cur.zero==null) { cur.zero = new trie_node(); } if(v==1&&cur.one==null) { cur.one = new trie_node(); } cur.lvl = i; if(i==0) { cur.end = true; cur.val = x; }else { if(v==0) cur = cur.zero; else cur = cur.one; cur.val = v; cur.lvl = i; } } } int search(int num, int limit, trie_node r, int lvl) { if(r==null) return -1; if(r.end) return r.val; int f = -1; int num_val = (num&1<<lvl)==0?0:1; int limit_val = (limit&1<<lvl)==0?0:1; if(limit_val==1) { if(num_val==0) { int t = search(num,limit,r.one,lvl-1); if(t>f) return t; t = search(num,limit,r.zero,lvl-1); if(t>f) return t; }else { int t = search(num,limit,r.zero,lvl-1); if(t>f) return t; t = search(num,limit,r.one,lvl-1); if(t>f) return t; } }else { int t = search(num,limit,r.zero,lvl-1); if(t>f) return t; } return f; } } public int[] maximizeXor(int[] nums, int[][] queries) { int m = queries.length; int ret[] = new int[m]; trie t = new trie(); int sz = 5; for(int i:nums) t.build(i,sz); int p = 0; for(int x[]:queries) { if(p==1) { Dumper.print("here"); } ret[p++] = t.search(x[0], x[1], t.root, sz); } return ret; } class edge implements Comparable<edge>{ int id,f,t; int len;int short_len; public edge(int a, int b, int c, int d, int e) { f=a;t=b;len=c;id=d;short_len = e; } @Override public int compareTo(edge t) { if(this.len-t.len>0) return 1; else if(this.len-t.len<0) return -1; return 0; } } static class lca_naive{ int n; ArrayList<edge>[] g; int lvl[]; int pare[]; int dist[]; public lca_naive(int t, ArrayList<edge>[] x) { n=t; g=x; lvl = new int[n]; pare = new int[n]; dist = new int[n]; } void pre_process() { dfs(0,-1,g,lvl,pare,dist); } void dfs(int cur, int pre, ArrayList<edge>[] g, int lvl[], int pare[], int dist[]) { for(edge nxt_edge:g[cur]) { if(nxt_edge.t!=pre) { lvl[nxt_edge.t] = lvl[cur]+1; dist[nxt_edge.t] = dist[cur]+nxt_edge.len; pare[nxt_edge.t] = cur; dfs(nxt_edge.t,cur,g,lvl,pare,dist); } } } public int work(int p, int q) { int a = p; int b = q; while(lvl[p]<lvl[q]) q = pare[q]; while(lvl[p]>lvl[q]) p = pare[p]; while(p!=q){p = pare[p]; q = pare[q];} int c = p; return dist[a]+dist[b]-dist[c]*2; } } static class lca_binary_lifting{ int n; ArrayList<edge>[] g; int lvl[]; int pare[]; int dist[]; int table[][]; public lca_binary_lifting(int a, ArrayList<edge>[] t) { n = a; g = t; lvl = new int[n]; pare = new int[n]; dist = new int[n]; table = new int[20][n]; } void pre_process() { dfs(0,-1,g,lvl,pare,dist); for(int i=0;i<20;i++) { for(int j=0;j<n;j++) { if(i==0) table[0][j] = pare[j]; else table[i][j] = table[i-1][table[i-1][j]]; } } } void dfs(int cur, int pre, ArrayList<edge>[] g, int lvl[], int pare[], int dist[]) { for(edge nxt_edge:g[cur]) { if(nxt_edge.t!=pre) { lvl[nxt_edge.t] = lvl[cur]+1; dist[nxt_edge.t] = dist[cur]+nxt_edge.len; pare[nxt_edge.t] = cur; dfs(nxt_edge.t,cur,g,lvl,pare,dist); } } } public int work(int p, int q) { int a = p; int b = q; if(lvl[p]>lvl[q]) { int tmp = p; p=q; q=tmp; } for(int i=19;i>=0;i--) { if(lvl[table[i][q]]>=lvl[p]) q=table[i][q]; } if(p==q) return p;// return dist[a]+dist[b]-dist[p]*2; for(int i=19;i>=0;i--) { if(table[i][p]!=table[i][q]) { p = table[i][p]; q = table[i][q]; } } return table[0][p]; //return dist[a]+dist[b]-dist[table[0][p]]*2; } } static class lca_sqrt_root{ int n; ArrayList<edge>[] g; int lvl[]; int pare[]; int dist[]; int jump[]; int sz; public lca_sqrt_root(int a, ArrayList<edge>[] b) { n=a; g=b; lvl = new int[n]; pare = new int[n]; dist = new int[n]; jump = new int[n]; sz = (int) Math.sqrt(n); } void pre_process() { dfs(0,-1,g,lvl,pare,dist,jump); } void dfs(int cur, int pre, ArrayList<edge>[] g, int lvl[], int pare[], int dist[], int[] jump) { for(edge nxt_edge:g[cur]) { if(nxt_edge.t!=pre) { lvl[nxt_edge.t] = lvl[cur]+1; dist[nxt_edge.t] = dist[cur]+nxt_edge.len; pare[nxt_edge.t] = cur; if(lvl[nxt_edge.t]%sz==0) { jump[nxt_edge.t] = cur; }else { jump[nxt_edge.t] = jump[cur]; } dfs(nxt_edge.t,cur,g,lvl,pare,dist,jump); } } } int work(int p, int q) { int a = p; int b = q; if(lvl[p]>lvl[q]) { int tmp = p; p=q; q=tmp; } while(jump[p]!=jump[q]) { if(lvl[p]>lvl[q]) p = jump[p]; else q = jump[q]; } while(p!=q) { if(lvl[p]>lvl[q]) p = pare[p]; else q = pare[q]; } return dist[a]+dist[b]-dist[p]*2; } } // class edge implements Comparable<edge>{ // int f,t,len; // public edge(int a, int b, int c) { // f=a;t=b;len=c; // } // @Override // public int compareTo(edge t) { // return t.len-this.len; // } // } class pair implements Comparable<pair>{ int idx,lvl; public pair(int a, int b) { idx = a; lvl = b; } @Override public int compareTo(pair t) { return t.lvl-this.lvl; } } static class lca_RMQ{ int n; ArrayList<edge>[] g; int lvl[]; int dist[]; int tour[]; int tour_rank[]; int first_occ[]; int c; sgt s; public lca_RMQ(int a, ArrayList<edge>[] b) { n=a; g=b; c=0; lvl = new int[n]; dist = new int[n]; tour = new int[2*n]; tour_rank = new int[2*n]; first_occ = new int[n]; Arrays.fill(first_occ, -1); } void pre_process() { tour[c++] = 0; dfs(0,-1); for(int i=0;i<2*n;i++) { tour_rank[i] = lvl[tour[i]]; if(first_occ[tour[i]]==-1) first_occ[tour[i]] = i; } s = new sgt(0,2*n,tour_rank); } void dfs(int cur, int pre) { for(edge nxt_edge:g[cur]) { if(nxt_edge.t!=pre) { lvl[nxt_edge.t] = lvl[cur]+1; dist[nxt_edge.t] = dist[cur]+nxt_edge.len; tour[c++] = nxt_edge.t; dfs(nxt_edge.t,cur); tour[c++] = cur; } } } int work(int p,int q) { int a = Math.max(first_occ[p], first_occ[q]); int b = Math.min(first_occ[p], first_occ[q]); int idx = s.query_min_idx(b, a+1); //Dumper.print(a+" "+b+" "+idx); int c = tour[idx]; return dist[p]+dist[q]-dist[c]*2; } } static class sgt{ sgt lt; sgt rt; int l,r; int sum, max, min, lazy; int min_idx; public sgt(int L, int R, int arr[]) { l=L;r=R; if(l==r-1) { sum = max = min = arr[l]; lazy = 0; min_idx = l; return; } lt = new sgt(l, l+r>>1, arr); rt = new sgt(l+r>>1, r, arr); pop_up(); } void pop_up() { this.sum = lt.sum + rt.sum; this.max = Math.max(lt.max, rt.max); this.min = Math.min(lt.min, rt.min); if(lt.min<rt.min) this.min_idx = lt.min_idx; else if(lt.min>rt.min) this.min_idx = rt.min_idx; else this.min = Math.min(lt.min_idx, rt.min_idx); } void push_down() { if(this.lazy!=0) { lt.sum+=lazy; rt.sum+=lazy; lt.max+=lazy; lt.min+=lazy; rt.max+=lazy; rt.min+=lazy; lt.lazy+=this.lazy; rt.lazy+=this.lazy; this.lazy = 0; } } void change(int L, int R, int v) { if(R<=l||r<=L) return; if(L<=l&&r<=R) { this.max+=v; this.min+=v; this.sum+=v*(r-l); this.lazy+=v; return; } push_down(); lt.change(L, R, v); rt.change(L, R, v); pop_up(); } int query_max(int L, int R) { if(L<=l&&r<=R) return this.max; if(r<=L||R<=l) return Integer.MIN_VALUE; push_down(); return Math.max(lt.query_max(L, R), rt.query_max(L, R)); } int query_min(int L, int R) { if(L<=l&&r<=R) return this.min; if(r<=L||R<=l) return Integer.MAX_VALUE; push_down(); return Math.min(lt.query_min(L, R), rt.query_min(L, R)); } int query_sum(int L, int R) { if(L<=l&&r<=R) return this.sum; if(r<=L||R<=l) return 0; push_down(); return lt.query_sum(L, R) + rt.query_sum(L, R); } int query_min_idx(int L, int R) { if(L<=l&&r<=R) return this.min_idx; if(r<=L||R<=l) return Integer.MAX_VALUE; int a = lt.query_min_idx(L, R); int b = rt.query_min_idx(L, R); int aa = lt.query_min(L, R); int bb = rt.query_min(L, R); if(aa<bb) return a; else if(aa>bb) return b; return Math.min(a,b); } } List<List<Integer>> convert(int arr[][]){ int n = arr.length; List<List<Integer>> ret = new ArrayList<>(); for(int i=0;i<n;i++) { ArrayList<Integer> tmp = new ArrayList<Integer>(); for(int j=0;j<arr[i].length;j++) tmp.add(arr[i][j]); ret.add(tmp); } return ret; } public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public int GCD(int a, int b) { if (b==0) return a; return GCD(b,a%b); } public long GCD(long a, long b) { if (b==0) return a; return GCD(b,a%b); } } static class ArrayUtils { static final long seed = System.nanoTime(); static final Random rand = new Random(seed); public static void sort(int[] a) { shuffle(a); Arrays.sort(a); } public static void shuffle(int[] a) { for (int i = 0; i < a.length; i++) { int j = rand.nextInt(i + 1); int t = a[i]; a[i] = a[j]; a[j] = t; } } public static void sort(long[] a) { shuffle(a); Arrays.sort(a); } public static void shuffle(long[] a) { for (int i = 0; i < a.length; i++) { int j = rand.nextInt(i + 1); long t = a[i]; a[i] = a[j]; a[j] = t; } } } static class BIT{ int arr[]; int n; public BIT(int a) { n=a; arr = new int[n]; } int sum(int p) { int s=0; while(p>0) { s+=arr[p]; p-=p&(-p); } return s; } void add(int p, int v) { while(p<n) { arr[p]+=v; p+=p&(-p); } } } static class DSU{ int[] arr; int[] sz; public DSU(int n) { arr = new int[n]; sz = new int[n]; for(int i=0;i<n;i++) arr[i] = i; Arrays.fill(sz, 1); } public int find(int a) { if(arr[a]!=a) arr[a] = find(arr[a]); return arr[a]; } public void union(int a, int b) { int x = find(a); int y = find(b); if(x==y) return; arr[y] = x; sz[x] += sz[y]; } public int size(int x) { return sz[find(x)]; } } static class MinHeap<Key> implements Iterable<Key> { private int maxN; private int n; private int[] pq; private int[] qp; private Key[] keys; private Comparator<Key> comparator; public MinHeap(int capacity){ if (capacity < 0) throw new IllegalArgumentException(); this.maxN = capacity; n=0; pq = new int[maxN+1]; qp = new int[maxN+1]; keys = (Key[]) new Object[capacity+1]; Arrays.fill(qp, -1); } public MinHeap(int capacity, Comparator<Key> c){ if (capacity < 0) throw new IllegalArgumentException(); this.maxN = capacity; n=0; pq = new int[maxN+1]; qp = new int[maxN+1]; keys = (Key[]) new Object[capacity+1]; Arrays.fill(qp, -1); comparator = c; } public boolean isEmpty() { return n==0; } public int size() { return n; } public boolean contains(int i) { if (i < 0 || i >= maxN) throw new IllegalArgumentException(); return qp[i] != -1; } public int peekIdx() { if (n == 0) throw new NoSuchElementException("Priority queue underflow"); return pq[1]; } public Key peek(){ if(isEmpty()) throw new NoSuchElementException("Priority queue underflow"); return keys[pq[1]]; } public int poll(){ if(isEmpty()) throw new NoSuchElementException("Priority queue underflow"); int min = pq[1]; exch(1,n--); down(1); assert min==pq[n+1]; qp[min] = -1; keys[min] = null; pq[n+1] = -1; return min; } public void update(int i, Key key) { if (i < 0 || i >= maxN) throw new IllegalArgumentException(); if (!contains(i)) { this.add(i, key); }else { keys[i] = key; up(qp[i]); down(qp[i]); } } private void add(int i, Key x){ if (i < 0 || i >= maxN) throw new IllegalArgumentException(); if (contains(i)) throw new IllegalArgumentException("index is already in the priority queue"); n++; qp[i] = n; pq[n] = i; keys[i] = x; up(n); } private void up(int k){ while(k>1&&less(k,k/2)){ exch(k,k/2); k/=2; } } private void down(int k){ while(2*k<=n){ int j=2*k; if(j<n&&less(j+1,j)) j++; if(less(k,j)) break; exch(k,j); k=j; } } public boolean less(int i, int j){ if (comparator == null) { return ((Comparable<Key>) keys[pq[i]]).compareTo(keys[pq[j]]) < 0; } else { return comparator.compare(keys[pq[i]], keys[pq[j]]) < 0; } } public void exch(int i, int j){ int swap = pq[i]; pq[i] = pq[j]; pq[j] = swap; qp[pq[i]] = i; qp[pq[j]] = j; } @Override public Iterator<Key> iterator() { // TODO Auto-generated method stub return null; } } private static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int zcurChar; private int znumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (znumChars == -1) throw new InputMismatchException(); if (zcurChar >= znumChars) { zcurChar = 0; try { znumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (znumChars <= 0) return -1; } return buf[zcurChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return nextString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } public int[] readIntArray(int n) { int[] ret = new int[n]; for (int i = 0; i < n; i++) { ret[i] = nextInt(); } return ret; } } static class Dumper { static void print_int_arr(int[] arr) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); System.out.println("---------------------"); } static void print_char_arr(char[] arr) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); System.out.println("---------------------"); } static void print_double_arr(double[] arr) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); System.out.println("---------------------"); } static void print_2d_arr(int[][] arr, int x, int y) { for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { System.out.print(arr[i][j] + " "); } System.out.println(); } System.out.println(); System.out.println("---------------------"); } static void print_2d_arr(boolean[][] arr, int x, int y) { for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { System.out.print(arr[i][j] + " "); } System.out.println(); } System.out.println(); System.out.println("---------------------"); } static void print(Object o) { System.out.println(o.toString()); } static void getc() { System.out.println("here"); } } }
Java
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
4 seconds
["0 98 49 25 114", "0 -1 9"]
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "dp", "flows", "graphs", "shortest paths" ]
abee4d188bb59d82fcf4579c7416a343
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
2,200
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
standard output
PASSED
4ef4f7a309cc7008a59d1d5abb6c3982
train_110.jsonl
1613658900
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
512 megabytes
import java.util.*; import java.io.*; public class A{ public static void main(String [] args)throws IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); FastReader sc=new FastReader(); PrintWriter pw=new PrintWriter(System.out); int test=1; StringBuffer ans=new StringBuffer(); while(test-->0){ int n=sc.nextInt(); int m=sc.nextInt(); ArrayList<Pair> arr[]=new ArrayList[n+1]; for(int i=0;i<=n;i++) arr[i]=new ArrayList<Pair>(); while(m-->0){ int source=sc.nextInt(); int dest = sc.nextInt(); int weight = sc.nextInt(); arr[source].add(new Pair(dest,weight)); arr[dest].add(new Pair(source,weight)); } int [][] d=djikstra(1,n,arr); for(int i=1;i<=n;i++){ if(d[i][0] == Integer.MAX_VALUE) d[i][0]=-1; ans.append(d[i][0]+" "); } pw.println(ans); pw.close(); } } static class Pair{ int dest=0; int wt=0; int lastEdg=0; Pair(){} Pair(int d,int w){ dest=d; wt =w; } Pair(int d,int v,int lastEdg){ dest=d; wt=v; this.lastEdg=lastEdg; } } static class customSort implements Comparator<Pair>{ public int compare(Pair a,Pair b){ if(a.wt<b.wt){ return -1; } else if(a.wt>b.wt){ return 1; } return 0; } } public static int [][] djikstra(int source,int n,ArrayList<Pair> arr[]){ int dp[][]=new int[n+1][51]; for(int i=0;i<=n;i++) Arrays.fill(dp[i], Integer.MAX_VALUE); PriorityQueue<Pair> pq=new PriorityQueue<>(new customSort()); boolean vis[][]=new boolean[n+1][51]; pq.add(new Pair(source,0)); dp[1][0]=0; while(!pq.isEmpty()){ Pair x=pq.poll(); int nd =x.dest; int wt =x.wt; int lastEdg =x.lastEdg; if(vis[nd][lastEdg]){ continue; } vis[nd][lastEdg]=true; for(int i=0;i<arr[nd].size();i++){ Pair y=arr[nd].get(i); int ch=y.dest; int wtc=y.wt; int newDist = wt; if(lastEdg>0) { newDist +=((lastEdg+wtc)*(lastEdg+wtc)); wtc=0; } if(dp[ch][wtc]>newDist) { dp[ch][wtc]=newDist; pq.add(new Pair(ch,newDist,wtc)); } } } return dp; } /** * Fast I/O */ static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
4 seconds
["0 98 49 25 114", "0 -1 9"]
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "dp", "flows", "graphs", "shortest paths" ]
abee4d188bb59d82fcf4579c7416a343
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
2,200
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
standard output
PASSED
82d3b17f44c70c036086865f3854c10a
train_110.jsonl
1613658900
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
512 megabytes
import java.util.*; import java.io.*; public class A{ public static void main(String [] args)throws IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); FastReader sc=new FastReader(); PrintWriter pw=new PrintWriter(System.out); int test=1; while(test-->0){ int n=sc.nextInt(); int m=sc.nextInt(); ArrayList<Pair> arr[]=new ArrayList[n+1]; for(int i=0;i<=n;i++) arr[i]=new ArrayList<Pair>(); try{ while(m-->0){ int source=sc.nextInt(); int dest = sc.nextInt(); int weight = sc.nextInt(); arr[source].add(new Pair(dest,weight)); arr[dest].add(new Pair(source,weight)); } } catch(Exception e){ } int [][] d=djikstra(1,n,arr); for(int i=1;i<=n;i++){ if(d[i][0] == Integer.MAX_VALUE) d[i][0]=-1; pw.print(d[i][0]+" "); } pw.println(); pw.close(); } } static class Pair{ int dest=0; int wt=0; int lastEdg=0; Pair(){} Pair(int d,int w){ dest=d; wt =w; } Pair(int d,int v,int lastEdg){ dest=d; wt=v; this.lastEdg=lastEdg; } } static class customSort implements Comparator<Pair>{ public int compare(Pair a,Pair b){ if(a.wt<b.wt){ return -1; } else if(a.wt>b.wt){ return 1; } return 0; } } public static int [][] djikstra(int source,int n,ArrayList<Pair> arr[]){ int dp[][]=new int[n+1][51]; for(int i=0;i<=n;i++) Arrays.fill(dp[i], Integer.MAX_VALUE); PriorityQueue<Pair> pq=new PriorityQueue<>(new customSort()); boolean vis[][]=new boolean[n+1][51]; pq.add(new Pair(source,0)); dp[1][0]=0; while(!pq.isEmpty()){ Pair x=pq.poll(); int nd =x.dest; int wt =x.wt; int lastEdg =x.lastEdg; if(vis[nd][lastEdg]){ continue; } vis[nd][lastEdg]=true; for(int i=0;i<arr[nd].size();i++){ Pair y=arr[nd].get(i); int ch=y.dest; int wtc=y.wt; int newDist = wt; if(lastEdg>0) { newDist +=((lastEdg+wtc)*(lastEdg+wtc)); wtc=0; } if(dp[ch][wtc]>newDist) { dp[ch][wtc]=newDist; pq.add(new Pair(ch,newDist,wtc)); } } } return dp; } /** * Fast I/O */ static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
4 seconds
["0 98 49 25 114", "0 -1 9"]
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "dp", "flows", "graphs", "shortest paths" ]
abee4d188bb59d82fcf4579c7416a343
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
2,200
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
standard output
PASSED
985dd4e360bdfd1458244e5769622c60
train_110.jsonl
1613658900
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
512 megabytes
import java.io.*; import java.util.*; public class E { static class node implements Comparable<node> { int node, p; Cost cost; node(int u, int par, Cost c) { node = u; p = par; cost = c; } @Override public int compareTo(node o) { // TODO Auto-generated method stub return cost.compareTo(o.cost); } } static class Cost { long cost; int last; Cost(long c, int l) { cost = c; last = l; } public int compareTo(Cost other) { if (cost != other.cost) return Long.compare(cost, other.cost); return last - other.last; } } static int n, m; static ArrayList<int[]> adj[]; static long INF = (long) 1e18; static long[] solve() { PriorityQueue<node> pq = new PriorityQueue(); long[][] dist2 = new long[n][51]; long[] dist = new long[n]; Arrays.fill(dist, INF); for (long[] x : dist2) Arrays.fill(x, INF); dist[0] = 0; pq.add(new node(0, 0, new Cost(0, 0))); while (!pq.isEmpty()) { node curr = pq.poll(); int u = curr.node, p = curr.p; Cost cost = curr.cost; if (p == 0 && cost.cost > dist[u]) continue; if (p == 1 && cost.cost > dist2[u][cost.last]) continue; for (int[] nxt : adj[u]) { int v = nxt[0]; int w = nxt[1]; if (p == 0) { if (dist2[v][w] > cost.cost) pq.add(new node(v, p ^ 1, new Cost(dist2[v][w] = cost.cost, w))); } else { long total = cost.cost + (w + cost.last) * 1L * (w + cost.last); if (dist[v] > total) pq.add(new node(v, p ^ 1, new Cost(dist[v] = total, 0))); } } } return dist; } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); n = sc.nextInt(); m = sc.nextInt(); adj = new ArrayList[n]; for (int i = 0; i < n; i++) adj[i] = new ArrayList(); while (m-- > 0) { int u = sc.nextInt() - 1, v = sc.nextInt() - 1, w = sc.nextInt(); adj[u].add(new int[] { v, w }); adj[v].add(new int[] { u, w }); } long[] ans = solve(); for (long x : ans) { if (x == INF) out.print(-1 + " "); else out.print(x + " "); } out.println(); out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } Scanner(String fileName) throws FileNotFoundException { br = new BufferedReader(new FileReader(fileName)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { return br.readLine(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } boolean ready() throws IOException { return br.ready() || st.hasMoreTokens(); } int[] nxtArr(int n) throws IOException { int[] ans = new int[n]; for (int i = 0; i < n; i++) ans[i] = nextInt(); return ans; } } static void sort(int[] a) { shuffle(a); Arrays.sort(a); } static void shuffle(int[] a) { int n = a.length; Random rand = new Random(); for (int i = 0; i < n; i++) { int tmpIdx = rand.nextInt(n); int tmp = a[i]; a[i] = a[tmpIdx]; a[tmpIdx] = tmp; } } }
Java
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
4 seconds
["0 98 49 25 114", "0 -1 9"]
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "dp", "flows", "graphs", "shortest paths" ]
abee4d188bb59d82fcf4579c7416a343
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
2,200
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
standard output
PASSED
e95764f259adba36cb57164c10a10dd8
train_110.jsonl
1613658900
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
512 megabytes
import java.util.*; import java.io.*; public class E1486 { static ArrayList<int[]>[] adjList; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); int m = sc.nextInt(); adjList = new ArrayList[n]; for (int i = 0; i < n; i++) { adjList[i] = new ArrayList<int[]>(); } while (m-- > 0) { int u = sc.nextInt() - 1; int v = sc.nextInt() - 1; int w = sc.nextInt(); adjList[u].add(new int[] { v, w }); adjList[v].add(new int[] { u, w }); } int[][] dist = new int[51][n]; for (int[] x : dist) Arrays.fill(x, (int) 1e9); dist[0][0] = 0; PriorityQueue<int[]> pq = new PriorityQueue<int[]>((u, v) -> u[2] - v[2]); pq.add(new int[] { 0, 0, 0 }); while (!pq.isEmpty()) { int[] cur = pq.poll(); if (cur[2] > dist[cur[1]][cur[0]]) continue; if (cur[1] == 0) { for (int[] x : adjList[cur[0]]) { if (cur[2] < dist[x[1]][x[0]]) { pq.add(new int[] { x[0], x[1], dist[x[1]][x[0]] = cur[2] }); } } } else { for (int[] x : adjList[cur[0]]) { if (cur[2] + (cur[1] + x[1]) * (cur[1] + x[1]) < dist[0][x[0]]) { pq.add(new int[] { x[0], 0, dist[0][x[0]] = cur[2] + (cur[1] + x[1]) * (cur[1] + x[1]) }); } } } } for (int x : dist[0]) { pw.print((x == (int) 1e9 ? -1 : x) + " "); } pw.println(); pw.close(); } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader f) { br = new BufferedReader(f); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public int[] nextIntArr(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = Integer.parseInt(next()); } return arr; } } }
Java
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
4 seconds
["0 98 49 25 114", "0 -1 9"]
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "dp", "flows", "graphs", "shortest paths" ]
abee4d188bb59d82fcf4579c7416a343
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
2,200
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
standard output
PASSED
374cbfcd344f81c2f029f861c4c4292e
train_110.jsonl
1613658900
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
512 megabytes
import java.util.*; import java.io.*; public class Div708 { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////// ///////// //////// ///////// //////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOOOOO SSSSSSS EEEEEEEEEEEEE ///////// //////// HHHH HHHH EEEEEEEEEEEEE MMMMMM MMMMMM OOO OOO SSSS SSS EEEEEEEEEEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMM MMM MMMM OOO OOO SSSS SSS EEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMMMMM MMMM OOO OOO SSSS EEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSSSSSS EEEEE ///////// //////// HHHHHHHHHHHHHHHH EEEEEEEEEEE MMMM MMMM OOO OOO SSSSSS EEEEEEEEEEE ///////// //////// HHHHHHHHHHHHHHHH EEEEEEEEEEE MMMM MMMM OOO OOO SSSSSSS EEEEEEEEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSSS EEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSS SSSS EEEEE ///////// //////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOO OOO SSS SSSS EEEEEEEEEEEEE ///////// //////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOOOOO SSSSSSS EEEEEEEEEEEEE ///////// //////// ///////// //////// ///////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); int m = sc.nextInt(); ArrayList<int[]> adj[] = new ArrayList[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); } while (m-- > 0) { int u = sc.nextInt() - 1; int v = sc.nextInt() - 1; int w = sc.nextInt(); adj[u].add(new int[]{v, w}); adj[v].add(new int[]{u, w}); } long[][][] dis = new long[2][51][n]; for (long[][] x : dis) for (long[] y : x) Arrays.fill(y, -1); PriorityQueue<long[]> pq = new PriorityQueue<>((x, y) -> Long.compare(x[3], y[3])); long[] st = new long[]{1, 0, 0, 0}; pq.add(st); dis[1][0][0] = 0; while (!pq.isEmpty()) { long[] cur = pq.poll(); int s = (int) cur[0]; int w = (int) cur[1]; int u = (int) cur[2]; long cost = cur[3]; if (dis[s][w][u] < cost) continue; // System.err.println(Arrays.toString(cur)); if (s == 0) { for (int[] v : adj[u]) { long ncost = cost + (w + v[1]) * (w + v[1]); if (dis[1][v[1]][v[0]] == -1 || ncost < dis[1][v[1]][v[0]]) { pq.add(new long[]{1, v[1], v[0], dis[1][v[1]][v[0]] = ncost}); } } } else { for (int[] v : adj[u]) { if (dis[0][v[1]][v[0]] == -1 || cost < dis[0][v[1]][v[0]]) { pq.add(new long[]{0, v[1], v[0], dis[0][v[1]][v[0]] = cost}); } } } } long[] cost = new long[n]; Arrays.fill(cost, -1); for (int i = 0; i < n; i++) { for (int w = 0; w <= 50; w++) { if (dis[1][w][i] == -1) continue; if (cost[i] == -1 || dis[1][w][i] < cost[i]) cost[i] = dis[1][w][i]; } pw.print(cost[i] + " "); } pw.println(); pw.flush(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(FileReader r) { br = new BufferedReader(r); } public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int[] nextIntArr(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
4 seconds
["0 98 49 25 114", "0 -1 9"]
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "dp", "flows", "graphs", "shortest paths" ]
abee4d188bb59d82fcf4579c7416a343
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
2,200
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
standard output
PASSED
a21691ca9a82c0945fb44e8bdea712cc
train_110.jsonl
1613658900
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.PriorityQueue; import java.util.AbstractQueue; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.AbstractCollection; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Khater */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); EPairedPayment solver = new EPairedPayment(); solver.solve(1, in, out); out.close(); } static class EPairedPayment { long INF = (long) 1e15; ArrayList<EPairedPayment.Edge>[] adjList; long[] dist; int[] cnt; int V; public void solve(int testNumber, Scanner sc, PrintWriter pw) { int t = 1; // t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int m = sc.nextInt(); V = n; adjList = new ArrayList[n]; for (int i = 0; i < n; i++) adjList[i] = new ArrayList<>(); for (int i = 0; i < m; i++) { int x = sc.nextInt() - 1; int y = sc.nextInt() - 1; long w = sc.nextLong(); adjList[x].add(new EPairedPayment.Edge(y, w)); adjList[y].add(new EPairedPayment.Edge(x, w)); } } dijkstra(0, -1); for (long x : dist) pw.print((x == (long) 1e15 ? -1 : x) + " "); pw.println(); } long dijkstra(int S, int T) { dist = new long[V]; Arrays.fill(dist, INF); cnt = new int[V]; Arrays.fill(cnt, 0); PriorityQueue<EPairedPayment.Edge> pq = new PriorityQueue<EPairedPayment.Edge>(); dist[S] = 0; pq.add(new EPairedPayment.Edge(S, 0)); //may add more in case of MSSP (Mult-Source) while (!pq.isEmpty()) { EPairedPayment.Edge cur = pq.remove(); if (cur.cost > dist[cur.node]) //lazy deletion continue; for (EPairedPayment.Edge nxt : adjList[cur.node]) { if (cnt[nxt.node] < 100) { for (EPairedPayment.Edge nxtnxt : adjList[nxt.node]) { if (nxtnxt.node != cur.node) if (cur.cost + (nxt.cost + nxtnxt.cost) * (nxt.cost + nxtnxt.cost) < dist[nxtnxt.node]) pq.add(new EPairedPayment.Edge(nxtnxt.node, dist[nxtnxt.node] = cur.cost + (nxt.cost + nxtnxt.cost) * (nxt.cost + nxtnxt.cost))); } } cnt[nxt.node] += 1; } } return -1; } static class Edge implements Comparable<EPairedPayment.Edge> { int node; long cost; Edge(int a, long b) { node = a; cost = b; } public int compareTo(EPairedPayment.Edge e) { return Long.compare(cost, e.cost); } } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(FileReader r) { br = new BufferedReader(r); } public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
4 seconds
["0 98 49 25 114", "0 -1 9"]
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "dp", "flows", "graphs", "shortest paths" ]
abee4d188bb59d82fcf4579c7416a343
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
2,200
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
standard output
PASSED
0cd3d20d3406d78bf100443445d45d2e
train_110.jsonl
1613658900
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.PriorityQueue; import java.util.AbstractQueue; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.AbstractCollection; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Khater */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); EPairedPayment solver = new EPairedPayment(); solver.solve(1, in, out); out.close(); } static class EPairedPayment { long INF = (long) 1e15; ArrayList<EPairedPayment.Edge>[] adjList; long[] dist; long[] dist2; int V; public void solve(int testNumber, Scanner sc, PrintWriter pw) { int t = 1; // t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int m = sc.nextInt(); V = n; adjList = new ArrayList[n]; for (int i = 0; i < n; i++) adjList[i] = new ArrayList<>(); for (int i = 0; i < m; i++) { int x = sc.nextInt() - 1; int y = sc.nextInt() - 1; long w = sc.nextLong(); adjList[x].add(new EPairedPayment.Edge(y, w)); adjList[y].add(new EPairedPayment.Edge(x, w)); } } dijkstra(0, -1); for (long x : dist) pw.print((x == (long) 1e15 ? -1 : x) + " "); pw.println(); } long dijkstra(int S, int T) { dist = new long[V]; Arrays.fill(dist, INF); dist2 = new long[V]; Arrays.fill(dist2, INF); PriorityQueue<EPairedPayment.Edge> pq = new PriorityQueue<EPairedPayment.Edge>(); dist[S] = 0; pq.add(new EPairedPayment.Edge(S, 0)); //may add more in case of MSSP (Mult-Source) while (!pq.isEmpty()) { EPairedPayment.Edge cur = pq.remove(); if (cur.cost > dist[cur.node]) //lazy deletion continue; for (EPairedPayment.Edge nxt : adjList[cur.node]) { if (dist2[nxt.node] > nxt.cost) { for (EPairedPayment.Edge nxtnxt : adjList[nxt.node]) { if (nxtnxt.node != cur.node) if (cur.cost + (nxt.cost + nxtnxt.cost) * (nxt.cost + nxtnxt.cost) < dist[nxtnxt.node]) pq.add(new EPairedPayment.Edge(nxtnxt.node, dist[nxtnxt.node] = cur.cost + (nxt.cost + nxtnxt.cost) * (nxt.cost + nxtnxt.cost))); } } dist2[nxt.node] = nxt.cost; } } return -1; } static class Edge implements Comparable<EPairedPayment.Edge> { int node; long cost; Edge(int a, long b) { node = a; cost = b; } public int compareTo(EPairedPayment.Edge e) { return Long.compare(cost, e.cost); } } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(FileReader r) { br = new BufferedReader(r); } public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
4 seconds
["0 98 49 25 114", "0 -1 9"]
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "dp", "flows", "graphs", "shortest paths" ]
abee4d188bb59d82fcf4579c7416a343
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
2,200
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
standard output
PASSED
1ac780ff2ad16a78728180eb8f26827e
train_110.jsonl
1613658900
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.PriorityQueue; import java.util.AbstractQueue; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.AbstractCollection; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Khater */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); EPairedPayment solver = new EPairedPayment(); solver.solve(1, in, out); out.close(); } static class EPairedPayment { long INF = (long) 1e15; ArrayList<EPairedPayment.Edge>[] adjList; long[] dist; int V; public void solve(int testNumber, Scanner sc, PrintWriter pw) { int t = 1; // t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int m = sc.nextInt(); V = n; adjList = new ArrayList[n]; for (int i = 0; i < n; i++) adjList[i] = new ArrayList<>(); for (int i = 0; i < m; i++) { int x = sc.nextInt() - 1; int y = sc.nextInt() - 1; long w = sc.nextLong(); adjList[x].add(new EPairedPayment.Edge(y, w)); adjList[y].add(new EPairedPayment.Edge(x, w)); } } dijkstra(0, -1); for (long x : dist) pw.print((x == (long) 1e15 ? -1 : x) + " "); pw.println(); } long dijkstra(int S, int T) { dist = new long[V]; Arrays.fill(dist, INF); PriorityQueue<EPairedPayment.Edge> pq = new PriorityQueue<EPairedPayment.Edge>(); dist[S] = 0; pq.add(new EPairedPayment.Edge(S, 0)); //may add more in case of MSSP (Mult-Source) while (!pq.isEmpty()) { EPairedPayment.Edge cur = pq.remove(); if (cur.cost > dist[cur.node]) //lazy deletion continue; for (EPairedPayment.Edge nxt : adjList[cur.node]) { for (EPairedPayment.Edge nxtnxt : adjList[nxt.node]) { if (nxtnxt.node != cur.node) if (cur.cost + (nxt.cost + nxtnxt.cost) * (nxt.cost + nxtnxt.cost) < dist[nxtnxt.node]) pq.add(new EPairedPayment.Edge(nxtnxt.node, dist[nxtnxt.node] = cur.cost + (nxt.cost + nxtnxt.cost) * (nxt.cost + nxtnxt.cost))); } } } return -1; } static class Edge implements Comparable<EPairedPayment.Edge> { int node; long cost; Edge(int a, long b) { node = a; cost = b; } public int compareTo(EPairedPayment.Edge e) { return Long.compare(cost, e.cost); } } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(FileReader r) { br = new BufferedReader(r); } public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
4 seconds
["0 98 49 25 114", "0 -1 9"]
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "dp", "flows", "graphs", "shortest paths" ]
abee4d188bb59d82fcf4579c7416a343
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
2,200
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
standard output
PASSED
f62f047cdd2e949c6233fcb949fdc423
train_110.jsonl
1613658900
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
512 megabytes
import java.util.*; import java.io.*; public class E { public static void main(String[] args) { FastScanner sc = new FastScanner(); int n = sc.nextInt(); int m = sc.nextInt(); ArrayList<Edge>[] g = new ArrayList[n]; for(int i = 0; i < n; i++){ g[i] = new ArrayList<>(); } for(int i = 0; i < m; i++){ int u = sc.nextInt()-1; int v = sc.nextInt()-1; int w = sc.nextInt(); g[u].add(new Edge(v, w)); g[v].add(new Edge(u, w)); } long maxv = 2000000000; PriorityQueue<Pair> q = new PriorityQueue<>(); long[][] dist = new long[n][51]; for(int i = 0; i < n; i++){ Arrays.fill(dist[i], maxv); } dist[0][0] = 0; q.add(new Pair(0, 0, 0)); while(!q.isEmpty()) { Pair p = q.poll(); for(Edge e: g[p.u]) { if(p.k == 0) { if(dist[e.u][e.w] > p.w) { dist[e.u][e.w] = p.w; q.add(new Pair(e.u, e.w, p.w)); } } else { long ww = p.w + (p.k + e.w) * (p.k + e.w); if(dist[e.u][0] > ww) { dist[e.u][0] = ww; q.add(new Pair(e.u, 0, ww)); } } } } StringBuilder sb = new StringBuilder(); for(int i = 0; i < n; i++){ if(dist[i][0] == maxv) sb.append("-1 "); else sb.append(dist[i][0]+" "); } sb.replace(sb.length()-1, sb.length(), "\n"); PrintWriter pw = new PrintWriter(System.out); pw.println(sb.toString().trim()); pw.flush(); } static class Edge implements Comparable<Edge>{ int u, w; public Edge(int u, int w){ this.u = u; this.w = w; } public int compareTo(Edge p){ if(w == p.w) return u - p.u; //if you delete this line you will die else return w - p.w; } public String toString(){ return u + " " + w; } } static class Pair implements Comparable<Pair>{ int u, k; long w; public Pair(int u, int k, long w){ this.u = u; this.k = k; this.w = w; } public int compareTo(Pair p){ return Long.compare(w, p.w); } public String toString(){ return u + ", " + k + ": " + w; } } static class FastScanner { public BufferedReader reader; public StringTokenizer tokenizer; public FastScanner() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { try { return reader.readLine(); } catch(IOException e) { throw new RuntimeException(e); } } } }
Java
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
4 seconds
["0 98 49 25 114", "0 -1 9"]
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "dp", "flows", "graphs", "shortest paths" ]
abee4d188bb59d82fcf4579c7416a343
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
2,200
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
standard output
PASSED
33f6b1167f4f4c52820b2f7c982ae9ac
train_110.jsonl
1613658900
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
512 megabytes
import java.util.*; import java.io.*; public class E { public static void main(String[] args) { FastScanner sc = new FastScanner(); int n = sc.nextInt(); int m = sc.nextInt(); ArrayList<Edge>[] g = new ArrayList[n]; for(int i = 0; i < n; i++){ g[i] = new ArrayList<>(); } for(int i = 0; i < m; i++){ int u = sc.nextInt()-1; int v = sc.nextInt()-1; int w = sc.nextInt(); g[u].add(new Edge(v, w)); g[v].add(new Edge(u, w)); } long maxv = 2000000000; PriorityQueue<Pair> q = new PriorityQueue<>(); long[][] dist = new long[n][51]; boolean[][] seen = new boolean[n][51]; for(int i = 0; i < n; i++){ Arrays.fill(dist[i], maxv); } dist[0][0] = 0; q.add(new Pair(0, 0, 0)); while(!q.isEmpty()) { Pair p = q.poll(); if(seen[p.u][p.k]) continue; seen[p.u][p.k] = true; for(Edge e: g[p.u]) { if(p.k == 0) { if(dist[e.u][e.w] > p.w) { dist[e.u][e.w] = p.w; q.add(new Pair(e.u, e.w, p.w)); } } else { long ww = p.w + (p.k + e.w) * (p.k + e.w); if(dist[e.u][0] > ww) { dist[e.u][0] = ww; q.add(new Pair(e.u, 0, ww)); } } } } StringBuilder sb = new StringBuilder(); for(int i = 0; i < n; i++){ if(dist[i][0] == maxv) sb.append("-1 "); else sb.append(dist[i][0]+" "); } sb.replace(sb.length()-1, sb.length(), "\n"); PrintWriter pw = new PrintWriter(System.out); pw.println(sb.toString().trim()); pw.flush(); } static class Edge{ int u, w; public Edge(int u, int w){ this.u = u; this.w = w; } public String toString(){ return u + " " + w; } } static class Pair implements Comparable<Pair>{ int u, k; long w; public Pair(int u, int k, long w){ this.u = u; this.k = k; this.w = w; } public int compareTo(Pair p){ return Long.compare(w, p.w); } public String toString(){ return u + ", " + k + ": " + w; } } static class FastScanner { public BufferedReader reader; public StringTokenizer tokenizer; public FastScanner() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { try { return reader.readLine(); } catch(IOException e) { throw new RuntimeException(e); } } } }
Java
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
4 seconds
["0 98 49 25 114", "0 -1 9"]
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "dp", "flows", "graphs", "shortest paths" ]
abee4d188bb59d82fcf4579c7416a343
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
2,200
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
standard output
PASSED
392c18941517e1d256ceb462bdffe2c3
train_110.jsonl
1613658900
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
512 megabytes
import java.io.*; import java.util.*; public class tr1 { static PrintWriter out; static StringBuilder sb; static long mod = (long) 1e9 + 7; static int[] memo; static int[][][] memo1; static int n, m; static ArrayList<long[]>[] ad; static HashMap<Integer, Integer>[] going; static long inf = Long.MAX_VALUE; static char[][] g; static boolean[] vis; static int[] dep; static int hh; static HashMap<Integer, Integer> hmC, hmG; public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); out = new PrintWriter(System.out); n = sc.nextInt(); m = sc.nextInt(); ad = new ArrayList[n]; for (int i = 0; i < n; i++) ad[i] = new ArrayList<>(); for (int i = 0; i < m; i++) { int a = sc.nextInt() - 1; int b = sc.nextInt() - 1; int w = sc.nextInt(); ad[a].add(new long[] { b, w }); ad[b].add(new long[] { a, w }); } long INF = Long.MAX_VALUE; long[] dist = new long[n]; Arrays.fill(dist, INF); PriorityQueue<long[]> pq = new PriorityQueue<long[]>((x, y) -> Long.compare(x[1], y[1])); dist[0] = 0; pq.add(new long[] { 0, 0 }); long[] vis1 = new long[n]; Arrays.fill(vis1, INF); while (!pq.isEmpty()) { long[] cur = pq.remove(); if (cur[1] > dist[(int) cur[0]]) continue; int u = (int) cur[0]; long cost = cur[1]; ArrayList<long[]> fresh = new ArrayList<>(); for (long[] v : ad[u]) if (vis1[(int) v[0]] <= v[1]) continue; else { vis1[(int) v[0]] = v[1]; fresh.add(new long[] { v[0], v[1] }); } for (long[] y : fresh) { for (long[] v : ad[(int) y[0]]) if (dist[(int) v[0]] > cost + (v[1] + y[1]) * (v[1] + y[1])) { dist[(int) v[0]] = cost + (v[1] + y[1]) * (v[1] + y[1]); pq.add(new long[] { v[0], dist[(int) v[0]] }); } } } for (int i = 0; i < n; i++) if (dist[i] == Long.MAX_VALUE) out.print(-1 + " "); else out.print(dist[i] + " "); out.flush(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public int[] nextArrInt(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextArrLong(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public int[] nextArrIntSorted(int n) throws IOException { int[] a = new int[n]; Integer[] a1 = new Integer[n]; for (int i = 0; i < n; i++) a1[i] = nextInt(); Arrays.sort(a1); for (int i = 0; i < n; i++) a[i] = a1[1].intValue(); return a; } public long[] nextArrLongSorted(int n) throws IOException { long[] a = new long[n]; Long[] a1 = new Long[n]; for (int i = 0; i < n; i++) a1[i] = nextLong(); Arrays.sort(a1); for (int i = 0; i < n; i++) a[i] = a1[1].longValue(); return a; } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } }
Java
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
4 seconds
["0 98 49 25 114", "0 -1 9"]
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "dp", "flows", "graphs", "shortest paths" ]
abee4d188bb59d82fcf4579c7416a343
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
2,200
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
standard output
PASSED
ae5bb8965b681ad1e48cd5c428f84ffb
train_110.jsonl
1613658900
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
512 megabytes
import java.util.*; import java.awt.geom.AffineTransform; import java.io.*; public class Main { public static void main(String[] args) throws Exception { int n=sc.nextInt(); int m=sc.nextInt(); ArrayList<pair>[]gr=new ArrayList[n]; for(int i=0;i<n;i++)gr[i]=new ArrayList<pair>(); for(int i=0;i<m;i++) { int x=sc.nextInt()-1; int y=sc.nextInt()-1; int v=sc.nextInt(); gr[x].add(new pair(y, v)); gr[y].add(new pair(x, v)); } PriorityQueue<tuble>pq=new PriorityQueue<Main.tuble>(); Integer[][]ans=new Integer[51][n]; Integer[][]dist=new Integer[51][n]; dist[0][0]=0; pq.add(new tuble(0, 0, 0)); while(!pq.isEmpty()) { // pw.println(pq); tuble z =pq.poll(); if(ans[(int) z.y][(int) z.z]==null) { ans[(int) z.y][(int) z.z]=(int) (z.x); // pw.println(z); for(pair i:gr[(int) z.z]) { if(z.y==0) { if(dist[(int) i.y][(int) i.x]==null||dist[(int) i.y][(int) i.x]>(z.x+i.y)) { dist[(int) i.y][(int) i.x]=(int) (z.x+i.y); pq.add(new tuble(z.x+i.y, i.y, i.x)); } }else { if(dist[0][(int) i.x]==null||dist[0][(int) i.x]>(z.x-z.y+(i.y+z.y)*(i.y+z.y))) { dist[0][(int) i.x]=(int) (z.x-z.y+(i.y+z.y)*(i.y+z.y)); pq.add(new tuble(z.x-z.y+(i.y+z.y)*(i.y+z.y), 0, i.x)); } } } } } for(int i=0;i<n;i++) { if(ans[0][i]==null) { pw.print(-1+" "); }else { pw.print(ans[0][i]+" "); } } pw.close(); } 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 long[] nextlongArray(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public Long[] nextLongArray(int n) throws IOException { Long[] a = new Long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public int[] nextIntArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public Integer[] nextIntegerArray(int n) throws IOException { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public boolean ready() throws IOException { return br.ready(); } } static class pair implements Comparable<pair> { long x; long y; public pair(long x, long y) { this.x = x; this.y = y; } public String toString() { return x + " " + y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair) o; return p.x == x && p.y == y; } return false; } public int hashCode() { return new Double(x).hashCode() * 31 + new Double(y).hashCode(); } public int compareTo(pair other) { if (this.x == other.x) { return Long.compare(this.y, other.y); } return Long.compare(this.x, other.x); } } static class tuble implements Comparable<tuble> { long x; long y; long z; public tuble(long x, long y, long z) { this.x = x; this.y = y; this.z = z; } public String toString() { return x + " " + y + " " + z; } public int compareTo(tuble other) { if (this.x == other.x) { if (this.y == other.y) { return Long.compare(this.z , other.z); } return Long.compare(this.y , other.y); } else { return Long.compare(this.x , other.x); } } } static long mod = 1000000007; static Random rn = new Random(); static Scanner sc = new Scanner(System.in); static PrintWriter pw = new PrintWriter(System.out); }
Java
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
4 seconds
["0 98 49 25 114", "0 -1 9"]
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "dp", "flows", "graphs", "shortest paths" ]
abee4d188bb59d82fcf4579c7416a343
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
2,200
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
standard output
PASSED
624b5739a05382c5b6b9df71b621c4e7
train_110.jsonl
1613658900
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
512 megabytes
import java.util.*; import java.awt.geom.AffineTransform; import java.io.*; public class Main { public static void main(String[] args) throws Exception { int n=sc.nextInt(); int m=sc.nextInt(); ArrayList<pair>[]gr=new ArrayList[n]; for(int i=0;i<n;i++)gr[i]=new ArrayList<pair>(); for(int i=0;i<m;i++) { int x=sc.nextInt()-1; int y=sc.nextInt()-1; int v=sc.nextInt(); gr[x].add(new pair(y, v)); gr[y].add(new pair(x, v)); } PriorityQueue<tuble>pq=new PriorityQueue<Main.tuble>(); Integer[][]ans=new Integer[n][51]; Integer[][]dist=new Integer[n][51]; dist[0][0]=0; pq.add(new tuble(0, 0, 0)); while(!pq.isEmpty()) { // pw.println(pq); tuble z =pq.poll(); if(ans[(int) z.z][(int) z.y]==null) { ans[(int) z.z][(int) z.y]=(int) (z.x); // pw.println(z); for(pair i:gr[(int) z.z]) { if(z.y==0) { if(dist[(int) i.x][(int) i.y]==null||dist[(int) i.x][(int) i.y]>(z.x+i.y)) { dist[(int) i.x][(int) i.y]=(int) (z.x+i.y); pq.add(new tuble(z.x+i.y, i.y, i.x)); } }else { if(dist[(int) i.x][0]==null||dist[(int) i.x][0]>(z.x-z.y+(i.y+z.y)*(i.y+z.y))) { dist[(int) i.x][0]=(int) (z.x-z.y+(i.y+z.y)*(i.y+z.y)); pq.add(new tuble(z.x-z.y+(i.y+z.y)*(i.y+z.y), 0, i.x)); } } } } } for(int i=0;i<n;i++) { if(ans[i][0]==null) { pw.print(-1+" "); }else { pw.print(ans[i][0]+" "); } } pw.close(); } 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 long[] nextlongArray(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public Long[] nextLongArray(int n) throws IOException { Long[] a = new Long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public int[] nextIntArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public Integer[] nextIntegerArray(int n) throws IOException { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public boolean ready() throws IOException { return br.ready(); } } static class pair implements Comparable<pair> { long x; long y; public pair(long x, long y) { this.x = x; this.y = y; } public String toString() { return x + " " + y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair) o; return p.x == x && p.y == y; } return false; } public int hashCode() { return new Double(x).hashCode() * 31 + new Double(y).hashCode(); } public int compareTo(pair other) { if (this.x == other.x) { return Long.compare(this.y, other.y); } return Long.compare(this.x, other.x); } } static class tuble implements Comparable<tuble> { long x; long y; long z; public tuble(long x, long y, long z) { this.x = x; this.y = y; this.z = z; } public String toString() { return x + " " + y + " " + z; } public int compareTo(tuble other) { if (this.x == other.x) { if (this.y == other.y) { return Long.compare(this.z , other.z); } return Long.compare(this.y , other.y); } else { return Long.compare(this.x , other.x); } } } static long mod = 1000000007; static Random rn = new Random(); static Scanner sc = new Scanner(System.in); static PrintWriter pw = new PrintWriter(System.out); }
Java
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
4 seconds
["0 98 49 25 114", "0 -1 9"]
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "dp", "flows", "graphs", "shortest paths" ]
abee4d188bb59d82fcf4579c7416a343
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
2,200
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
standard output
PASSED
eb22a195fb72b3a6bbb03c35a9c0d0c9
train_110.jsonl
1613658900
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
512 megabytes
import java.io.*; import java.util.*; public class CF703E { static final int N = (int)(2e5 + 11), INF = (int)(1e9 + 11); static int n, m, v, u, w; static ArrayList< int[] > g[] = new ArrayList[N]; static int[][] d; static PriorityQueue<Node> pq; public static void main (String[] args) throws IOException { // BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); // StringTokenizer st = new StringTokenizer(br.readLine()); // n = Integer.parseInt(st.nextToken()); // m = Integer.parseInt(st.nextToken()); n = sc.nextInt(); m = sc.nextInt(); for (int i = 0; i < n; ++i) g[i] = new ArrayList<>(); while (m-- > 0) { // st = new StringTokenizer(br.readLine()); // v = Integer.parseInt(st.nextToken()); // u = Integer.parseInt(st.nextToken()); // w = Integer.parseInt(st.nextToken()); v = sc.nextInt(); u = sc.nextInt(); w = sc.nextInt(); --v; --u; g[v].add(new int[] {u, w}); g[u].add(new int[] {v, w}); } d = new int[n][]; for (int i = 0; i < n; ++i) { d[i] = new int[51]; for (int j = 0; j < 51; ++j) d[i][j] = INF; } d[0][0] = 0; Node V; pq = new PriorityQueue<Node>(); pq.add(new Node(0, 0, d[0][0])); while (pq.size() > 0) { V = pq.remove(); int v = V.v; int lvl = V.lvl; int cost = V.cost; if (d[v][lvl] != cost) continue; for (int[] u : g[v]) { int to = u[0], w = u[1], lvl1; if (lvl == 0) { lvl1 = w; w = w*w; } else { lvl1 = 0; w = w*w + 2*lvl*w; } if (d[to][lvl1] > w + d[v][lvl]) { d[to][lvl1] = w + d[v][lvl]; pq.add(new Node(to, lvl1, d[to][lvl1])); } } } for (int i = 0; i < n; ++i) if (d[i][0] == INF) out.print("-1 "); else out.print(d[i][0] + " "); out.close(); } static class Node implements Comparable<Node> { public int v, lvl, cost; Node (int v1, int lvl1, int cost1) { v = v1; lvl = lvl1; cost = cost1; } @Override public int compareTo (Node a) { return Integer.compare(cost, a.cost); } } }
Java
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
4 seconds
["0 98 49 25 114", "0 -1 9"]
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "dp", "flows", "graphs", "shortest paths" ]
abee4d188bb59d82fcf4579c7416a343
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
2,200
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
standard output
PASSED
25056bbdbfe6421d0a8ecb34d186fad3
train_110.jsonl
1613658900
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
512 megabytes
import java.io.*; import java.util.*; public class CF703E { static final int N = (int)(2e5 + 11), INF = (int)(1e9 + 11); static int n, m, v, u, w; static ArrayList< int[] > g[] = new ArrayList[N]; static int[][] d; static PriorityQueue<Node> pq; public static void main (String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); StringTokenizer st = new StringTokenizer(br.readLine()); n = Integer.parseInt(st.nextToken()); m = Integer.parseInt(st.nextToken()); for (int i = 0; i < n; ++i) g[i] = new ArrayList<>(); while (m-- > 0) { st = new StringTokenizer(br.readLine()); v = Integer.parseInt(st.nextToken()); u = Integer.parseInt(st.nextToken()); w = Integer.parseInt(st.nextToken()); --v; --u; g[v].add(new int[] {u, w}); g[u].add(new int[] {v, w}); } d = new int[n][]; for (int i = 0; i < n; ++i) { d[i] = new int[51]; for (int j = 0; j < 51; ++j) d[i][j] = INF; } d[0][0] = 0; Node V; pq = new PriorityQueue<Node>(); pq.add(new Node(0, 0, d[0][0])); while (pq.size() > 0) { V = pq.remove(); int v = V.v; int lvl = V.lvl; int cost = V.cost; if (d[v][lvl] != cost) continue; for (int[] u : g[v]) { int to = u[0], w = u[1], lvl1; if (lvl == 0) { lvl1 = w; w = w*w; } else { lvl1 = 0; w = w*w + 2*lvl*w; } if (d[to][lvl1] > w + d[v][lvl]) { d[to][lvl1] = w + d[v][lvl]; pq.add(new Node(to, lvl1, d[to][lvl1])); } } } for (int i = 0; i < n; ++i) if (d[i][0] == INF) out.print("-1 "); else out.print(d[i][0] + " "); out.close(); } static class Node implements Comparable<Node> { public int v, lvl, cost; Node (int v1, int lvl1, int cost1) { v = v1; lvl = lvl1; cost = cost1; } @Override public int compareTo (Node a) { return Integer.compare(cost, a.cost); } } }
Java
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
4 seconds
["0 98 49 25 114", "0 -1 9"]
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "dp", "flows", "graphs", "shortest paths" ]
abee4d188bb59d82fcf4579c7416a343
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
2,200
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
standard output
PASSED
7b7bc7b3e1b1fb07eb04602e5e151ca8
train_110.jsonl
1613658900
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
512 megabytes
//package round703; import java.io.*; import java.util.ArrayDeque; import java.util.Arrays; import java.util.InputMismatchException; import java.util.Queue; public class E { InputStream is; FastWriter out; String INPUT = ""; void solve() { int n = ni(), m = ni(); int[] from = new int[m]; int[] to = new int[m]; int[] ws = new int[m]; for(int i = 0;i < m;i++){ from[i] = ni()-1; to[i] = ni()-1; ws[i] = ni(); } int[][][] g = packWU(n, from, to, ws); long[] ptns = new long[n]; for(int i = 0;i < n;i++){ for(int[] e : g[i]){ ptns[i] |= 1L<<e[1]; } } long[] td = new long[n*51]; Arrays.fill(td, Long.MAX_VALUE / 2); MinHeapL q = new MinHeapL(n*51); q.add(0, 0); td[0] = 0; while(q.size() > 0){ int cur = q.argmin(); q.remove(cur); if(cur < n){ for(int[] e : g[cur]){ int next = e[0]; for(long i = ptns[next];i != 0;i &= i-1){ int o = Long.numberOfTrailingZeros(i); long nd = td[cur] + (long)(e[1] + o) * (e[1] + o); int ne = next + o * n; if(nd < td[ne]){ td[ne] = nd; q.update(ne, nd); } } } }else{ int ww = cur / n; for(int[] e : g[cur%n]){ if(e[1] == ww){ if(td[cur] < td[e[0]]){ td[e[0]] = td[cur]; q.update(e[0], td[e[0]]); } } } } } for(int i = 0;i < n;i++){ out.print(td[i] >= Long.MAX_VALUE / 3 ? -1 : td[i]).print(" "); } out.println(); } public static class MinHeapL { public long[] a; public int[] map; public int[] imap; public int n; public int pos; public static long INF = Long.MAX_VALUE; public MinHeapL(int m) { n = Integer.highestOneBit((m+1)<<1); a = new long[n]; map = new int[n]; imap = new int[n]; Arrays.fill(a, INF); Arrays.fill(map, -1); Arrays.fill(imap, -1); pos = 1; } public long add(int ind, long x) { int ret = imap[ind]; if(imap[ind] < 0){ a[pos] = x; map[pos] = ind; imap[ind] = pos; pos++; up(pos-1); } return ret != -1 ? a[ret] : x; } public long update(int ind, long x) { int ret = imap[ind]; if(imap[ind] < 0){ a[pos] = x; map[pos] = ind; imap[ind] = pos; pos++; up(pos-1); }else{ a[ret] = x; up(ret); down(ret); } return x; } public long remove(int ind) { if(pos == 1)return INF; if(imap[ind] == -1)return INF; pos--; int rem = imap[ind]; long ret = a[rem]; map[rem] = map[pos]; imap[map[pos]] = rem; imap[ind] = -1; a[rem] = a[pos]; a[pos] = INF; map[pos] = -1; up(rem); down(rem); return ret; } public long min() { return a[1]; } public int argmin() { return map[1]; } public int size() { return pos-1; } private void up(int cur) { for(int c = cur, p = c>>>1;p >= 1 && a[p] > a[c];c>>>=1, p>>>=1){ long d = a[p]; a[p] = a[c]; a[c] = d; int e = imap[map[p]]; imap[map[p]] = imap[map[c]]; imap[map[c]] = e; e = map[p]; map[p] = map[c]; map[c] = e; } } private void down(int cur) { for(int c = cur;2*c < pos;){ int b = a[2*c] < a[2*c+1] ? 2*c : 2*c+1; if(a[b] < a[c]){ long d = a[c]; a[c] = a[b]; a[b] = d; int e = imap[map[c]]; imap[map[c]] = imap[map[b]]; imap[map[b]] = e; e = map[c]; map[c] = map[b]; map[b] = e; c = b; }else{ break; } } } } public static int[][][] packWU(int n, int[] from, int[] to, int[] w) { return packWU(n, from, to, w, from.length); } public static int[][][] packWU(int n, int[] from, int[] to, int[] w, int sup) { int[][][] g = new int[n][][]; int[] p = new int[n]; for (int i = 0; i < sup; i++) p[from[i]]++; for (int i = 0; i < sup; i++) p[to[i]]++; for (int i = 0; i < n; i++) g[i] = new int[p[i]][2]; for (int i = 0; i < sup; i++) { --p[from[i]]; g[from[i]][p[from[i]]][0] = to[i]; g[from[i]][p[from[i]]][1] = w[i]; --p[to[i]]; g[to[i]][p[to[i]]][0] = from[i]; g[to[i]][p[to[i]]][1] = w[i]; } return g; } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new FastWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new E().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private long[] nal(int n) { long[] a = new long[n]; for(int i = 0;i < n;i++)a[i] = nl(); return a; } 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[][] nmi(int n, int m) { int[][] map = new int[n][]; for(int i = 0;i < n;i++)map[i] = na(m); return map; } private int ni() { return (int)nl(); } 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(); } } public static class FastWriter { private static final int BUF_SIZE = 1<<13; private final byte[] buf = new byte[BUF_SIZE]; private final OutputStream out; private int ptr = 0; private FastWriter(){out = null;} public FastWriter(OutputStream os) { this.out = os; } public FastWriter(String path) { try { this.out = new FileOutputStream(path); } catch (FileNotFoundException e) { throw new RuntimeException("FastWriter"); } } public FastWriter write(byte b) { buf[ptr++] = b; if(ptr == BUF_SIZE)innerflush(); return this; } public FastWriter write(char c) { return write((byte)c); } public FastWriter write(char[] s) { for(char c : s){ buf[ptr++] = (byte)c; if(ptr == BUF_SIZE)innerflush(); } return this; } public FastWriter write(String s) { s.chars().forEach(c -> { buf[ptr++] = (byte)c; if(ptr == BUF_SIZE)innerflush(); }); return this; } private static int countDigits(int l) { if (l >= 1000000000) return 10; if (l >= 100000000) return 9; if (l >= 10000000) return 8; if (l >= 1000000) return 7; if (l >= 100000) return 6; if (l >= 10000) return 5; if (l >= 1000) return 4; if (l >= 100) return 3; if (l >= 10) return 2; return 1; } public FastWriter write(int x) { if(x == Integer.MIN_VALUE){ return write((long)x); } if(ptr + 12 >= BUF_SIZE)innerflush(); if(x < 0){ write((byte)'-'); x = -x; } int d = countDigits(x); for(int i = ptr + d - 1;i >= ptr;i--){ buf[i] = (byte)('0'+x%10); x /= 10; } ptr += d; return this; } private static int countDigits(long l) { if (l >= 1000000000000000000L) return 19; if (l >= 100000000000000000L) return 18; if (l >= 10000000000000000L) return 17; if (l >= 1000000000000000L) return 16; if (l >= 100000000000000L) return 15; if (l >= 10000000000000L) return 14; if (l >= 1000000000000L) return 13; if (l >= 100000000000L) return 12; if (l >= 10000000000L) return 11; if (l >= 1000000000L) return 10; if (l >= 100000000L) return 9; if (l >= 10000000L) return 8; if (l >= 1000000L) return 7; if (l >= 100000L) return 6; if (l >= 10000L) return 5; if (l >= 1000L) return 4; if (l >= 100L) return 3; if (l >= 10L) return 2; return 1; } public FastWriter write(long x) { if(x == Long.MIN_VALUE){ return write("" + x); } if(ptr + 21 >= BUF_SIZE)innerflush(); if(x < 0){ write((byte)'-'); x = -x; } int d = countDigits(x); for(int i = ptr + d - 1;i >= ptr;i--){ buf[i] = (byte)('0'+x%10); x /= 10; } ptr += d; return this; } public FastWriter write(double x, int precision) { if(x < 0){ write('-'); x = -x; } x += Math.pow(10, -precision)/2; // if(x < 0){ x = 0; } write((long)x).write("."); x -= (long)x; for(int i = 0;i < precision;i++){ x *= 10; write((char)('0'+(int)x)); x -= (int)x; } return this; } public FastWriter writeln(char c){ return write(c).writeln(); } public FastWriter writeln(int x){ return write(x).writeln(); } public FastWriter writeln(long x){ return write(x).writeln(); } public FastWriter writeln(double x, int precision){ return write(x, precision).writeln(); } public FastWriter write(int... xs) { boolean first = true; for(int x : xs) { if (!first) write(' '); first = false; write(x); } return this; } public FastWriter write(long... xs) { boolean first = true; for(long x : xs) { if (!first) write(' '); first = false; write(x); } return this; } public FastWriter writeln() { return write((byte)'\n'); } public FastWriter writeln(int... xs) { return write(xs).writeln(); } public FastWriter writeln(long... xs) { return write(xs).writeln(); } public FastWriter writeln(char[] line) { return write(line).writeln(); } public FastWriter writeln(char[]... map) { for(char[] line : map)write(line).writeln(); return this; } public FastWriter writeln(String s) { return write(s).writeln(); } private void innerflush() { try { out.write(buf, 0, ptr); ptr = 0; } catch (IOException e) { throw new RuntimeException("innerflush"); } } public void flush() { innerflush(); try { out.flush(); } catch (IOException e) { throw new RuntimeException("flush"); } } public FastWriter print(byte b) { return write(b); } public FastWriter print(char c) { return write(c); } public FastWriter print(char[] s) { return write(s); } public FastWriter print(String s) { return write(s); } public FastWriter print(int x) { return write(x); } public FastWriter print(long x) { return write(x); } public FastWriter print(double x, int precision) { return write(x, precision); } public FastWriter println(char c){ return writeln(c); } public FastWriter println(int x){ return writeln(x); } public FastWriter println(long x){ return writeln(x); } public FastWriter println(double x, int precision){ return writeln(x, precision); } public FastWriter print(int... xs) { return write(xs); } public FastWriter print(long... xs) { return write(xs); } public FastWriter println(int... xs) { return writeln(xs); } public FastWriter println(long... xs) { return writeln(xs); } public FastWriter println(char[] line) { return writeln(line); } public FastWriter println(char[]... map) { return writeln(map); } public FastWriter println(String s) { return writeln(s); } public FastWriter println() { return writeln(); } } public void trnz(int... o) { for(int i = 0;i < o.length;i++)if(o[i] != 0)System.out.print(i+":"+o[i]+" "); System.out.println(); } // print ids which are 1 public void trt(long... o) { Queue<Integer> stands = new ArrayDeque<>(); for(int i = 0;i < o.length;i++){ for(long x = o[i];x != 0;x &= x-1)stands.add(i<<6|Long.numberOfTrailingZeros(x)); } System.out.println(stands); } public void tf(boolean... r) { for(boolean x : r)System.out.print(x?'#':'.'); System.out.println(); } public void tf(boolean[]... b) { for(boolean[] r : b) { for(boolean x : r)System.out.print(x?'#':'.'); System.out.println(); } System.out.println(); } public void tf(long[]... b) { if(INPUT.length() != 0) { for (long[] r : b) { for (long x : r) { for (int i = 0; i < 64; i++) { System.out.print(x << ~i < 0 ? '#' : '.'); } } System.out.println(); } System.out.println(); } } public void tf(long... b) { if(INPUT.length() != 0) { for (long x : b) { for (int i = 0; i < 64; i++) { System.out.print(x << ~i < 0 ? '#' : '.'); } } System.out.println(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
4 seconds
["0 98 49 25 114", "0 -1 9"]
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "dp", "flows", "graphs", "shortest paths" ]
abee4d188bb59d82fcf4579c7416a343
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
2,200
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
standard output
PASSED
f31603ed5f2ac47cfdc570bb5f8fb248
train_110.jsonl
1613658900
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
512 megabytes
import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; import java.util.List; import java.util.*; public class realfast implements Runnable { private static final int INF = (int) 1e9; long in= 1000000007; long fac[]= new long[1000001]; long inv[]=new long[1000001]; public void solve() throws IOException { //int t = readInt(); int n = readInt(); int m = readInt(); ArrayList<edge> adj[]=new ArrayList[n+1]; for(int i =0;i<=n;i++) adj[i]= new ArrayList<edge>(); long dist[][]=new long[n+1][51]; long inf =0; for(int i =0;i<=n;i++) { for(int j=0;j<=50;j++) { dist[i][j]=2000000000; dist[i][j]= dist[i][j]*10; inf=dist[i][j]; } } boolean visited[][]=new boolean[n+1][51]; for(int i =0;i<m;i++) { int u = readInt(); int v = readInt(); int w = readInt(); adj[u].add(new edge(v,0,w)); adj[v].add(new edge(u,0,w)); } PriorityQueue<edge> h = new PriorityQueue<edge>(); dist[1][0]=0; h.add(new edge(1,0,0)); while(h.size()!=0) { edge lo = h.poll(); int cur= lo.u; int s = lo.state; long dist1 = lo.dist; if(visited[cur][s]) continue; visited[cur][s]= true; if(s==0) { for(int j =0;j<adj[cur].size();j++) { int v = adj[cur].get(j).u; int dl= (int)adj[cur].get(j).dist; if(!visited[v][dl]&&(dl*dl)+dist1<dist[v][dl]) { dist[v][dl]= (dl*dl)+dist1; h.add(new edge(v,dl,dist[v][dl])); } } } else { for(int j =0;j<adj[cur].size();j++) { int v = adj[cur].get(j).u; int dl= (int)adj[cur].get(j).dist; if(!visited[v][0]&&((dl*dl)+dist1+2*dl*s<dist[v][0])) { dist[v][0]= (dl*dl)+dist1+2*dl*s; h.add(new edge(v,0,dist[v][0])); } } } } for(int i =1;i<=n;i++) { if(dist[i][0]<inf) out.print(dist[i][0]+" "); else out.print((-1)+" "); } } public int value (int seg[], int left , int right ,int index, int l, int r) { if(left>right) { return -100000000; } if(right<l||left>r) return -100000000; if(left>=l&&right<=r) return seg[index]; int mid = left+(right-left)/2; int val = value(seg,left,mid,2*index+1,l,r); int val2 = value(seg,mid+1,right,2*index+2,l,r); return Math.max(val,val2); } public int gcd(int a , int b ) { if(a<b) { int t =a; a=b; b=t; } if(a%b==0) return b ; return gcd(b,a%b); } public long pow(long n , long p,long m) { if(p==0) return 1; long val = pow(n,p/2,m);; val= (val*val)%m; if(p%2==0) return val; else return (val*n)%m; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static void main(String[] args) { new Thread(null, new realfast(), "", 128 * (1L << 20)).start(); } private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; private BufferedReader reader; private StringTokenizer tokenizer; private PrintWriter out; @Override public void run() { try { if (ONLINE_JUDGE || !new File("input.txt").exists()) { reader = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { reader = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } solve(); } catch (IOException e) { throw new RuntimeException(e); } finally { try { reader.close(); } catch (IOException e) { // nothing } out.close(); } } private String readString() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } @SuppressWarnings("unused") private int readInt() throws IOException { return Integer.parseInt(readString()); } @SuppressWarnings("unused") private long readLong() throws IOException { return Long.parseLong(readString()); } @SuppressWarnings("unused") private double readDouble() throws IOException { return Double.parseDouble(readString()); } } class edge implements Comparable<edge>{ int u; int state; long dist; edge(int u, int state, long dist) { this.u=u; this.state=state; this.dist= dist; } public int compareTo(edge e) { if(this.dist-e.dist>0) return 1; else if(this.dist==e.dist) return 0; else return -1; } }
Java
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
4 seconds
["0 98 49 25 114", "0 -1 9"]
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "dp", "flows", "graphs", "shortest paths" ]
abee4d188bb59d82fcf4579c7416a343
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
2,200
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
standard output
PASSED
2b32d6a59b01975f510dfd1550a3344b
train_110.jsonl
1613658900
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
512 megabytes
import java.io.*; import java.util.*; public class E { static class node implements Comparable<node> { int node, p; Cost cost; node(int u, int par, Cost c) { node = u; p = par; cost = c; } @Override public int compareTo(node o) { // TODO Auto-generated method stub return cost.compareTo(o.cost); } } static class Cost { long cost; int last; Cost(long c, int l) { cost = c; last = l; } public int compareTo(Cost other) { if (cost != other.cost) return Long.compare(cost, other.cost); return last - other.last; } } static int n, m; static ArrayList<int[]> adj[]; static long INF = (long) 1e18; static long[] solve() { PriorityQueue<node> pq = new PriorityQueue(); long[][] dist2 = new long[n][51]; long[] dist = new long[n]; Arrays.fill(dist, INF); for (long[] x : dist2) Arrays.fill(x, INF); dist[0] = 0; pq.add(new node(0, 0, new Cost(0, 0))); while (!pq.isEmpty()) { node curr = pq.poll(); int u = curr.node, p = curr.p; Cost cost = curr.cost; if (p == 0 && cost.cost > dist[u]) continue; if (p == 1 && cost.cost > dist2[u][cost.last]) continue; for (int[] nxt : adj[u]) { int v = nxt[0]; int w = nxt[1]; if (p == 0) { if (dist2[v][w] > cost.cost) pq.add(new node(v, p ^ 1, new Cost(dist2[v][w] = cost.cost, w))); } else { long total = cost.cost + (w + cost.last) * 1L * (w + cost.last); if (dist[v] > total) pq.add(new node(v, p ^ 1, new Cost(dist[v] = total, 0))); } } } return dist; } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); n = sc.nextInt(); m = sc.nextInt(); adj = new ArrayList[n]; for (int i = 0; i < n; i++) adj[i] = new ArrayList(); while (m-- > 0) { int u = sc.nextInt() - 1, v = sc.nextInt() - 1, w = sc.nextInt(); adj[u].add(new int[] { v, w }); adj[v].add(new int[] { u, w }); } long[] ans = solve(); for (long x : ans) { if (x == INF) out.print(-1 + " "); else out.print(x + " "); } out.println(); out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } Scanner(String fileName) throws FileNotFoundException { br = new BufferedReader(new FileReader(fileName)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { return br.readLine(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } boolean ready() throws IOException { return br.ready() || st.hasMoreTokens(); } int[] nxtArr(int n) throws IOException { int[] ans = new int[n]; for (int i = 0; i < n; i++) ans[i] = nextInt(); return ans; } } static void sort(int[] a) { shuffle(a); Arrays.sort(a); } static void shuffle(int[] a) { int n = a.length; Random rand = new Random(); for (int i = 0; i < n; i++) { int tmpIdx = rand.nextInt(n); int tmp = a[i]; a[i] = a[tmpIdx]; a[tmpIdx] = tmp; } } }
Java
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
4 seconds
["0 98 49 25 114", "0 -1 9"]
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "dp", "flows", "graphs", "shortest paths" ]
abee4d188bb59d82fcf4579c7416a343
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
2,200
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
standard output
PASSED
c994e7dca75506883fe8e2ab8f1901c6
train_110.jsonl
1613658900
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
512 megabytes
import java.io.*; import java.util.*; public class Main2{ static int INF=(int)2e9; static ArrayList<int[]>[] adjListW; static int n; static int[] dijkstra(int S) //O(E log E) { int[][][] dist = new int[2][51][n]; for(int i=0;i<2;i++) { for(int j=0;j<=50;j++) { for(int o=0;o<n;o++)dist[i][j][o]=INF; } } PriorityQueue<int[]> pq = new PriorityQueue<int[]>((x,y)->x[0]-y[0]); dist[0][0][S] = 0; pq.add(new int[] {0,0,0,S}); while(!pq.isEmpty()) { int[] cur = pq.remove(); int node=cur[3],cost=cur[0],p=cur[1],prevW=cur[2]; if(cost > dist[p][prevW][node]) continue; for(int[] nxt: adjListW[node]) { if(p==0) { if(cost < dist[1][nxt[1]][nxt[0]]) pq.add(new int[] {dist[1][nxt[1]][nxt[0]] = cost,1,nxt[1],nxt[0]}); } else { int curCost=(prevW+nxt[1])*(prevW+nxt[1]); if(cost + curCost < dist[0][0][nxt[0]]) pq.add(new int[] {dist[0][0][nxt[0]] = cost+curCost,0,0,nxt[0]}); } } } int[]ans=new int[n]; for(int i=0;i<n;i++)ans[i]=dist[0][0][i]==INF?-1:dist[0][0][i]; return ans; } static void main() throws Exception{ n=sc.nextInt();int m=sc.nextInt(); adjListW=new ArrayList[n]; for(int i=0;i<n;i++)adjListW[i]=new ArrayList<int[]>(); for(int i=0;i<m;i++) { int x=sc.nextInt()-1,y=sc.nextInt()-1,w=sc.nextInt(); adjListW[x].add(new int[] {y,w}); adjListW[y].add(new int[] {x,w}); } int[]ans=dijkstra(0); for(int i=0;i<n;i++)pw.print(ans[i]+ " "); pw.println(); } public static void main(String[] args) throws Exception{ sc=new MScanner(System.in); pw = new PrintWriter(System.out); int tc=1; // tc=sc.nextInt(); for(int i=1;i<=tc;i++) { // pw.printf("Case %d:\n", i); main(); } pw.flush(); } static PrintWriter pw; static MScanner sc; static class MScanner { StringTokenizer st; BufferedReader br; public MScanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public MScanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int[] intArr(int n) throws IOException { int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public long[] longArr(int n) throws IOException { long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public int[] intSortedArr(int n) throws IOException { int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt(); shuffle(in); Arrays.sort(in); return in; } public long[] longSortedArr(int n) throws IOException { long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong(); shuffle(in); Arrays.sort(in); return in; } public Integer[] IntegerArr(int n) throws IOException { Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public Long[] LongArr(int n) throws IOException { Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } static void shuffle(int[]in) { for(int i=0;i<in.length;i++) { int idx=(int)(Math.random()*in.length); int tmp=in[i]; in[i]=in[idx]; in[idx]=tmp; } } static void shuffle(long[]in) { for(int i=0;i<in.length;i++) { int idx=(int)(Math.random()*in.length); long tmp=in[i]; in[i]=in[idx]; in[idx]=tmp; } } }
Java
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
4 seconds
["0 98 49 25 114", "0 -1 9"]
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "dp", "flows", "graphs", "shortest paths" ]
abee4d188bb59d82fcf4579c7416a343
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
2,200
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
standard output
PASSED
1c79e71906596be9ddd89d837c611562
train_110.jsonl
1613658900
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
512 megabytes
import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.math.BigInteger; import java.math.BigDecimal; import java.math.MathContext; import java.math.RoundingMode; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Map.Entry; import java.util.PriorityQueue; import java.util.Random; import java.util.Scanner; import java.util.TreeSet; public final class CF_703_D2_E { static boolean verb=true; static void log(Object X){if (verb) System.err.println(X);} static void log(Object[] X){if (verb) {for (Object U:X) System.err.print(U+" ");System.err.println("");}} static void log(int[] X){if (verb) {for (int U:X) System.err.print(U+" ");System.err.println("");}} static void log(int[] X,int L){if (verb) {for (int i=0;i<L;i++) System.err.print(X[i]+" ");System.err.println("");}} static void log(long[] X){if (verb) {for (long U:X) System.err.print(U+" ");System.err.println("");}} static void logWln(Object X){if (verb) System.err.print(X);} static void info(Object o){ System.out.println(o);} static void output(Object o){outputWln(""+o+"\n"); } static void outputWln(Object o){try {out.write(""+ o);} catch (Exception e) {}} // Global vars static BufferedWriter out; static InputReader reader; static long powerMod(long b,long e,long m){ long x=1; while (e>0) { if (e%2==1) x=(b*x)%m; b=(b*b)%m; e=e/2; } return x; } /* static void test() { log("testing"); Random r=new Random(); int NTESTS=1000000000; int NMAX=40; //int MMAX=10000; int VMAX=50; for( int t=0;t<NTESTS;t++) { int n=r.nextInt(NMAX)+2; int MMAX=(n*(n-1))/2; int m=r.nextInt(MMAX)+1; HashSet<String> hs=new HashSet<String>(); ArrayList<Integer>[] friends=new ArrayList[n]; ArrayList<Integer>[] cost=new ArrayList[n]; for (int u=0;u<n;u++) { friends[u]=new ArrayList<Integer>(); cost[u]=new ArrayList<Integer>(); } StringBuffer script=new StringBuffer(); for (int i=0;i<m;i++) { boolean goon=true; while (goon) { int u=r.nextInt(n); int v=r.nextInt(n); if (u!=v) { if (u>v) { int w=u; u=v; v=w; } String s=u+" "+v; if (!hs.contains(s)) { hs.add(s); goon=false; int w=r.nextInt(VMAX)+1; friends[u].add(v); friends[v].add(u); cost[u].add(w); cost[v].add(w); script.append((u+1)+" "+(v+1)+" "+w+"\n"); } } } } long[] ans1=solveSubtil(friends,cost); long[] ans2=solveBourrin(friends,cost); for (int i=0;i<n;i++) { if (ans1[i]!=ans2[i]) { log("Error"); log(n+" "+m); log(script); log(ans1); log(ans2); return; } } } log("done"); } */ static int sign(int x) { if (x>0) return 1; if (x==0) return 0; return -1; } static class Segment implements Comparable<Segment>{ int a; int b; public int compareTo(Segment X) { if (a!=X.a) return a-X.a; if (b!=X.b) return b-X.b; return 0; } public Segment(int a, int b) { this.a = a; this.b = b; } } static int order; static int BYA=0; static int BYB=1; static class Composite implements Comparable<Composite>{ int p; long v; int idx; int temp; public int compareTo(Composite X) { if (v<X.v) return -1; if (v>X.v) return 1; if (p!=X.p) return p-X.p; if (temp!=X.temp) return temp-X.temp; return idx-X.idx; } public Composite(int p, long v, int idx, int temp) { this.p = p; this.v = v; this.idx = idx; this.temp = temp; } public String toString() { return "p:"+p+" dist:"+v+" node:"+(idx+1)+" temp:"+temp; } } static class BIT { int[] tree; int N; BIT(int N){ tree=new int[N+1]; this.N=N; } void add(int idx,int val){ idx++; while (idx<=N){ tree[idx]+=val; idx+=idx & (-idx); } } int read(int idx){ idx++; int sum=0; while (idx>0){ sum+=tree[idx]; idx-=idx & (-idx); } return sum; } } static ArrayList<ArrayList<Integer>> generatePermutations(ArrayList<Integer> items){ ArrayList<ArrayList<Integer>> globalRes=new ArrayList<ArrayList<Integer>>(); if (items.size()>1) { for (Integer item:items){ ArrayList<Integer> itemsTmp=new ArrayList<Integer>(items); itemsTmp.remove(item); ArrayList<ArrayList<Integer>> res=generatePermutations(itemsTmp); for (ArrayList<Integer> list:res){ list.add(item); } globalRes.addAll(res); } } else { Integer item=items.get(0); ArrayList<Integer> list=new ArrayList<Integer>(); list.add(item); globalRes.add(list); } return globalRes; } static int VX=51; static long[] solveSubtil(int[][] friends,int[][] cost) { int n=friends.length; long[] ct=new long[n]; Arrays.fill(ct,MX); ct[0]=0; long[][] cst=new long[VX][n]; for (int e=0;e<VX;e++) Arrays.fill(cst[e],MX); //int[] tmp=new int[n]; PriorityQueue<Composite> pq=new PriorityQueue<Composite>(); pq.add(new Composite(0,0,0,0)); while (pq.size()>0) { Composite X=pq.poll(); // don't process obsolete values //if (X.v==cst[X.p][X.idx]) { //log("processing X:"+X); int u=X.idx; int L=friends[u].length; int p=X.p; for (int t=0;t<L;t++) { int node=friends[u][t]; int price=cost[u][t]; //log("considering node:"+(node+1)); if (p==0) { long dist=cst[price][node]; if (dist>X.v) { cst[price][node]=X.v; //tmp[node]=price; Composite Y=new Composite(1-p,X.v,node,price); pq.add(Y); //log("--adding : "+Y); } else { //log("--not interesting"); } } else { long nextDest=X.v+(X.temp+price)*(X.temp+price); if (ct[node]>nextDest) { ct[node]=nextDest; Composite Y=new Composite(1-p,nextDest,node,0); pq.add(Y); //log("--adding : "+Y); } else { //log("--not interesting"); } } } } } ////logWln("cst1:"); ////log(cst[1]); return ct; } static long[] solveSubtilSlow(ArrayList<Integer>[] friends,ArrayList<Integer>[] cost) { int n=friends.length; long[][] cst=new long[2][n]; for (int e=0;e<2;e++) Arrays.fill(cst[e],MX); cst[0][0]=0; //int[] tmp=new int[n]; Composite[][] ref=new Composite[2][n]; for (int e=0;e<2;e++) for (int i=0;i<n;i++) ref[e][i]=new Composite(e,cst[e][i],i,0); PriorityQueue<Composite> pq=new PriorityQueue<Composite>(); pq.add(ref[0][0]); while (pq.size()>0) { Composite X=pq.poll(); // don't process obsolete values //if (X.v==cst[X.p][X.idx]) { //log("processing X:"+X); int u=X.idx; int L=friends[u].size(); int p=X.p; for (int t=0;t<L;t++) { int node=friends[u].get(t); int price=cost[u].get(t); long dst=cst[1-p][node]; //log("considering node:"+(node+1)); if (p==0) { long worstv=dst+(100*100); long best=X.v+(price+1)*(price+1); if (worstv>best) { cst[1-p][node]=X.v; //tmp[node]=price; Composite Y=new Composite(1-p,X.v,node,price); pq.add(Y); //log("--adding"); } else { //log("--not interesting // "+worstv+" "+best); } } else { long nextDest=X.v+(X.temp+price)*(X.temp+price); if (dst>nextDest) { cst[1-p][node]=nextDest; Composite Y=new Composite(1-p,nextDest,node,0); pq.add(Y); //log("--adding"); } else { //log("--not interesting"); } } } } } //logWln("cst1:"); //log(cst[1]); return cst[0]; } static long MX=Long.MAX_VALUE/2; static long[] solveBourrin(int[][] friends,int[][] cost) { int n=friends.length; long[] cst=new long[n]; Arrays.fill(cst,MX); cst[0]=0; int[] tmp=new int[n]; Composite[] ref=new Composite[n]; for (int i=0;i<n;i++) ref[i]=new Composite(0,cst[i],i,0); PriorityQueue<Composite> pq=new PriorityQueue<Composite>(); pq.add(ref[0]); while (pq.size()>0) { Composite X=pq.poll(); int u=X.idx; int LU=friends[u].length; for (int tu=0;tu<LU;tu++) { int v=friends[u][tu]; int cv=cost[u][tu]; int LV=friends[v].length; for (int tv=0;tv<LV;tv++) { int w=friends[v][tv]; int cw=cost[v][tv]; long diff=(cw+cv); diff*=diff; long nxt=X.v+diff; if (cst[w]>nxt) { cst[w]=nxt; pq.add(new Composite(0,cst[w],w,0)); } } } } return cst; } static long mod=1000000007; static void process() throws Exception { out = new BufferedWriter(new OutputStreamWriter(System.out)); reader=new InputReader(System.in); Locale.setDefault(Locale.US); //test(); int n=reader.readInt(); int m=reader.readInt(); int[] ed=new int[m]; int[] to=new int[m]; int[] from=new int[m]; int[] cst=new int[m]; int[] ptr=new int[n]; for (int i=0;i<m;i++) { int u=reader.readInt()-1; int v=reader.readInt()-1; int w=reader.readInt(); ptr[u]++; ptr[v]++; from[i]=u; to[i]=v; cst[i]=w; } int[][] friends=new int[n][]; int[][] cost=new int[n][]; for (int i=0;i<n;i++) { friends[i]=new int[ptr[i]]; cost[i]=new int[ptr[i]]; } for (int i=0;i<m;i++) { int u=from[i]; int v=to[i]; int w=cst[i]; friends[u][ptr[u]-1]=v; cost[u][ptr[u]-1]=w; friends[v][ptr[v]-1]=u; cost[v][ptr[v]-1]=w; ptr[u]--; ptr[v]--; } //long[] ans=solveBourrin(friends,cost); long[] ans=solveSubtil(friends,cost); //log(ans); //log(alt); for (long x:ans) { if (x!=MX) outputWln(x+" "); else outputWln("-1 "); } output(""); try { out.close(); } catch (Exception EX){} } public static void main(String[] args) throws Exception { process(); } static final class InputReader { private final InputStream stream; private final byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } private int read() throws IOException { if (curChar >= numChars) { curChar = 0; numChars = stream.read(buf); if (numChars <= 0) { return -1; } } return buf[curChar++]; } public final String readString() throws IOException { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res=new StringBuilder(); do { res.append((char)c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public final int readInt() throws IOException { int c = read(); boolean neg=false; while (isSpaceChar(c)) { c = read(); } char d=(char)c; //log("d:"+d); if (d=='-') { neg=true; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); //log("res:"+res); if (neg) return -res; return res; } public final long readLong() throws IOException { int c = read(); boolean neg=false; while (isSpaceChar(c)) { c = read(); } char d=(char)c; //log("d:"+d); if (d=='-') { neg=true; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); //log("res:"+res); if (neg) return -res; return res; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
4 seconds
["0 98 49 25 114", "0 -1 9"]
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "dp", "flows", "graphs", "shortest paths" ]
abee4d188bb59d82fcf4579c7416a343
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
2,200
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
standard output
PASSED
7d9e454d762d48fa9377a491af29b03a
train_110.jsonl
1613658900
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
512 megabytes
/** * BaZ :D */ import java.util.*; import java.io.*; import static java.lang.Math.*; public class Main { static MyScanner scan; static PrintWriter pw; static long MOD = 1_000_000_007; static long INF = 2_000_000_000_000_000_000L; static long inf = 2_000_000_000; public static void main(String[] args) { new Thread(null, null, "BaZ", 1 << 27) { public void run() { try { solve(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } }.start(); } static void solve() throws java.lang.Exception { //initIo(true, ""); initIo(false, ""); StringBuilder sb = new StringBuilder(); int n = ni(), m = ni(); ArrayList<Pair> adj[] = new ArrayList[n+1]; for(int i=1;i<=n;i++) { adj[i] = new ArrayList<>(); } for(int i=0;i<m;i++) { int u = ni(), v = ni(), w = ni(); adj[u].add(new Pair(v,w)); adj[v].add(new Pair(u,w)); } boolean vis[][] = new boolean[n+1][51]; int dis[][] = new int[n+1][51]; for(int i=1;i<=n;i++) { for(int j=0;j<=50;j++) { dis[i][j] = Integer.MAX_VALUE; } } PriorityQueue<Pair> queue = new PriorityQueue<>(); queue.add(new Pair(0, (n+1) * 0 + 1)); dis[1][0] = 0; while (!queue.isEmpty()) { Pair curr = queue.poll(); int v = curr.y % (n+1); int last_weight = curr.y / (n+1); if(vis[v][last_weight]) { continue; } vis[v][last_weight] = true; for(Pair p : adj[v]) { if(last_weight==0) { if(!vis[p.x][p.y] && dis[p.x][p.y] > curr.x) { dis[p.x][p.y] = curr.x; queue.add(new Pair(curr.x, (n+1) * p.y + p.x)); } } else { if(!vis[p.x][0] && dis[p.x][0] > curr.x + (last_weight + p.y) * (last_weight + p.y)) { dis[p.x][0] = curr.x + (last_weight + p.y) * (last_weight + p.y); queue.add(new Pair(dis[p.x][0], (n+1) * 0 + p.x)); } } } } for(int i=1;i<=n;i++) { if(dis[i][0]==Integer.MAX_VALUE) { p(-1); } else { p(dis[i][0]); } } pl(); pw.flush(); pw.close(); } static class Pair implements Comparable<Pair> { int x,y; Pair(int x,int y) { this.x=x; this.y=y; } public int compareTo(Pair other) { if(this.x!=other.x) return this.x-other.x; return this.y-other.y; } public String toString() { return "("+x+","+y+")"; } } static void assert_in_range(String varName, int n, int l, int r) { if (n >=l && n<=r) return; System.out.println(varName + " is not in range. Actual: "+n+" l : "+l+" r: "+r); System.exit(1); } static void assert_in_range(String varName, long n, long l, long r) { if (n>=l && n<=r) return; System.out.println(varName + " is not in range. Actual: "+n+" l : "+l+" r: "+r); System.exit(1); } static void initIo(boolean isFileIO, String suffix) throws IOException { scan = new MyScanner(isFileIO, suffix); if(isFileIO) { pw = new PrintWriter("/Users/amandeep/Desktop/output"+suffix+".txt"); } else { pw = new PrintWriter(System.out, true); } } static int ni() throws IOException { return scan.nextInt(); } static long nl() throws IOException { return scan.nextLong(); } static double nd() throws IOException { return scan.nextDouble(); } static String ne() throws IOException { return scan.next(); } static String nel() throws IOException { return scan.nextLine(); } static void pl() { pw.println(); } static void p(Object o) { pw.print(o+" "); } static void pl(Object o) { pw.println(o); } static void psb(StringBuilder sb) { pw.print(sb); } static void pa(String arrayName, Object arr[]) { pl(arrayName+" : "); for(Object o : arr) p(o); pl(); } static void pa(String arrayName, int arr[]) { pl(arrayName+" : "); for(int o : arr) p(o); pl(); } static void pa(String arrayName, long arr[]) { pl(arrayName+" : "); for(long o : arr) p(o); pl(); } static void pa(String arrayName, double arr[]) { pl(arrayName+" : "); for(double o : arr) p(o); pl(); } static void pa(String arrayName, char arr[]) { pl(arrayName+" : "); for(char o : arr) p(o); pl(); } static void pa(String arrayName, boolean arr[]) { pl(arrayName+" : "); for(boolean o : arr) p(o); pl(); } static void pa(String listName, List list) { pl(listName+" : "); for(Object o : list) p(o); pl(); } static void pa(String arrayName, Object[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(Object o : arr[i]) p(o); pl(); } } static void pa(String arrayName, int[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(int o : arr[i]) p(o); pl(); } } static void pa(String arrayName, long[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(long o : arr[i]) p(o); pl(); } } static void pa(String arrayName, char[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(char o : arr[i]) p(o); pl(); } } static void pa(String arrayName, double[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(double o : arr[i]) p(o); pl(); } } static void pa(String arrayName, boolean[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(boolean o : arr[i]) p(o); pl(); } } static class MyScanner { BufferedReader br; StringTokenizer st; MyScanner(boolean readingFromFile, String suffix) throws IOException { if(readingFromFile) { br = new BufferedReader(new FileReader("/Users/amandeep/Desktop/input"+suffix+".txt")); } else { br = new BufferedReader(new InputStreamReader(System.in)); } } String nextLine()throws IOException { return br.readLine(); } String next() throws IOException { if(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()); } } }
Java
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
4 seconds
["0 98 49 25 114", "0 -1 9"]
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "dp", "flows", "graphs", "shortest paths" ]
abee4d188bb59d82fcf4579c7416a343
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
2,200
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
standard output
PASSED
db23a38f9396f27f20395fb838068ccb
train_110.jsonl
1613658900
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
512 megabytes
import java.io.*; import java.util.*; /* polyakoff */ public class Main { static FastReader in; static PrintWriter out; static Random rand = new Random(); static final int oo = (int) 1e9 + 10; static final long OO = (long) 2e18 + 10; static final int MOD = (int) 1e9 + 7; static class Edge { int v, w; Edge(int v, int w) { this.v = v; this.w = w; } } static class State { int v, x; long d; State(int v, int x, long d) { this.v = v; this.x = x; this.d = d; } } static long square(long x) { return x * x; } static void solve() { int n = in.nextInt(); int m = in.nextInt(); ArrayList<Edge>[] g = new ArrayList[n]; Arrays.setAll(g, i -> new ArrayList<>()); for (int i = 0; i < m; i++) { int v = in.nextInt() - 1; int u = in.nextInt() - 1; int w = in.nextInt(); g[v].add(new Edge(u, w)); g[u].add(new Edge(v, w)); } // dijkstra long[][] dp = new long[n][51]; for (int i = 0; i < n; i++) { Arrays.fill(dp[i], -1); } dp[0][0] = 0; TreeSet<State> set = new TreeSet<>((o1, o2) -> { if (o1.d == o2.d) return Integer.compare(o1.x * n + o1.v, o2.x * n + o2.v); return Long.compare(o1.d, o2.d); }); set.add(new State(0, 0, dp[0][0])); while (!set.isEmpty()) { State st0 = set.pollFirst(); int v = st0.v; int x = st0.x; long d = st0.d; for (Edge e : g[st0.v]) { if (x == 0) { if (dp[e.v][e.w] == -1 || dp[v][0] < dp[e.v][e.w]) { if (dp[e.v][e.w] != -1) set.remove(new State(e.v, e.w, dp[e.v][e.w])); dp[e.v][e.w] = dp[v][0]; set.add(new State(e.v, e.w, dp[e.v][e.w])); } } else { if (dp[e.v][0] == -1 || d + square(x + e.w) < dp[e.v][0]) { if (dp[e.v][0] != -1) set.remove(new State(e.v, 0, dp[e.v][0])); dp[e.v][0] = d + square(x + e.w); set.add(new State(e.v, 0, dp[e.v][0])); } } } } for (int i = 0; i < n; i++) { out.print(dp[i][0] + " "); } out.println(); } public static void main(String[] args) { in = new FastReader(); out = new PrintWriter(System.out); int T = 1; // T = in.nextInt(); while (T-- > 0) solve(); out.flush(); out.close(); } static class FastReader { BufferedReader br; StringTokenizer st; FastReader() { this(System.in); } FastReader(String file) throws FileNotFoundException { this(new FileInputStream(file)); } FastReader(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } int 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 line; try { line = br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return line; } } }
Java
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
4 seconds
["0 98 49 25 114", "0 -1 9"]
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "dp", "flows", "graphs", "shortest paths" ]
abee4d188bb59d82fcf4579c7416a343
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
2,200
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
standard output
PASSED
1c3c35dbacbcf095f3628baab2ab8a31
train_110.jsonl
1613658900
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
512 megabytes
import java.util.*; import java.io.*; import java.math.*; /** * * @Har_Har_Mahadev */ public class E { private static long INF = 2000000000000000000L, M = 1000000007, MM = 998244353; private static int N = 0; static ArrayList<Edge>[] edges; public static void process() throws IOException { int N = sc.nextInt(); int M = sc.nextInt(); edges = new ArrayList[N]; for(int i=0; i < N; i++) edges[i] = new ArrayList<E.Edge>(); while(M-->0) { int u = sc.nextInt()-1; int v = sc.nextInt()-1; int w = sc.nextInt(); edges[u].add(new Edge(v, w)); edges[v].add(new Edge(u, w)); } long[][] dp = new long[N][51]; for(int i=0; i < N; i++) Arrays.fill(dp[i], INF); boolean[][] seen = new boolean[N][51]; PriorityQueue<Node> pq = new PriorityQueue<Node>(); pq.add(new Node(0, 0, 0L)); dp[0][0] = 0L; while(pq.size() > 0) { Node curr = pq.poll(); if(seen[curr.id][curr.tag]) continue; seen[curr.id][curr.tag] = true; for(Edge e: edges[curr.id]) { if(curr.tag == 0) { if(dp[e.to][e.weight] > curr.dist) { dp[e.to][e.weight] = curr.dist; pq.add(new Node(e.to, e.weight, curr.dist)); } } else { int add = (e.weight+curr.tag)*(e.weight+curr.tag); if(dp[e.to][0] > curr.dist+add) { dp[e.to][0] = curr.dist+add; pq.add(new Node(e.to, 0, curr.dist+add)); } } } } for(int v=0; v < N; v++) { if(dp[v][0] == INF) dp[v][0] = -1; print(dp[v][0]+" "); } println(); } static class Node implements Comparable<Node> { public int id; public int tag; public long dist; public Node(int a, int b, long d) { id = a; tag = b; dist = d; } public int compareTo(Node oth) { return Long.compare(dist, oth.dist); } } static class Edge { public int to; public int weight; public Edge(int a, int b) { to = a; weight = b; } } //============================================================================= //--------------------------The End--------------------------------- //============================================================================= static FastScanner sc; static PrintWriter out; public static void main(String[] args) throws IOException { boolean oj = true; if (oj) { sc = new FastScanner(); out = new PrintWriter(System.out); } else { sc = new FastScanner(100); out = new PrintWriter("output.txt"); } int t = 1; // t = sc.nextInt(); while (t-- > 0) { process(); } out.flush(); out.close(); } static class Pair implements Comparable<Pair> { int x, y; Pair(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(Pair o) { return Integer.compare(this.x, o.x); } // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Pair)) return false; // Pair key = (Pair) o; // return x == key.x && y == key.y; // } // // @Override // public int hashCode() { // int result = x; // result = 31 * result + y; // return result; // } } ///////////////////////////////////////////////////////////////////////////////////////////////////////// static void println(Object o) { out.println(o); } static void println() { out.println(); } static void print(Object o) { out.print(o); } static void pflush(Object o) { out.println(o); out.flush(); } static int ceil(int x, int y) { return (x % y == 0 ? x / y : (x / y + 1)); } static long ceil(long x, long y) { return (x % y == 0 ? x / y : (x / y + 1)); } static int max(int x, int y) { return Math.max(x, y); } static int min(int x, int y) { return Math.min(x, y); } static int abs(int x) { return Math.abs(x); } static long abs(long x) { return Math.abs(x); } static int log2(int N) { int result = (int) (Math.log(N) / Math.log(2)); return result; } static long max(long x, long y) { return Math.max(x, y); } static long min(long x, long y) { return Math.min(x, y); } public static int gcd(int a, int b) { BigInteger b1 = BigInteger.valueOf(a); BigInteger b2 = BigInteger.valueOf(b); BigInteger gcd = b1.gcd(b2); return gcd.intValue(); } public static long gcd(long a, long b) { BigInteger b1 = BigInteger.valueOf(a); BigInteger b2 = BigInteger.valueOf(b); BigInteger gcd = b1.gcd(b2); return gcd.longValue(); } public static long lcm(long a, long b) { return (a * b) / gcd(a, b); } public static int lcm(int a, int b) { return (a * b) / gcd(a, b); } public static int lower_bound(int[] arr, int x) { int low = 0, high = arr.length, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] >= x) high = mid; else low = mid + 1; } return low; } public static int upper_bound(int[] arr, int x) { int low = 0, high = arr.length, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] > x) high = mid; else low = mid + 1; } return low; } ///////////////////////////////////////////////////////////////////////////////////////////////////////// static class FastScanner { BufferedReader br; StringTokenizer st; FastScanner() throws FileNotFoundException { br = new BufferedReader(new InputStreamReader(System.in)); } FastScanner(int a) throws FileNotFoundException { br = new BufferedReader(new FileReader("input.txt")); } String next() throws IOException { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } 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 { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readArray(int n) throws IOException { int[] A = new int[n]; for (int i = 0; i != n; i++) { A[i] = sc.nextInt(); } return A; } long[] readArrayLong(int n) throws IOException { long[] A = new long[n]; for (int i = 0; i != n; i++) { A[i] = sc.nextLong(); } return A; } } static void ruffleSort(int[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); int temp = a[i]; a[i] = a[r]; a[r] = temp; } Arrays.sort(a); } static void ruffleSort(long[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); long temp = a[i]; a[i] = a[r]; a[r] = temp; } Arrays.sort(a); } }
Java
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
4 seconds
["0 98 49 25 114", "0 -1 9"]
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "dp", "flows", "graphs", "shortest paths" ]
abee4d188bb59d82fcf4579c7416a343
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
2,200
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
standard output
PASSED
848dde397f313fca9dc88a09e5237e34
train_110.jsonl
1613658900
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
512 megabytes
import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.PriorityQueue; import java.util.StringTokenizer; public class PairedPayment implements Closeable { private InputReader in = new InputReader(System.in); private PrintWriter out = new PrintWriter(System.out); public void solve() { read(); dijkstra(); for (int i = 0; i < n; i++) { out.print(dist[i] == oo ? -1 : dist[i]); out.print(' '); } } private void read() { n = in.ni(); m = in.ni(); graph = new ArrayList<>(); for (int i = 0; i <= n; i++) { graph.add(new ArrayList<>()); } for (int i = 0; i < m; i++) { int from = in.ni() - 1, to = in.ni() - 1; long weight = in.nl(); graph.get(from).add(new Edge(to, weight)); graph.get(to).add(new Edge(from, weight)); } dist = new long[n]; for (int i = 0; i < n; i++) { dist[i] = oo; } } private final long oo = (long) 1e16; private int n, m; private long[] dist; private List<List<Edge>> graph; private class Edge { private int to; private long cost; private Edge(int to, long cost) { this.to = to; this.cost = cost; } public long getCost() { return cost; } } private void dijkstra() { PriorityQueue<Edge> queue = new PriorityQueue<>(Comparator.comparingLong(Edge::getCost)); queue.add(new Edge(0, 0)); dist[0] = 0; while (queue.size() > 0) { Edge top = queue.poll(); int u = top.to; for (Edge first : graph.get(u)) { long wa = first.cost; for (Edge second : graph.get(first.to)) { long wb = second.cost; int v = second.to; long relax = dist[u] + (wa + wb) * (wa + wb); if (relax < dist[v]) { queue.add(new Edge(v, relax)); dist[v] = relax; } } } } } @Override public void close() throws IOException { in.close(); out.close(); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int ni() { return Integer.parseInt(next()); } public long nl() { return Long.parseLong(next()); } public void close() throws IOException { reader.close(); } } public static void main(String[] args) throws IOException { try (PairedPayment instance = new PairedPayment()) { instance.solve(); } } }
Java
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
4 seconds
["0 98 49 25 114", "0 -1 9"]
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "dp", "flows", "graphs", "shortest paths" ]
abee4d188bb59d82fcf4579c7416a343
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
2,200
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
standard output
PASSED
8848d25133efd7f6358f5e9b6f8ab9bb
train_110.jsonl
1613658900
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
512 megabytes
import java.io.*; import java.util.*; public class A { static FastScanner fs; public static void main(String[] args) { fs=new FastScanner(); // int t = fs.nextInt(); // while (t-->0) solve(); } public static void solve() { int n = fs.nextInt(); int m = fs.nextInt(); HashMap<Integer, ArrayList<pair>> g = new HashMap<>(); for (int i=0; i<n; i++) g.put(i, new ArrayList<>()); for (int i=0; i<m; i++) { int x = fs.nextInt()-1; int y = fs.nextInt()-1; int d = fs.nextInt(); g.get(x).add(new pair(y, d)); g.get(y).add(new pair(x, d)); } int[] dist = new int[n]; Arrays.fill(dist, Integer.MAX_VALUE); dist[0] = 0; boolean[] finalized = new boolean[n]; PriorityQueue<pair> list = new PriorityQueue<pair>(n, (a, b) -> a.di - b.di); pair p0 = new pair(0, 0); list.add(p0); while(!list.isEmpty()) { pair p = list.poll(); int i = p.de; if( finalized[i] ) continue; if( dist[i]==Integer.MAX_VALUE ) break; finalized[i] = true; for (pair np : g.get(i)) { for (pair n2p : g.get(np.de)) { int j = n2p.de; int di = n2p.di; if(!finalized[j] && dist[i] + (di+np.di)*(di+np.di) < dist[j]) { dist[j] = dist[i] + (di+np.di)*(di+np.di); list.add( new pair(j, dist[j])); } } } } for (int i=0; i<n; i++) { if (i!=0) System.out.print(" "); if (dist[i] == Integer.MAX_VALUE) System.out.print(-1); else System.out.print(dist[i]); } System.out.println(); } static class pair { int de, di; pair(int a, int b) { de=a; di=b; } } static void ruffleSort(int[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n), temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static final Random random =new Random(); static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } static int[] reverse(int[] a) { int n=a.length; int[] res=new int[n]; for (int i=0; i<n; i++) res[i]=a[n-1-i]; return res; } }
Java
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
4 seconds
["0 98 49 25 114", "0 -1 9"]
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "dp", "flows", "graphs", "shortest paths" ]
abee4d188bb59d82fcf4579c7416a343
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
2,200
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
standard output
PASSED
e10b713a00542f1e20140e5617a53375
train_110.jsonl
1613658900
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
512 megabytes
import java.util.*; import java.io.*; public class E1486 { static ArrayList<int[]>[] adjList; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); int m = sc.nextInt(); adjList = new ArrayList[n]; for (int i = 0; i < n; i++) { adjList[i] = new ArrayList<int[]>(); } while (m-- > 0) { int u = sc.nextInt() - 1; int v = sc.nextInt() - 1; int w = sc.nextInt(); adjList[u].add(new int[] { v, w }); adjList[v].add(new int[] { u, w }); } int[][] dist = new int[51][n]; for (int[] x : dist) Arrays.fill(x, (int) 1e9); dist[0][0] = 0; PriorityQueue<int[]> pq = new PriorityQueue<int[]>((u, v) -> u[2] - v[2]); pq.add(new int[] { 0, 0, 0 }); while (!pq.isEmpty()) { int[] cur = pq.poll(); if (cur[2] > dist[cur[1]][cur[0]]) continue; if (cur[1] == 0) { for (int[] x : adjList[cur[0]]) { if (cur[2] < dist[x[1]][x[0]]) { pq.add(new int[] { x[0], x[1], dist[x[1]][x[0]] = cur[2] }); } } } else { for (int[] x : adjList[cur[0]]) { if (cur[2] + (cur[1] + x[1]) * (cur[1] + x[1]) < dist[0][x[0]]) { pq.add(new int[] { x[0], 0, dist[0][x[0]] = cur[2] + (cur[1] + x[1]) * (cur[1] + x[1]) }); } } } } for (int x : dist[0]) { pw.print((x == (int) 1e9 ? -1 : x) + " "); } pw.println(); pw.close(); } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader f) { br = new BufferedReader(f); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public int[] nextIntArr(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = Integer.parseInt(next()); } return arr; } } }
Java
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
4 seconds
["0 98 49 25 114", "0 -1 9"]
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "dp", "flows", "graphs", "shortest paths" ]
abee4d188bb59d82fcf4579c7416a343
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
2,200
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
standard output
PASSED
6ade6c259775dae3ff6c6e7cdbee568c
train_110.jsonl
1613658900
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
512 megabytes
//stan hu tao import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import java.util.*; import java.io.*; import java.math.*; public class x1486E { static final long INF = (Long.MAX_VALUE-420)/3; static ArrayDeque<Edge>[] edges; public static void main(String hi[]) throws Exception { FastScanner infile = new FastScanner(); int N = infile.nextInt(); int M = infile.nextInt(); edges = new ArrayDeque[N]; for(int i=0; i < N; i++) edges[i] = new ArrayDeque<Edge>(); while(M-->0) { int u = infile.nextInt()-1; int v = infile.nextInt()-1; int w = infile.nextInt(); edges[u].add(new Edge(v, w)); edges[v].add(new Edge(u, w)); } long[][] dp = new long[N][51]; for(int i=0; i < N; i++) Arrays.fill(dp[i], INF); boolean[][] seen = new boolean[N][51]; PriorityQueue<Node> pq = new PriorityQueue<Node>(); pq.add(new Node(0, 0, 0L)); dp[0][0] = 0L; while(pq.size() > 0) { Node curr = pq.poll(); if(seen[curr.id][curr.tag]) continue; seen[curr.id][curr.tag] = true; for(Edge e: edges[curr.id]) { if(curr.tag == 0) { if(dp[e.to][e.weight] > curr.dist) { dp[e.to][e.weight] = curr.dist; pq.add(new Node(e.to, e.weight, curr.dist)); } } else { int add = (e.weight+curr.tag)*(e.weight+curr.tag); if(dp[e.to][0] > curr.dist+add) { dp[e.to][0] = curr.dist+add; pq.add(new Node(e.to, 0, curr.dist+add)); } } } } StringBuilder sb = new StringBuilder(); for(int v=0; v < N; v++) { if(dp[v][0] == INF) dp[v][0] = -1; sb.append(dp[v][0]+" "); } System.out.println(sb); } } class Node implements Comparable<Node> { public int id; public int tag; public long dist; public Node(int a, int b, long d) { id = a; tag = b; dist = d; } public int compareTo(Node oth) { return Long.compare(dist, oth.dist); } } class Edge { public int to; public int weight; public Edge(int a, int b) { to = a; weight = b; } } class FastScanner { private int BS = 1 << 16; private char NC = (char) 0; private byte[] buf = new byte[BS]; private int bId = 0, size = 0; private char c = NC; private double cnt = 1; private BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } private char getChar() { while (bId == size) { try { size = in.read(buf); } catch (Exception e) { return NC; } if (size == -1) return NC; bId = 0; } return (char) buf[bId++]; } public int nextInt() { return (int) nextLong(); } public int[] nextInts(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) nextLong(); } return res; } public long[] nextLongs(int N) { long[] res = new long[N]; for (int i = 0; i < N; i++) { res[i] = nextLong(); } return res; } public long nextLong() { cnt = 1; boolean neg = false; if (c == NC) c = getChar(); for (; (c < '0' || c > '9'); c = getChar()) { if (c == '-') neg = true; } long res = 0; for (; c >= '0' && c <= '9'; c = getChar()) { res = (res << 3) + (res << 1) + c - '0'; cnt *= 10; } return neg ? -res : res; } public double nextDouble() { double cur = nextLong(); return c != '.' ? cur : cur + nextLong() / cnt; } public double[] nextDoubles(int N) { double[] res = new double[N]; for (int i = 0; i < N; i++) { res[i] = nextDouble(); } return res; } public String next() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c > 32) { res.append(c); c = getChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c != '\n') { res.append(c); c = getChar(); } return res.toString(); } public boolean hasNext() { if (c > 32) return true; while (true) { c = getChar(); if (c == NC) return false; else if (c > 32) return true; } } }
Java
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
4 seconds
["0 98 49 25 114", "0 -1 9"]
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "dp", "flows", "graphs", "shortest paths" ]
abee4d188bb59d82fcf4579c7416a343
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
2,200
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
standard output
PASSED
64d01a0151ebc56a06ef9d96ec53c3f4
train_110.jsonl
1613658900
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
512 megabytes
import java.util.*; import java.io.*; public class Div708 { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////// ///////// //////// ///////// //////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOOOOO SSSSSSS EEEEEEEEEEEEE ///////// //////// HHHH HHHH EEEEEEEEEEEEE MMMMMM MMMMMM OOO OOO SSSS SSS EEEEEEEEEEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMM MMM MMMM OOO OOO SSSS SSS EEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMMMMM MMMM OOO OOO SSSS EEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSSSSSS EEEEE ///////// //////// HHHHHHHHHHHHHHHH EEEEEEEEEEE MMMM MMMM OOO OOO SSSSSS EEEEEEEEEEE ///////// //////// HHHHHHHHHHHHHHHH EEEEEEEEEEE MMMM MMMM OOO OOO SSSSSSS EEEEEEEEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSSS EEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSS SSSS EEEEE ///////// //////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOO OOO SSS SSSS EEEEEEEEEEEEE ///////// //////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOOOOO SSSSSSS EEEEEEEEEEEEE ///////// //////// ///////// //////// ///////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); int m = sc.nextInt(); ArrayList<int[]> adj[] = new ArrayList[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); } while (m-- > 0) { int u = sc.nextInt() - 1; int v = sc.nextInt() - 1; int w = sc.nextInt(); adj[u].add(new int[]{v, w}); adj[v].add(new int[]{u, w}); } long[][][] dis = new long[2][51][n]; for (long[][] x : dis) for (long[] y : x) Arrays.fill(y, -1); PriorityQueue<long[]> pq = new PriorityQueue<>((x, y) -> Long.compare(x[3], y[3])); long[] st = new long[]{1, 0, 0, 0}; pq.add(st); dis[1][0][0] = 0; while (!pq.isEmpty()) { long[] cur = pq.poll(); int s = (int) cur[0]; int w = (int) cur[1]; int u = (int) cur[2]; long cost = cur[3]; if (dis[s][w][u] < cost) continue; // System.err.println(Arrays.toString(cur)); if (s == 0) { for (int[] v : adj[u]) { long ncost = cost + (w + v[1]) * (w + v[1]); if (dis[1][v[1]][v[0]] == -1 || ncost < dis[1][v[1]][v[0]]) { pq.add(new long[]{1, v[1], v[0], dis[1][v[1]][v[0]] = ncost}); } } } else { for (int[] v : adj[u]) { if (dis[0][v[1]][v[0]] == -1 || cost < dis[0][v[1]][v[0]]) { pq.add(new long[]{0, v[1], v[0], dis[0][v[1]][v[0]] = cost}); } } } } long[] cost = new long[n]; Arrays.fill(cost, -1); for (int i = 0; i < n; i++) { for (int w = 0; w <= 50; w++) { if (dis[1][w][i] == -1) continue; if (cost[i] == -1 || dis[1][w][i] < cost[i]) cost[i] = dis[1][w][i]; } pw.print(cost[i] + " "); } pw.println(); pw.flush(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(FileReader r) { br = new BufferedReader(r); } public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int[] nextIntArr(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
4 seconds
["0 98 49 25 114", "0 -1 9"]
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "dp", "flows", "graphs", "shortest paths" ]
abee4d188bb59d82fcf4579c7416a343
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
2,200
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
standard output
PASSED
796ef787dcfa83f8a99d1ed74bbbdb45
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
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.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.StringTokenizer; import java.util.TreeMap; /** * * @author is2ac */ public class C_CF { public static void main(String[] args) { FastScanner57 fs = new FastScanner57(); PrintWriter pw = new PrintWriter(System.out); int t = fs.ni(); //int t = 1; for (int tc = 0; tc < t; tc++) { int n = fs.ni(); int m = fs.ni(); Map<Integer,Integer> map = new HashMap(); int[][] a = new int[n][2]; for (int i = 0; i < n; i++) { a[i][0] = fs.ni(); } for (int i = 0; i < n; i++) { String s = fs.next(); if (s.equals("R")) { a[i][1] = 1; } else { a[i][1] = -1; } } TreeMap<Integer,Integer> tm = new TreeMap(); List<int[]> left = new ArrayList(); for (int i = 0; i < n; i++) { if (a[i][0]%2==0) { continue; } if (a[i][1]==-1) { left.add(new int[] {a[i][0],i}); } else { tm.put(a[i][0], i); } } List<int[]> exl = new ArrayList(); List<int[]> exr = new ArrayList(); Collections.sort(left,new Comparator<int[]>(){ public int compare(int[] a, int[] b) { return a[0]-b[0]; } }); for (int i = 0; i < left.size(); i++) { int[] l = left.get(i); Integer lower = tm.lowerKey(l[0]); if (lower==null) { exl.add(l); continue; } int[] r = new int[] {lower,tm.get(lower)}; int d = Math.abs(l[0]-r[0])/2; map.put(l[1], d); map.put(r[1],d); tm.remove(lower); } for (int key: tm.keySet()) { exr.add(new int[] {key,tm.get(key)}); } Collections.sort(exr,new Comparator<int[]>(){ public int compare(int[] a, int[] b) { return a[0]-b[0]; } }); int lp = 0; while (lp+1<exl.size()) { int[] l = exl.get(lp); int[] r = exl.get(lp+1); l[0] *= -1; int d = Math.abs(l[0]-r[0])/2; map.put(l[1], d); map.put(r[1],d); lp += 2; } int rp = exr.size()-1; while (rp-1>-1) { int[] l = exr.get(rp-1); int[] r = exr.get(rp); r[0] = (m-r[0]) + m; int d = Math.abs(l[0]-r[0])/2; map.put(l[1], d); map.put(r[1],d); rp-=2; } if (rp==0 && lp==exl.size()-1) { int[]l = exl.get(lp); int[]r = exr.get(0); l[0] *= -1; r[0] = m-r[0]+m; int d = Math.abs(l[0]-r[0])/2; map.put(l[1], d); map.put(r[1],d); } tm = new TreeMap(); left = new ArrayList(); for (int i = 0; i < n; i++) { if (a[i][0]%2==1) { continue; } if (a[i][1]==-1) { left.add(new int[] {a[i][0],i}); } else { tm.put(a[i][0], i); } } exl = new ArrayList(); exr = new ArrayList(); Collections.sort(left,new Comparator<int[]>(){ public int compare(int[] a, int[] b) { return a[0]-b[0]; } }); for (int i = 0; i < left.size(); i++) { int[] l = left.get(i); Integer lower = tm.lowerKey(l[0]); if (lower==null) { exl.add(l); continue; } int[] r = new int[] {lower,tm.get(lower)}; int d = Math.abs(l[0]-r[0])/2; map.put(l[1], d); map.put(r[1],d); tm.remove(lower); } for (int key: tm.keySet()) { exr.add(new int[] {key,tm.get(key)}); } Collections.sort(exr,new Comparator<int[]>(){ public int compare(int[] a, int[] b) { return a[0]-b[0]; } }); lp = 0; while (lp+1<exl.size()) { int[] l = exl.get(lp); int[] r = exl.get(lp+1); l[0] *= -1; int d = Math.abs(l[0]-r[0])/2; map.put(l[1], d); map.put(r[1],d); lp += 2; } rp = exr.size()-1; while (rp-1>-1) { int[] l = exr.get(rp-1); int[] r = exr.get(rp); r[0] = (m-r[0]) + m; int d = Math.abs(l[0]-r[0])/2; map.put(l[1], d); map.put(r[1],d); rp-=2; } if (rp==0 && lp==exl.size()-1) { int[]l = exl.get(lp); int[]r = exr.get(0); l[0] *= -1; r[0] = m-r[0]+m; int d = Math.abs(l[0]-r[0])/2; map.put(l[1], d); map.put(r[1],d); } for (int i = 0; i < n; i++) { if (map.containsKey(i)) { pw.print(map.get(i)); } else { pw.print(-1); } pw.print(" "); } pw.println(); } pw.close(); } public static boolean good(int[] a, int[] b) { for (int i = 0; i < a.length; i++) { if (a[i]<b[i]) return true; if (a[i]>b[i]) return false; } return true; } public static String print(int[] b) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < b.length; i++) { sb.append(b[i]); } return sb.toString(); } public static int recur(int ind, int p, int[] a, Integer[][] dp) { if (ind==a.length) return 0; int n = (int)(1e9); if (dp[ind][p]!=null) return dp[ind][p]; for (int i = 0; i < 3; i++) { int c = 1; if (i==a[ind]) c--; if (i==p) continue; n = Math.min(n,recur(ind+1,i,a,dp)+c); } return dp[ind][p] = n; } public static void sort(long[] a) { List<Long> list = new ArrayList(); for (int i = 0; i < a.length; i++) { list.add(a[i]); } Collections.sort(list); for (int i = 0; i < a.length; i++) { a[i] = list.get(i); } } public static int gcd(int n1, int n2) { if (n2 == 0) { return n1; } return gcd(n2, n1 % n2); } } class UnionFind16 { int[] id; public UnionFind16(int size) { id = new int[size]; for (int i = 0; i < size; i++) { id[i] = i; } } public int find(int p) { int root = p; while (root != id[root]) { root = id[root]; } while (p != root) { int next = id[p]; id[p] = root; p = next; } return root; } public void union(int p, int q) { int a = find(p), b = find(q); if (a == b) { return; } id[b] = a; } } class FastScanner57 { BufferedReader br; StringTokenizer st; public FastScanner57() { br = new BufferedReader(new InputStreamReader(System.in), 32768); st = null; } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int ni() { return Integer.parseInt(next()); } int[] intArray(int N) { int[] ret = new int[N]; for (int i = 0; i < N; i++) { ret[i] = ni(); } return ret; } long nl() { return Long.parseLong(next()); } long[] longArray(int N) { long[] ret = new long[N]; for (int i = 0; i < N; i++) { ret[i] = nl(); } return ret; } double nd() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
db9283f2db3f6fc265ac613099540e27
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.util.*; import java.io.*; public class Main { static long mod = 1000000007; static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); public static void main(String[] args) throws IOException { FastReader sc = new FastReader(); int t = sc.nextInt(); while( t-- > 0) { ArrayList<pair> odd = new ArrayList<>(); ArrayList<pair> even = new ArrayList<>(); int n = sc.nextInt(); int m= sc.nextInt(); int arr[] = new int[n]; for( int i =0 ; i< n ;i++) { arr[i] = sc.nextInt(); } char a[] = new char[n]; for( int i =0 ; i< n; i++) { a[i] = sc.next().charAt(0); } for( int i = 0 ;i< n; i++) { if( arr[i]%2 != 0) { odd.add( new pair(arr[i] , a[i] , i+1)); } else{ even.add( new pair( arr[i] , a[i], i+1)); } } int ans[] =new int[n+1]; Arrays.fill( ans, -1); solve( odd , ans , m ); solve( even , ans , m); for(int i = 1 ;i <= n; i++) { out.print(ans[i] + " "); } out.println(); } out.flush(); } private static void solve(ArrayList<pair> arr, int[] ans, int m) { int n = arr.size(); Stack<pair> s = new Stack<>(); Collections.sort( arr , new sort()); for( int i = 0 ;i <n; i++) { if( arr.get(i).c == 'L') { if( !s.isEmpty() && s.peek().c == 'R') { pair pr = s.pop(); int fst = pr.val; int scnd = arr.get(i).val; ans[pr.idx] = ans[arr.get(i).idx] = (scnd-fst)/2; } else { s.add( arr.get(i)); } } else { s.add( arr.get(i)); } } arr = new ArrayList<>(); Stack<pair> S = new Stack<>(); while(!s.isEmpty()) { // out.println(s.peek().val); S.add(s.pop()); // arr.add( s.pop()); } while(!S.isEmpty()) { // out.println(s.peek().val); // S.add(s.pop()); arr.add( S.pop()); } n = arr.size(); // Collections.sort( arr , new sort()); int i =0 ; while( i < n && i+1 < n && arr.get(i).c == 'L' && arr.get(i+1).c == 'L') { // out.println( arr.get(i).val + " " + arr.get(i+1).val); ans[arr.get(i).idx] = ans[arr.get(i+1).idx] = (arr.get(i+1).val - arr.get(i).val)/2 + arr.get(i).val; i+=2; } int j = n-1; while( j >= 0 && j-1 >= 0 && arr.get(j).c == 'R' && arr.get(j-1).c == 'R') { // out.println( arr.get(j).idx + " " +arr.get(j-1).idx + " " + (arr.get(j).val )); ans[arr.get(j).idx] = ans[arr.get(j-1).idx] = (arr.get(j).val - arr.get(j-1).val)/2 + m - arr.get(j).val; j-=2; } if( j > i) { ans[arr.get(j).idx] = ans[arr.get(j-1).idx] = (arr.get(j).val - arr.get(j-1).val)/2 + m - arr.get(j).val+arr.get(j-1).val; } } static class pair { int val; char c; int idx; pair( int val , char c ,int idx){ this.val = val; this.c = c; this.idx = idx; } } static class sort implements Comparator<pair>{ @Override public int compare(Main.pair o1, Main.pair o2) { return o1.val - o2.val; } } /* * use the hints * Read the question again * think of binary search * look at test cases * do significant case work */ static class DSU{ int n; int[] leaders,size; public DSU(int n){ this.n=n; leaders=new int[n+1]; size=new int[n+1]; for(int i=1;i<=n;i++){ leaders[i]=i; size[i]=1; } } public int find(int a){ if(leaders[a]==a) return a; return leaders[a]=find (leaders[a]); } public void merge(int a,int b){ a = find(a); b = find(b); if (a == b) return; if (size[a] < size[b]) swap(a, b); leaders[b] = a; size[a] += size[b]; } public void swap(int a,int b){ int temp=a; a=b; b=temp; } } static long power(long x, long y, long p) { long res = 1; x = x % p; if (x == 0) return 0; while (y > 0) { if ((y & 1) != 0) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res%p; } public static boolean ifpowof2(long n ) { return ((n&(n-1)) == 0); } static boolean isprime(long x ) { if( x== 2) { return true; } if( x%2 == 0) { return false; } for( long i = 3 ;i*i <= x ;i+=2) { if( x%i == 0) { return false; } } return true; } static boolean[] sieveOfEratosthenes(long n) { boolean prime[] = new boolean[(int)n + 1]; for (int i = 0; i <= n; i++) { prime[i] = true; } for (long p = 2; p * p <= n; p++) { if (prime[(int)p] == true) { for (long i = p * p; i <= n; i += p) prime[(int)i] = false; } } return prime; } public List<Integer> goodIndices(int[] nums, int k) { int n = nums.length; int fst[] = nextLargerElement(nums, n); int scnd[] = nextlargerElement(nums, n); List<Integer> ans = new ArrayList<>(); for( int i = 0 ;i < n; i++) { if( fst[i] == -1 || scnd[i] == -1) { continue; } if( fst[i]-i >= k && i - scnd[i] >= k) { ans.add(i); } } return ans; } public static int[] nextLargerElement(int[] arr, int n) { Stack<Integer> stack = new Stack<>(); int rtrn[] = new int[n]; rtrn[n-1] = -1; stack.push( n-1); for( int i = n-2 ;i >= 0 ; i--){ int temp = arr[i]; int lol = -1; while( !stack.isEmpty() && arr[stack.peek()] <= temp){ if(arr[stack.peek()] == temp ) { lol = stack.peek(); } stack.pop(); } if( stack.isEmpty()){ if( lol != -1) { rtrn[i] = lol; } else { rtrn[i] = -1; } } else{ rtrn[i] = stack.peek(); } stack.push( i); } return rtrn; } public static int[] nextlargerElement(int[] arr, int n) { Stack<Integer> stack = new Stack<>(); int rtrn[] = new int[n]; rtrn[0] = -1; stack.add( 0); for( int i = 1 ;i < n ; i++){ int temp = arr[i]; int lol = -1; while( !stack.isEmpty() && arr[stack.peek()] <= temp){ if(arr[stack.peek()] == temp ) { lol = stack.peek(); } stack.pop(); } if( stack.isEmpty()){ if( lol != -1) { rtrn[i] = lol; } else { rtrn[i] = -1; } } else{ rtrn[i] = stack.peek(); } stack.add( i); } return rtrn; } static void mysort(int[] arr) { for(int i=0;i<arr.length;i++) { int rand = (int) (Math.random() * arr.length); int loc = arr[rand]; arr[rand] = arr[i]; arr[i] = loc; } Arrays.sort(arr); } static void mySort(long[] arr) { for(int i=0;i<arr.length;i++) { int rand = (int) (Math.random() * arr.length); long loc = arr[rand]; arr[rand] = arr[i]; arr[i] = loc; } Arrays.sort(arr); } static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } static long lcm(long a, long b) { return (a / gcd(a, b)) * b; } static long rightmostsetbit(long n) { return n&-n; } static long leftmostsetbit(long n) { long k = (long)(Math.log(n) / Math.log(2)); return k; } static HashMap<Long,Long> primefactor( long n){ HashMap<Long ,Long> hm = new HashMap<>(); long temp = 0; while( n%2 == 0) { temp++; n/=2; } if( temp!= 0) { hm.put( 2L, temp); } long c = (long)Math.sqrt(n); for( long i = 3 ; i <= c ; i+=2) { temp = 0; while( n% i == 0) { temp++; n/=i; } if( temp!= 0) { hm.put( i, temp); } } if( n!= 1) { hm.put( n , 1L); } return hm; } static TreeSet<Long> allfactors(long abs) { HashMap<Long,Integer> hm = new HashMap<>(); TreeSet<Long> rtrn = new TreeSet<>(); rtrn.add(1L); for( long i = 2 ;i*i <= abs; i++) { if( abs% i == 0) { hm.put( i , 0); hm.put(abs/i, 0); } } for( long x : hm.keySet()) { rtrn.add(x); } if( abs != 0) { rtrn.add(abs); } return rtrn; } public static int[][] prefixsum( int n , int m , int arr[][] ){ int prefixsum[][] = new int[n+1][m+1]; for( int i = 1 ;i <= n ;i++) { for( int j = 1 ; j<= m ; j++) { int toadd = 0; if( arr[i-1][j-1] == 1) { toadd = 1; } prefixsum[i][j] = toadd + prefixsum[i][j-1] + prefixsum[i-1][j] - prefixsum[i-1][j-1]; } } return prefixsum; } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
916c7d2d77de42bb60053d1216e9df94
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.util.*; import java.io.*; public class Solution { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static final long mod=(long)1e9+7; public static long pow(long a,int p) { long res=1; while(p>0) { if(p%2==1) { p--; res*=a; res%=mod; } else { a*=a; a%=mod; p/=2; } } return res; } /*static class Pair { int i,j; Pair(int i,int j) { this.i=i; this.j=j; } }*/ static class Pair implements Comparable<Pair> { int v,l; Pair(int v,int l) { this.v=v; this.l=l; } public int compareTo(Pair p) { return l-p.l; } } static int gcd(int a,int b) { if(b%a==0) return a; return gcd(b%a,a); } public static void dfs(int u,int dist[],int sub[],int mxv[],int par[],ArrayList<Integer> edge[]) { sub[u]=1; for(int v:edge[u]) { if(dist[v]==-1) { par[v]=u; dist[v]=dist[u]+1; dfs(v,dist,sub,mxv,par,edge); if(sub[v]+1>sub[u]) { sub[u]=sub[v]+1; mxv[u]=v; } } } } public static void main(String args[])throws Exception { FastReader fs=new FastReader(); PrintWriter pw=new PrintWriter(System.out); int tc=fs.nextInt(); while(tc-->0) { int n=fs.nextInt(); int m=fs.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) a[i]=fs.nextInt(); char d[]=new char[n]; String str[]=fs.nextLine().split(" "); for(int i=0;i<str.length;i++) d[i]=str[i].charAt(0); TreeSet<Pair> re=new TreeSet<>(); TreeSet<Pair> ro=new TreeSet<>(); TreeSet<Pair> le=new TreeSet<>(); TreeSet<Pair> lo=new TreeSet<>(); int ans[]=new int[n]; Arrays.fill(ans,-1); for(int i=0;i<n;i++) { if(d[i]=='L') { if(a[i]%2==0) le.add(new Pair(i,a[i])); else lo.add(new Pair(i,a[i])); } else { if(a[i]%2==0) re.add(new Pair(i,a[i])); else ro.add(new Pair(i,a[i])); } } TreeSet<Pair> temp=new TreeSet<>(); for(Pair p:le) { if(re.floor(new Pair(0,p.l))!=null) { temp.add(p); Pair pp=re.floor(new Pair(0,p.l)); ans[pp.v]=ans[p.v]=(p.l-pp.l)/2; re.remove(pp); } } for(Pair p:temp) le.remove(p); temp.clear(); for(Pair p:lo) { if(ro.floor(new Pair(0,p.l))!=null) { temp.add(p); Pair pp=ro.floor(new Pair(0,p.l)); ans[pp.v]=ans[p.v]=(p.l-pp.l)/2; ro.remove(pp); } } for(Pair p:temp) lo.remove(p); while(le.size()>1) { Pair t1=le.pollFirst(),t2=le.pollFirst(); ans[t1.v]=ans[t2.v]=t1.l+(t2.l-t1.l)/2; } while(lo.size()>1) { Pair t1=lo.pollFirst(),t2=lo.pollFirst(); ans[t1.v]=ans[t2.v]=t1.l+(t2.l-t1.l)/2; } while(re.size()>1) { Pair t2=re.pollLast(),t1=re.pollLast(); ans[t1.v]=ans[t2.v]=m-t2.l+(t2.l-t1.l)/2; } while(ro.size()>1) { Pair t2=ro.pollLast(),t1=ro.pollLast(); ans[t1.v]=ans[t2.v]=m-t2.l+(t2.l-t1.l)/2; } if(le.size()==1&&re.size()==1) { Pair p1=le.pollFirst(); Pair p2=re.pollFirst(); int pos1=p1.l,pos2=p2.l; int mx=Math.max(p1.l,m-p2.l); if(mx==p1.l) { pos1=0; int rem=mx-(m-pos2); pos2=m-rem; } else { pos1=mx-p1.l; pos2=m; } ans[p1.v]=ans[p2.v]=mx+(pos2-pos1)/2; } if(lo.size()==1&&ro.size()==1) { Pair p1=lo.pollFirst(); Pair p2=ro.pollFirst(); int pos1=p1.l,pos2=p2.l; int mx=Math.max(p1.l,m-p2.l); if(mx==p1.l) { pos1=0; int rem=mx-(m-pos2); pos2=m-rem; } else { pos1=mx-p1.l; pos2=m; } ans[p1.v]=ans[p2.v]=mx+(pos2-pos1)/2; } for(int i:ans) pw.print(i+" "); pw.println(); } pw.flush(); pw.close(); } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
3a6475ea5ccbfba3cf850b6eac024421
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class feb20 { // *** ++ // +=-==+ +++=- // +-:---==+ *+=----= // +-:------==+ ++=------== // =-----------=++========================= // +--:::::---:-----============-=======+++==== // +---:..:----::-===============-======+++++++++ // =---:...---:-===================---===++++++++++ // +----:...:-=======================--==+++++++++++ // +-:------====================++===---==++++===+++++ // +=-----======================+++++==---==+==-::=++**+ // +=-----================---=======++=========::.:-+***** // +==::-====================--: --:-====++=+===:..-=+***** // +=---=====================-... :=..:-=+++++++++===++***** // +=---=====+=++++++++++++++++=-:::::-====+++++++++++++*****+ // +=======++++++++++++=+++++++============++++++=======+****** // +=====+++++++++++++++++++++++++==++++==++++++=:... . .+**** // ++====++++++++++++++++++++++++++++++++++++++++-. ..-+**** // +======++++++++++++++++++++++++++++++++===+====:. ..:=++++ // +===--=====+++++++++++++++++++++++++++=========-::....::-=++* // ====--==========+++++++==+++===++++===========--:::....:=++* // ====---===++++=====++++++==+++=======-::--===-:. ....:-+++ // ==--=--====++++++++==+++++++++++======--::::...::::::-=+++ // ===----===++++++++++++++++++++============--=-==----==+++ // =--------====++++++++++++++++=====================+++++++ // =---------=======++++++++====+++=================++++++++ // -----------========+++++++++++++++=================+++++++ // =----------==========++++++++++=====================++++++++ // =====------==============+++++++===================+++==+++++ // =======------==========================================++++++ // created by : Nitesh Gupta public static void main(String[] args) throws Exception { first(); // sec(); } private static void first() throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); StringBuilder sb = new StringBuilder(); while (t-- > 0) { String[] scn = (br.readLine()).trim().split(" "); int n = Integer.parseInt(scn[0]); int m = Integer.parseInt(scn[1]); int[] arr = new int[n]; scn = (br.readLine()).trim().split(" "); for (int i = 0; i < n; i++) { arr[i] = (int) Long.parseLong(scn[i]); } char[] brr = new char[n]; scn = (br.readLine()).trim().split(" "); for (int i = 0; i < n; i++) { brr[i] = scn[i].charAt(0); } ArrayList<pair> odd = new ArrayList<>(); ArrayList<pair> even = new ArrayList<>(); for (int i = 0; i < n; i++) { if (arr[i] % 2 == 1) { odd.add(new pair(i, arr[i], brr[i])); } else { even.add(new pair(i, arr[i], brr[i])); } } int[] ans = new int[n]; Arrays.fill(ans, -1); fun(even, ans, n, m); fun(odd, ans, n, m); for (int ele : ans) sb.append(ele + " "); sb.append("\n"); } System.out.println(sb); return; } public static void fun(ArrayList<pair> list, int[] ans, int n, int m) { Stack<pair> st = new Stack<>(); Collections.sort(list, (a, b) -> { return a.pos - b.pos; }); ArrayList<pair> sl = new ArrayList<>(); for (pair ele : list) { // System.out.println(ele.pos + " " + ele.idx + " " + ele.ch); if (ele.ch == 'R') { st.push(ele); } else { if (st.isEmpty()) { sl.add(ele); } else { pair rp = st.pop(); int dis = ele.pos - rp.pos; dis /= 2; ans[rp.idx] = ans[ele.idx] = dis; } } } // System.out.println(); while (!st.isEmpty()) { sl.add(st.pop()); } if (sl.size() <= 1) { return; } // // for (pair ele : sl) { // System.out.println(ele.pos + " " + ele.idx + " " + ele.ch); // } // System.out.println(); Collections.sort(sl, (a, b) -> { return a.pos - b.pos; }); int i = 0, j = 1; int ll = -1; while (true) { pair first = sl.get(i); pair second = sl.get(j); if (first.ch == second.ch && first.ch == 'L') { int diff = (second.pos - first.pos) / 2; diff += first.pos; ans[first.idx] = ans[second.idx] = diff; } else if (second.ch == 'R' && first.ch == 'L') { ll = i; break; } else { break; } i += 2; j += 2; if (i == sl.size()) { break; } if (j == sl.size()) { break; } } i = sl.size() - 2; j = i + 1; int rr = -1; while (true) { pair first = sl.get(i); pair second = sl.get(j); if (first.ch == second.ch && first.ch == 'R') { int diff = (second.pos - first.pos) / 2; diff += (m - second.pos); ans[second.idx] = ans[first.idx] = diff; } else if (second.ch == 'R' && first.ch == 'L') { rr = j; break; } else { break; } i -= 2; j -= 2; if (i == -1) { break; } if (j == -1) { break; } } if (ll != -1 && rr != -1) { pair first = sl.get(ll); pair second = sl.get(rr); int ff = first.pos; int ss = m - second.pos; int diff = Math.max(ff, ss); if (ff > ss) { ss = m - (ff - ss); ff = 0; } else { ff = 0 + (ss - ff); ss = m; } diff += (ss - ff) / 2; ans[second.idx] = ans[first.idx] = diff; } } static class pair { int idx; int pos; char ch; pair(int a, int b, char c) { idx = a; pos = b; ch = c; } } private static void sec() throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); StringBuilder sb = new StringBuilder(); while (t-- > 0) { String[] scn = (br.readLine()).trim().split(" "); int n = Integer.parseInt(scn[0]); long[] arr = new long[n]; scn = (br.readLine()).trim().split(" "); for (int i = 0; i < n; i++) { arr[i] = Long.parseLong(scn[i]); } sb.append("\n"); } System.out.println(sb); return; } private static void third() throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); String[] scn = (br.readLine()).trim().split(" "); int n = Integer.parseInt(scn[0]); long[] arr = new long[n]; scn = (br.readLine()).trim().split(" "); for (int i = 0; i < n; i++) { arr[i] = Long.parseLong(scn[i]); } System.out.println(sb); return; } public static void sort(long[] arr) { int n = arr.length; for (int i = 0; i < n; i++) { int idx = (int) Math.random() * n; long temp = arr[i]; arr[i] = arr[idx]; arr[idx] = temp; } Arrays.sort(arr); } public static void sort(int[] arr) { int n = arr.length; for (int i = 0; i < n; i++) { int idx = (int) Math.random() * n; int temp = arr[i]; arr[i] = arr[idx]; arr[idx] = temp; } Arrays.sort(arr); } public static void print(long[][] dp) { for (long[] a : dp) { for (long ele : a) { System.out.print(ele + " "); } System.out.println(); } } public static void print(int[][] dp) { for (int[] a : dp) { for (int ele : a) { System.out.print(ele + " "); } System.out.println(); } } public static void print(int[] dp) { for (int ele : dp) { System.out.print(ele + " "); } System.out.println(); } public static void print(long[] dp) { for (long ele : dp) { System.out.print(ele + " "); } System.out.println(); } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
333b183e6aec84743471088f58f24ad6
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.util.*; public class j { static class Robot implements Comparable<Robot> { int val,ind; char ch; Robot(int val,char ch,int ind) { this.ind=ind;this.ch=ch; this.val=val; } @Override public int compareTo(Robot r) { return this.val-r.val; } } public static void main(String args[]) { Scanner in=new Scanner(System.in); int t=in.nextInt(); while(t-->0) { int n=in.nextInt(); int m=in.nextInt(); int ind[]=new int[n]; char dir[]=new char[n]; for(int i=0;i<n;i++) ind[i]=in.nextInt(); for(int i=0;i<n;i++) dir[i]=in.next().charAt(0); ArrayList<Robot> odd=new ArrayList<>(); ArrayList<Robot> even=new ArrayList<>(); for(int i=0;i<n;i++) { if(ind[i]%2==0) even.add(new Robot(ind[i],dir[i],i)); else odd.add(new Robot(ind[i],dir[i],i)); } Collections.sort(odd); Collections.sort(even); int ans[]=new int[n]; Arrays.fill(ans,-1); findans(even,ans,m); findans(odd,ans,m); for(int i:ans) System.out.print(i+" "); System.out.println(); } } public static void findans(ArrayList<Robot> al,int ans[],int m) { Stack<Robot> st=new Stack<>(); for(Robot r:al) { if(r.ch=='R') st.add(r); else { if(st.isEmpty()) { st.add(r); } else { Robot right=st.pop(); if(right.ch=='R') { ans[r.ind]=Math.abs(r.val-right.val)/2; ans[right.ind]=ans[r.ind]; } else { ans[r.ind]=Math.abs(right.val+r.val)/2;; ans[right.ind]=Math.abs(right.val+r.val)/2; } } } } while(st.size()>=2) { Robot a=st.pop(); Robot b=st.pop(); if(b.ch=='R') { ans[a.ind]=Math.abs(m-a.val+m-b.val)/2; ans[b.ind]=ans[a.ind]; } else { ans[a.ind]=Math.abs(m-a.val+m+b.val)/2; ans[b.ind]=ans[a.ind]; } } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
5701123e0cee0319ccf6cb25ccf0d654
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.util.*; public class Practice { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int m = sc.nextInt(); int[] start = new int[n]; char[] dir = new char[n]; ArrayList<Node> even = new ArrayList<>(); ArrayList<Node> odd = new ArrayList<>(); for(int i=0;i<n;i++) start[i] = sc.nextInt(); for (int i=0;i<n;i++) { dir[i] = sc.next().charAt(0); if(start[i]%2==0) even.add(new Node(start[i], dir[i], i)); else odd.add(new Node(start[i], dir[i], i)); } Collections.sort(even); Collections.sort(odd); int[] ans = new int[n]; Arrays.fill(ans, -1); findAns(even, ans, m); findAns(odd,ans,m); for(int x: ans) System.out.print(x + " "); System.out.println(); } } private static void findAns(ArrayList<Node> val, int[] ans, int m) { Stack<Node> stack = new Stack<>(); for(Node x : val) { if(x.dir == 'R'){ stack.add(x); }else{ if(stack.empty()) stack.add(x); else{ Node right = stack.pop(); if(right.dir == 'R'){ ans[x.idx] = Math.abs(right.value - x.value)/2; ans[right.idx] = Math.abs(right.value - x.value)/2; }else{ ans[x.idx] = (right.value + x.value)/2; ans[right.idx] = (right.value + x.value)/2; } } } } while (stack.size() >=2){ Node a = stack.pop(); Node b = stack.pop(); if(b.dir == 'R'){ ans[a.idx] = (m-a.value+m-b.value)/2; ans[b.idx] = (m-a.value+m-b.value)/2; }else{ ans[a.idx] = (m-a.value+m+b.value)/2; ans[b.idx] = (m-a.value+m+b.value)/2; } } } private static class Node implements Comparable<Node>{ int value; char dir; int idx; Node(int value, char dir, int idx){ this.value = value; this.dir = dir; this.idx = idx; } @Override public int compareTo(Node o) { return this.value - o.value; } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
938f80ca89bb32d4b5328bb6ab54043e
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.util.*; // import java.lang.*; import java.io.*; // THIS TEMPLATE MADE BY AKSH BANSAL. public class Solution { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } private static boolean[] isPrime; private static void primes(){ int num = (int)1e6; // PRIMES FROM 1 TO NUM isPrime = new boolean[num]; for (int i = 2; i< isPrime.length; i++) { isPrime[i] = true; } for (int i = 2; i< Math.sqrt(num); i++) { if(isPrime[i] == true) { for(int j = (i*i); j<num; j = j+i) { isPrime[j] = false; } } } } private static long gcd(long a, long b){ if(b==0)return a; return gcd(b,a%b); } private static long pow(long x,long y){ if(y==0)return 1; long temp = pow(x, y/2); if(y%2==1){ return x*temp*temp; } else{ return temp*temp; } } // static ArrayList<Integer>[] adj; // static void getAdj(int n,int q, FastReader sc){ // adj = new ArrayList[n+1]; // for(int i=1;i<=n;i++){ // adj[i] = new ArrayList<>(); // } // for(int i=0;i<q;i++){ // int a = sc.nextInt(); // int b = sc.nextInt(); // adj[a].add(b); // adj[b].add(a); // } // } public static void main(String[] args) throws IOException { FastReader sc = new FastReader(); PrintWriter out = new PrintWriter(System.out); // primes(); // ________________________________ int t = sc.nextInt(); StringBuilder output = new StringBuilder(); while (t-- > 0) { int n = sc.nextInt(); int k = sc.nextInt(); int[][] arr = new int[n][3]; for(int i=0;i<n;i++){ arr[i][1] = sc.nextInt(); arr[i][0] = i; } String[] s = sc.nextLine().split(" "); for(int i=0;i<n;i++){ if(s[i].equals("R")){ arr[i][2] = 1; } else{ arr[i][2] = -1; } } Arrays.sort(arr, (a,b)->a[1]-b[1]); // output.append().append("\n"); solver(n,k,arr, out); } out.println(output); // _______________________________ // int n = sc.nextInt(); // out.println(solver()); // ________________________________ out.flush(); } public static void solver(int n, int k, int[][] arr, PrintWriter out) { map = new HashMap<>(); dir = new HashMap<>(); ArrayList<Integer> odd = new ArrayList<>(); ArrayList<Integer> even = new ArrayList<>(); for(int i=0;i<n;i++){ map.put(arr[i][0], arr[i][1]); dir.put(arr[i][0], arr[i][2]); if(arr[i][1]%2==0){ even.add(arr[i][0]); } else{ odd.add(arr[i][0]); } } // System.out.println("__"+ odd); // System.out.println("__"+ even); int[] res = new int[n]; Arrays.fill(res, -1); helper(odd, res, n, k); helper(even, res, n, k); for(int i=0;i<n;i++){ out.print(res[i]+" "); } out.println(); } static HashMap<Integer, Integer> map; static HashMap<Integer, Integer> dir; private static void helper(ArrayList<Integer> arr, int[] res, int n, int m){ Stack<Integer> stack = new Stack<>(); HashSet<Integer> temp = new HashSet<>(); for(int e: arr){ if(dir.get(e)==1){ stack.push(e); } else{ if(stack.isEmpty()){ continue; } else{ int cur = stack.pop(); int ans = Math.abs(map.get(cur)-map.get(e))/2; res[cur] = ans; res[e] = ans; temp.add(cur); temp.add(e); } } } ArrayList<Integer> copy = new ArrayList<>(); for(int e: arr){ if(!temp.contains(e)){ copy.add(e); } } temp.clear(); arr = copy; for(int i=0;i<arr.size()-1;i++){ if( dir.get(arr.get(i))==dir.get(arr.get(i+1)) && dir.get(arr.get(i))==-1 ){ int pos1 = map.get(arr.get(i)); int pos2 = map.get(arr.get(i+1)); int ans = Math.abs(pos1-pos2)/2; if(dir.get(arr.get(i))==-1){ ans+=Math.min(pos1, pos2); } else{ ans+=m-Math.max(pos1, pos2); } res[arr.get(i)] = ans; res[arr.get(i+1)] = ans; temp.add(arr.get(i)); temp.add(arr.get(i+1)); i++; } else{ break; } } for(int i=arr.size()-2;i>=0;i--){ if( dir.get(arr.get(i))==dir.get(arr.get(i+1)) && dir.get(arr.get(i))==1 ){ int pos1 = map.get(arr.get(i)); int pos2 = map.get(arr.get(i+1)); int ans = Math.abs(pos1-pos2)/2; if(dir.get(arr.get(i))==-1){ ans+=Math.min(pos1, pos2); } else{ ans+=m-Math.max(pos1, pos2); } res[arr.get(i)] = ans; res[arr.get(i+1)] = ans; temp.add(arr.get(i)); temp.add(arr.get(i+1)); i--; } else{ break; } } // System.out.println("__"+ arr); ArrayList<Integer> copy2 = new ArrayList<>(); for(int e: arr){ if(!temp.contains(e)){ copy2.add(e); } } arr = copy2; // System.out.println("__"+ arr); // System.out.println("__"+ copy2); // for(int e: temp){ // arr.remove(Integer.valueOf(e)); // } // System.out.println("__"+ arr); if(arr.size()==2){ int pos1 = map.get(arr.get(0)); int pos2 = map.get(arr.get(1)); int ans = (2*m-Math.abs(pos1-pos2))/2; res[arr.get(0)] = ans; res[arr.get(1)] = ans; } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
a648297d0fb2cf74ace78efc62792906
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.util.*; public class Robots { public static void main(String[] args) { Scanner in = new Scanner(System.in); StringBuffer out = new StringBuffer(); int t = in.nextInt(); while (t-- != 0) { int n = in.nextInt(), m = in.nextInt(); int x[] = new int[n]; for (int i = 0; i < n; i++) x[i] = in.nextInt(); HashMap<Integer, Character> map = new HashMap<>(); for (int i = 0; i < n; i++) map.put(x[i], in.next().charAt(0)); List<Integer> values[] = new ArrayList[2]; for (int i = 0; i < 2; i++) values[i] = new ArrayList<>(); for (int item : x) { values[item % 2].add(item); } HashMap<Integer, Integer> ans = new HashMap<>(); for (int i = 0; i < 2; i++) { Collections.sort(values[i]); // System.out.println(values[i]); LinkedList<Integer> left = new LinkedList<>(), right = new LinkedList<>(); for (int item : values[i]) { if (map.get(item) == 'L') { if (!right.isEmpty()) { int ant1 = right.pollLast(), ant2 = item; ans.put(ant1, Math.abs(ant1 - ant2) / 2); ans.put(ant2, Math.abs(ant1 - ant2) / 2); } else { left.add(item); } } else { right.add(item); } } // System.out.println(left + " " + right + " " + ans); while (left.size() >= 2) { int ant1 = left.pollFirst(), ant2 = left.pollFirst(); ans.put(ant1, ant1 + Math.abs(ant1 - ant2) / 2); ans.put(ant2, ant1 + Math.abs(ant1 - ant2) / 2); } // System.out.println(left + " " + right + " " + ans); while (right.size() >= 2) { int ant1 = right.pollLast(), ant2 = right.pollLast(); ans.put(ant1, (m - ant1) + Math.abs(ant1 - ant2) / 2); ans.put(ant2, (m - ant1) + Math.abs(ant1 - ant2) / 2); } // System.out.println(left + " " + right + " " + ans); if (left.size() == 1 && right.size() == 1) { int ant1 = left.poll(), ant2 = right.poll(); int min = Math.min(ant1, (m - ant2)); int max = Math.max(ant1, (m - ant2)); int diff = (ant2 + min) - (ant1 - min); ans.put(ant1, max + diff / 2); ans.put(ant2, max + diff / 2); } // System.out.println(left + " " + right + " " + ans); if (!left.isEmpty()) ans.put(left.poll(), -1); if (!right.isEmpty()) ans.put(right.poll(), -1); // System.out.println(left + " " + right + " " + ans); } for (int item : x) out.append(ans.get(item) + " "); out.append("\n"); } System.out.println(out); } private static int GCD(int a, int b) { if (a == 0) return b; return GCD(b % a, a); } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
f3ce271da082ed5c1e4b81cc634a9511
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
/*input 5 7 12 1 2 3 4 9 10 11 R R L L R R R 2 10 1 6 R R 2 10 1 3 L L 1 10 5 R 7 8 6 1 7 2 3 5 4 R L R L L L L */ import java.util.*; import java.lang.*; import java.io.*; public class Main { static PrintWriter out; static int MOD = 1000000007; static FastReader scan; /*-------- I/O usaing short named function ---------*/ public static String ns(){return scan.next();} public static int ni(){return scan.nextInt();} public static long nl(){return scan.nextLong();} public static double nd(){return scan.nextDouble();} public static String nln(){return scan.nextLine();} public static void p(Object o){out.print(o);} public static void ps(Object o){out.print(o + " ");} public static void pn(Object o){out.println(o);} /*-------- for output of an array ---------------------*/ static void iPA(int arr []){ StringBuilder output = new StringBuilder(); for(int i=0; i<arr.length; i++)output.append(arr[i] + " ");out.println(output); } static void lPA(long arr []){ StringBuilder output = new StringBuilder(); for(int i=0; i<arr.length; i++)output.append(arr[i] + " ");out.println(output); } static void sPA(String arr []){ StringBuilder output = new StringBuilder(); for(int i=0; i<arr.length; i++)output.append(arr[i] + " ");out.println(output); } static void dPA(double arr []){ StringBuilder output = new StringBuilder(); for(int i=0; i<arr.length; i++)output.append(arr[i] + " ");out.println(output); } /*-------------- for input in an array ---------------------*/ static void iIA(int arr[]){ for(int i=0; i<arr.length; i++)arr[i] = ni(); } static void lIA(long arr[]){ for(int i=0; i<arr.length; i++)arr[i] = nl(); } static void sIA(String arr[]){ for(int i=0; i<arr.length; i++)arr[i] = ns(); } static void dIA(double arr[]){ for(int i=0; i<arr.length; i++)arr[i] = nd(); } /*------------ for taking input faster ----------------*/ 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; } } // Method to check if x is power of 2 static boolean isPowerOfTwo (int x) { return x!=0 && ((x&(x-1)) == 0);} //Method to return lcm of two numbers static int gcd(int a, int b){return a==0?b:gcd(b % a, a); } //Method to count digit of a number static int countDigit(long n){return (int)Math.floor(Math.log10(n) + 1);} //Method for sorting static void ruffle_sort(int[] a) { //shandom_ruffle Random r=new Random(); int n=a.length; for (int i=0; i<n; i++) { int oi=r.nextInt(n); int temp=a[i]; a[i]=a[oi]; a[oi]=temp; } //sort Arrays.sort(a); } //Method for checking if a number is prime or not static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } public static void main (String[] args) throws java.lang.Exception { OutputStream outputStream =System.out; out =new PrintWriter(outputStream); scan =new FastReader(); //for fast output sometimes StringBuilder sb = new StringBuilder(); int t = ni(); while(t-->0){ int n = ni(), m = ni(); int pos[] = new int[n]; iIA(pos); char dir[] = new char[n]; for(int i=0; i<n; i++) dir[i] = ns().charAt(0); int res[] = new int[n]; Arrays.fill(res, -1); Pair p[] = new Pair[n]; for(int i=0; i<n; i++){ p[i] = new Pair(i, pos[i]); } Arrays.sort(p, new CustomSort()); Stack<Pair> odd = new Stack<>(); Stack<Pair> even = new Stack<>(); for(int i=0; i<n; i++){ if(p[i].position%2 == 0){ if(even.isEmpty()){ even.add(p[i]); } else{ if(dir[p[i].idx] == 'R'){ even.add(p[i]); } else{ if(dir[even.peek().idx] == 'R'){ Pair p1 = even.pop(), p2 = p[i]; int colTime = (p2.position - p1.position)/2; res[p1.idx] = colTime; res[p2.idx] = colTime; }else{ Pair p1 = even.pop(), p2 = p[i]; int colTime = (p2.position + p1.position)/2; res[p1.idx] = colTime; res[p2.idx] = colTime; } } } }else{ if(odd.isEmpty()){ odd.add(p[i]); } else{ if(dir[p[i].idx] == 'R'){ odd.add(p[i]); } else{ if(dir[odd.peek().idx] == 'R'){ Pair p1 = odd.pop(), p2 = p[i]; int colTime = (p2.position - p1.position)/2; res[p1.idx] = colTime; res[p2.idx] = colTime; }else{ Pair p1 = odd.pop(), p2 = p[i]; int colTime = (p2.position + p1.position)/2; res[p1.idx] = colTime; res[p2.idx] = colTime; } } } } } //Pair evenLeft = while(even.size() > 1){ Pair p1 = even.pop(); Pair p2 = even.pop(); if(dir[p1.idx] == 'R' && dir[p2.idx] == 'R'){ int colTime = (m - p2.position + m - p1.position)/2; res[p1.idx] = colTime; res[p2.idx] = colTime; } else if(dir[p1.idx] == 'L' && dir[p2.idx] == 'L'){ int colTime = (p2.position + p1.position)/2; res[p1.idx] = colTime; res[p2.idx] = colTime; } else if(dir[p1.idx] == 'R' && dir[p2.idx] == 'L'){ if(even.size()%2 == 0){ int colTime = (p2.position + m - p1.position + m)/2; res[p1.idx] = colTime; res[p2.idx] = colTime; }else{ even.push(p2); } } } while(odd.size() > 1){ Pair p1 = odd.pop(); Pair p2 = odd.pop(); if(dir[p1.idx] == 'R' && dir[p2.idx] == 'R'){ int colTime = (m - p2.position + m - p1.position)/2; res[p1.idx] = colTime; res[p2.idx] = colTime; } else if(dir[p1.idx] == 'L' && dir[p2.idx] == 'L'){ int colTime = (p2.position + p1.position)/2; res[p1.idx] = colTime; res[p2.idx] = colTime; } else if(dir[p1.idx] == 'R' && dir[p2.idx] == 'L'){ if(odd.size()%2 == 0){ int colTime = (p2.position + m - p1.position + m)/2; res[p1.idx] = colTime; res[p2.idx] = colTime; }else{ odd.push(p2); } } } iPA(res); } out.flush(); out.close(); } static class CustomSort implements Comparator<Pair>{ @Override public int compare(Pair p1, Pair p2){ return p1.position - p2.position; } } } class Pair{ int idx, position; Pair(int idx, int position){ this.idx = idx; this.position = position; } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
7e4bbc057ea73a67d67ef3f059d79e4e
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.io.PrintWriter; import java.util.*; public class C { public static void main(String[] args) { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int t = sc.nextInt(); for (int i = 0; i < t; i++) { solve(sc, pw); } pw.close(); } static void solve(Scanner in, PrintWriter out){ int n = in.nextInt(), m = in.nextInt(); int[] arr = new int[n]; String[] cs = new String[n]; for (int i = 0; i < n; i++) { arr[i] = in.nextInt(); } for (int i = 0; i < n; i++) { cs[i] = in.next(); } TreeSet<Integer> evenR = new TreeSet<>(); TreeSet<Integer> evenL = new TreeSet<>(); TreeSet<Integer> oddR = new TreeSet<>(); TreeSet<Integer> oddL = new TreeSet<>(); Map<Integer, Integer> mp = new HashMap<>(); for (int i = 0; i < n; i++) { if (arr[i] % 2 == 0){ if (cs[i].equals("L")){ evenL.add(arr[i]); }else{ evenR.add(arr[i]); } }else{ if (cs[i].equals("L")){ oddL.add(arr[i]); }else{ oddR.add(arr[i]); } } mp.put(arr[i], i); } Map<Integer, Integer> a1 = new HashMap<>(); Map<Integer, Integer> a2 = new HashMap<>(); helper(a1, evenL, evenR, m); helper(a2, oddL, oddR, m); int[] ans = new int[n]; Arrays.fill(ans, -1); for(int x : a1.keySet()){ ans[mp.get(x)] = a1.get(x); } for(int x : a2.keySet()){ ans[mp.get(x)] = a2.get(x); } for(int x : ans){ out.print(x+" "); } out.println(); } static void helper(Map<Integer, Integer> ans, TreeSet<Integer> l, TreeSet<Integer> r, int m){ LinkedList<Integer> ql = new LinkedList<>(); LinkedList<Integer> qr = new LinkedList<>(); // System.out.println(ql+" "+qr); for(int x : l){ Integer get = r.lower(x); if (get != null){ int time = (x - get) / 2; ans.put(x, time); ans.put(get, time); r.remove(get); } } // System.out.println("r"+r); while (r.size() > 1){ int v = r.last(); r.remove(v); int vv = r.last(); r.remove(vv); int time = (m - v) + (v - vv) / 2; ans.put(v, time); ans.put(vv, time); } for(int x : ans.keySet()){ if (l.contains(x)) l.remove(x); } while (l.size() > 1){ int v = l.first(); l.remove(v); int vv = l.first(); l.remove(vv); int time = v + (vv - v) / 2; ans.put(v, time); ans.put(vv, time); } if (r.size() > 0 && l.size() > 0){ int ok = l.last(); int ok2 = r.last(); int time = (2 * m - (ok2 - ok)) / 2; ans.put(ok, time); ans.put(ok2, time); } } static boolean isPrime(long n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } // method to return LCM of two numbers static long lcm(long a, long b) { return (a / gcd(a, b)) * b; } public static int[] sieveEratosthenes(int n) { if (n <= 32) { int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31}; for (int i = 0; i < primes.length; i++) { if (n < primes[i]) { return Arrays.copyOf(primes, i); } } return primes; } int u = n + 32; double lu = Math.log(u); int[] ret = new int[(int) (u / lu + u / lu / lu * 1.5)]; ret[0] = 2; int pos = 1; int[] isnp = new int[(n + 1) / 32 / 2 + 1]; int sup = (n + 1) / 32 / 2 + 1; int[] tprimes = {3, 5, 7, 11, 13, 17, 19, 23, 29, 31}; for (int tp : tprimes) { ret[pos++] = tp; int[] ptn = new int[tp]; for (int i = (tp - 3) / 2; i < tp << 5; i += tp) ptn[i >> 5] |= 1 << (i & 31); for (int j = 0; j < sup; j += tp) { for (int i = 0; i < tp && i + j < sup; i++) { isnp[j + i] |= ptn[i]; } } } // 3,5,7 // 2x+3=n int[] magic = {0, 1, 23, 2, 29, 24, 19, 3, 30, 27, 25, 11, 20, 8, 4, 13, 31, 22, 28, 18, 26, 10, 7, 12, 21, 17, 9, 6, 16, 5, 15, 14}; int h = n / 2; for (int i = 0; i < sup; i++) { for (int j = ~isnp[i]; j != 0; j &= j - 1) { int pp = i << 5 | magic[(j & -j) * 0x076be629 >>> 27]; int p = 2 * pp + 3; if (p > n) break; ret[pos++] = p; if ((long) p * p > n) continue; for (int q = (p * p - 3) / 2; q <= h; q += p) isnp[q >> 5] |= 1 << q; } } return Arrays.copyOf(ret, pos); } // reverse division for 2 public static long[] rdiv2(int n, int mod){ long[] arr = new long[n + 5]; arr[0] = 1; long rev2 = (mod + 1) / 2; for (int i = 1; i < n; i++) { arr[i] = arr[i - 1] * rev2 % mod; } return arr; } static List<Integer> primeFactors(int n) { // Print the number of 2s that divide n List<Integer> ls = new ArrayList<>(); if (n % 2 == 0) ls.add(2); while (n%2==0) { n /= 2; } // n must be odd at this point. So we can // skip one element (Note i = i +2) for (int i = 3; i <= Math.sqrt(n); i+= 2) { // While i divides n, print i and divide n if (n % i == 0) ls.add(i); while (n%i == 0) { n /= i; } } if (n > 1) ls.add(n); return ls; } static int find(int i, int[] par){ if (par[i] < 0) return i; return par[i] = find(par[i], par); } static boolean union(int i, int j, int[] par){ int pi = find(i, par); int pj = find(j, par); if (pi == pj) return false; if (par[pi] < par[pj]){ par[pi] += par[pj]; par[pj] = pi; }else{ par[pj] += par[pi]; par[pi] = pj; } return true; } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
50e03b6886407b22e777a85f3891e77b
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; // Created by @thesupremeone on 16/05/21 public class C { static class Robot implements Comparable<Robot>{ int index; int location; boolean right; public Robot(int index, int location, boolean right) { this.index = index; this.location = location; this.right = right; } @Override public int compareTo(Robot robot) { return Integer.compare(location, robot.location); } } HashMap<Integer, Integer> map = new HashMap<>(); int index(int value){ return map.get(value); } void solveForPair(TreeSet<Integer> leftSet, TreeSet<Integer> rightSet, int[] time, int m){ while (leftSet.size()>=2){ int first = leftSet.pollFirst(); int second = leftSet.pollFirst(); int t = Math.abs(first-second)/2+Math.min(first, second); time[index(first)] = t; time[index(second)] = t; } while (rightSet.size()>=2){ int first = rightSet.pollLast(); int second = rightSet.pollLast(); int t = Math.abs(first-second)/2+Math.min(m-first, m-second); time[index(first)] = t; time[index(second)] = t; } if(leftSet.size()+rightSet.size()==2){ int left = leftSet.pollFirst(); int right = rightSet.pollFirst(); int li = index(left); int ri = index(right); int t; if(left>m-right){ t = left; int p = left-(m-right); right = m-p; t += right/2; }else { t = m-right; left = m-right-left; right = m; t += (right-left)/2; } time[li] = t; time[ri] = t; } } void solve() throws IOException { int ts = getInt(); for (int test = 1; test <= ts; test++){ int n = getInt(); int m = getInt(); int[] x = new int[n]; int[] time = new int[n]; Arrays.fill(time, -1); for (int i = 0; i < n; i++){ x[i] = getInt(); map.put(x[i], i); } TreeSet<Integer> oddRightSet = new TreeSet<>(); TreeSet<Integer> evenRightSet = new TreeSet<>(); TreeSet<Integer> oddLeftSet = new TreeSet<>(); TreeSet<Integer> evenLeftSet = new TreeSet<>(); Robot[] robots = new Robot[n]; for (int i = 0; i < n; i++){ String dir = getToken(); robots[i] = new Robot(i,x[i], dir.equals("R")); } Arrays.sort(robots); for (int i = 0; i < n; i++) { Robot robot = robots[i]; int xi = robot.location; if(robot.right){ if(xi%2==0){ evenRightSet.add(xi); }else { oddRightSet.add(xi); } }else { Integer right; if(xi%2==0){ right = evenRightSet.lower(xi); }else { right = oddRightSet.lower(xi); } if(right!=null){ int t = Math.abs((right-xi)/2); time[robot.index] = t; time[index(right)] = t; evenRightSet.remove(right); oddRightSet.remove(right); }else { if(xi%2==0){ evenLeftSet.add(xi); }else { oddLeftSet.add(xi); } } } } solveForPair(oddLeftSet, oddRightSet, time, m); solveForPair(evenLeftSet, evenRightSet, time, m); for (int i = 0; i < n; i++) { print(time[i]+" "); } println(""); } } public static void main(String[] args) throws Exception { if (isOnlineJudge()) { in = new BufferedReader(new InputStreamReader(System.in)); out = new BufferedWriter(new OutputStreamWriter(System.out)); new C().solve(); out.flush(); } else { localJudge = new Thread(); in = new BufferedReader(new FileReader("input.txt")); out = new BufferedWriter(new FileWriter("output.txt")); localJudge.start(); new C().solve(); out.flush(); localJudge.suspend(); } } static boolean isOnlineJudge(){ try { return System.getProperty("ONLINE_JUDGE")!=null || System.getProperty("LOCAL")==null; }catch (Exception e){ return true; } } // Fast Input & Output static Thread localJudge = null; static BufferedReader in; static StringTokenizer st; static BufferedWriter out; static String getLine() throws IOException{ return in.readLine(); } static String getToken() throws IOException{ if(st==null || !st.hasMoreTokens()) st = new StringTokenizer(getLine()); return st.nextToken(); } static int getInt() throws IOException { return Integer.parseInt(getToken()); } static long getLong() throws IOException { return Long.parseLong(getToken()); } static void print(Object s) throws IOException{ out.write(String.valueOf(s)); } static void println(Object s) throws IOException{ out.write(String.valueOf(s)); out.newLine(); } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
e18a502fa740a07e5610537ca040fcec
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; import java.lang.*; public class JaiShreeRam{ static class pair{ int first; int second; public pair(int x,int y) { first=x; second=y; } } static Scanner in=new Scanner(); static long mod = 1000000007; static int seive[]=new int[1000001]; static int level[]=new int[200001]; static int parent[][]=new int[200001][18]; static int ans[]; static int b1,n; static ArrayList<ArrayList<Integer>> al=new ArrayList<>(); public static void main(String[] args) throws Exception{ int t=in.readInt(); while(t-->0) { n=in.readInt(); ArrayList<pair> e=new ArrayList<>(); ArrayList<pair> o=new ArrayList<>(); b1=in.readInt(); int a[]=nextIntArray(n); for(int i=0;i<n;i++) { if(a[i]%2==0) { e.add(new pair(a[i],i)); } else { o.add(new pair(a[i],i)); } } ans=new int[n]; int d[]=new int[n]; for(int i=0;i<n;i++) { char c=in.readString().charAt(0); if(c=='R') { d[i]=1; } else { d[i]=0; } } Collections.sort(e,(x,y)->(x.first-y.first)); Collections.sort(o,(x,y)->(x.first-y.first)); func(e,d); func(o,d); for(int i=0;i<n;i++) { System.out.print(ans[i]+" "); } System.out.println(); } } static void func(ArrayList<pair> al,int d[]) { Stack<pair> st=new Stack<>(); for(int i=0;i<al.size();i++) { int idx=al.get(i).second; if(d[idx]==0) { if(st.isEmpty()) { st.add(new pair(-al.get(i).first,idx)); } else { pair peek=st.pop(); int time=(al.get(i).first-peek.first)/2; ans[peek.second]=time; ans[al.get(i).second]=time; } } else { st.add(al.get(i)); } } while(st.size()>1) { pair p1=st.pop(); pair p2=st.pop(); int time=(b1+b1-p1.first-p2.first)/2; ans[p1.second]=time; ans[p2.second]=time; } if(!st.isEmpty()) { ans[st.peek().second]=-1; } return; } static void seive() { Arrays.fill(seive, 1); seive[0]=0; seive[1]=0; for(int i=2;i*i<1000001;i++) { if(seive[i]==1) { for(int j=i*i;j<1000001;j+=i) { if(seive[j]==1) { seive[j]=0; } } } } } static int[] nextIntArray(int n){ int[] arr= new int[n]; int i=0; while(i<n){ arr[i++]=in.readInt(); } return arr; } static int[] nextIntArray1(int n){ int[] arr= new int[n+1]; int i=1; while(i<=n){ arr[i++]=in.readInt(); } return arr; } static long gcd(long a, long b) { if (b==0) return a; return gcd(b, a%b); } static void ruffleSort(long[] a) { int n=a.length; Random r=new Random(); for (int i=0; i<a.length; i++) { int oi=r.nextInt(n); long temp=a[i]; a[i]=a[oi]; a[oi]=temp; } Arrays.sort(a); } static class Scanner{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String readString() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } double readDouble() { return Double.parseDouble(readString()); } int readInt() { return Integer.parseInt(readString()); } long readLong() { return Long.parseLong(readString()); } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
3091decc51a299583d06ad86db8f7435
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
//https://codeforces.com/contest/1525/problem/C //C. Robot Collisions import java.util.*; import java.io.*; public class CF_1525_C{ public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out)); StringBuilder sb = new StringBuilder(); StringTokenizer st, st1; int t = Integer.parseInt(br.readLine()); while(t-->0){ st = new StringTokenizer(br.readLine().trim()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); Triplet x[] = new Triplet[n]; st = new StringTokenizer(br.readLine()); st1 = new StringTokenizer(br.readLine()); for(int i=0;i<n;i++){ int xi = Integer.parseInt(st.nextToken()); char lri = st1.nextToken().charAt(0); x[i] = new Triplet(xi, i, lri); } Arrays.sort(x); int ans[] = new int[n]; Arrays.fill(ans, -1); for(int i=0;i<2;i++){ //even and odd places Stack<Triplet> s = new Stack<Triplet>(); for(int j=0;j<n;j++){ if(x[j].x%2==i){ if(x[j].lr=='R') s.push(x[j]); else{ if(s.size()==0){ x[j].x = -x[j].x; s.push(x[j]); } else{ Triplet y = s.pop(); int time = (x[j].x-y.x)/2; ans[x[j].pos] = time; ans[y.pos] = time; } } } } while(s.size()>1){ Triplet y = s.pop(); Triplet z = s.pop(); int time = (m-y.x)+(y.x-z.x)/2; ans[y.pos] = time; ans[z.pos] = time; } } for(int i=0;i<n;i++) sb.append(ans[i]+" "); sb.append("\n"); } pw.print(sb); pw.flush(); pw.close(); } } class Triplet implements Comparable<Triplet>{ int x, pos; char lr; Triplet(int x, int pos, char lr){ this.x = x; this.pos = pos; this.lr = lr; } public int compareTo(Triplet A){ return this.x-A.x; } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
bec23cbad233b8b04e9a6df76acf9ef6
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.BufferedReader; import java.io.InputStreamReader; 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); PrintWriter out = new PrintWriter(outputStream); solve(in, out); out.close(); } static String reverse(String s) { return (new StringBuilder(s)).reverse().toString(); } static void sieveOfEratosthenes(int n, int factors[], ArrayList<Integer> ar) { factors[1]=1; int p; for(p = 2; p*p <=n; p++) { if(factors[p] == 0) { ar.add(p); factors[p]=p; for(int i = p*p; i <= n; i += p) factors[i] = p; } } for(;p<=n;p++){ if(factors[p] == 0) { ar.add(p); } } } static void sort(int ar[]) { int n = ar.length; ArrayList<Integer> a = new ArrayList<>(); for (int i = 0; i < n; i++) a.add(ar[i]); Collections.sort(a); for (int i = 0; i < n; i++) ar[i] = a.get(i); } static void sort1(long ar[]) { int n = ar.length; ArrayList<Long> a = new ArrayList<>(); for (int i = 0; i < n; i++) a.add(ar[i]); Collections.sort(a); for (int i = 0; i < n; i++) ar[i] = a.get(i); } static long ncr(long n, long r, long mod) { if (r == 0) return 1; long val = ncr(n - 1, r - 1, mod); val = (n * val) % mod; val = (val * modInverse(r, mod)) % mod; return val; } static int findMax(int a[], int n, int vis[], int i, int d){ if(i>=n) return 0; if(vis[i]==1) return findMax(a, n, vis, i+1, d); int max = 0; for(int j=i+1;j<n;j++){ if(Math.abs(a[i]-a[j])>d||vis[j]==1) continue; vis[j] = 1; max = Math.max(max, 1 + findMax(a, n, vis, i+1, d)); vis[j] = 0; } return max; } static int dfs(int u, int par, ArrayList<Integer> removed, ArrayList<Integer> added, ArrayList<Integer> ar[]){ int num = 0; int end = u; for(int v: ar[u]){ if(v==par) continue; int endprev = dfs(v,u,removed,added,ar); if(endprev==-1) continue; num++; if(num==1){ end = endprev; } else if(num==2){ removed.add(u); removed.add(par); added.add(end); added.add(endprev); end = -1; } else{ removed.add(u); removed.add(v); added.add(v); added.add(endprev); } } return end; } public static void solve(InputReader sc, PrintWriter pw) { int i, j = 0; // int t = 1; int t = sc.nextInt(); int k = 1; u: while (t-- > 0) { int n = sc.nextInt(); int m = sc.nextInt(); int a[] = new int[n]; int dir[] = new int[n]; int o = 0, e = 0; for(i=0;i<n;i++){ a[i] = sc.nextInt(); if(a[i]%2==0) e++; else o++; } for(i=0;i<n;i++){ dir[i] = (sc.next().charAt(0)=='L'?0:1); } Pair odd[] = new Pair[o]; Pair even[] = new Pair[e]; o = 0; e = 0; for(i=0;i<n;i++){ if(a[i]%2==0){ even[e++] = new Pair(a[i],i); } else{ odd[o++] = new Pair(a[i],i); } } Arrays.sort(odd); Arrays.sort(even); int ans[] = new int[n]; Arrays.fill(ans,-1); Stack<Integer> st1 = new Stack<>(); Stack<Integer> st2 = new Stack<>(); for(i=0;i<o;i++){ j = odd[i].b; if(dir[j]==0){ if(st2.size()>0){ int val = st2.pop(); ans[odd[val].b] = ans[j] = (odd[i].a-odd[val].a)/2; continue; } st1.push(i); } else{ st2.push(i); } } int left = -1, right = -1; if(st1.size()%2==1){ left = st1.pop(); } while(st1.size()>0){ int y1 = st1.pop(); int y2 = st1.pop(); ans[odd[y1].b] = ans[odd[y2].b] = (odd[y1].a+odd[y2].a)/2; } while(st2.size()>1){ int y1 = st2.pop(); int y2 = st2.pop(); ans[odd[y1].b] = ans[odd[y2].b] = (m-odd[y1].a+m-odd[y2].a)/2; } if(st2.size()%2==1){ right = st2.pop(); } if(left>=0&&right>=0){ ans[odd[left].b] = ans[odd[right].b] = (2*m-odd[right].a+odd[left].a)/2; } st1 = new Stack<>(); st2 = new Stack<>(); for(i=0;i<e;i++){ j = even[i].b; if(dir[j]==0){ if(st2.size()>0){ int val = st2.pop(); ans[even[val].b] = ans[j] = (even[i].a-even[val].a)/2; continue; } st1.push(i); } else{ st2.push(i); } } left = -1; right = -1; if(st1.size()%2==1){ left = st1.pop(); } while(st1.size()>0){ int y1 = st1.pop(); int y2 = st1.pop(); ans[even[y1].b] = ans[even[y2].b] = (even[y1].a+even[y2].a)/2; } while(st2.size()>1){ int y1 = st2.pop(); int y2 = st2.pop(); ans[even[y1].b] = ans[even[y2].b] = (m-even[y1].a+m-even[y2].a)/2; } if(st2.size()%2==1){ right = st2.pop(); } if(left>=0&&right>=0){ ans[even[left].b] = ans[even[right].b] = (2*m-even[right].a+even[left].a)/2; } for(i=0;i<n;i++){ pw.print(ans[i]+" "); } pw.println(); } } static int findLCA(int a, int b, int par[][], int depth[]){ if(depth[a]>depth[b]){ a = a^b; b = a^b; a = a^b; } int diff = depth[b] - depth[a]; for(int i=19;i>=0;i--){ if((diff&(1<<i))>0){ b = par[b][i]; } } if(a==b) return a; for(int i=19;i>=0;i--){ if(par[b][i]!=par[a][i]){ b = par[b][i]; a = par[a][i]; } } return par[a][0]; } static void formArrayForBinaryLifting(int n, int par[][]){ for(int j=1;j<20;j++){ for(int i=0;i<n;i++){ if(par[i][j-1]==-1) continue; par[i][j] = par[par[i][j-1]][j-1]; } } } static long lcm(int a, int b){ return a*b/gcd(a,b); } static class Pair1 { long a; long b; Pair1(long a, long b) { this.a = a; this.b = b; } } static class Pair implements Comparable<Pair> { int a; int b; // int c; Pair(int a, int b) { this.a = a; this.b = b; // this.c = c; } public int compareTo(Pair p) { if(a!=p.a) return a-p.a; return b-p.b; } } // static boolean isPrime(long n) { // if (n <= 1) // return false; // if (n <= 999) // return true; // if (n % 2 == 0 || n % 999 == 0) // return false; // for (int i = 5; i * i <= n; i = i + 6) // if (n % i == 0 || n % (i + 2) == 0) // return false; // return true; // } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static long fast_pow(long base, long n, long M) { if (n == 0) return 1; if (n == 1) return base % M; long halfn = fast_pow(base, n / 2, M); if (n % 2 == 0) return (halfn * halfn) % M; else return (((halfn * halfn) % M) * base) % M; } static long modInverse(long n, long M) { return fast_pow(n, M - 2, M); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 9992768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
1e5d80bbb641f3bd4a9b8d6a8f28d778
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.util.*; import java.io.*; import static java.lang.System.currentTimeMillis; public class Sol{ static class Pair{ int dir, id , pos,life; public Pair(int id, int pos ,int dir ,int life){ this.pos = pos; this.id = id; this.dir =dir; this.life=life; } } public static void main(String []args){ InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in=new FastReader(inputStream); PrintWriter out=new PrintWriter(outputStream); //long start = currentTimeMillis(); int t=in.nextInt(); while(t-->0){ int n=in.nextInt();int m=in.nextInt(); /*--------Start---------*/ Pair p[]=new Pair[n+1];int e=0;int a[]=new int[n+1]; for(int i=1;i<=n;i++){a[i]=in.nextInt();if(a[i]%2==0)e++;}String s=in.nextLine(); int c[]=new int[n+1];for(int i=1;i<=n;i++){char b=s.charAt(2*i-2);if(b=='L'){c[i]=-1;}else c[i]=1;} p[0]=new Pair(0,0,0,0); for(int i=1;i<=n;i++){p[i]=new Pair(i,a[i],c[i],-1);} Arrays.sort(p,(o1,o2)->o1.pos-o2.pos); Pair x[]=new Pair[n-e+1]; Pair y[]=new Pair[e+1]; int i=1;int j=1;int k=1; while(k<=n){if(p[k].pos%2==0){y[j]=p[k];k++;j++;}else{x[i]=p[k];k++;i++;}} int N=n;int ci=1;j=1;int l=0; i=1;n=N-e;boolean check[]=new boolean[N+1]; while(i<n){ if(x[i].dir==1 && x[i+1].dir==-1) {l=(-x[i].pos+x[i+1].pos)/2; x[i].life=l;x[i+1].life=l; check[x[i].id]=true;check[x[i+1].id]=true; ci=i-1;i+=2; while(ci>=1&&i<=n) { if(x[i].dir==1)break; else{ if(x[ci].dir==1&&!check[x[ci].id]){ l=(-x[ci].pos+x[i].pos)/2; x[ci].life=l;x[i].life=l;check[x[ci].id]=true;check[x[i].id]=true;ci--;i++; } else {ci--;} } } } else{i++;} } i=1; while(i<n){ if(!check[x[i].id]&&x[i].dir==-1){ j=i+1; while(x[i].dir!=x[j].dir || check[x[j].id]){j++;if(j>n)break;} if(j<=n) {if(x[i].dir==-1){l=(x[i].pos+x[j].pos)/2;}else{l=m+(-x[i].pos-x[j].pos)/2;}x[i].life=l;x[j].life=l;check[x[i].id]=true;check[x[j].id]=true;i=j+1;} else{i++;} } else{i++;} } i=n; while(i>1){ if(!check[x[i].id]&&x[i].dir==1){ j=i-1; while(x[i].dir!=x[j].dir || check[x[j].id]){j--;if(j<1)break;} if(j>=1) {l=m+(-x[i].pos-x[j].pos)/2;x[i].life=l;x[j].life=l;check[x[i].id]=true;check[x[j].id]=true;i=j-1;} else{i--;} } else{i--;} } int count=0; i=1; while(i<=n){if(!check[x[i].id]){count++;}i++;} i=1; if(count>1){ while(check[x[i].id]){i++;} j=i+1;while(check[x[j].id]){j++;} check[x[i].id]=true;check[x[j].id]=true; l=(m+m-x[j].pos+x[i].pos)/2;x[i].life=l;x[j].life=l; } i=1;n=e; while(i<n){ if(y[i].dir==1 && y[i+1].dir==-1) {l=(-y[i].pos+y[i+1].pos)/2; y[i].life=l;y[i+1].life=l; check[y[i].id]=true;check[y[i+1].id]=true; ci=i-1;i+=2; while(ci>=1&&i<=n) { if(y[i].dir==1)break; else{ if(y[ci].dir==1&&!check[y[ci].id]){ l=(-y[ci].pos+y[i].pos)/2; y[ci].life=l;y[i].life=l;check[y[ci].id]=true;check[y[i].id]=true;ci--;i++; } else{ci--;} } } } else{i++;} } i=1; while(i<n){ if(!check[y[i].id]&&y[i].dir==-1){ j=i+1; while(y[i].dir!=y[j].dir || check[y[j].id]){j++;if(j>n)break;} if(j<=n) {l=(y[i].pos+y[j].pos)/2;y[i].life=l;y[j].life=l;check[y[i].id]=true;check[y[j].id]=true;i=j+1;} else{i++;} } else{i++;} } i=n; while(i>1){ if(!check[y[i].id]&&y[i].dir==1){ j=i-1; while(y[i].dir!=y[j].dir || check[y[j].id]){j--;if(j<1)break;} if(j>=1) {l=m+(-y[i].pos-y[j].pos)/2;y[i].life=l;y[j].life=l;check[y[i].id]=true;check[y[j].id]=true;i=j-1;} else{i--;} } else{i--;} } count=0; i=1; while(i<=n){if(!check[y[i].id]){count++;}i++;} i=1; if(count>1){ while(check[y[i].id])i++; j=i+1;while(true){if(check[y[j].id])j++;else break;} l=(m+m-y[j].pos+y[i].pos)/2;y[i].life=l;y[j].life=l; } i=1;k=1;j=1; while(i<=N-e){p[k]=x[i];i++;k++;} while(j<=e){p[k]=y[j];j++;k++;} Arrays.sort(p,(o1,o2)-> o1.id-o2.id); /*for(i=1;i<=N;i++)out.print(check[i]+" "); out.println(); for(i=1;i<=N;i++)out.print(p[i].dir+" "); out.println();*/ for(i=1;i<=N;i++)out.print(p[i].life+" "); /*out.println(); for(i=1;i<=N;i++)out.print(p[i].id+" "); */ out.println(); } out.close(); //System.out.println(currentTimeMillis() - start); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader(InputStream in) { br = new BufferedReader(new InputStreamReader(System.in)); } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
2f9791c87e95543ea01b9bb87dd90b15
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.io.*; import java.util.*; public class RobotCollision { 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; } } static class Output { private final PrintWriter writer; public Output(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public Output(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } public static void main(String args[]) { FastReader sc=new FastReader(); Output out=new Output(System.out); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); int m=sc.nextInt(); int a[]=new int[n]; char ch[]=new char[n]; int ans[]=new int[n]; List<Integer> odd=new ArrayList(); List<Integer> even=new ArrayList(); HashMap<Integer,Integer> map=new HashMap(); for(int i=0;i<n;i++) { a[i]=sc.nextInt(); map.put(a[i],i); if(a[i]%2==0) even.add(a[i]); else odd.add(a[i]); } Collections.sort(even); Collections.sort(odd); for(int i=0;i<n;i++) ch[i]=sc.next().charAt(0); Stack<Integer> r1=new Stack(); int f=0; for(int i=0;i<odd.size();i++) { if(ch[map.get(odd.get(i))]=='R') r1.push(odd.get(i)); else { if(r1.isEmpty()) { r1.push(odd.get(i)); f++; continue; } if(r1.size()==1 && f>0) { int x=r1.pop(); int cal=(odd.get(i)+x)/2; ans[map.get(x)]=cal; ans[map.get(odd.get(i))]=cal; f=0; continue; } int x=r1.pop(); int cal=(odd.get(i)-x)/2; ans[map.get(x)]=cal; ans[map.get(odd.get(i))]=cal; } } if(!r1.isEmpty()) { while(r1.size()>1) { int x1=r1.pop(); int x2=r1.pop(); int cal=0; if(f>0 && r1.size()==0) cal=((m-x1)+(m+x2))/2; else cal=((m-x1)+(m-x2))/2; ans[map.get(x1)]=cal; ans[map.get(x2)]=cal; } if(!r1.isEmpty()) ans[map.get(r1.pop())]=-1; } Stack<Integer> r2=new Stack(); int z=0; for(int i=0;i<even.size();i++) { if(ch[map.get(even.get(i))]=='R') r2.push(even.get(i)); else { if(r2.isEmpty()) { r2.push(even.get(i)); z++; continue; } if(r2.size()==1 && z>0) { int x=r2.pop(); int cal=(even.get(i)+x)/2; ans[map.get(x)]=cal; ans[map.get(even.get(i))]=cal; z=0; continue; } int x=r2.pop(); int cal=(even.get(i)-x)/2; ans[map.get(x)]=cal; ans[map.get(even.get(i))]=cal; } } if(!r2.isEmpty()) { while(r2.size()>1) { int x1=r2.pop(); int x2=r2.pop(); int cal=0; if(z>0 && r2.size()==0) cal=((m-x1)+(m+x2))/2; else cal=((m-x1)+(m-x2))/2; ans[map.get(x1)]=cal; ans[map.get(x2)]=cal; } if(!r2.isEmpty()) ans[map.get(r2.pop())]=-1; } for(int i=0;i<n;i++) out.print(ans[i]+" "); out.printLine(); out.flush(); } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
3d056293583e68c8a81896c16ff9034e
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import com.sun.source.tree.Tree; import java.util.*; import java.io.*; public class C { PrintWriter out; StringTokenizer st; BufferedReader br; final int imax = Integer.MAX_VALUE, imin = Integer.MIN_VALUE; final int mod = 1000000007; Map<Integer, Integer> map; long[] ans; void solve() throws Exception { int t= 1; t= ni(); for (int ii = 0; ii < t; ii++) { map= new HashMap<>(); int n= ni(), m= ni(); int[] arr= new int[n]; for (int i = 0; i < n; i++) { arr[i]= ni(); map.put(arr[i], i); } char[] dir= new char[n]; for (int i = 0; i < n; i++) dir[i]= nc(); ans= new long[n]; Arrays.fill(ans, -1l); List<Integer> list= new ArrayList<>(); List<Character> d = new ArrayList<>(); for(int i=0;i<n;i++) if(arr[i]%2== 0) { list.add(arr[i]); d.add(dir[i]); } helper(list, d, m); list= new ArrayList<>(); d= new ArrayList<>(); for(int i=0;i<n;i++) if(arr[i]%2!= 0) { list.add(arr[i]); d.add(dir[i]); } helper(list, d, m); print(ans); } } private void helper(List<Integer> arr, List<Character> dir, int m) { TreeSet<Integer> left= new TreeSet<>(); TreeSet<Integer> right= new TreeSet<>(); for (int i = 0; i < dir.size(); i++) { if(dir.get(i)== 'L') left.add(arr.get(i)); else right.add(arr.get(i)); } // -> <- right, left List<Integer> deleted = new ArrayList<>(); for(int i: left) { if(right.lower(i)!= null) { int j= right.lower(i); right.remove(j); deleted.add(i); int i1= map.get(i); int i2= map.get(j); ans[i1]= (i-j)/2; ans[i2]= ans[i1]; } } for(int i: deleted) left.remove(i); List<Integer> l = new ArrayList<>(); List<Integer> r = new ArrayList<>(); for(int i: left) l.add(i); for(int i: right) r.add(i); Collections.sort(l); Collections.sort(r, Collections.reverseOrder()); // <- <- for(int i=0;i<l.size()-1;i+=2) { int i1= map.get(l.get(i)); int i2= map.get(l.get(i+1)); ans[i1]= (l.get(i+1)- l.get(i))/2+ l.get(i);; ans[i2]= ans[i1]; } // -> -> for(int i=0;i<r.size()-1;i+=2) { int i1= map.get(r.get(i)); int i2= map.get(r.get(i+1)); ans[i1]= (r.get(i)- r.get(i+1))/2+ (m- r.get(i)); ans[i2]= ans[i1]; } // <- -> if(l.size()%2== 1 && r.size()%2== 1) { int index1 = map.get(l.get(l.size() - 1)); int index2 = map.get(r.get(r.size() - 1)); int d1 = l.get(l.size() - 1); int d2 = m - r.get(r.size() - 1); if (d1 < d2) { d1 = d1 ^ d2; d2 = d1 ^ d2; d1 = d1 ^ d2; } ans[index1] = d1 + (m - (d1 - d2)) / 2; ans[index2] = d1 + (m - (d1 - d2)) / 2; } } public static void main(String[] args) throws Exception { new C().run(); } void run() throws Exception { if (System.getProperty("ONLINE_JUDGE") == null) { File file = new File("C:\\college\\CodeForces\\inputf.txt"); br = new BufferedReader(new FileReader(file)); out = new PrintWriter("C:\\college\\CodeForces\\outputf.txt"); } else { out = new PrintWriter(System.out); br = new BufferedReader(new InputStreamReader(System.in)); } st = new StringTokenizer(""); while (true) { solve(); String s = br.readLine(); if (s == null) break; else st = new StringTokenizer(s); } out.flush(); } void read() throws Exception { st = new StringTokenizer(br.readLine()); } int ni() throws Exception { if (!st.hasMoreTokens()) read(); return Integer.parseInt(st.nextToken()); } char nc() throws Exception { if (!st.hasMoreTokens()) read(); return st.nextToken().charAt(0); } long nl() throws Exception { if (!st.hasMoreTokens()) read(); return Long.parseLong(st.nextToken()); } double nd() throws Exception { if (!st.hasMoreTokens()) read(); return Double.parseDouble(st.nextToken());} String ns() throws Exception { String s = br.readLine(); return s.length() == 0 ? br.readLine() : s; } void print(int[] arr) { for (int i : arr) out.print(i + " "); out.println();} void print(long[] arr) { for (long i : arr) out.print(i + " "); out.println();} void print(int[][] arr) { for (int[] i : arr) { for (int j : i) out.print(j + " "); out.println(); } } void print(long[][] arr) { for (long[] i : arr) { for (long j : i) out.print(j + " "); out.println(); } } long add(long a, long b) { if (a + b >= mod) return (a + b) - mod; else return a + b >= 0 ? a + b : a + b + mod; } long mul(long a, long b) { return (a * b) % mod; } void print(boolean b) { if (b) out.println("YES"); else out.println("NO"); } long binExp(long base, long power ) { long res= 1l; while(power!= 0) { if((power&1)== 1) res= mul(res, base); base= mul(base, base); power>>= 1; } return res; } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
fa3726858e6a7c9260e77619e1ad0c3d
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.util.Arrays; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.Stack; import java.util.StringTokenizer; public class C { public static class Robot { public int pos, dir; } public static void main(String[] args) { // Write code here FastScanner fs = new FastScanner(); int t = fs.nextInt(); while (t-- > 0) { int n = fs.nextInt(); int m = fs.nextInt(); int[] pos = fs.readArray(n); String[] dir = fs.readStrArray(n); Robot[] rbs = new Robot[n]; for (int i = 0; i < n; i++) { rbs[i] = new Robot(); rbs[i].dir = (dir[i].compareTo("L")==0) ? -1 : 1; rbs[i].pos = pos[i]; } Integer[] ord = new Integer[n]; for (int i = 0; i < n; i++) { ord[i] = i; } Arrays.sort(ord, (a, b) -> Integer.compare(rbs[a].pos, rbs[b].pos)); int[] cols = robotCollision(m, ord, rbs); System.out.print(cols[0]); for (int i = 1; i < n; i++) { System.out.print(" " + cols[i]); } System.out.println(); } } static int[] robotCollision(int m, Integer[] ord, Robot[] rbs) { int[] ans = new int[ord.length]; for (int i=0;i<ord.length;i++) ans[i] = -1; Stack<Integer>[] robBuf = new Stack[2]; robBuf[0] = new Stack<>(); robBuf[1] = new Stack<>(); for (int o: ord){ int op = (rbs[o].pos%2); // Left if (rbs[o].dir==-1){ if (robBuf[op].empty()){ robBuf[op].push(o); } else { int l = robBuf[op].pop(); if (rbs[l].dir==-1){ int time = (rbs[o].pos + rbs[l].pos)/2; ans[o] = time; ans[l] = time; } else { int time = (rbs[o].pos - rbs[l].pos)/2; ans[o] = time; ans[l] = time; } } } else { robBuf[op].push(o); } } for (int i=0;i<2;i++){ while (robBuf[i].size()>1){ int p = robBuf[i].pop(); int q = robBuf[i].pop(); int time = (2*m - rbs[p].pos - ((rbs[q].dir==1)?rbs[q].pos:-rbs[q].pos))/2; ans[p] = time; ans[q] = time; } } return ans; } static void sort(int[] a) { ArrayList<Integer> l = new ArrayList<>(); for (int i : a) { l.add(i); } Collections.sort(l); for (int i = 0; i < a.length; i++) { a[i] = l.get(i); } } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } String[] readStrArray(int n) { String[] a = new String[n]; for (int i = 0; i < n; i++) { a[i] = next(); } return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
e244929ee2a715a24e586cf349f1a952
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.util.*; public class C { public static void solve(List<Robot> v, int[] ans, int m) { Stack<Robot> stk = new Stack<>(); for (Robot r: v) { if (r.dir == -1) { if (stk.isEmpty()) { stk.push(r); } else { Robot r2 = stk.pop(); if (r2.dir == 1) { ans[r.id] = (r.x - r2.x) / 2; ans[r2.id] = (r.x - r2.x) / 2; } else { ans[r.id] = (r.x + r2.x) / 2; ans[r2.id] = (r.x + r2.x) / 2; } } } else { stk.push(r); } } while (stk.size() >= 2) { Robot r = stk.pop(); Robot r2 = stk.pop(); if (r2.dir == 1) { ans[r.id] = (m - r.x + m - r2.x) / 2; ans[r2.id] = (m - r.x + m - r2.x) / 2; } else { ans[r.id] = (m - r.x + m + r2.x) / 2; ans[r2.id] = (m - r.x + m + r2.x) / 2; } } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int m = sc.nextInt(); int[] pos = new int[n]; String[] dir = new String[n]; for (int i = 0; i < n; i++) pos[i] = sc.nextInt(); for (int i = 0; i < n; i++) dir[i] = sc.next(); Robot[] robots = new Robot[n]; for (int i = 0; i < n; i++) { robots[i] = new Robot(pos[i], dir[i].equals("R") ? 1 : -1, i); } Arrays.sort(robots, (a, b) -> a.x - b.x); List<Robot> e = new ArrayList<>(); List<Robot> o = new ArrayList<>(); for (Robot r: robots) { if (r.x % 2 == 0) { e.add(r); } else { o.add(r); } } int[] ans = new int[n]; for (int i = 0; i < n; i++) { ans[i] = -1; } solve(e, ans, m); solve(o, ans, m); for (int i = 0; i < n; i++) System.out.print(ans[i] + " "); System.out.println(""); } } } class Robot { int x, dir, id; Robot(int x, int dir, int id) { this.x = x; this.dir = dir; this.id = id; } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
5fe189d0866998e703aa1104cf992397
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.util.*; public class Robots { public static void main(String[] args) { Scanner in = new Scanner(System.in); StringBuffer out = new StringBuffer(); int t = in.nextInt(); while (t-- != 0) { int n = in.nextInt(), m = in.nextInt(); int x[] = new int[n]; for (int i = 0; i < n; i++) x[i] = in.nextInt(); HashMap<Integer, Character> map = new HashMap<>(); for (int i = 0; i < n; i++) map.put(x[i], in.next().charAt(0)); List<Integer> values[] = new ArrayList[2]; for (int i = 0; i < 2; i++) values[i] = new ArrayList<>(); for (int item : x) { values[item % 2].add(item); } HashMap<Integer, Integer> ans = new HashMap<>(); for (int i = 0; i < 2; i++) { Collections.sort(values[i]); // System.out.println(values[i]); LinkedList<Integer> left = new LinkedList<>(), right = new LinkedList<>(); for (int item : values[i]) { if (map.get(item) == 'L') { if (!right.isEmpty()) { int ant1 = right.pollLast(), ant2 = item; ans.put(ant1, Math.abs(ant1 - ant2) / 2); ans.put(ant2, Math.abs(ant1 - ant2) / 2); } else { left.add(item); } } else { right.add(item); } } // System.out.println(left + " " + right + " " + ans); while (left.size() >= 2) { int ant1 = left.pollFirst(), ant2 = left.pollFirst(); ans.put(ant1, ant1 + Math.abs(ant1 - ant2) / 2); ans.put(ant2, ant1 + Math.abs(ant1 - ant2) / 2); } // System.out.println(left + " " + right + " " + ans); while (right.size() >= 2) { int ant1 = right.pollLast(), ant2 = right.pollLast(); ans.put(ant1, (m - ant1) + Math.abs(ant1 - ant2) / 2); ans.put(ant2, (m - ant1) + Math.abs(ant1 - ant2) / 2); } // System.out.println(left + " " + right + " " + ans); if (left.size() == 1 && right.size() == 1) { int ant1 = left.poll(), ant2 = right.poll(); int min = Math.min(ant1, (m - ant2)); int max = Math.max(ant1, (m - ant2)); int diff = (ant2 + min) - (ant1 - min); ans.put(ant1, max + diff / 2); ans.put(ant2, max + diff / 2); } // System.out.println(left + " " + right + " " + ans); if (!left.isEmpty()) ans.put(left.poll(), -1); if (!right.isEmpty()) ans.put(right.poll(), -1); // System.out.println(left + " " + right + " " + ans); } for (int item : x) out.append(ans.get(item) + " "); out.append("\n"); } System.out.println(out); } private static int GCD(int a, int b) { if (a == 0) return b; return GCD(b % a, a); } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
362661d9d80d3b30667163c78eb16cd7
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
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.InputMismatchException; import java.io.IOException; import java.util.Stack; import java.util.ArrayList; import java.util.Vector; import java.util.Comparator; import java.util.Collections; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author dauom */ 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); CRobotCollisions solver = new CRobotCollisions(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class CRobotCollisions { private static int L = 0; private static int R = 1; public final void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); int[] x = in.nextIntArray(n); String[] dir = in.nextStringArray(n); int countOdd = 0, countEven = 0; int[][] odds = new int[n][]; int[][] evens = new int[n][]; for (int i = 0; i < n; i++) { int pos = x[i]; int d = dir[i].charAt(0) == 'R' ? R : L; if (pos % 2 == 1) { odds[countOdd++] = new int[]{pos, i + 1, d}; } else { evens[countEven++] = new int[]{pos, i + 1, d}; } } odds = Arrays.copyOf(odds, countOdd); evens = Arrays.copyOf(evens, countEven); int[] ansOdd = solve(n, m, odds); int[] ansEven = solve(n, m, evens); for (int i = 1; i <= n; i++) { out.print(Integer.max(ansOdd[i], ansEven[i]) + " "); } out.println(); } private int[] solve(final int n, final int m, final int[][] robots) { int[] ans = new int[n + 1]; Arrays.fill(ans, -1); Stack<int[]> cur = new Stack<>(); Arrays.sort(robots, Comparators.singletonIntArr); for (int[] r : robots) { if (cur.empty()) { cur.push(r); } else { int pos = r[0], idx = r[1], dir = r[2]; int opos = cur.peek()[0], oidx = cur.peek()[1], odir = cur.peek()[2]; if (dir == L && odir == R) { ans[idx] = ans[oidx] = (pos - opos) / 2; cur.pop(); } else { cur.push(r); } } } ArrayList<int[]> unused = new ArrayList<>(); // Treat only the right going ones while (cur.size() >= 2) { int[] r1 = cur.pop(); int pos = r1[0], idx = r1[1], dir = r1[2]; int[] r2 = cur.pop(); int opos = r2[0], oidx = r2[1], odir = r2[2]; if (dir == L || odir == L) { if (odir == L) cur.push(r2); else unused.add(r2); if (dir == L) cur.push(r1); else unused.add(r1); break; } int time = m - pos + (m - (opos + m - pos)) / 2; ans[idx] = ans[oidx] = time; } ArrayList<int[]> leftList = new ArrayList<>(cur); Collections.reverse(leftList); cur.clear(); cur.addAll(leftList); // Treat only the left going ones while (cur.size() >= 2) { int[] r1 = cur.pop(); int pos = r1[0], idx = r1[1]; int[] r2 = cur.pop(); int opos = r2[0], oidx = r2[1]; int time = pos + (opos - pos) / 2; ans[idx] = ans[oidx] = time; } unused.addAll(cur); if (unused.size() == 2) { int[] right = unused.get(0); int[] left = unused.get(1); int time = Integer.min(m - right[0], left[0]); right[0] += time; left[0] -= time; if (right[0] != m) { time += m - right[0]; left[0] = m - right[0]; right[0] = m; } else { time += left[0]; right[0] -= left[0]; left[0] = 0; } time += (right[0] - left[0]) / 2; ans[right[1]] = ans[left[1]] = time; } return ans; } } static final class InputReader { private final InputStream stream; private final byte[] buf = new byte[1 << 18]; private int curChar; private int numChars; public InputReader() { this.stream = System.in; } public InputReader(final InputStream stream) { this.stream = stream; } private int read() { if (this.numChars == -1) { throw new UnknownError(); } else { if (this.curChar >= this.numChars) { this.curChar = 0; try { this.numChars = this.stream.read(this.buf); } catch (IOException ex) { throw new InputMismatchException(); } if (this.numChars <= 0) { return -1; } } return this.buf[this.curChar++]; } } public final int nextInt() { int c; for (c = this.read(); isSpaceChar(c); c = this.read()) { } byte sgn = 1; if (c == 45) { // 45 == '-' sgn = -1; c = this.read(); } int res = 0; while (c >= 48 && c <= 57) { // 48 == '0', 57 == '9' res *= 10; res += c - 48; // 48 == '0' c = this.read(); if (isSpaceChar(c)) { return res * sgn; } } throw new InputMismatchException(); } public final String next() { int c; while (isSpaceChar(c = this.read())) { } StringBuilder result = new StringBuilder(); result.appendCodePoint(c); while (!isSpaceChar(c = this.read())) { result.appendCodePoint(c); } return result.toString(); } private static boolean isSpaceChar(final int c) { return c == 32 || c == 10 || c == 13 || c == 9 || c == -1; // 32 == ' ', 10 == '\n', 13 == '\r', 9 == '\t' } public final int[] nextIntArray(final int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public final String[] nextStringArray(final int n) { String[] arr = new String[n]; for (int i = 0; i < n; i++) { arr[i] = next(); } return arr; } } static final class Comparators { public static final Comparator<int[]> singletonIntArr = (x, y) -> compare(x[0], y[0]); private static final int compare(final int x, final int y) { return x < y ? -1 : (x == y ? 0 : 1); } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
660ee8147dd9d9a705985c541ee17975
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.io.*; import java.util.*; public class Solution { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } String nextLine() throws IOException { return br.readLine(); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } float nextFloat() { return Float.parseFloat(nextToken()); } } static FastReader f = new FastReader(); static StringBuilder sb = new StringBuilder(); static long[] fact; static int[] inputArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) { // a[i] = (int) (Math.random()*1e5 + 1); a[i] = f.nextInt(); } return a; } static void print2DArray(int[][] a) { int n = a.length, m = a[0].length; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { System.out.print(a[i][j] + " "); } System.out.println(); } } static void print2DArray(long[][] a) { int n = a.length, m = a[0].length; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { System.out.print(a[i][j] + " "); } System.out.println(); } } static long[] inputLongArray(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = f.nextLong(); // a[i] = (long) (Math.random() * 1e9 + 1); } return a; } static long gcd(long a, long b) { if (a == 0 || b == 0) { return Math.max(a, b); } //System.out.println("a - " + a + " b - " + b); if (a % b == 0) { return b; } return gcd(b, a % b); } static void initializeFact() { fact = new long[MAX_N]; for (int i = 0; i < fact.length; i++) { if (i == 0) { fact[i] = 1; } else { fact[i] = fact[i - 1] * i % mod; } } } static long longModulus(long x, long m) { if (x < m) { return x; } long d = x / m; return x - d * m; } static BitSet sieveOfEratosthenes(int n) { BitSet isPrime = new BitSet(n + 1); isPrime.set(0, n + 1); isPrime.set(0); isPrime.set(1); for (int i = 2; i * i <= n; i++) { if (isPrime.get(i)) for (int j = i * i; j <= n; j += i) isPrime.clear(j); } return isPrime; } static long moduloInversePrime(long a) { //System.out.println("modulo inverse of " + a + " -> " + ans); return modPow(a, mod - 2); } static long mult(long a, long b) { return (a * b % mod); } static long modPow(long a, int step) { long ans = 1; while (step != 0) { if ((step & 1) != 0) ans = mult(ans, a); a = mult(a, a); step >>= 1; } return ans; } static int query(int t, int i, int j, int x) { System.out.println("? " + t + " " + i + " " + j + " " + x); System.out.flush(); return f.nextInt(); } private static boolean isBipartite(ArrayList<ArrayList<Integer>> adj, int s, boolean[] visited, int[] color, int c, int parent) { visited[s] = true; color[s] = c; for(int x: adj.get(s)) { if(x == parent) continue; if(color[x] == c) { return false; } if(!visited[x]) { if(!isBipartite(adj, x, visited, color, 1-c, s)) { return false; } } } return true; } static class Pair implements Comparator<Pair>{ int x; char dir; int ind; public Pair() { } public Pair(int x, char dir, int ind) { this.x = x; this.dir = dir; this.ind = ind; } @Override public String toString() { return "Pair{" + "x=" + x + ", dir=" + dir + ", ind=" + ind + '}'; } @Override public int compare(Pair o1, Pair o2) { return o1.x - o2.x; } } static long explosionTime(Pair p1, Pair p2, int m) { if(p1.dir == p2.dir) { if(p1.dir == 'L') { return p1.x + (p2.x - p1.x)/2; } else { return (m-p2.x) + (p2.x - p1.x)/2; } } else { if(p1.dir == 'L') { if(p1.x < (m-p2.x)) { int dif = (m-p2.x) - p1.x; return (m-p2.x) + (m-(dif))/2; } else { int dif = p1.x - (m-p2.x); return p1.x + (m-(dif))/2; } } else { return (p2.x - p1.x)/2; } } } private static int mod = (int) (1e9 + 7); static int MAX_N = (int) Math.sqrt(1e9); public static void main(String[] args) throws IOException { int test = f.nextInt(); for (int t = 1 ; t <= test ; t++) { int n = f.nextInt(), m = f.nextInt(); int x[] = inputArray(n); char s[] = new char[n]; for(int i = 0 ; i < n ; i++) { s[i] = f.nextToken().charAt(0); } ArrayList<Pair> even = new ArrayList<>(); ArrayList<Pair> odd = new ArrayList<>(); for(int i = 0 ; i < n ; i++) { if(x[i] % 2 == 0) { even.add(new Pair(x[i], s[i], i)); } else { odd.add(new Pair(x[i], s[i], i)); } } long[] res = new long[n]; Arrays.fill(res, -1); even.sort(new Pair()); odd.sort(new Pair()); solve(even, m, res); solve(odd, m, res); for(long i : res) { sb.append(i).append(" "); } sb.append("\n"); } System.out.println(sb); } private static void solve(ArrayList<Pair> list, int m, long[] res) { Stack<Pair> stack = new Stack<>(); ArrayList<Pair> second_list = new ArrayList<>(); for(Pair p : list) { if(p.dir == 'L') { if(!stack.isEmpty()) { Pair temp = stack.pop(); long t = explosionTime(temp, p, m); res[p.ind] = t; res[temp.ind] = t; } else { second_list.add(p); } } else { stack.push(p); } } int left_cnt = second_list.size(); while(!stack.isEmpty()) { second_list.add(stack.pop()); } int left_done = 0, right_done = 0; for(int i = 0 ; i < left_cnt ; i++) { if(i + 1 < left_cnt) { long t = explosionTime(second_list.get(i), second_list.get(i+1), m); res[second_list.get(i).ind] = t; res[second_list.get(i+1).ind] = t; i++; left_done += 2; } } for(int i = left_cnt ; i < second_list.size() ; i++) { if(i + 1 < second_list.size()) { long t = explosionTime(second_list.get(i+1), second_list.get(i), m); res[second_list.get(i+1).ind] = t; res[second_list.get(i).ind] = t; i++; right_done += 2; } } if(left_cnt - left_done > 0 && (second_list.size() - left_cnt) - right_done > 0) { long t = explosionTime(second_list.get(left_cnt-1), second_list.get(second_list.size()-1), m); res[second_list.get(left_cnt-1).ind] = t; res[second_list.get(second_list.size()-1).ind] = t; } } } /* 1 10 15 1 3 4 5 6 7 11 12 14 9 R L R R L L L L R R */
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
449207cd65c00c62c98302bddc88909e
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.math.BigInteger; import java.util.*; import java.io.*; public class Div716 { static int n, m; static int[] a; static int comp(int x, int y) { return a[x] - a[y]; } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int t = sc.nextInt(); while (t-- > 0) { n = sc.nextInt(); m = sc.nextInt(); a = sc.nextIntArr(n); TreeSet<Integer>[] left = new TreeSet[2], right = new TreeSet[2]; for (int j = 0; j < 2; j++) { left[j] = new TreeSet<>((x, y) -> comp(x, y)); right[j] = new TreeSet<>((x, y) -> comp(x, y)); } for (int i = 0; i < n; i++) { if (sc.next().equals("L")) { left[a[i] % 2].add(i); } else { right[a[i] % 2].add(i); } } int[] ans = new int[n]; Arrays.fill(ans, -1); for (int j = 0; j < 2; j++) { TreeSet<Integer> rlef = new TreeSet<>((x, y) -> comp(x, y)); while (!left[j].isEmpty()) { int u = left[j].pollFirst(); Integer v = right[j].floor(u); if (v == null) { rlef.add(u); continue; } right[j].remove(v); ans[u] = ans[v] = Math.abs(a[u] - a[v]) / 2; } left[j] = rlef; while (left[j].size() > 1) { int u = left[j].pollFirst(); int v = left[j].pollFirst(); ans[u] = ans[v] = a[u] + Math.abs(a[u] - a[v]) / 2; } while (right[j].size() > 1) { int u = right[j].pollLast(); int v = right[j].pollLast(); ans[u] = ans[v] = (m - a[u]) + Math.abs(a[u] - a[v]) / 2; } if (left[j].size() == 1 && right[j].size() == 1) { int u = left[j].pollFirst(); int v = right[j].pollFirst(); int va = a[u]; int vb = m - a[v]; ans[u] = ans[v] = va + vb + (Math.abs(a[u] - a[v]) / 2); } } for (int x : ans) pw.print(x + " "); pw.println(); } pw.flush(); } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(FileReader r) { br = new BufferedReader(r); } public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int[] nextIntArr(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
97598d1a37801a2b0962af15ee6f6010
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.io.*; import java.util.*; public class CCC { public static void main(String[] args) throws IOException { int T = readInt(); final Comparator<int[]> comparator = (a, b) -> a[POS] - b[POS]; while (T-- > 0) { int n = readInt(); int m = readInt(); int[][] x = new int[n][3]; for (int i = 0; i < n; i++) { x[i][POS] = readInt(); x[i][INDEX] = i; } for (int i = 0; i < n; i++) { x[i][DIR] = readToken().charAt(0); } Arrays.sort(x, comparator); ArrayList<int[]> evens = new ArrayList<>(); ArrayList<int[]> odds = new ArrayList<>(); for (int[] robot : x) { (robot[POS] % 2 == 0 ? evens : odds).add(robot); } int[] answer = new int[n]; Arrays.fill(answer, -1); process(m, evens, answer); process(m, odds, answer); for (int i = 0; i < n; i++) { pw.print(answer[i] + " "); } pw.println(); } pw.close(); } static final int LEFT = 'L', RIGHT = 'R'; static final int POS = 0, DIR = 1, INDEX = 2; private static void process(int m, ArrayList<int[]> evens, int[] answer) { Deque<int[]> st = new ArrayDeque<>(); for (int[] robot : evens) { if (st.isEmpty() || st.peekLast()[DIR] == LEFT || robot[DIR] == RIGHT) { st.addLast(robot); } else { int[] rL = st.pollLast(); int time = (robot[POS] - rL[POS]) / 2; answer[rL[INDEX]] = time; answer[robot[INDEX]] = time; } } int[] lastRight = null; while (!st.isEmpty()) { if (st.peekLast()[DIR] == LEFT) { break; } else { int[] top = st.pollLast(); if (lastRight == null) { lastRight = top; } else { int time = m - lastRight[POS] + (lastRight[POS] - top[POS]) / 2; answer[lastRight[INDEX]] = time; answer[top[INDEX]] = time; lastRight = null; } } } int[] lastLeft = null; while (!st.isEmpty()) { int[] top = st.pollFirst(); if (lastLeft == null) { lastLeft = top; } else { int time = lastLeft[POS] + (top[POS] - lastLeft[POS]) / 2; answer[lastLeft[INDEX]] = time; answer[top[INDEX]] = time; lastLeft = null; } } if (lastLeft != null && lastRight != null) { int time = m - (lastRight[POS] - lastLeft[POS]) / 2; answer[lastLeft[INDEX]] = time; answer[lastRight[INDEX]] = time; } } // @formatter:off static final BufferedReader br=new BufferedReader(new InputStreamReader(System.in));static final PrintWriter pw=new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));static StringTokenizer st;static final String READ_ERROR="Error Reading.";static String readToken(){try{while(st==null||!st.hasMoreTokens())st=new StringTokenizer(br.readLine());return st.nextToken();}catch(IOException e){throw new RuntimeException(READ_ERROR);}}static int readInt(){return Integer.parseInt(readToken());}static int[]readIntArray(final int n){int[]a=new int[n];for(int i=0;i<n;i++)a[i]=readInt();return a;}static String[]readStringArray(final int n){String[]a=new String[n];for(int i=0;i<n;i++)a[i]=readToken();return a;}static long readLong(){return Long.parseLong(readToken());}static double readDouble(){return Double.parseDouble(readToken());}static char[]readLineAsCharArray(){try{return br.readLine().toCharArray();}catch(IOException e){throw new RuntimeException(READ_ERROR);}}static String readLine(){try{return br.readLine();}catch(IOException e){throw new RuntimeException(READ_ERROR);}} }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
56e2376f3b8390c71eade159ae2da4e7
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.nio.file.Paths; import java.util.*; public class Main extends PrintWriter { static BufferedReader s = new BufferedReader(new InputStreamReader(System.in));Main () { super(System.out); }public static void main(String[] args) throws IOException{ Main d1=new Main ();d1.main();d1.flush(); } void main() throws IOException { StringBuilder sb = new StringBuilder(); StringBuilder sb1 = new StringBuilder(); int t = 1; t = i(s()[0]); while (t-- > 0) { String[] s1 = s(); int n = i (s1[0]); int m = i(s1[1]); int[] a=new int[n]; arri(a, n); char[] c = new char[n]; String[] s3 = s(); Pair[] p = new Pair[n]; for(int i=0;i<n;i++){ c[i] = s3[i].toCharArray()[0]; p[i] = new Pair(a[i], c[i], i); }Arrays.sort(p, new Comparator<Pair>() { @Override public int compare(Pair o1, Pair o2) { return o1.ind - o2.ind; } }); Stack<Integer> evenl = new Stack<>(); Deque<Integer> evenr = new LinkedList<>(); Stack<Integer> oddl = new Stack<>(); Deque<Integer> oddr = new LinkedList<>(); long[] ans = new long[n]; Arrays.fill(ans, -1); for(int i = n - 1; i >= 0; i--){ if(p[i].ind % 2 == 0){ if(p[i].c == 'R'){ if(!evenl.isEmpty()){ int ind = evenl.pop(); ans[p[i].iind] = (p[ind].ind - p[i].ind) / 2; ans[p[ind].iind] = ans[p[i].iind]; }else if(evenr.isEmpty() == false){ int ind = evenr.pollLast(); ans[p[i].iind] = (p[ind].ind - p[i].ind) / 2 + m - p[ind].ind; ans[p[ind].iind] = ans[p[i].iind]; }else evenr.addFirst(i); }else{ evenl.add(i); } }else{ if(p[i].c == 'R'){ if(!oddl.isEmpty()){ int ind = oddl.pop(); ans[p[i].iind] = (p[ind].ind - p[i].ind) / 2; ans[p[ind].iind] = ans[p[i].iind]; }else if(oddr.isEmpty() == false){ int ind = oddr.pollLast(); ans[p[i].iind] = (p[ind].ind - p[i].ind) / 2 + m - p[ind].ind; ans[p[ind].iind] = ans[p[i].iind]; }else oddr.addFirst(i); }else{ oddl.add(i); } } } while(!evenl.isEmpty()){ int ind1 = evenl.pop(); if(evenl.isEmpty() == false){ int ind2 = evenl.pop(); ans[p[ind1].iind] = (p[ind2].ind - p[ind1].ind) / 2 + p[ind1].ind; ans[p[ind2].iind] = ans[p[ind1].iind]; }else {evenl.push(ind1);break;} } while(!oddl.isEmpty()){ int ind1 = oddl.pop(); if(oddl.isEmpty() == false){ int ind2 = oddl.pop(); ans[p[ind1].iind] = (p[ind2].ind - p[ind1].ind) / 2 + p[ind1].ind; ans[p[ind2].iind] = ans[p[ind1].iind]; }else {oddl.push(ind1);break;} } if(oddl.isEmpty() == false && oddr.isEmpty() == false){ int ind1 = oddl.pop(); int ind2 = oddr.pollLast(); ans[p[ind1].iind] = (p[ind2].ind - p[ind1].ind) / 2 + p[ind1].ind + m - p[ind2].ind; ans[p[ind2].iind] = ans[p[ind1].iind]; }if(evenl.isEmpty() == false && evenr.isEmpty() == false){ int ind1 = evenl.pop(); int ind2 = evenr.pollLast(); ans[p[ind1].iind] = (p[ind2].ind - p[ind1].ind) / 2 + p[ind1].ind + m - p[ind2].ind; ans[p[ind2].iind] = ans[p[ind1].iind]; } for(int i=0;i<n;i++){ sb.append(ans[i] + " "); }sb.append("\n"); } System.out.println(sb); } static int maxdis; public static void dfs(int i,ArrayList<Integer>[] adj,HashMap<Integer, Integer> vis, int d, HashMap<Integer, Integer> h, int[] dis){ vis.put(i, 0); dis[i] = d; if(h.containsKey(i)) {maxdis = Math.max(maxdis, d);} if(adj[i]==null) return; for(Integer j:adj[i]){ if(!vis.containsKey(j)){ dfs(j,adj,vis, d + 1, h, dis); } } } static String[] s() throws IOException { return s.readLine().trim().split("\\s+"); } static int i(String ss) {return Integer.parseInt(ss); } static long l(String ss) {return Long.parseLong(ss); } public void arr(long[] a,int n) throws IOException {String[] s2=s();for(int i=0;i<n;i++){ a[i]=l(s2[i]); }} public void arri(int[] a,int n) throws IOException {String[] s2=s();for(int i=0;i<n;i++){ a[i]=i(s2[i]); }} }class Pair{ int ind;char c;int iind; public Pair(int i, char cc, int ii){ ind = i; c = cc;iind = ii; } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
2ae53f5fd9b8cd22ead03f161c6f1bdc
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.io.*; import java.util.*; public class C { public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); public static void main(String[] args) throws IOException { readInput(); out.close(); } static class Info implements Comparable<Info>{ int ind; int x; char c; public Info(int a, int b, char d) { ind=a; x=b; c=d; } public int compareTo(Info o) {return x - o.x;} } public static void readInput() throws IOException { // br = new BufferedReader(new FileReader(".in")); // out = new PrintWriter(new FileWriter(".out")); int t= Integer.parseInt(br.readLine()); while(t-->0) { //System.out.println("Test case shitty "); StringTokenizer st = new StringTokenizer(br.readLine()); int n =Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); char[] c = new char[n]; int[] a= new int[n]; 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 < n; i++) { c[i] = st.nextToken().charAt(0); } Info[] info = new Info[n]; for (int i = 0; i < n; i++) info[i] = new Info(i,a[i],c[i]); Arrays.sort(info); for (int i = 0; i < n; i++) { a[i] = info[i].x; c[i] = info[i].c; } int[] ans = new int[n]; Arrays.fill(ans, -1); Deque<Integer> collideRL = new ArrayDeque<Integer>(); Deque<Integer> collideLL = new ArrayDeque<Integer>(); for (int mod = 0; mod < 2; mod++) { collideRL.clear(); collideLL.clear(); for (int i = 0; i < n; i++) { if (a[i] % 2 == mod) { if (c[i] == 'R') collideRL.addLast(i); else if (c[i] == 'L' && collideRL.size() > 0) { int x = collideRL.pollLast(); int mid = Math.abs(a[i] - a[x])/2; ans[info[x].ind] = ans[info[i].ind] = mid; } else collideLL.addLast(i); } } // Collide RL becomes collideRR while (collideLL.size() >= 2) { int a2 = collideLL.pollFirst(); int a1 = collideLL.pollFirst(); int anss = Math.min(a[a1],a[a2])+Math.abs(a[a2]-a[a1])/2; ans[info[a1].ind]=ans[info[a2].ind]=anss; } while (collideRL.size() >= 2) { int a2 = collideRL.pollLast(); int a1 = collideRL.pollLast(); int anss = m - Math.max(a[a1],a[a2])+Math.abs(a[a2]-a[a1])/2; ans[info[a1].ind]=ans[info[a2].ind]= anss; } if (collideLL.size() == 1 && collideRL.size() == 1) { int a1 = collideLL.pollFirst(); int a2 = collideRL.pollFirst(); //System.out.println(info[a1].ind + " " + info[a2].ind); int flip = -Math.min(a[a1],a[a2]); int flip2 = m+(m-Math.max(a[a2],a[a1])); int avg = (flip2-flip)/2; ans[info[a1].ind]=ans[info[a2].ind]=avg; } } for (int x: ans) out.print(x + " "); out.println(); } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
850d5f8b5d7358a619cdf15756c16280
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.util.*; import java.io.*; public class C { static FastIO f; public static void main(String args[]) throws IOException { f = new FastIO(); int t, n, m, x[], ans[], i; char d[]; Stack<Robot> o, e; Robot r[], p, c; t = f.ni(); while(t-->0) { n = f.ni(); m = f.ni(); o = new Stack<>(); e = new Stack<>(); x = f.nia(n); d = f.nca(n); r = new Robot[n]; ans = new int[n]; Arrays.fill(ans, -1); for(i = 0; i < n; i++) r[i] = new Robot(d[i], x[i], i); Arrays.sort(r, new Comparator<Robot>(){ @Override public int compare(Robot a, Robot b) { return a.x - b.x; } }); f.err(Arrays.toString(r) + "\n"); for(i = 0; i < n; i++) { if(r[i].x%2 == 1) { p = o.isEmpty() ? null : o.peek(); c = r[i]; if(p == null || p.d == 'L' || c.d == 'R') o.push(c); else { o.pop(); ans[p.i] = ans[c.i] = calculate(p, c); } } else { p = e.isEmpty() ? null : e.peek(); c = r[i]; if(p == null || p.d == 'L' || c.d == 'R') e.push(c); else { e.pop(); ans[p.i] = ans[c.i] = calculate(p, c); } } } f.err(o + "\n" + e + "\n\n"); finish(o, ans, m); finish(e, ans, m); for(i = 0; i < n; i++) f.out(ans[i] + " "); f.out("\n"); } f.flush(); } public static void finish(Stack<Robot> s, int[] ans, int m) { Robot a, b, d; while(s.size() > 1) { a = s.pop(); b = s.pop(); if(a.d == b.d) { if(a.d == 'R') { d = new Robot('L', m + (m - a.x), a.i); ans[a.i] = ans[b.i] = calculate(b, d); } else { if(s.size()%2 == 0) { d = new Robot('R', 0 - b.x, b.i); ans[a.i] = ans[b.i] = calculate(d, a); } else { s.push(b); } } } else { if(s.size()%2 == 0) { a = new Robot('L', m + (m - a.x), a.i); b = new Robot('R', 0 - b.x, b.i); ans[a.i] = ans[b.i] = calculate(b, a); } else { s.push(b); } } } } public static int calculate(Robot a, Robot b) { return (b.x - a.x)/2; } static class Robot { char d; int x, i; Robot(char a, int b, int c) { d = a; x = b; i = c; } @Override public int hashCode() { return x; } @Override public boolean equals(Object obj) { Robot that = (Robot)obj; return x == that.x; } @Override public String toString() { return "[" + x + ", " + d + "]"; } } public static class FastIO { BufferedReader br; BufferedWriter bw, be; StringTokenizer st; public FastIO() { br = new BufferedReader(new InputStreamReader(System.in)); bw = new BufferedWriter(new OutputStreamWriter(System.out)); be = new BufferedWriter(new OutputStreamWriter(System.err)); st = new StringTokenizer(""); } private void read() throws IOException { st = new StringTokenizer(br.readLine()); } public String ns() throws IOException { while(!st.hasMoreTokens()) read(); return st.nextToken(); } public int ni() throws IOException { return Integer.parseInt(ns()); } public long nl() throws IOException { return Long.parseLong(ns()); } public float nf() throws IOException { return Float.parseFloat(ns()); } public double nd() throws IOException { return Double.parseDouble(ns()); } public char nc() throws IOException { return ns().charAt(0); } public int[] nia(int n) throws IOException { int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = ni(); return a; } public long[] nla(int n) throws IOException { long[] a = new long[n]; for(int i = 0; i < n; i++) a[i] = nl(); return a; } public char[] nca(int n) throws IOException { char[] a = new char[n]; for(int i = 0; i < n; i++) a[i] = nc(); return a; } public void out(String s) throws IOException { bw.write(s); } public void flush() throws IOException { bw.flush(); be.flush(); } public void err(String s) throws IOException { be.write(s); } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
f4fb345c5fec085b6ce0dcd0d137e576
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.io.*; import java.util.*; public class gotoJapan { public static void main(String[] args) throws java.lang.Exception { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Solution solver = new Solution(); boolean isTest = true; int tC = isTest ? Integer.parseInt(in.next()) : 1; for (int i = 1; i <= tC; i++) solver.solve(in, out, i); out.close(); } /* ............................................................. */ static class Solution { InputReader in; PrintWriter out; public void solve(InputReader in, PrintWriter out, int test) { this.in = in; this.out = out; int n=ni(); int m=ni(); ArrayList<Pair> ev=new ArrayList<>(); ArrayList<Pair> od=new ArrayList<>(); int a[]=new int[n]; char b[]=new char[n]; for(int i=0;i<n;i++) { a[i]=ni(); } for(int i=0;i<n;i++) { b[i]=n().charAt(0); } for(int i=0;i<n;i++) { if(a[i]%2==0) { ev.add(new Pair(a[i], b[i],i)); } else { od.add(new Pair(a[i], b[i],i)); } } Collections.sort(ev,new Comparator<Pair>() { public int compare(Pair p1,Pair p2) { return p1.x-p2.x; } }); Collections.sort(od,new Comparator<Pair>() { public int compare(Pair p1,Pair p2) { return p1.x-p2.x; } }); int ans[]=new int[n]; Arrays.fill(ans, -1); Stack<Pair> st=new Stack<>(); for(Pair i:ev) { if(i.y=='R') { st.add(i); } else { if(st.empty())st.add(new Pair(i.x*-1, i.y, i.z)); else { Pair p=st.pop(); ans[p.z]=(i.x-p.x)/2; ans[i.z]=(i.x-p.x)/2; } } } while(st.size()>=2) { Pair i=st.pop(); Pair p=st.pop(); ans[i.z]=(m*2-i.x-p.x)/2; ans[p.z]=(m*2-i.x-p.x)/2; } st.clear(); for(Pair i:od) { if(i.y=='R') { st.add(i); } else { if(st.empty())st.add(new Pair(i.x*-1, i.y, i.z)); else { Pair p=st.pop(); ans[p.z]=(i.x-p.x)/2; ans[i.z]=(i.x-p.x)/2; } } } while(st.size()>=2) { Pair i=st.pop(); Pair p=st.pop(); ans[i.z]=(m*2-i.x-p.x)/2; ans[p.z]=(m*2-i.x-p.x)/2; } for(int i:ans) { out.print(i+" "); } out.println(); } class Pair { int x; char y; int z; Pair(int x, char y,int z) { this.x = x; this.y = y; this.z=z; } } String n() { return in.next(); } int ni() { return in.nextInt(); } long nl() { return in.nextLong(); } long[] nal(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) a[i] = nl(); return a; } void pn(long zx) { out.println(zx); } void pn(String sz) { out.println(sz); } void pn(double dx) { out.println(dx); } void pn(long ar[]) { for (int i = 0; i < ar.length; i++) out.print(ar[i] + " "); out.println(); } void pn(String ar[]) { for (int i = 0; i < ar.length; i++) out.println(ar[i]); } } /* ......................Just Input............................. */ static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } /* ......................Just Input............................. */ }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
4bca579e64acbbf7bc6cc54f65238b81
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.io.DataInputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.PriorityQueue; public class Main { private static void run() throws IOException { int n = in.nextInt(); int m = in.nextInt(); Node[] nodes = new Node[n]; int count_even = 0; for (int i = 0; i < n; i++) { nodes[i] = new Node(i); nodes[i].pos = in.nextInt(); if ((nodes[i].pos & 1) == 0) { count_even++; } } for (int i = 0; i < n; i++) { nodes[i].right = in.nc() == 'R'; } Arrays.sort(nodes, Comparator.comparingInt((Node o) -> o.pos % 2).thenComparingInt(o -> o.pos)); solve(nodes, 0, count_even - 1, m); solve(nodes, count_even, n - 1, m); Arrays.sort(nodes, Comparator.comparingInt(o -> o.index)); for (int i = 0; i < n; i++) { out.printf("%d ", nodes[i].ans); } out.println(); } private static void solve(Node[] nodes, int left, int right, int m) { if (left > right) return; PriorityQueue<Node> queue = new PriorityQueue<>(Comparator.comparingInt(o -> o.pos_if_force_left)); for (int now = right; now >= left; now--) { if (!nodes[now].right) { nodes[now].pos_if_force_left = nodes[now].pos; queue.add(nodes[now]); } else { Node right_node = queue.poll(); if (right_node == null) { nodes[now].pos_if_force_left = m + m - nodes[now].pos; queue.add(nodes[now]); } else { right_node.ans = nodes[now].ans = (right_node.pos_if_force_left - nodes[now].pos) / 2; } } } while (true) { Node left_node = queue.poll(); Node right_node = queue.poll(); if (left_node == null || right_node == null) { break; } left_node.ans = right_node.ans = (right_node.pos_if_force_left + left_node.pos_if_force_left) / 2; } } static class Node { int index; int pos, pos_if_force_left; boolean right; int ans = -1; public Node(int index) { this.index = index; } } public static void main(String[] args) throws IOException { in = new Reader(); out = new PrintWriter(new OutputStreamWriter(System.out)); int t = in.nextInt(); for (int i = 0; i < t; i++) { run(); } out.flush(); in.close(); out.close(); } private static int gcd(int a, int b) { if (a == 0 || b == 0) return 0; while (b != 0) { int tmp; tmp = a % b; a = b; b = tmp; } return a; } static final long mod = 1000000007; static long pow_mod(long a, long b) { long result = 1; while (b != 0) { if ((b & 1) != 0) result = (result * a) % mod; a = (a * a) % mod; b >>= 1; } return result; } private static long multiplied_mod(long... longs) { long ans = 1; for (long now : longs) { ans = (ans * now) % mod; } return ans; } @SuppressWarnings("FieldCanBeLocal") private static Reader in; private static PrintWriter out; private static int[] read_int_array(int len) throws IOException { int[] a = new int[len]; for (int i = 0; i < len; i++) { a[i] = in.nextInt(); } return a; } private static long[] read_long_array(int len) throws IOException { long[] a = new long[len]; for (int i = 0; i < len; i++) { a[i] = in.nextLong(); } return a; } private static void print_array(int[] array) { for (int now : array) { out.print(now); out.print(' '); } out.println(); } private static void print_array(long[] array) { for (long now : array) { out.print(now); out.print(' '); } out.println(); } static class Reader { private static final int BUFFER_SIZE = 1 << 16; private final DataInputStream din; private final byte[] buffer; private int bufferPointer, bytesRead; Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { final byte[] buf = new byte[1024]; // 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 nextSign() throws IOException { byte c = read(); while ('+' != c && '-' != c) { c = read(); } return '+' == c ? 0 : 1; } private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } public int skip() throws IOException { int b; // noinspection ALL while ((b = read()) != -1 && isSpaceChar(b)) { ; } return b; } public char nc() throws IOException { return (char) skip(); } public String next() throws IOException { int b = skip(); final StringBuilder sb = new StringBuilder(); while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = read(); } return sb.toString(); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') { c = read(); } final boolean neg = c == '-'; if (neg) { c = read(); } do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) { return -ret; } return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') { c = read(); } final boolean neg = c == '-'; if (neg) { c = read(); } do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) { return -ret; } return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') { c = read(); } final boolean neg = c == '-'; if (neg) { c = read(); } do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) { return -ret; } return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) { buffer[0] = -1; } } private byte read() throws IOException { if (bufferPointer == bytesRead) { fillBuffer(); } return buffer[bufferPointer++]; } public void close() throws IOException { din.close(); } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
045d1a78b3a7c9f57ffee5d761f58796
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
//package edu109div2; import java.util.*; import java.util.stream.Collectors; public class C_Robot_Collisions_2 { static int m; public static class Robot implements Comparable<Robot> { int index; int pos; char dir; int explosion = -1; public Robot(int index, int pos, char dir) { this.index = index; this.pos = pos; this.dir = dir; } @Override public int compareTo(Robot o) { // "exclude" from binary search return this.pos - o.pos; } public void collideWith(Robot other) { if (this.dir == 'R' && other.dir == 'L') { other.collideWith(this); return; } int dis; if (this.dir == 'L' && other.dir == 'R' && this.pos < other.pos) { dis = this.pos + (m - other.pos) + m; } else if (this.dir == 'L' && other.dir == 'R') { dis = this.pos - other.pos; } else if (this.dir == 'L' && other.dir == 'L') { dis = this.pos + other.pos; } else if (this.dir == 'R' && other.dir == 'R') { dis = (m - this.pos) + (m - other.pos); } else { throw new RuntimeException(); } var timing = dis / 2; this.explosion = timing; other.explosion = timing; } } static Scanner in = new Scanner(System.in); public static void main(String[] args) { int t = in.nextInt(); for (int i = 0; i < t; i++) { solve(); } } public static void solve() { int n = in.nextInt(); m = in.nextInt(); // Robots that are an odd number of positions apart can never collide ArrayList<Robot> evenRobots = new ArrayList<>(); ArrayList<Robot> oddRobots = new ArrayList<>(); ArrayList<Robot> allRobots = new ArrayList<>(); for (int i = 0; i < n; i++) { int pos = in.nextInt(); var robot = new Robot(i, pos, '-'); allRobots.add(robot); if (pos % 2 == 0) { evenRobots.add(robot); } else { oddRobots.add(robot); } } var c = 0; in.nextLine(); for (var dir : in.nextLine().split(" ")) { allRobots.get(c++).dir = dir.charAt(0); } solveEvenOdd(evenRobots); solveEvenOdd(oddRobots); Collections.sort(allRobots, Comparator.comparing(r -> r.index)); System.out.println(allRobots.stream().map(r -> r.explosion + "").collect(Collectors.joining( " "))); } /* 1 6 16 2 4 6 8 10 12 R R L L R R */ public static void solveEvenOdd(ArrayList<Robot> robots) { robots.sort(Robot::compareTo); var right = new Stack<Robot>(); var leftRemaining = new Stack<Robot>(); for (var robot : robots) { if (robot.dir == 'R') { right.push(robot); } else { if (right.size() > 0) { right.pop().collideWith(robot); } else { leftRemaining.push(robot); } } } // left stack must be traversed left to right Collections.reverse(leftRemaining); while (leftRemaining.size() > 1) { leftRemaining.pop().collideWith(leftRemaining.pop()); } while (right.size() > 1) { right.pop().collideWith(right.pop()); } if (leftRemaining.size() > 0 && right.size() > 0) { leftRemaining.pop().collideWith(right.pop()); } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
3763590a911455550f830ed3984271d4
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.util.HashMap; import java.io.IOException; import java.io.InputStreamReader; import java.util.TreeSet; import java.util.ArrayList; import java.util.StringTokenizer; import java.io.Writer; import java.io.OutputStreamWriter; 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); OutputWriter out = new OutputWriter(outputStream); CRobotCollisions solver = new CRobotCollisions(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class CRobotCollisions { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(), m = in.nextInt(); HashMap<Integer, Integer> ids = new HashMap<>(); int[] arr = in.nextIntArray(n); for (int i = 0; i < n; i++) ids.put(arr[i], i); TreeSet<Integer> rightodd = new TreeSet<>(); TreeSet<Integer> righteven = new TreeSet<>(); TreeSet<Integer> leftodd = new TreeSet<>(); TreeSet<Integer> lefteven = new TreeSet<>(); for (int i = 0; i < n; i++) { char c = in.next().charAt(0); if (c == 'R') { if (arr[i] % 2 == 0) { righteven.add(arr[i]); } else { rightodd.add(arr[i]); } } else { if (arr[i] % 2 == 0) { lefteven.add(arr[i]); } else { leftodd.add(arr[i]); } } } int[] ans = new int[n]; Arrays.fill(ans, -1); ArrayList<Integer> rem = new ArrayList<>(); for (int a : lefteven) { if (righteven.lower(a) != null) { int id = righteven.lower(a); int dis = (a - id) / 2; ans[ids.get(id)] = dis; ans[ids.get(a)] = dis; righteven.remove(id); rem.add(a); } } for (int a : rem) lefteven.remove(a); rem = new ArrayList<>(); for (int a : leftodd) { if (rightodd.lower(a) != null) { int id = rightodd.lower(a); int dis = (a - id) / 2; ans[ids.get(id)] = dis; ans[ids.get(a)] = dis; rightodd.remove(id); rem.add(a); } } for (int a : rem) leftodd.remove(a); int i = m; while (righteven.lower(i) != null) { int x = righteven.lower(i); if (righteven.lower(x) != null) { int y = righteven.lower(x); int dis = (x - y) / 2 + m - x; ans[ids.get(x)] = ans[ids.get(y)] = dis; righteven.remove(x); righteven.remove(y); } i = x; } i = m; while (rightodd.lower(i) != null) { int x = rightodd.lower(i); if (rightodd.lower(x) != null) { int y = rightodd.lower(x); int dis = (x - y) / 2 + m - x; ans[ids.get(x)] = ans[ids.get(y)] = dis; rightodd.remove(x); rightodd.remove(y); } i = x; } i = 0; while (lefteven.higher(i) != null) { int x = lefteven.higher(i); if (lefteven.higher(x) != null) { int y = lefteven.higher(x); int dis = (y - x) / 2 + x; ans[ids.get(x)] = ans[ids.get(y)] = dis; lefteven.remove(x); lefteven.remove(y); } i = x; } i = 0; // for(int a:leftodd) out.println(a); while (leftodd.higher(i) != null) { int x = leftodd.higher(i); if (leftodd.higher(x) != null) { int y = leftodd.higher(x); int dis = (y - x) / 2 + x; ans[ids.get(x)] = ans[ids.get(y)] = dis; leftodd.remove(x); leftodd.remove(y); } i = x; } if (!lefteven.isEmpty() && !righteven.isEmpty()) { int x = lefteven.first(); int y = righteven.first(); int dis = (y - x) / 2 + m - y + x; ans[ids.get(x)] = ans[ids.get(y)] = dis; } if (!leftodd.isEmpty() && !rightodd.isEmpty()) { int x = leftodd.first(); int y = rightodd.first(); int dis = (y - x) / 2 + m - y + x; ans[ids.get(x)] = ans[ids.get(y)] = dis; } out.println(ans); } } static class InputReader { BufferedReader reader; StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; ++i) array[i] = nextInt(); return array; } public int nextInt() { return Integer.parseInt(next()); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(int[] array) { for (int i = 0; i < array.length; i++) { if (i != 0) { writer.print(' '); } writer.print(array[i]); } } public void println(int[] array) { print(array); writer.println(); } public void close() { writer.close(); } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
1b247bfa9e85723c45f2ba0369b31fb1
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
/* "Everything in the universe is balanced. Every disappointment you face in life will be balanced by something good for you! Keep going, never give up." Just have Patience + 1... */ import java.util.*; import java.lang.*; import java.io.*; import java.util.concurrent.CopyOnWriteArrayList; public class Solution { static class Robot { int position; int direction; int index; Robot (int position, int direction, int index) { this.position = position; this.direction = direction; this.index = index; } } static int MAX = 300005; static int[] positions = new int[MAX]; static int[] directions = new int[MAX]; static int[] timeOfCollision = new int[MAX]; static int rightWallPosition; public static void main(String[] args) throws java.lang.Exception { out = new PrintWriter(new BufferedOutputStream(System.out)); sc = new FastReader(); int test = sc.nextInt(); for (int t = 0; t < test; t++) { solve(); } out.close(); } private static void solve() { int n = sc.nextInt(); rightWallPosition = sc.nextInt(); for (int i = 1; i <= n; i++) { timeOfCollision[i] = -1; positions[i] = sc.nextInt(); } for (int i = 1; i <= n; i++) { char direction = sc.next().charAt(0); directions[i] = direction == 'L' ? 0 : 1; } List<Robot> evenPositionRobots = new ArrayList<>(); List<Robot> oddPositionRobots = new ArrayList<>(); for (int i = 1; i <= n; i++) { if (positions[i] % 2 == 0) { evenPositionRobots.add(new Robot(positions[i], directions[i], i)); }else { oddPositionRobots.add(new Robot(positions[i], directions[i], i)); } } findRobotCollisions(evenPositionRobots); findRobotCollisions(oddPositionRobots); for (int i = 1; i <= n; i++) { out.print(timeOfCollision[i] + " "); } out.println(); } private static void findRobotCollisions(List<Robot> robots) { robots.sort(Comparator.comparingInt(a -> a.position)); Stack<Robot> rightMovingRobots = new Stack<>(); int n = robots.size(); for (int i = 0; i < n; i++) { Robot currRobot = robots.get(i); if (currRobot.direction == 1) { rightMovingRobots.add(currRobot); continue; } if (rightMovingRobots.size() > 0) { Robot rightMostRobotMovingRight = rightMovingRobots.pop(); timeOfCollision[currRobot.index] = timeOfCollision[rightMostRobotMovingRight.index] = (currRobot.position - rightMostRobotMovingRight.position) / 2; }else { currRobot.position *= -1; currRobot.direction = 1; rightMovingRobots.add(currRobot); } } while (rightMovingRobots.size() > 1) { Robot right = rightMovingRobots.pop(); Robot left = rightMovingRobots.pop(); right.position = 2 * rightWallPosition - right.position; timeOfCollision[left.index] = timeOfCollision[right.index] = (right.position - left.position) / 2; } } public static FastReader sc; public static PrintWriter out; static class FastReader { BufferedReader br; StringTokenizer str; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (str == null || !str.hasMoreElements()) { try { str = new StringTokenizer(br.readLine()); } catch (IOException end) { end.printStackTrace(); } } return str.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 end) { end.printStackTrace(); } return str; } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
5168a6b08a13960691cdeff1855c36d7
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.io.*; import java.util.*; public class Collisions { public static void main(String[] args) throws Exception { FastIO in = new FastIO(); int t = in.nextInt(); for (int tc=0; tc<t; tc++) { int n = in.nextInt(); int m = in.nextInt(); int[][] robotData = new int[n][2]; int[] ans = new int[n]; Arrays.fill(ans, -1); for (int i=0; i<n; i++) { robotData[i][0] = in.nextInt(); } for (int i=0; i<n; i++) { String s = in.next(); if (s.equals("L")) robotData[i][1] = -1; else robotData[i][1] = 1; } ArrayList<Robot> evenRobots = new ArrayList<Robot>(); ArrayList<Robot> oddRobots = new ArrayList<Robot>(); for (int i=0; i<n; i++) { Robot r = new Robot(robotData[i][0], robotData[i][1], i); if (robotData[i][0]%2==0) { evenRobots.add(r); } else oddRobots.add(r); } Collections.sort(evenRobots, (o1, o2) -> Integer.compare(o1.start, o2.start)); Collections.sort(oddRobots, (o1, o2) -> Integer.compare(o1.start, o2.start)); Stack<Robot> rightRobots = new Stack<Robot>(); for (int i=0; i<evenRobots.size(); i++) { if (evenRobots.get(i).direction==1) { rightRobots.add(evenRobots.get(i)); } else { if (rightRobots.isEmpty()) { Robot r = evenRobots.get(i); r.start*=(-1); rightRobots.add(r); } else { Robot prev = rightRobots.pop(); // System.out.println(prev.start+" "+evenRobots.get(i).start); int answer = (evenRobots.get(i).start-prev.start)/2; ans[prev.id] = answer; ans[evenRobots.get(i).id] = answer; } } } while (rightRobots.size()>=2) { Robot first = rightRobots.pop(); Robot second = rightRobots.pop(); int collision1 = m-first.start; int answer = (m-(second.start+collision1))/2 + collision1; ans[first.id] = answer; ans[second.id] = answer; } rightRobots.clear(); for (int i=0; i<oddRobots.size(); i++) { if (oddRobots.get(i).direction==1) { rightRobots.add(oddRobots.get(i)); } else { if (rightRobots.isEmpty()) { Robot r = oddRobots.get(i); r.start*=(-1); rightRobots.add(r); } else { Robot prev = rightRobots.pop(); int answer = (oddRobots.get(i).start-prev.start)/2; ans[prev.id] = answer; ans[oddRobots.get(i).id] = answer; } } } while (rightRobots.size()>=2) { Robot first = rightRobots.pop(); Robot second = rightRobots.pop(); int collision1 = m-first.start; int answer = (m-(second.start+collision1))/2+collision1; ans[first.id] = answer; ans[second.id] = answer; } for (int i=0; i<n; i++) { System.out.print(ans[i]+" "); } System.out.println(); } } static class Robot { int start, direction, id; public Robot(int start, int direction, int id) { this.start = start; this.direction = direction; this.id = id; } } static class FastIO { BufferedReader br; StringTokenizer st; public FastIO() throws IOException { br = new BufferedReader( new InputStreamReader(System.in)); } public String next() throws IOException { while (st == null || !st.hasMoreElements()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } public int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); } public long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } public double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } public String nextLine() throws IOException { String str = br.readLine(); return str; } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
f59479a567d2c779ef2f0049092a13c7
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.io.*; import java.util.*; public class Main { private static class Cow implements Comparable<Cow> { private int pos; private int dir; private int idx; private Cow() {} @Override public int compareTo(Cow o) { return pos-o.pos; } } private static int m; private static int[] res; private static void solve(ArrayList<Cow> cows) { Collections.sort(cows); Stack<Cow> right = new Stack<>(); Cow left = null; for(Cow i: cows) { if(i.dir == 1) { right.push(i); } else { if(right.isEmpty()) { if(left == null) { left = i; } else { res[i.idx] = res[left.idx] = (i.pos+left.pos)/2; left = null; } } else { Cow j = right.pop(); res[i.idx] = res[j.idx] = (i.pos-j.pos)/2; } } } while(right.size() > 1) { Cow i = right.pop(); Cow j = right.pop(); res[i.idx] = res[j.idx] = m-(i.pos+j.pos)/2; } if(!right.isEmpty() && left != null) { Cow i = right.pop(); res[i.idx] = res[left.idx] = m-(i.pos-left.pos)/2; } } public static void main(String[] args) throws IOException { //BufferedReader f = new BufferedReader(new FileReader("uva.in")); BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); //PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("cowjump.out"))); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int t = Integer.parseInt(f.readLine()); while(t-- > 0) { StringTokenizer st = new StringTokenizer(f.readLine()); int n = Integer.parseInt(st.nextToken()); m = Integer.parseInt(st.nextToken()); st = new StringTokenizer(f.readLine()); Cow[] cows = new Cow[n]; for(int i = 0; i < n; i++) { cows[i] = new Cow(); cows[i].pos = Integer.parseInt(st.nextToken()); cows[i].idx = i; } st = new StringTokenizer(f.readLine()); ArrayList<Cow> even = new ArrayList<>(); ArrayList<Cow> odd = new ArrayList<>(); for(int i = 0; i < n; i++) { cows[i].dir = st.nextToken().charAt(0) == 'L' ? -1 : 1; if(cows[i].pos%2 == 0) { even.add(cows[i]); } else { odd.add(cows[i]); } } res = new int[n]; Arrays.fill(res, -1); solve(even); solve(odd); out.print(res[0]); for(int i = 1; i < n; i++) { out.print(" " + res[i]); } out.println(); } f.close(); out.close(); } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
0f673a0fddb09bb0223e016c77d86cbe
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.util.*; import java.io.*; public class _1525_C { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int t = Integer.parseInt(in.readLine()); while(t-- > 0) { StringTokenizer line = new StringTokenizer(in.readLine()); int n = Integer.parseInt(line.nextToken()); int m = Integer.parseInt(line.nextToken()); int[][] x = new int[n][2]; int[] dir = new int[n]; line = new StringTokenizer(in.readLine()); for(int i = 0; i < n; i++) { x[i][0] = Integer.parseInt(line.nextToken()); x[i][1] = i; } Arrays.sort(x, new Comparator<int[]>() { @Override public int compare(int[] a, int[] b) { return a[0] - b[0]; } }); line = new StringTokenizer(in.readLine()); for(int i = 0; i < n; i++) { char c = line.nextToken().charAt(0); if(c == 'R') { dir[i] = 1; } } int[] res = new int[n]; Arrays.fill(res, -1); find_times(x, dir, 0, res, m); find_times(x, dir, 1, res, m); StringBuilder sb = new StringBuilder(); for(int i = 0; i < n; i++) { sb.append(res[i]); sb.append(' '); } out.println(sb.toString()); } in.close(); out.close(); } static void find_times(int[][] x, int[] dir, int parity, int[] res, int m) { ArrayList<Robot> left = new ArrayList<Robot>(); for(int i = 0; i < x.length; i++) { if(x[i][0] % 2 == parity) { Robot top = left.size() > 0 ? left.get(left.size() - 1) : null; if(top != null && top.d == 1 && dir[x[i][1]] == 0) { int time = (x[i][0] - top.x) / 2; res[top.i] = time; res[x[i][1]] = time; left.remove(left.size() - 1); }else { left.add(new Robot(x[i][0], dir[x[i][1]], x[i][1])); } } } for(int i = 1; i < left.size(); i += 2) { Robot cur = left.get(i); Robot prev = left.get(i - 1); if(cur.d == 1) { break; } int time = prev.x + (cur.x - prev.x) / 2; res[prev.i] = time; res[cur.i] = time; } for(int i = left.size() - 2; i >= 0; i -= 2) { Robot cur = left.get(i); Robot prev = left.get(i + 1); if(cur.d == 0) { break; } int time = m - prev.x + (prev.x - cur.x) / 2; res[prev.i] = time; res[cur.i] = time; } int start = left.size(); for(int i = 0; i < left.size(); i++) { if(left.get(i).d == 1) { start = i; break; } } int end = left.size() - start; if(start % 2 == 1 && end % 2 == 1) { Robot one = left.get(start - 1); Robot two = left.get(start); int time = (m + m - two.x + one.x) / 2; res[one.i] = time; res[two.i] = time; } } static class Robot { int x, d, i; Robot(int xx, int dd, int ii) { x = xx; d = dd; i = ii; } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
83e5293752fb3c67e43cd552f31f7fcd
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.*; public class Main { static final long MOD=1000000007; static final long MOD1=998244353; static long ans=0; //static ArrayList<Integer> ans=new ArrayList<>(); public static void main(String[] args){ PrintWriter out = new PrintWriter(System.out); InputReader sc=new InputReader(System.in); int t = sc.nextInt(); for (int i = 0; i < t; i++) { int n = sc.nextInt(); int m = sc.nextInt(); int[] x = sc.nextIntArray(n); String[] s = new String[n]; for (int j = 0; j < s.length; j++) { s[j] = sc.next(); } int[] ans = solve(n, m, x, s); for (int j = 0; j < ans.length; j++) { out.print(ans[j]+" "); } out.println(); } out.flush(); } static int[] solve(int n, int m, int[] x,String[] s){ TreeSet<Pair> oddL = new TreeSet<Pair>(); TreeSet<Pair> oddR = new TreeSet<Pair>(); TreeSet<Pair> evenL = new TreeSet<Pair>(); TreeSet<Pair> evenR = new TreeSet<Pair>(); for (int i = 0; i < s.length; i++) { if (x[i]%2==0) { if (s[i].equals("L")) { evenL.add(new Pair(x[i], i)); }else { evenR.add(new Pair(x[i], i)); } }else { if (s[i].equals("L")) { oddL.add(new Pair(x[i], i)); }else { oddR.add(new Pair(x[i], i)); } } } int[] ans = new int[n]; Arrays.fill(ans, -1); solve2(oddL, oddR, ans, m); solve2(evenL, evenR, ans, m); return ans; } static void solve2(TreeSet<Pair> setL,TreeSet<Pair> setR,int[] ans,int m) { ArrayList<Pair> removelist = new ArrayList<Main.Pair>(); for (Pair p: setL) { Pair colp = setR.lower(p); if (colp!=null) { int t = Math.abs(p.x-colp.x)/2; ans[p.y] = t; ans[colp.y] = t; removelist.add(p); setR.remove(colp); } } for (Pair pair : removelist) { setL.remove(pair); } while (setL.size()>1) { Pair p1 = setL.pollFirst(); Pair p2 = setL.pollFirst(); int t = p1.x + (p2.x-p1.x)/2; ans[p1.y] = t; ans[p2.y] = t; } while (setR.size()>1) { Pair p1 = setR.pollLast(); Pair p2 = setR.pollLast(); int t = m - p1.x + (p1.x-p2.x)/2; ans[p1.y] = t; ans[p2.y] = t; } if (setL.size()>0&&setR.size()>0) { Pair p1 = setL.pollFirst(); Pair p2 = setR.pollFirst(); int t = 0; if (p1.x<=m - p2.x) { t = m - p2.x + (p1.x+p2.x)/2; }else { t = p1.x + m - (p1.x+p2.x)/2; } ans[p1.y] = t; ans[p2.y] = t; } } static class Pair implements Comparable<Pair>{ public int x; public int y; public Pair(int x,int y) { this.x=x; this.y=y; } @Override public boolean equals(Object obj) { if(obj instanceof Pair) { Pair other = (Pair) obj; return other.x==this.x && other.y==this.y; } return false; }//同値の定義 @Override public int hashCode() { return Objects.hash(this.x,this.y); }//これ書かないと正しく動作しない(要 勉強) @Override public int compareTo( Pair p){ if (this.x>p.x) { return 1; } else if (this.x<p.x) { return -1; } else { return 0; } } } static class InputReader { private InputStream in; private byte[] buffer = new byte[1024]; private int curbuf; private int lenbuf; public InputReader(InputStream in) { this.in = in; this.curbuf = this.lenbuf = 0; } public boolean hasNextByte() { if (curbuf >= lenbuf) { curbuf = 0; try { lenbuf = in.read(buffer); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return false; } return true; } private int readByte() { if (hasNextByte()) return buffer[curbuf++]; else return -1; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private void skip() { while (hasNextByte() && isSpaceChar(buffer[curbuf])) curbuf++; } public boolean hasNext() { skip(); return hasNextByte(); } public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (!isSpaceChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public int nextInt() { if (!hasNext()) throw new NoSuchElementException(); int c = readByte(); while (isSpaceChar(c)) c = readByte(); boolean minus = false; if (c == '-') { minus = true; c = readByte(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = res * 10 + c - '0'; c = readByte(); } while (!isSpaceChar(c)); return (minus) ? -res : res; } public long nextLong() { if (!hasNext()) throw new NoSuchElementException(); int c = readByte(); while (isSpaceChar(c)) c = readByte(); boolean minus = false; if (c == '-') { minus = true; c = readByte(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = res * 10 + c - '0'; c = readByte(); } while (!isSpaceChar(c)); return (minus) ? -res : res; } public double nextDouble() { return Double.parseDouble(next()); } public int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public double[] nextDoubleArray(int n) { double[] a = new double[n]; for (int i = 0; i < n; i++) a[i] = nextDouble(); return a; } public long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public char[][] nextCharMap(int n, int m) { char[][] map = new char[n][m]; for (int i = 0; i < n; i++) map[i] = next().toCharArray(); return map; } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
f447e28d4486743ec6612839fbf83c1f
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.math.BigInteger; import java.util.*; /** * @author Mubtasim Shahriar */ public class RobotCollisions { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader sc = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Solver solver = new Solver(); int t = sc.nextInt(); // int t = 1; while (t-- != 0) { solver.solve(sc, out); } out.close(); } static class Solver { public void solve(InputReader sc, PrintWriter out) { int n = sc.nextInt(); int m = sc.nextInt(); int[] arr = sc.nextIntArray(n); char[] dir = new char[n]; for (int i = 0; i < n; i++) { dir[i] = sc.next().charAt(0); } int ecnt = 0; for(int i : arr) if(i%2==0) ecnt++; int ocnt = n-ecnt; Node[] evenNodes = new Node[ecnt]; Node[] oddNodes = new Node[ocnt]; int eIdx = 0; int oIdx = 0; for (int i = 0; i < n; i++) { int nowx = arr[i]; if(nowx%2==0) evenNodes[eIdx++] = new Node(nowx,dir[i],i); else oddNodes[oIdx++] = new Node(nowx,dir[i],i); } Arrays.sort(evenNodes, new Comparator<Node>() { @Override public int compare(Node o1, Node o2) { int o = Long.compare(o1.x,o2.x); return o; } }); Arrays.sort(oddNodes, new Comparator<Node>() { @Override public int compare(Node o1, Node o2) { int o = Long.compare(o1.x,o2.x); return o; } }); long[] ans = new long[n]; work(evenNodes,ans,m); work(oddNodes,ans,m); for(int i = 0; i < n; i++) { if(i>0) out.print(" "); out.print(ans[i]); } out.println(); } private void work(Node[] nodes, long[] ans, int rightLimit) { Stack<Node> stk = new Stack<>(); int n = nodes.length; for(int i = 0; i < n; i++) { char dir = nodes[i].dir; long x = nodes[i].x; if(stk.isEmpty()) { if(dir=='L') { nodes[i].dir = 'R'; nodes[i].x = nodes[i].x*(-1); } stk.add(nodes[i]); continue; } if(dir=='R') { stk.add(nodes[i]); continue; } Node top = stk.pop(); int idx1 = top.idx; int idx2 = nodes[i].idx; if(idx1==idx2) throw new RuntimeException(); long topx = top.x; long time = Math.abs(topx-x)/2; ans[idx1] = time; ans[idx2] = time; } while(!stk.isEmpty()) { if(stk.size()==1) { ans[stk.pop().idx] = -1; continue; } Node right = stk.pop(); Node left = stk.pop(); if(right.dir=='L' || left.dir=='L') throw new RuntimeException(); int idx1 = right.idx; int idx2 = left.idx; long rightx = right.x; rightx = rightLimit+(rightLimit-rightx); long leftx = left.x; long time = Math.abs(rightx-leftx)/2; ans[idx1] = time; ans[idx2] = time; } } } static class Node { long x; char dir; int idx; public Node(long x, char dir, int idx) { this.x = x; this.dir = dir; this.idx = idx; } @Override public String toString() { return "Node{" + "x=" + x + ", dir=" + dir + ", idx=" + idx + '}'; } } static void sort(int[] arr) { Random rand = new Random(); int n = arr.length; for (int i = 0; i < n; i++) { int idx = rand.nextInt(n); if (idx == i) continue; arr[i] ^= arr[idx]; arr[idx] ^= arr[i]; arr[i] ^= arr[idx]; } Arrays.sort(arr); } static void sort(long[] arr) { Random rand = new Random(); int n = arr.length; for (int i = 0; i < n; i++) { int idx = rand.nextInt(n); if (idx == i) continue; arr[i] ^= arr[idx]; arr[idx] ^= arr[i]; arr[i] ^= arr[idx]; } Arrays.sort(arr); } static void sortDec(int[] arr) { Random rand = new Random(); int n = arr.length; for (int i = 0; i < n; i++) { int idx = rand.nextInt(n); if (idx == i) continue; arr[i] ^= arr[idx]; arr[idx] ^= arr[i]; arr[i] ^= arr[idx]; } Arrays.sort(arr); int l = 0; int r = n - 1; while (l < r) { arr[l] ^= arr[r]; arr[r] ^= arr[l]; arr[l] ^= arr[r]; l++; r--; } } static void sortDec(long[] arr) { Random rand = new Random(); int n = arr.length; for (int i = 0; i < n; i++) { int idx = rand.nextInt(n); if (idx == i) continue; arr[i] ^= arr[idx]; arr[idx] ^= arr[i]; arr[i] ^= arr[idx]; } Arrays.sort(arr); int l = 0; int r = n - 1; while (l < r) { arr[l] ^= arr[r]; arr[r] ^= arr[l]; arr[l] ^= arr[r]; l++; r--; } } static class InputReader { private boolean finished = false; 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 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 nextString() { 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(nextString()); } catch (NumberFormatException e) { throw new InputMismatchException(); } } public char nextCharacter() { int c = read(); while (isSpaceChar(c)) { c = read(); } return (char) c; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') { return res * Math.pow(10, nextInt()); } if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') { return res * Math.pow(10, nextInt()); } if (c < '0' || c > '9') { throw new InputMismatchException(); } m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public boolean isExhausted() { int value; while (isSpaceChar(value = peek()) && value != -1) { read(); } return value == -1; } public String next() { return nextString(); } public SpaceCharFilter getFilter() { return filter; } public void setFilter(SpaceCharFilter filter) { this.filter = filter; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } public int[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; ++i) array[i] = nextInt(); return array; } public int[] nextSortedIntArray(int n) { int array[] = nextIntArray(n); Arrays.sort(array); return array; } public int[] nextSumIntArray(int n) { int[] array = new int[n]; array[0] = nextInt(); for (int i = 1; i < n; ++i) array[i] = array[i - 1] + nextInt(); return array; } public long[] nextLongArray(int n) { long[] array = new long[n]; for (int i = 0; i < n; ++i) array[i] = nextLong(); return array; } public long[] nextSumLongArray(int n) { long[] array = new long[n]; array[0] = nextInt(); for (int i = 1; i < n; ++i) array[i] = array[i - 1] + nextInt(); return array; } public long[] nextSortedLongArray(int n) { long array[] = nextLongArray(n); Arrays.sort(array); return array; } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
0adfc3f21d606b1a61a25de005bf9880
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class RobotCollisions { static class Point { int x; boolean left; int index; public Point(int x, boolean left, int index) { this.x = x; this.left = left; this.index = index; } } public static void update (int n, int m, List<Point> list, int[] ans){ Collections.sort(list, new Comparator<Point>() { @Override public int compare(Point o1, Point o2) { return o1.x - o2.x; } }); Stack<Point> stack = new Stack<>(); Point l = new Point (-1, true, -1); for (Point i : list){ if (i.left){ if (stack.isEmpty()){ if (l.index == -1){ l = i; } else { int t = (i.x+l.x)/2; ans[l.index] = t; ans[i.index] = t; l.index = -1; } } else { Point p = stack.pop(); int t = (i.x-p.x)/2; ans[p.index] = t; ans[i.index] = t; } } else { stack.add(i); } } while (stack.size() >= 2){ Point p1 = stack.pop(); Point p2 = stack.pop(); int t = (m*2-p1.x-p2.x)/2; ans[p1.index] = t; ans[p2.index] = t; } if (l.index != -1 && stack.size() == 1){ Point p1 = l; Point p2 = stack.pop(); int t = (p1.x + m - p2.x + m)/2; ans[p1.index] = t; ans[p2.index] = t; } } public static int[] solve (int n, int m, int[] pos, boolean[] left){ List<Point> list1 = new ArrayList<>(); List<Point> list2 = new ArrayList<>(); int[] ans = new int[n]; for (int i=0; i < n; i++){ ans[i] = -1; } for (int i=0; i < n; i++){ if (pos[i]%2 == 0){ list1.add(new Point (pos[i], left[i], i)); } else { list2.add(new Point (pos[i], left[i], i)); } } update (n, m, list1, ans); update (n, m, list2, ans); return ans; } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); for (int i = 0; i < t; i++) { StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int[] pos = new int[n]; st = new StringTokenizer(br.readLine()); for (int j=0; j < n; j++){ pos[j] = Integer.parseInt(st.nextToken()); } boolean[] left = new boolean[n]; st = new StringTokenizer(br.readLine()); for (int j=0; j < n; j++){ left[j] = st.nextToken().charAt(0) == 'L'; } int[] ans = solve (n, m, pos, left); for (int j=0; j < n; j++){ if (j==0){ System.out.print(ans[j]); } else { System.out.print(" " + ans[j]); } } System.out.println(); } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
c7e4995697115e700254580944f0953a
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.io.*; import java.nio.charset.StandardCharsets; import java.util.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Solution { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) throws Exception { BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(java.io.FileDescriptor.out), StandardCharsets.US_ASCII), 512); FastReader sc = new FastReader(); int t=sc.nextInt(); for(int k=0;k<t;k++){ int n= sc.nextInt(); int m = sc.nextInt(); int[] temp=new int[n]; Obj[] arr=new Obj[n]; for(int i=0;i<n;i++) { int key=sc.nextInt(); temp[i]=key; arr[i]=new Obj(key,null); } for(int i=0;i<n;i++) arr[i].setVal(sc.next().charAt(0)); Arrays.sort(arr, new Comparator<Obj>() { @Override public int compare(Obj o1, Obj o2) { return o1.key.compareTo(o2.key); } }); Map<Integer,Long> map=new HashMap<>(); Stack<Obj>stk=new Stack<>(); for(int i=0;i<n;i++){ if(arr[i].key%2==1) continue; if(arr[i].val=='R') stk.push(arr[i]); else if(arr[i].val=='L'&&!stk.isEmpty()){ long dist=(arr[i].key-stk.peek().key)/2; map.put(arr[i].key,dist); map.put(stk.peek().key,dist); stk.pop(); } else{ arr[i].setKey(arr[i].key*-1); arr[i].setVal('R'); stk.push(arr[i]); } } while(stk.size()>=2){ Obj a= stk.pop(); Obj b= stk.pop(); long dist=(m-((a.key+b.key)/2)); map.put(a.key,dist); map.put(b.key,dist); } stk=new Stack<>(); for(int i=0;i<n;i++){ if(arr[i].key%2==0) continue; if(arr[i].val=='R') stk.push(arr[i]); else if(arr[i].val=='L'&&!stk.isEmpty()){ long dist=(arr[i].key-stk.peek().key)/2; map.put(arr[i].key,dist); map.put(stk.peek().key,dist); stk.pop(); } else{ arr[i].setKey(arr[i].key*-1); arr[i].setVal('R'); stk.push(arr[i]); } } while(stk.size()>=2){ Obj a= stk.pop(); Obj b= stk.pop(); long dist=(m-((a.key+b.key)/2)); map.put(a.key,dist); map.put(b.key,dist); } for(int i : temp){ if(!map.containsKey(i)&&!map.containsKey(i*-1)) out.write(-1+" "); else if (map.containsKey(i*-1)) out.write(map.get(i*-1)+" "); else out.write(map.get(i)+" "); } out.write("\n"); out.flush(); } } static class Obj{ Integer key; Character val; Obj(Integer key, Character val){ this.key=key; this.val=val; } void setVal(Character val){ this.val=val; } public void setKey(Integer key) { this.key = key; } } } //import java.io.*;
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
761ed12456f2369a4d3280c271ad647c
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.io.*; import java.util.*; public class robot_collisions { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int m = sc.nextInt(); int[] start = new int[n]; char[] dir = new char[n]; ArrayList<Node> even = new ArrayList<>(); ArrayList<Node> odd = new ArrayList<>(); for(int i=0;i<n;i++) start[i] = sc.nextInt(); for (int i=0;i<n;i++) { dir[i] = sc.next().charAt(0); if(start[i]%2==0) even.add(new Node(start[i], dir[i], i)); else odd.add(new Node(start[i], dir[i], i)); } Collections.sort(even); Collections.sort(odd); int[] ans = new int[n]; Arrays.fill(ans, -1); findAns(even, ans, m); findAns(odd,ans,m); for (int i: ans) { System.out.print(i + " "); } System.out.println(); } } static void findAns(ArrayList<Node> val, int[] ans, int m) { Stack<Node> stack = new Stack<>(); for(Node x : val) { if(x.dir == 'R'){ stack.add(x); }else{ if(stack.empty()) stack.add(x); else{ Node right = stack.pop(); if(right.dir == 'R'){ ans[x.idx] = Math.abs(right.value - x.value)/2; ans[right.idx] = Math.abs(right.value - x.value)/2; }else{ ans[x.idx] = (right.value + x.value)/2; ans[right.idx] = (right.value + x.value)/2; } } } } while (stack.size() >=2){ Node a = stack.pop(); Node b = stack.pop(); if(b.dir == 'R'){ ans[a.idx] = (m-a.value+m-b.value)/2; ans[b.idx] = (m-a.value+m-b.value)/2; }else{ ans[a.idx] = (m-a.value+m+b.value)/2; ans[b.idx] = (m-a.value+m+b.value)/2; } } } static class Node implements Comparable<Node>{ int value; char dir; int idx; Node(int value, char dir, int idx){ this.value = value; this.dir = dir; this.idx = idx; } @Override public int compareTo(Node o) { return this.value - o.value; } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
957a6742800715a3e12c01438dce6381
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Scanner; import java.util.StringTokenizer; import java.util.function.BiConsumer; import javax.sound.midi.SysexMessage; import java.io.IOException; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; public class S2 { static class Reader { static BufferedReader reader; static StringTokenizer tokenizer; static void init(InputStream input) { reader = new BufferedReader(new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } static String next() throws IOException { while(!tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } } private static void arrInp(int n1) throws IOException { // TODO Auto-generated method stub arr = new long[n1]; for(int i=0; i<n1; i++) { long a = Reader.nextLong(); arr[i] = a; } } static long[] merge(long[] a, long[] b) { int m = a.length; int n = b.length; long [] c = new long[n+m]; int j=0, k=0; while(j+k<m+n) { if(j>=m) { c[j+k] = b[k]; k++; } else if(k>=n) { c[j+k] = a[j]; j++; } else { if(a[j]<b[k]) { c[j+k] = a[j]; j++; } else if(a[j]==b[k]) { if(a[j]<b[k]) { c[j+k] = a[j]; j++; } else { c[j+k] = b[k]; k++; } } else { c[j+k] = b[k]; k++; } } } return c; } static long[] Msort(long[] unsorted){ int l = unsorted.length; if(l<=1) { return unsorted; } else { long[] Msorted = new long[l]; long[] m1 = new long[l/2]; long[] m2 = new long[l-(l/2)]; for(int i=0; i<l; i++) { if(i<l/2) { m1[i] = unsorted[i]; } else { m2[i-(l/2)] = unsorted[i]; } } Msorted = merge(Msort(m1), Msort(m2)); return Msorted; } } private static long inf = 1<<27; private static long ans; private static long n; private static long k; private static long[] arr; private static char[] str; private final static long qwerty = 1000000007; private static boolean bruh; private static class Node implements Comparable<Node> { public int i; public int v; public char ch; public Node(int ix, int x, char c) { // TODO Auto-generated constructor stub i=ix; v=x; ch=c; } @Override public int compareTo(Node o) { // TODO Auto-generated method stub return this.v - o.v; } } public static void main(String[] args) throws IOException { ans = 0; Reader.init(System.in); OutputStream out = new BufferedOutputStream(System.out); int tc=1; tc = Reader.nextInt(); main_loop: for(int tn=0; tn<tc; tn++) { ans=0; bruh = false; n=tn+1; n = Reader.nextInt(); k = Reader.nextInt(); int n1 = (int) n; arrInp(n1); Node[] odd = new Node[n1]; Node[] even = new Node[n1]; int io=0,ie=0; for(int i=0; i<n1; i++) { char dir = Reader.next().charAt(0); if((arr[i]&1)==1) odd[io++] = new Node(i, (int) arr[i], dir); else even[ie++] = new Node(i, (int) arr[i], dir); } for(int i=0; i<n; i++) { arr[i]=-1; } odd = Msort(Arrays.copyOfRange(odd, 0, io)); even = Msort(Arrays.copyOfRange(even, 0, ie)); int a=-1,b=-1; Node[] stack = new Node[n1]; int l=0; for(int i=0; i<io; i++) { if(odd[i].ch=='L' && l>0 && stack[l-1].ch=='R') { int x = odd[i].v-stack[l-1].v; x/=2; int ix = odd[i].i; arr[ix] = x; ix = stack[l-1].i; arr[ix] = x; l--; } else { stack[l++]=odd[i]; } } for(int i=1; i<l; i+=2) { long x1 = stack[i-1].v; long x2 = stack[i].v; if(stack[i].ch=='L') { long x = x1+x2; x/=2; int ix = stack[i-1].i; arr[ix] = x; ix = stack[i].i; arr[ix] = x; } else { if(stack[i-1].ch=='L') { a=i-1; } break; } } for(int i=l-2; i>=0; i-=2) { long x1 = k-stack[i].v; long x2 = k-stack[i+1].v; if(stack[i].ch=='R') { long x = x1+x2; x/=2; int ix = stack[i+1].i; arr[ix] = x; ix = stack[i].i; arr[ix] = x; } else { if(stack[i+1].ch=='R') { b=i+1; } break; } } if(a!=-1 && b!=-1) { long x1 = stack[a].v; long x2 = k-stack[b].v; long x = k+x1+x2; x/=2; int ix = stack[a].i; arr[ix] = x; ix = stack[b].i; arr[ix] = x; } a=-1;b=-1; stack = new Node[n1]; l=0; for(int i=0; i<ie; i++) { if(even[i].ch=='L' && l>0 && stack[l-1].ch=='R') { int x = even[i].v-stack[l-1].v; x/=2; int ix = even[i].i; arr[ix] = x; ix = stack[l-1].i; arr[ix] = x; l--; } else { stack[l++]=even[i]; } } for(int i=1; i<l; i+=2) { long x1 = stack[i-1].v; long x2 = stack[i].v; if(stack[i].ch=='L') { long x = x1+x2; x/=2; int ix = stack[i-1].i; arr[ix] = x; ix = stack[i].i; arr[ix] = x; } else { if(stack[i-1].ch=='L') { a=i-1; } break; } } for(int i=l-2; i>=0; i-=2) { long x1 = k-stack[i].v; long x2 = k-stack[i+1].v; if(stack[i].ch=='R') { long x = x1+x2; x/=2; int ix = stack[i+1].i; arr[ix] = x; ix = stack[i].i; arr[ix] = x; } else { if(stack[i+1].ch=='R') { b=i+1; } break; } } if(a!=-1 && b!=-1) { long x1 = stack[a].v; long x2 = k-stack[b].v; long x = k+x1+x2; x/=2; int ix = stack[a].i; arr[ix] = x; ix = stack[b].i; arr[ix] = x; } for(int i=0; i<n1; i++) { ans=arr[i]; out.write((ans+" ").getBytes()); } // out.write(("YES").getBytes()); // out.write(("NO").getBytes()); // out.write((ans+" ").getBytes()); out.write(("\n").getBytes()); } out.flush(); out.close(); } static Node[] merge(Node[] a, Node[] b) { int m = a.length; int n = b.length; Node [] c = new Node[n+m]; int j=0, k=0; while(j+k<m+n) { if(j>=m) { c[j+k] = b[k]; k++; } else if(k>=n) { c[j+k] = a[j]; j++; } else { if(a[j].compareTo(b[k])<0) { c[j+k] = a[j]; j++; } else { c[j+k] = b[k]; k++; } } } return c; } static Node[] Msort(Node[] unsorted){ int l = unsorted.length; if(l<=1) { return unsorted; } else { Node[] Msorted = new Node[l]; Node[] m1 = new Node[l/2]; Node[] m2 = new Node[l-(l/2)]; for(int i=0; i<l; i++) { if(i<l/2) { m1[i] = unsorted[i]; } else { m2[i-(l/2)] = unsorted[i]; } } Msorted = merge(Msort(m1), Msort(m2)); return Msorted; } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
5c74cedd4f83499cfbb5f57a251f3d38
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.io.*; import java.util.*; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { // InputReader sc = new InputReader(System.in); // PrintWriter out = new PrintWriter(System.out); BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); FastReader reader =new FastReader(); BufferedWriter output = new BufferedWriter( new OutputStreamWriter(System.out)); int test = reader.nextInt(); for (int o = 0; o < test; o++){ int n = reader.nextInt(); int m = reader.nextInt(); int[] ans1 = new int[n]; int[] ans2 = new int[n]; for (int i = 0; i < n; i++){ans1[i] = reader.nextInt();} for (int i = 0; i < n; i++){String jk = reader.next(); ans2[i] = jk.equals("R") ? 1 : -1;} Robot[] robots = new Robot[n]; for (int i = 0; i < n; i++){robots[i] = new Robot(ans2[i], i, ans1[i]);} int[] ans =new int[n]; Arrays.sort(robots, new Comparator<Robot>() { @Override public int compare(Robot o1, Robot o2) { return o1.start - o2.start; } }); Arrays.fill(ans, -1); ArrayList<Robot> even = new ArrayList<>(); ArrayList<Robot> odd = new ArrayList<>(); for (int i =0; i < n; i++){ if (robots[i].start % 2 == 0){even.add(robots[i]);} else {odd.add(robots[i]);} } processing(even, ans, m); processing(odd, ans, m); for (int i = 0; i < n; i++){ System.out.print(ans[i] + " "); } System.out.println(""); } } public static void processing(ArrayList<Robot> robots, int[] ans, int m){ Stack<Robot> stack = new Stack<>(); Collections.sort(robots, new Comparator<Robot>() { @Override public int compare(Robot o1, Robot o2) { return o1.start - o2.start; } }); for (Robot robot: robots){ if (robot.dir == -1){ if (stack.isEmpty()){ stack.push(robot); } else { Robot kk = stack.pop(); int s1 = robot.start; int s2 = kk.start; if (kk.dir == 1){ ans[kk.index] = ((s1 - s2)/2); ans[robot.index] = ((s1 - s2)/2); } else { ans[kk.index] = (s1 + s2)/2; ans[robot.index] = (s1 + s2)/2; } } } else { stack.push(robot); } } while (stack.size() >= 2){ Robot r1 = stack.pop(); Robot r2 = stack.pop(); // System.out.println(r1.index + " " + r2.index); if (r2.dir == 1){ ans[r1.index] = ((m - r1.start + m - r2.start)/2) ; ans[r2.index] = ((m - r1.start + m - r2.start)/2) ; } else { ans[r1.index] = ((m - r1.start + m + r2.start)/2) ; ans[r2.index] = ((m - r1.start + m + r2.start)/2) ; } } } } class Robot{ int dir; int index; int start; public Robot(int dir, int index, int start){this.index = index; this.start = start; this.dir = dir; } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
0e6a28b0b15f1e499e32724742100702
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import java.io.*; import java.util.*; public class A { static int n, m; static int[] x; static char[] d; public static void main(String[] args) throws IOException { f = new Flash(); out = new PrintWriter(System.out); int T = ni(); for(int tc = 1; tc <= T; tc++){ n = ni(); m = ni(); x = arr(n); d = new char[n]; for(int i = 0; i < n; i++) d[i] = next().charAt(0); fn(); } out.flush(); out.close(); } static void fn() { Node[] arr = new Node[n]; for(int i = 0; i < n; i++) { arr[i] = new Node(x[i], i, d[i]); } Arrays.sort(arr); Stack<Node>[] st = new Stack[2]; int[] ans = new int[n]; Arrays.fill(ans, -1); for(int i = 0; i < 2; i++) st[i] = new Stack<Node>(); for(Node N : arr) { int p = N.x%2; if(N.d == 'L') { if(st[p].isEmpty()) st[p].push(N); else { Node N2 = st[p].pop(); ans[N.idx] = ans[N2.idx] = (N.x - (N2.d == 'R' ? N2.x : -N2.x)) / 2; } } else st[p].push(N); } for(int i = 0; i < 2; i++) { while(st[i].size() > 1) { Node N = st[i].pop(), N2 = st[i].pop(); if(N2.d == 'R') ans[N.idx] = ans[N2.idx] = ((m-N.x) + (m-N2.x)) / 2; else ans[N.idx] = ans[N2.idx] = ((m-N.x) + N2.x + m) / 2; } } print(ans); } static class Node implements Comparable<Node>{ int x, idx; char d; Node(int x, int idx, char d){ this.x = x; this.idx = idx; this.d = d; } public int compareTo(Node n2) { return Integer.compare(x, n2.x); } } static Flash f; static PrintWriter out; static final long mod = (long)1e9+7; static final long inf = Long.MAX_VALUE; static final int _inf = Integer.MAX_VALUE; static final int maxN = (int)5e5+5; static long[] fact, inv; static void sort(int[] a){ List<Integer> A = new ArrayList<>(); for(int i : a) A.add(i); Collections.sort(A); for(int i = 0; i < A.size(); i++) a[i] = A.get(i); } static void sort(long[] a){ List<Long> A = new ArrayList<>(); for(long i : a) A.add(i); Collections.sort(A); for(int i = 0; i < A.size(); i++) a[i] = A.get(i); } static void print(int[] a){ StringBuilder sb = new StringBuilder(); for(int i = 0; i < a.length; i++) sb.append(a[i] + " "); sop(sb); } static void print(long[] a){ StringBuilder sb = new StringBuilder(); for(int i = 0; i < a.length; i++) sb.append(a[i] + " "); sop(sb); } static int swap(int itself, int dummy){return itself;} static long swap(long itself, long dummy){return itself;} static void sop(Object o){out.println(o);} static int ni(){return f.ni();} static long nl(){return f.nl();} static double nd(){return f.nd();} static String next(){return f.next();} static String ns(){return f.ns();} static char[] nc(){return f.nc();} static int[] arr(int len){return f.arr(len);} static int gcd(int a, int b){if(b == 0) return a; return gcd(b, a%b);} static long gcd(long a, long b){if(b == 0) return a; return gcd(b, a%b);} static int lcm(int a, int b){return (a*b)/gcd(a, b);} static long lcm(long a, long b){return (a*b)/gcd(a, b);} static class Flash { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next(){ while(!st.hasMoreTokens()){ try{ st = new StringTokenizer(br.readLine()); }catch(IOException e){ e.printStackTrace(); } } return st.nextToken(); } String ns(){ String s = new String(); try{ s = br.readLine().trim(); }catch(IOException e){ e.printStackTrace(); } return s; } int[] arr(int n){ int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = ni(); return a; } char[] nc(){return ns().toCharArray();} int ni(){return Integer.parseInt(next());} long nl(){return Long.parseLong(next());} double nd(){return Double.parseDouble(next());} } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
4530d4a10aca394b05977c8e16cd06d9
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
//------------------>>>>>>>>>>>>>>>> HI . HOW ARE YOU? <<<<<<<<<<<<<<<<<<<<<<<<<<<<<------------------------------ import java.util.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.List; import java.util.StringTokenizer; //---------------------------->>>>>>>>>>>>>>>>>>>>>> FK OFF <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<------------------- //--------------------------->>>>>>>>>>>>>>>>>>>>>>>> HACKER MF <<<<<<<<<<<<------------------------------------- public class practice{ static long[] count,count1,count2; static boolean[] prime; static int[] spf; static Node[] nodes,nodes1,nodes2; static long[] arr; static long[][] cost; static int[] arrInt,darrInt,farrInt; static long[][] dp; static char[] ch,ch1,ch2; static long[] darr,farr; static long[][] mat,mat1; static boolean[] vis; static long x,h; static long maxl,sum,total; static double dec; static long mx = (long)1e7; static long inf = (long)1e18; static String s,s1,s2,s3,s4; static long minl; static long mod = (long)1e9+7; // static int minl = -1; // static long n; static int n,n1,n2,q,r1,c1,r2,c2; static int arr_size = (int)2e5+10; static long a; static long b; static long c; static long d; static long y,z; static int m; static int ans; static long k; static FastScanner sc; static String[] str,str1; static Set<Long> set,set1,set2; static SortedSet<Long> ss; static List<Long> list,list1,list2,list3; static PriorityQueue<Node> pq,pq1; static LinkedList<Node> ll,ll1,ll2; static Map<Integer,List<Node>> map; static Map<Integer,Integer> map2; static Map<Integer,Node> map1; static StringBuilder sb,sb1,sb2; static int index; static int[] dx = {0,-1,0,1,-1,1,-1,1}; static int[] dy = {-1,0,1,0,-1,-1,1,1}; static class Node{ long first; char second; Node(long f,char s){ this.first = f; this.second = s; } } // public static void solve(){ // // FastScanner sc = new FastScanner(); // int t = sc.nextInt(); // // int t = 1; // for(int tt = 1 ; tt <= t ; tt++){ // //// int n = sc.nextInt(); //// arr = new long[n]; //// //// for(int i = 0 ; i < n ; i++){ //// arr[i] = sc.nextLong(); //// } // // System.out.println("Case #"+tt+": "+cost); // // } // // } //--------------->>>>IF YOU ARE HERE FOR QUICKSORT HACK THEN SORRY NO HACK FOR YOU<<<------------------------------ public static void solve(){ LinkedList<Long> oddL = new LinkedList<>(); LinkedList<Long> evenL = new LinkedList<>(); LinkedList<Long> evenR = new LinkedList<>(); LinkedList<Long> oddR = new LinkedList<>(); Arrays.sort(nodes, new Comparator<Node>() { @Override public int compare(Node a, Node b) { return Long.compare(a.first,b.first); } }); Map<Long,Long> map = new HashMap<>(); for(int i = 0 ; i < n ; i++){ Node node = nodes[i]; char dir = node.second; long pos = node.first; if(dir == 'R'){ if(pos%2 == 0) evenR.addLast(pos); else oddR.addLast(pos); } else{ if(pos%2 == 0){ if(evenR.isEmpty()) evenL.addLast(pos); else{ long num = evenR.removeLast(); long time = (pos-num)/2; map.put(num,time); map.put(pos,time); } } else{ if(oddR.isEmpty()) oddL.addLast(pos); else{ long num = oddR.removeLast(); long time = (pos-num)/2; map.put(num,time); map.put(pos,time); } } } } while(evenR.size() > 1){ long first = evenR.removeLast(); long second = evenR.removeLast(); long time = (abs(first-second))/2 + k-first; map.put(first,time); map.put(second,time); } while(oddR.size() > 1){ long first = oddR.removeLast(); long second = oddR.removeLast(); long time = (abs(first-second))/2 + k-first; map.put(first,time); map.put(second,time); } while(evenL.size() > 1){ long first = evenL.removeFirst(); long second = evenL.removeFirst(); long time = (abs(second-first))/2 + first; map.put(first,time); map.put(second,time); } while(oddL.size() > 1){ long first = oddL.removeFirst(); long second = oddL.removeFirst(); long time = (abs(second-first))/2+first; map.put(first,time); map.put(second,time); } while(evenR.size() > 0 && evenL.size() > 0){ long r = evenR.removeLast(); long l = evenL.removeFirst(); long time = l+k-r+(r-l)/2; map.put(l,time); map.put(r,time); } while(oddR.size() > 0 && oddL.size() > 0){ long r = oddR.removeLast(); long l = oddL.removeFirst(); long time = l+k-r+(r-l)/2; map.put(l,time); map.put(r,time); } for(int i = 0 ; i < n ; i++){ long num = arr[i]; if(map.containsKey(num)) sb.append(map.get(num)+" "); else sb.append("-1 "); } sb.append("\n"); } //----------->>>>>>> SPEED UP SPEED UP . THIS IS SPEEDFORCES . SPEED UP SPEEEEEEEEEEEEEEEEEEEEEEEEEEDDDDDD <<<<<<<------------------ public static void main(String[] args) { sc = new FastScanner(); // Scanner sc = new Scanner(System.in); sb = new StringBuilder(); int t = sc.nextInt(); // int t = 1; while(t > 0){ // k = sc.nextLong(); // x = sc.nextLong(); // y = sc.nextLong(); // z = sc.nextLong(); // a = sc.nextLong(); // b = sc.nextLong(); // c = sc.nextLong(); // d = sc.nextLong(); // x = sc.nextLong(); // y = sc.nextLong(); // z = sc.nextLong(); // d = sc.nextLong(); n = sc.nextInt(); // n1 = sc.nextInt(); // m = sc.nextInt(); // q = sc.nextInt(); // a = sc.nextLong(); // b = sc.nextLong(); k = sc.nextLong(); // x = sc.nextLong(); // d = sc.nextLong(); // s = sc.next(); // ch = sc.next().toCharArray(); // ch1 = sc.next().toCharArray(); // m = sc.nextInt(); // n = 6; arr = new long[n]; for(int i = 0 ; i < n ; i++){ arr[i] = sc.nextLong(); } // arrInt = new int[n]; // for(int i = 0 ; i < n ; i++){ // arrInt[i] = sc.nextInt(); // } // x = sc.nextLong(); // y = sc.nextLong(); // ch = sc.next().toCharArray(); // m = n; //// m = sc.nextInt(); // darr = new long[m]; // for(int i = 0 ; i < m ; i++){ // darr[i] = sc.nextLong(); // } // k = sc.nextLong(); // m = n; // darrInt = new int[n]; // for(int i = 0 ; i < n ; i++){ // darrInt[i] = sc.nextInt(); // } // farr = new long[m]; // for(int i = 0 ; i < m ; i++){ // farr[i] = sc.nextLong(); // } // farrInt = new int[m]; // for(int i = 0; i < m ; i++){ // farrInt[i] = sc.nextInt(); // } // m = n; // mat = new long[n+1][m+1]; // for(int i = 1 ; i <= n ; i++){ // for(int j = 1 ; j <= m ; j++){ // mat[i][j] = sc.nextLong(); // } // } // m = n; // mat = new char[n][m]; // for(int i = 0 ; i < n ; i++){ // String s = sc.next(); // for(int j = 0 ; j < m ; j++){ // mat[i][j] = s.charAt(j); // } // } // str = new String[n]; // for(int i = 0 ; i < n ; i++) // str[i] = sc.next(); nodes = new Node[n]; for(int i = 0 ; i < n ;i++) nodes[i] = new Node(arr[i],sc.next().charAt(0)); solve(); t -= 1; } System.out.print(sb); } public static int log(double n,double base){ if(n == 0 || n == 1) return 0; if(n == base) return 1; double num = Math.log(n); double den = Math.log(base); if(den == 0) return 0; return (int)(num/den); } public static boolean isPrime(long n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n%2 == 0 || n%3 == 0) return false; for (int i=5; i*i<=n; i=i+6) if (n%i == 0 || n%(i+2) == 0) return false; return true; } public static void SpecialSieve(int MAXN) { spf = new int[MAXN]; spf[1] = 1; for (int i=2; i<MAXN; i++) // marking smallest prime factor for every // number to be itself. spf[i] = i; // separately marking spf for every even // number as 2 for (int i=4; i<MAXN; i+=2) spf[i] = 2; for (int i=3; i*i<MAXN; i++) { // checking if i is prime if (spf[i] == i) { // marking SPF for all numbers divisible by i for (int j=i*i; j<MAXN; j+=i) // marking spf[j] if it is not // previously marked if (spf[j]==j) spf[j] = i; } } } public static ArrayList<Integer> getFactorization(int x) { ArrayList<Integer> ret = new ArrayList<Integer>(); while (x != 1) { ret.add(spf[x]); x = x / spf[x]; } return ret; } public static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } public static long lcm(long a, long b) { return (b/gcd(b, a % b)) * a; } public static long mod_inverse(long a,long mod){ long x1=1,x2=0; long p=mod,q,t; while(a%p!=0){ q = a/p; t = x1-q*x2; x1=x2; x2=t; t=a%p; a=p; p=t; } return x2<0 ? x2+mod : x2; } public static void swap(int[] curr,int i,int j){ int temp = curr[j]; curr[j] = curr[i]; curr[i] = temp; } static final Random random=new Random(); static void ruffleSortLong(long[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n); long temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static void ruffleSortInt(int[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n); int temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static void ruffleSortChar(char[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n); char temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static long binomialCoeff(long n, long k){ long res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate value of // [n * (n-1) *---* (n-k+1)] / [k * (k-1) *----* 1] for (long i = 0; i < k; ++i) { res = (res*(n - i)); res = (res/(i + 1)); } return res; } static long mod(long x) { long y = mod; long result = x % y; if (result < 0) { result += y; } return result; } static long[] fact; public static long inv(long n){ return power(n, mod-2); } public static void fact(int n){ fact = new long[n+1]; fact[0] = 1; for(int j = 1;j<=n;j++) fact[j] = (fact[j-1]*(long)j)%mod; } public static long binom(int n, int k){ long prod = fact[n]; prod*=inv(fact[n-k]); prod%=mod; prod*=inv(fact[k]); prod%=mod; return prod; } static long power(long x, long y){ if (y == 0) return 1; if (y%2 == 1) return (x*power(x, y-1))%mod; return power((x*x)%mod, y/2)%mod; } static void sieve(int n){ prime = new boolean[n+1]; for(int i=2;i<n;i++) prime[i] = true; for(int p = 2; p*p <=n; p++) { if(prime[p]) { for(int i = p*p; i <= n; i += p) prime[i] = false; } } } static long abs(long a){ return Math.abs(a); } static int abs(int a){ return Math.abs(a); } static int max(int a,int b){ if(a>b) return a; else return b; } static double max(double a,double b){ if(a>b) return a; else return b; } static double min(double a,double b){ if(a>b) return b; else return a; } static int min(int a,int b){ if(a>b) return b; else return a; } static long max(long a,long b){ if(a>b) return a; else return b; } static long min(long a,long b){ if(a>b) return b; else return a; } static long sq(long num){ return num*num; } static double sq(double num){ return num*num; } static long sqrt(long num){ return (long)Math.sqrt(num); } static double sqrt(double num){ return Math.sqrt(num); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } void readArray(int n) { arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = nextLong(); } long nextLong() { return Long.parseLong(next()); } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
2870351ff8b0b1a568494d8bc56ed807
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.util.*; public class GOOD_bot_collisions { public static void solve(List<Robot> v, int[] ans, int m) { Stack<Robot> stk = new Stack<>(); for (Robot r: v) { if (r.dir == -1) { if (stk.isEmpty()) { stk.push(r); } else { Robot r2 = stk.pop(); if (r2.dir == 1) { ans[r.id] = (r.x - r2.x) / 2; ans[r2.id] = (r.x - r2.x) / 2; } else { ans[r.id] = (r.x + r2.x) / 2; ans[r2.id] = (r.x + r2.x) / 2; } } } else { stk.push(r); } } while (stk.size() >= 2) { Robot r = stk.pop(); Robot r2 = stk.pop(); if (r2.dir == 1) { ans[r.id] = (m - r.x + m - r2.x) / 2; ans[r2.id] = (m - r.x + m - r2.x) / 2; } else { ans[r.id] = (m - r.x + m + r2.x) / 2; ans[r2.id] = (m - r.x + m + r2.x) / 2; } } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int m = sc.nextInt(); int[] pos = new int[n]; String[] dir = new String[n]; for (int i = 0; i < n; i++) pos[i] = sc.nextInt(); for (int i = 0; i < n; i++) dir[i] = sc.next(); Robot[] robots = new Robot[n]; for (int i = 0; i < n; i++) { robots[i] = new Robot(pos[i], dir[i].equals("R") ? 1 : -1, i); } Arrays.sort(robots, (a, b) -> a.x - b.x); List<Robot> e = new ArrayList<>(); List<Robot> o = new ArrayList<>(); for (int i=0 ; i<robots.length ; i++) { if (robots[i].x % 2 == 0) { e.add(robots[i]); } else { o.add(robots[i]); } } int[] ans = new int[n]; for (int i = 0; i < n; i++) { ans[i] = -1; } solve(e, ans, m); solve(o, ans, m); for (int i = 0; i < n; i++) System.out.print(ans[i] + " "); System.out.println(""); } } } class Robot { int x, dir, id; Robot(int x, int dir, int id) { this.x = x; this.dir = dir; this.id = id; } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
9985220218102714c9ee06619da663f7
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.io.*; import java.util.*; public class C implements Runnable { void solve() throws IOException { int t = ri(); while (t-- > 0) { int n = ri(), limit = ri(); Node[] x = new Node[n]; for (int i = 0; i < n; i++) { x[i] = new Node(i, ri()); } for (int i = 0; i < n; i++) { x[i].setDir(rc()); } Arrays.sort(x, Comparator.comparingInt(o -> o.val)); Node[] ans = new Node[n]; ArrayDeque<Node> odd = new ArrayDeque<>(), even = new ArrayDeque<>(); for (Node curr : x) { if ((curr.val & 1) == 1) { // If it is odd if (curr.isLeft) { // It should destroy some other robot if possible if (!odd.isEmpty()) { Node opp = odd.pollLast(); ans[opp.index] = curr; ans[curr.index] = opp; }else odd.add(curr); } else { odd.add(curr); } } else { // If it is even if (curr.isLeft) { if (!even.isEmpty()) { Node opp = even.pollLast(); ans[opp.index] = curr; ans[curr.index] = opp; }else even.add(curr); } else { even.add(curr); } } } while (odd.size() >= 2) { Node first = odd.pollLast(); Node second = odd.pollLast(); ans[first.index] = second; ans[second.index] = first; } while (even.size() >= 2) { Node first = even.pollLast(); Node second = even.pollLast(); ans[first.index] = second; ans[second.index] = first; } int[] res = iArr(n); for (int i = 0; i < n; i++) { Node curr = x[i]; int ansIndex = curr.index; if (ans[curr.index] == null) { res[curr.index] = -1; } else { // We have the answer Node opp = ans[curr.index]; if (curr.val > opp.val) { Node temp = curr; curr = opp; opp = temp; } if (!curr.isLeft && opp.isLeft) { res[ansIndex] = (opp.val - curr.val) / 2; } else if (curr.isLeft && opp.isLeft) { res[ansIndex] = (opp.val + curr.val) / 2; } else if (!curr.isLeft && !opp.isLeft) { res[ansIndex] = (limit - curr.val + limit - opp.val) / 2; } else { res[ansIndex] = (limit + curr.val + limit - opp.val) / 2; } } } for (int i = 0; i < n; i++) { sbr.append(res[i]).append(" "); } println(sbr.toString()); sbr = new StringBuilder(); } } class Node { int index; int val; boolean isLeft; public Node(int x, int val) { index = x; this.val = val; } void setDir(char c) { isLeft = (c == 'L'); } } /************************************************************************************************************************************************/ public static void main(String[] args) throws IOException { new Thread(null, new C(), "1").start(); } static PrintWriter out = new PrintWriter(System.out); static Reader read = new Reader(); static StringBuilder sbr = new StringBuilder(); static int mod = (int) 1e9 + 7; static int dmax = Integer.MAX_VALUE; static long lmax = Long.MAX_VALUE; static int dmin = Integer.MIN_VALUE; static long lmin = Long.MIN_VALUE; @Override public void run() { try { solve(); out.close(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } static class Reader { private byte[] buf = new byte[1024]; private int index; private InputStream in; private int total; public Reader() { in = System.in; } public int scan() throws IOException { if (total < 0) throw new InputMismatchException(); if (index >= total) { index = 0; total = in.read(buf); if (total <= 0) return -1; } return buf[index++]; } public int intNext() throws IOException { int integer = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { integer *= 10; integer += n - '0'; n = scan(); } else throw new InputMismatchException(); } return neg * integer; } public double doubleNext() throws IOException { double doub = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n) && n != '.') { if (n >= '0' && n <= '9') { doub *= 10; doub += n - '0'; n = scan(); } else throw new InputMismatchException(); } if (n == '.') { n = scan(); double temp = 1; while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { temp /= 10; doub += (n - '0') * temp; n = scan(); } else throw new InputMismatchException(); } } return doub * neg; } public String read() throws IOException { StringBuilder sb = new StringBuilder(); int n = scan(); while (isWhiteSpace(n)) n = scan(); while (!isWhiteSpace(n)) { sb.append((char) n); n = scan(); } return sb.toString(); } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; return false; } } static void shuffle(int[] aa) { int n = aa.length; Random rand = new Random(); for (int i = 1; i < n; i++) { int j = rand.nextInt(i + 1); int tmp = aa[i]; aa[i] = aa[j]; aa[j] = tmp; } } static void shuffle(int[][] aa) { int n = aa.length; Random rand = new Random(); for (int i = 1; i < n; i++) { int j = rand.nextInt(i + 1); int first = aa[i][0]; int second = aa[i][1]; aa[i][0] = aa[j][0]; aa[i][1] = aa[j][1]; aa[j][0] = first; aa[j][1] = second; } } // Gives strict lowerBound that previous number would be smaller than the target int lowerBound(int[] arr, int val) { int l = 0, r = arr.length - 1; while (l < r) { int mid = (r + l) >> 1; if (arr[mid] >= val) { r = mid; } else l = mid + 1; } return l; } // Gives strict upperBound that next number would be greater than the target int upperBound(int[] arr, int val) { int l = 0, r = arr.length - 1; while (l < r) { int mid = (r + l + 1) >> 1; if (arr[mid] <= val) { l = mid; } else r = mid - 1; } return l; } static void print(Object object) { out.print(object); } static void println(Object object) { out.println(object); } static int[] iArr(int len) { return new int[len]; } static long[] lArr(int len) { return new long[len]; } static long min(long a, long b) { return Math.min(a, b); } static int min(int a, int b) { return Math.min(a, b); } static long max(Long a, Long b) { return Math.max(a, b); } static int max(int a, int b) { return Math.max(a, b); } static int ri() throws IOException { return read.intNext(); } static long rl() throws IOException { return Long.parseLong(read.read()); } static String rs() throws IOException { return read.read(); } static char rc() throws IOException { return rs().charAt(0); } static double rd() throws IOException { return read.doubleNext(); } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
a1b6dd090c775270edf1783e385bd82a
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
//package robotcollisions; import java.util.*; import java.io.*; public class robotcollosions { static int[] ans; static boolean[] v; static int m; public static void solve(int[][] robots) { //System.out.println("FUNCTION CALL"); TreeSet<int[]> left = new TreeSet<int[]>((a, b) -> a[0] - b[0]); TreeSet<int[]> right = new TreeSet<int[]>((a, b) -> a[0] - b[0]); for(int i = 0; i < robots.length; i++) { if(robots[i][1] == 0) { left.add(new int[] {robots[i][0], robots[i][2]}); } else { right.add(new int[] {robots[i][0], robots[i][2]}); } } //System.out.print("LEFT: "); // for(int[] i : left) { // //System.out.print("[" + i[0] + ", " + i[1] + "] "); // } //System.out.println(); //System.out.print("RIGHT: "); // for(int[] i : right) { // //System.out.print("[" + i[0] + ", " + i[1] + "] "); // } //System.out.println(); int[] pointer = new int[] {0, 0}; while(left.ceiling(pointer) != null) { pointer = left.ceiling(pointer); ////System.out.println(pointer[0] + " " + pointer[1]); if(right.floor(pointer) != null) { int[] next = right.floor(pointer); left.remove(pointer); right.remove(next); ans[pointer[1]] = (pointer[0] - next[0]) / 2; ans[next[1]] = (pointer[0] - next[0]) / 2; } else { pointer = new int[] {pointer[0] + 1, pointer[1]}; } } //System.out.println("REMAINING LEFT: " + left.size() + " REMAINING RIGHT: " + right.size()); while(left.size() > 1) { int[] a = left.pollFirst(); int[] b = left.pollFirst(); ans[a[1]] = (a[0] + b[0]) / 2; ans[b[1]] = (a[0] + b[0]) / 2; //System.out.println("LEFTWARDS: " + a[0] + " " + b[0] + " " + v.length); } while(right.size() > 1) { int[] a = right.pollLast(); int[] b = right.pollLast(); ans[a[1]] = ((m - a[0]) + (m - b[0])) / 2; ans[b[1]] = ((m - a[0]) + (m - b[0])) / 2; } if(left.size() == 1 && right.size() == 1) { int[] a = right.pollLast(); int[] b = left.pollFirst(); //System.out.println("FINAL CLAUSE: " + (m + (m - a[0])) + " " + b[0] + " " + a[0] + " " + b[0]); ans[a[1]] = (m + (m - a[0]) + b[0]) / 2; ans[b[1]] = (m + (m - a[0]) + b[0]) / 2; } //System.out.println(); } public static void main(String[] args) throws IOException { BufferedReader fin = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(fin.readLine()); StringBuilder fout = new StringBuilder(); while(t-- > 0) { StringTokenizer st = new StringTokenizer(fin.readLine()); int n = Integer.parseInt(st.nextToken()); m = Integer.parseInt(st.nextToken()); int[] nums = new int[n]; char[] directions = new char[n]; st = new StringTokenizer(fin.readLine()); StringTokenizer st2 = new StringTokenizer(fin.readLine()); int numEven = 0; for(int i = 0; i < n; i++) { nums[i] = Integer.parseInt(st.nextToken()); directions[i] = st2.nextToken().charAt(0); if(nums[i] % 2 == 0) { numEven ++; } } ans = new int[n]; v = new boolean[n]; Arrays.fill(ans, -1); int[][] next = new int[numEven][3]; //initial position, direction, id int pointer = 0; //System.out.print("INPUT EVEN: "); for(int i = 0; i < n; i++) { if(nums[i] % 2 == 0) { //System.out.print("{" + nums[i] + ", " + directions[i] + "} "); next[pointer][0] = nums[i]; next[pointer][1] = directions[i] == 'R'? 1 : 0; //1 for right, 0 for left next[pointer][2] = i; pointer ++; } } //System.out.println(); Arrays.sort(next, (a, b) -> a[0] - b[0]); solve(next); next = new int[n - numEven][3]; pointer = 0; //System.out.print("INPUT ODD: "); for(int i = 0; i < n; i++) { if(nums[i] % 2 == 1) { //System.out.print("{" + nums[i] + ", " + directions[i] + "} "); next[pointer][0] = nums[i]; next[pointer][1] = directions[i] == 'R'? 1 : 0; //1 for right, 0 for left next[pointer][2] = i; pointer ++; } } //System.out.println(); Arrays.sort(next, (a, b) -> a[0] - b[0]); solve(next); for(int i : ans) { fout.append(i).append(" "); } fout.append("\n"); ////System.out.print(fout);; } System.out.print(fout); } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
ed74a463f2c2542135e2f77bab164461
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
// Rohit Bohra | 18/05/2021 : 01:25:31 import java.io.*; import java.util.*; @SuppressWarnings("unchecked") public class C{ static int[] ans; static class Robot{ int id,x,dir; Robot(int id,int x,int dir){ this.id=id; this.x=x; this.dir=dir; } } public static void solve(Robot[] robots,int m){ Arrays.sort(robots,(a,b)->{ return a.x-b.x; }); int n=robots.length; Stack<Integer> rt = new Stack<>(); Queue<Integer> lq = new LinkedList<>(); for(int i=0;i<n;i++){ if(robots[i].dir==1) rt.add(i); else if(!rt.isEmpty()){ // right-left collision int j = rt.pop(); int time = (robots[i].x-robots[j].x)/2; ans[robots[i].id]=time; ans[robots[j].id]=time; }else{ lq.add(i); } } while(rt.size()>=2){ int i=rt.pop(); int j=rt.pop(); int time = (m-robots[i].x)+(robots[i].x-robots[j].x)/2; ans[robots[i].id]=time; ans[robots[j].id]=time; } while(lq.size()>=2){ int i=lq.poll(); int j=lq.poll(); int time = robots[i].x + (robots[j].x-robots[i].x)/2; // out.printf("C2 %d %d %d\n",i,j,time); ans[robots[i].id]=time; ans[robots[j].id]=time; } // 0 1 3 6 // 0 4 - 1 // 1 5 - 2 // 2 6 - 3 // 4 4 - 3+2=5 // 1+(6-3)+(3-1)/2 // 1+3+1 if(lq.size()==1 && rt.size()==1){ int l=lq.poll(); int r=rt.pop(); int time = robots[l].x+(m-robots[r].x)+(robots[r].x-robots[l].x)/2; ans[robots[l].id]=time; ans[robots[r].id]=time; } } public static void main(String args[])throws IOException{ int t=sc.nextInt(); while(t-->0){ int n=sc.nextInt(); int m=sc.nextInt(); int[] x = new int[n]; int cntOdd=0; for(int i=0;i<n;i++){ x[i]=sc.nextInt(); cntOdd += x[i]%2==0 ? 0 : 1; } Robot[] evenRobots = new Robot[n-cntOdd]; Robot[] oddRobots = new Robot[cntOdd]; int j=0,k=0; for(int i=0;i<n;i++){ int d = sc.next().equals("R") ? 1 : -1; if(x[i]%2==0){ evenRobots[j++] = new Robot(i,x[i],d); }else{ oddRobots[k++] = new Robot(i,x[i],d); } } ans = new int[n]; Arrays.fill(ans,-1); solve(evenRobots,m); solve(oddRobots,m); for(int a : ans){ out.print(a+" "); } out.println(); } out.close(); } static int M=(int)Math.pow(10,9)+7; public static void sort(int[] arr,boolean reverse){ ArrayList<Integer> list = new ArrayList<Integer>(); int n =arr.length; for(int i=0;i<n;i++){ list.add(arr[i]); } if(reverse) Collections.sort(list,Collections.reverseOrder()); else Collections.sort(list); for(int i=0;i<n;i++){ arr[i] = list.get(i); } } public static double min(double ...a){ double min=Double.MAX_VALUE; for(double i : a) min =Math.min(i,min); return min; } public static long min(long ...a){ long min=Long.MAX_VALUE; for(long i : a) min =Math.min(i,min); return min; } public static int min(int ...a){ int min=Integer.MAX_VALUE; for(int i : a) min =Math.min(i,min); return min; } public static double max(double ...a){ double max=Double.MIN_VALUE; for(double i : a) max =Math.max(i,max); return max; } public static long max(long ...a){ long max=Long.MIN_VALUE; for(long i : a) max =Math.max(i,max); return max; } public static int max(int ...a){ int max=Integer.MIN_VALUE; for(int i : a) max =Math.max(i,max); return max; } static class Pair{ // Implementing equals() and hashCode() // Map<Pair, V> map = //... private final int x; private final int y; public Pair(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Pair)) return false; Pair pair = (Pair) o; return x == pair.x && y == pair.y; } @Override public int hashCode() { int result = x; result = 31 * result + y; return result; } } static FastScanner sc = new FastScanner(); static PrintWriter out =new PrintWriter(System.out); static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } public long[] readLongArray(int n) { long[] a=new long[n]; for (int i=0; i<n; i++) a[i]=nextLong(); return a; } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
be7be79605806058e1fcf264c21a9d39
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.util.*; public class Robots { public static void main(String[] args) { Scanner in = new Scanner(System.in); StringBuffer out = new StringBuffer(); int t = in.nextInt(); while (t-- != 0) { int n = in.nextInt(), m = in.nextInt(); int x[] = new int[n]; for (int i = 0; i < n; i++) x[i] = in.nextInt(); HashMap<Integer, Character> map = new HashMap<>(); for (int i = 0; i < n; i++) map.put(x[i], in.next().charAt(0)); List<Integer> values[] = new ArrayList[2]; for (int i = 0; i < 2; i++) values[i] = new ArrayList<>(); for (int item : x) { values[item % 2].add(item); } HashMap<Integer, Integer> ans = new HashMap<>(); for (int i = 0; i < 2; i++) { Collections.sort(values[i]); // System.out.println(values[i]); LinkedList<Integer> left = new LinkedList<>(), right = new LinkedList<>(); for (int item : values[i]) { if (map.get(item) == 'L') { if (!right.isEmpty()) { int ant1 = right.pollLast(), ant2 = item; ans.put(ant1, Math.abs(ant1 - ant2) / 2); ans.put(ant2, Math.abs(ant1 - ant2) / 2); } else { left.add(item); } } else { right.add(item); } } // System.out.println(left + " " + right + " " + ans); while (left.size() >= 2) { int ant1 = left.pollFirst(), ant2 = left.pollFirst(); ans.put(ant1, ant1 + Math.abs(ant1 - ant2) / 2); ans.put(ant2, ant1 + Math.abs(ant1 - ant2) / 2); } // System.out.println(left + " " + right + " " + ans); while (right.size() >= 2) { int ant1 = right.pollLast(), ant2 = right.pollLast(); ans.put(ant1, (m - ant1) + Math.abs(ant1 - ant2) / 2); ans.put(ant2, (m - ant1) + Math.abs(ant1 - ant2) / 2); } // System.out.println(left + " " + right + " " + ans); if (left.size() == 1 && right.size() == 1) { int ant1 = left.poll(), ant2 = right.poll(); int min = Math.min(ant1, (m - ant2)); int max = Math.max(ant1, (m - ant2)); int diff = (ant2 + min) - (ant1 - min); ans.put(ant1, max + diff / 2); ans.put(ant2, max + diff / 2); } // System.out.println(left + " " + right + " " + ans); if (!left.isEmpty()) ans.put(left.poll(), -1); if (!right.isEmpty()) ans.put(right.poll(), -1); // System.out.println(left + " " + right + " " + ans); } for (int item : x) out.append(ans.get(item) + " "); out.append("\n"); } System.out.println(out); } private static int GCD(int a, int b) { if (a == 0) return b; return GCD(b % a, a); } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
2d03ff91b8d192849348fa9c4e7ec533
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.io.*; import java.util.*; public class Codeforces { public static void main(String args[])throws Exception { BufferedReader bu=new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb=new StringBuilder(); int t=Integer.parseInt(bu.readLine()); while(t-->0) { String s[]=bu.readLine().split(" "); int n=Integer.parseInt(s[0]),m=Integer.parseInt(s[1]); ArrayList<Robot> o=new ArrayList<>(),e=new ArrayList<>(); s=bu.readLine().split(" "); int i,a[]=new int[n]; for(i=0;i<n;i++) a[i]=Integer.parseInt(s[i]); s=bu.readLine().split(" "); for(i=0;i<n;i++) { int x=s[i].charAt(0); if(x=='L') x=1; else x=0; if(a[i]%2==0) e.add(new Robot(i,a[i],x)); else o.add(new Robot(i,a[i],x)); } long ans[]=new long[n]; fill(ans,e,m); fill(ans,o,m); for(i=0;i<n;i++) sb.append(ans[i]+" "); sb.append("\n"); } System.out.print(sb); } static void fill(long ans[],ArrayList<Robot> a,int m) { if(a.size()==0) return; Collections.sort(a, new Comparator<Robot>() { @Override public int compare(Robot o1, Robot o2) { if(o1.v>o2.v) return 1; else return -1; }}); Deque<Integer> dq=new LinkedList<>(),bad=new LinkedList<>(); int i; for(i=0;i<a.size();i++) if(a.get(i).t==0) dq.add(i); else { if(dq.isEmpty()) {bad.add(i); continue;} int x=dq.pollLast(); long d=a.get(i).v-a.get(x).v; d/=2; ans[a.get(i).i]=d; ans[a.get(x).i]=d; } int l=-1,r=-1; while(bad.size()>1) { int u=bad.removeFirst(),v=bad.removeFirst(); long d=a.get(v).v-a.get(u).v; d/=2; d+=a.get(u).v; ans[a.get(u).i]=d; ans[a.get(v).i]=d; } if(!bad.isEmpty()) l=bad.removeFirst(); while(dq.size()>1) { int u=dq.removeLast(),v=dq.removeLast(); long d=a.get(u).v-a.get(v).v; d/=2; d+=m-a.get(u).v; ans[a.get(u).i]=d; ans[a.get(v).i]=d; } if(!dq.isEmpty()) r=dq.removeFirst(); if(l!=-1 && r!=-1) { int max=Math.max(a.get(l).v,m-a.get(r).v); a.get(l).v-=max; a.get(r).v+=max; long d=max; a.get(l).v=Math.abs(a.get(l).v); if(a.get(r).v>m) a.get(r).v=2*m-a.get(r).v; d+=Math.abs(a.get(r).v-a.get(l).v)/2; ans[a.get(l).i]=d; ans[a.get(r).i]=d; } else { if(l!=-1) ans[a.get(l).i]=-1; if(r!=-1) ans[a.get(r).i]=-1; } } static class Robot { int i,v,t; Robot(int a,int b,int c) { i=a; v=b; t=c; } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
7466058a1ac53cc07948de37029650df
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.io.*; import java.util.*; /* 1 7 8 6 1 7 2 3 5 4 R L R L L L L */ public class P2 { static FastReader sc=null; static int ans[]; static int w; public static void main(String[] args) { sc=new FastReader(); PrintWriter out=new PrintWriter(System.out); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt();w=sc.nextInt(); ArrayList<Item> evens=new ArrayList<>(),odds=new ArrayList<>(); int a[]=sc.readArray(n); char dir[]=new char[n]; char line[]=sc.nextLine().toCharArray(); for(int i=0;i<n;i++)dir[i]=line[2*i]; ans=new int[n]; Arrays.fill(ans, -1); for(int i=0;i<n;i++) { Item p=new Item(a[i],dir[i],i); if(a[i]%2==0)evens.add(p); else odds.add(p); } solve(evens); solve(odds); for(int e:ans)out.print(e+" "); out.println(); } out.close(); } static void solve(ArrayList<Item> pos) { if(pos.size()==1) { return; } else if(pos.size()==2) { if(pos.get(0).dir!=pos.get(1).dir) { int time=2*w-Math.abs(pos.get(0).dist-pos.get(1).dist); ans[pos.get(0).id]=ans[pos.get(1).id]=time/2; return; } } ArrayDeque<Item> p=new ArrayDeque<>(); Collections.sort(pos,Collections.reverseOrder()); for(Item e:pos) { if(p.isEmpty() || e.dir=='L') { p.addFirst(e); } else { Item m=p.remove(); //m and e meet //if they are traveling in opp then time=(m.c-e.c)/2 //else time = (d2-d1)/2 [d -> distance from the wall] int time=0; if(m.dir!=e.dir)time=(Math.abs(m.c-e.c)/2); else time= Math.min(m.dist,e.dist)+Math.abs(m.dist-e.dist)/2; ans[m.id]=ans[e.id]=time; } } //TODO:GENERATE A SIMILAR PROCESS FOR THE LEFT MOVING CASE if(!p.isEmpty()) { ArrayList<Item>remains=new ArrayList<>(); for(Item e:p) { e.dir=(e.dir=='L'?'R':'L'); e.dist=e.c; e.c=w-e.c; remains.add(e); } solve(remains); } } static class Item implements Comparable<Item>{ int c,id,dist; char dir; Item(int c,char dir,int id){ this.c=c; this.dir=dir; this.id=id; this.dist=w-c; } public int compareTo(Item o) { return this.c-o.c; } @Override public String toString() { return "Item [c=" + c + ", dir=" + dir + "]"; } } static void reverseSort(int a[]) { ArrayList<Integer> al=new ArrayList<>(); for(int i:a)al.add(i); Collections.sort(al,Collections.reverseOrder()); for(int i=0;i<a.length;i++)a[i]=al.get(i); } static int gcd(int a,int b) { if(b==0)return a; else return gcd(b,a%b); } static long gcd(long a,long b) { if(b==0)return a; else return gcd(b,a%b); } static void reverse(int a[]) { int n=a.length; int b[]=new int[n]; for(int i=0;i<n;i++)b[i]=a[n-1-i]; for(int i=0;i<n;i++)a[i]=b[i]; } static void reverse(char a[]) { int n=a.length; char b[]=new char[n]; for(int i=0;i<n;i++)b[i]=a[n-1-i]; for(int i=0;i<n;i++)a[i]=b[i]; } static void ruffleSort(int a[]) { ArrayList<Integer> al=new ArrayList<>(); for(int i:a)al.add(i); Collections.sort(al); for(int i=0;i<a.length;i++)a[i]=al.get(i); } static void print(int a[]) { for(int e:a) { System.out.print(e+" "); } System.out.println(); } static void print(long a[]) { for(long e:a) { System.out.print(e+" "); } System.out.println(); } 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]=sc.nextInt(); } return a; } long[] readArrayL(int n) { long a[]=new long [n]; for(int i=0;i<n;i++) { a[i]=sc.nextLong(); } return a; } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
985f88cb254e7b2d9ef93bceac504630
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Codeforces { public static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main (String[] args) throws java.lang.Exception { // your code goes here FastReader sc=new FastReader(); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); int m=sc.nextInt(); int a[]=new int[n]; char c[]=new char[n]; int ans[]=new int[n]; for(int i=0;i<n;i++) { a[i]=sc.nextInt(); } for(int i=0;i<n;i++) { c[i]=sc.next().charAt(0); } for(int j=0;j<2;j++) { ArrayList<Integer> arr=new ArrayList<>(); for(int i=0;i<n;i++) { if(a[i]%2==j) arr.add(i); } Collections.sort(arr,(x,y)->Integer.compare(a[x],a[y])); Stack<Integer> st=new Stack<>(); for(int i:arr) { if(c[i]=='R') st.push(i); else if(c[i]=='L') { if(!st.isEmpty()) { int p=st.pop(); int mid=(a[p]+a[i])/2; ans[i]=Math.abs(mid-a[i]); ans[p]=Math.abs(mid-a[p]); } else { a[i]*=-1; st.push(i); } } } while(!st.isEmpty()) { if(st.size()==1) ans[st.pop()]=-1; else { int p=st.pop(); a[p]=2*m-a[p]; int q=st.pop(); int mid=(a[p]+a[q])/2; ans[p]=Math.abs(mid-a[p]); ans[q]=Math.abs(mid-a[q]); } } } StringBuffer sb=new StringBuffer(); for(int i=0;i<n;i++) { sb.append(ans[i]+" "); } System.out.println(sb.toString()); } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
19dd59a0d1ae1c37158c0597253e0e2c
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.io.DataInputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.PriorityQueue; public class Main { private static void run() throws IOException { int n = in.nextInt(); int m = in.nextInt(); Node[] nodes = new Node[n]; int count_even = 0; for (int i = 0; i < n; i++) { nodes[i] = new Node(i); nodes[i].pos = in.nextInt(); if ((nodes[i].pos & 1) == 0) { count_even++; } } for (int i = 0; i < n; i++) { nodes[i].right = in.nc() == 'R'; } Arrays.sort(nodes, Comparator.comparingInt((Node o) -> o.pos % 2).thenComparingInt(o -> o.pos)); solve(nodes, 0, count_even - 1, m); solve(nodes, count_even, n - 1, m); Arrays.sort(nodes, Comparator.comparingInt(o -> o.index)); for (int i = 0; i < n; i++) { out.printf("%d ", nodes[i].ans); } out.println(); } private static void solve(Node[] nodes, int left, int right, int m) { if (left > right) return; PriorityQueue<Node> queue = new PriorityQueue<>(Comparator.comparingInt(o -> o.pos_if_force_left)); for (int now = right; now >= left; now--) { if (!nodes[now].right) { nodes[now].pos_if_force_left = nodes[now].pos; queue.add(nodes[now]); } else { Node right_node = queue.poll(); if (right_node == null) { nodes[now].pos_if_force_left = m + m - nodes[now].pos; queue.add(nodes[now]); } else { right_node.ans = nodes[now].ans = (right_node.pos_if_force_left - nodes[now].pos) / 2; } } } while (true) { Node left_node = queue.poll(); Node right_node = queue.poll(); if (left_node == null || right_node == null) { break; } left_node.ans = right_node.ans = (right_node.pos_if_force_left + left_node.pos_if_force_left) / 2; } } static class Node { int index; int pos, pos_if_force_left; boolean right; int ans = -1; public Node(int index) { this.index = index; } } public static void main(String[] args) throws IOException { in = new Reader(); out = new PrintWriter(new OutputStreamWriter(System.out)); int t = in.nextInt(); for (int i = 0; i < t; i++) { run(); } out.flush(); in.close(); out.close(); } private static int gcd(int a, int b) { if (a == 0 || b == 0) return 0; while (b != 0) { int tmp; tmp = a % b; a = b; b = tmp; } return a; } static final long mod = 1000000007; static long pow_mod(long a, long b) { long result = 1; while (b != 0) { if ((b & 1) != 0) result = (result * a) % mod; a = (a * a) % mod; b >>= 1; } return result; } private static long multiplied_mod(long... longs) { long ans = 1; for (long now : longs) { ans = (ans * now) % mod; } return ans; } @SuppressWarnings("FieldCanBeLocal") private static Reader in; private static PrintWriter out; private static int[] read_int_array(int len) throws IOException { int[] a = new int[len]; for (int i = 0; i < len; i++) { a[i] = in.nextInt(); } return a; } private static long[] read_long_array(int len) throws IOException { long[] a = new long[len]; for (int i = 0; i < len; i++) { a[i] = in.nextLong(); } return a; } private static void print_array(int[] array) { for (int now : array) { out.print(now); out.print(' '); } out.println(); } private static void print_array(long[] array) { for (long now : array) { out.print(now); out.print(' '); } out.println(); } static class Reader { private static final int BUFFER_SIZE = 1 << 16; private final DataInputStream din; private final byte[] buffer; private int bufferPointer, bytesRead; Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { final byte[] buf = new byte[1024]; // 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 nextSign() throws IOException { byte c = read(); while ('+' != c && '-' != c) { c = read(); } return '+' == c ? 0 : 1; } private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } public int skip() throws IOException { int b; // noinspection ALL while ((b = read()) != -1 && isSpaceChar(b)) { ; } return b; } public char nc() throws IOException { return (char) skip(); } public String next() throws IOException { int b = skip(); final StringBuilder sb = new StringBuilder(); while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = read(); } return sb.toString(); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') { c = read(); } final boolean neg = c == '-'; if (neg) { c = read(); } do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) { return -ret; } return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') { c = read(); } final boolean neg = c == '-'; if (neg) { c = read(); } do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) { return -ret; } return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') { c = read(); } final boolean neg = c == '-'; if (neg) { c = read(); } do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) { return -ret; } return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) { buffer[0] = -1; } } private byte read() throws IOException { if (bufferPointer == bytesRead) { fillBuffer(); } return buffer[bufferPointer++]; } public void close() throws IOException { din.close(); } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
d57379b27941fe8447cf5ce2f75cf35f
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.util.*; import java.io.*; import static java.lang.Math.*; public class Main { static MyScanner scan; static PrintWriter pw; static long MOD = 1_000_000_007; static long INF = 2_000_000_000_000_000_000L; static long inf = 2_000_000_000; public static void main(String[] args) { new Thread(null, null, "_", 1 << 27) { public void run() { try { solve(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } }.start(); } static int n, m, ans[]; static void solve() throws java.lang.Exception { //initIo(true, ""); initIo(false, ""); StringBuilder sb = new StringBuilder(); int t = ni(); while (t-->0) { n = ni(); m = ni(); int pos[] = new int[n]; ans = new int[n]; Arrays.fill(ans, -1); ArrayList<Point> even = new ArrayList<>(); ArrayList<Point> odd = new ArrayList<>(); for(int i=0;i<n;i++) { pos[i] = ni(); } for(int i=0;i<n;i++) { char orn = ne().charAt(0); if(pos[i]%2==0) { even.add(new Point(pos[i], i, orn)); } else { odd.add(new Point(pos[i], i, orn)); } } Collections.sort(even); Collections.sort(odd); solve(even); solve(odd); for(int e : ans) { p(e); } pl(); } pw.flush(); pw.close(); } static void solve(ArrayList<Point> list) { Stack<Point> st = new Stack<>(); for(Point p : list) { if(p.orn==0) { if(st.isEmpty()) { st.push(p); } else if(st.peek().orn==1) { Point right = st.pop(); ans[right.idx] = ans[p.idx] = (p.pos - right.pos) / 2; } else { st.push(p); } } else { st.push(p); } } LinkedList<Point> right = new LinkedList<>(); LinkedList<Point> left = new LinkedList<>(); while(!st.isEmpty()) { Point p = st.pop(); if(p.orn == 1) { right.addFirst(p); } else { left.addFirst(p); } } // pa("right left", right); // pa("left left", left); while(right.size()>1) { Point p1 = right.pollLast(), p2 = right.pollLast(); ans[p1.idx] = ans[p2.idx] = (m - p1.pos) + ((p1.pos - p2.pos)/2); } while (left.size()>1) { Point p1 = left.pollFirst(), p2 = left.pollFirst(); ans[p1.idx] = ans[p2.idx] = p1.pos + ((p2.pos - p1.pos)/2); } if(left.size()==1 && right.size()==1) { Point p1 = left.pollFirst(), p2 = right.pollFirst(); ans[p1.idx] = ans[p2.idx] = (2*m - (p2.pos - p1.pos))/2; } } static class Point implements Comparable<Point> { int pos, idx, orn; Point(int pos, int idx, char orn) { this.pos = pos; this.idx = idx; this.orn = (orn == 'L' ? 0 : 1); } public int compareTo(Point other) { if(this.pos != other.pos) { return this.pos - other.pos; } return this.idx - other.idx; } public String toString() { return "{"+this.pos+","+this.idx+","+this.orn+"}"; } } static void assert_in_range(String varName, int n, int l, int r) { if (n >=l && n<=r) return; System.out.println(varName + " is not in range. Actual: "+n+" l : "+l+" r: "+r); System.exit(1); } static void assert_in_range(String varName, long n, long l, long r) { if (n>=l && n<=r) return; System.out.println(varName + " is not in range. Actual: "+n+" l : "+l+" r: "+r); System.exit(1); } static void initIo(boolean isFileIO, String suffix) throws IOException { scan = new MyScanner(isFileIO, suffix); if(isFileIO) { pw = new PrintWriter("/Users/dsds/Desktop/output"+suffix+".txt"); } else { pw = new PrintWriter(System.out, true); } } static int ni() throws IOException { return scan.nextInt(); } static long nl() throws IOException { return scan.nextLong(); } static double nd() throws IOException { return scan.nextDouble(); } static String ne() throws IOException { return scan.next(); } static String nel() throws IOException { return scan.nextLine(); } static void pl() { pw.println(); } static void p(Object o) { pw.print(o+" "); } static void pl(Object o) { pw.println(o); } static void psb(StringBuilder sb) { pw.print(sb); } static void pa(String arrayName, Object arr[]) { pl(arrayName+" : "); for(Object o : arr) p(o); pl(); } static void pa(String arrayName, int arr[]) { pl(arrayName+" : "); for(int o : arr) p(o); pl(); } static void pa(String arrayName, long arr[]) { pl(arrayName+" : "); for(long o : arr) p(o); pl(); } static void pa(String arrayName, double arr[]) { pl(arrayName+" : "); for(double o : arr) p(o); pl(); } static void pa(String arrayName, char arr[]) { pl(arrayName+" : "); for(char o : arr) p(o); pl(); } static void pa(String arrayName, TreeSet<Integer> set) { pl(arrayName+" : "); for(Object o : set) p(o); pl(); } static void pa(String arrayName, boolean arr[]) { pl(arrayName+" : "); for(boolean o : arr) p(o); pl(); } static void pa(String listName, List list) { pl(listName+" : "); for(Object o : list) p(o); pl(); } static void pa(String arrayName, Object[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(Object o : arr[i]) p(o); pl(); } } static void pa(String arrayName, int[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(int o : arr[i]) p(o); pl(); } } static void pa(String arrayName, long[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(long o : arr[i]) p(o); pl(); } } static void pa(String arrayName, char[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(char o : arr[i]) p(o); pl(); } } static void pa(String arrayName, double[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(double o : arr[i]) p(o); pl(); } } static void pa(String arrayName, boolean[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(boolean o : arr[i]) p(o); pl(); } } static class MyScanner { BufferedReader br; StringTokenizer st; MyScanner(boolean readingFromFile, String suffix) throws IOException { if(readingFromFile) { br = new BufferedReader(new FileReader("/Users/ddfds/Desktop/input"+suffix+".txt")); } else { br = new BufferedReader(new InputStreamReader(System.in)); } } String nextLine()throws IOException { return br.readLine(); } String next() throws IOException { if(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()); } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
b661beab42c8bd1ccd451bf56eca9251
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class A{ 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; } } static int __gcd(int a, int b) { if (b == 0) return a; return __gcd(b, a % b); } static int mul(int a,int b){ return (a*b)%mod; } static int add(int a,int b){ return (a+b)%mod; } static int nC2(int n){ return mul(n,n-1)/2; } static int mod = (int)(1e9)+7; public static void main(String args[]){ FastReader sc = new FastReader(); PrintWriter out = new PrintWriter(System.out); int t = sc.nextInt(); while(t-->0){ int n = sc.nextInt(); int m = sc.nextInt(); int[][] robot = new int[n][4]; int[] dir = new int[n]; for(int i=0;i<n;i++){ robot[i][0] = sc.nextInt(); robot[i][2] = i; } String inp = sc.nextLine(); //System.out.println(inp); for(int i=0;i<2*n;i+=2){ robot[i/2][1] = (inp.charAt(i) == 'L')?-1:1; } Arrays.sort(robot, Comparator.comparingInt(a -> a[0])); Stack<int[]> evenXStack = new Stack<>(); Stack<int[]> oddXStack = new Stack<>(); int[] collidingTimes = new int[n]; Arrays.fill(collidingTimes,-1); for(int i=0;i<n;i++){ if(robot[i][0]%2 == 0) { if (robot[i][1] == -1) { if (!evenXStack.isEmpty()) { int[] collidingRobotX = evenXStack.pop(); int time = (robot[i][0]-collidingRobotX[0])/2; collidingTimes[robot[i][2]] = time; collidingTimes[robot[collidingRobotX[2]][2]] = time; robot[i][3] = 1; robot[collidingRobotX[2]][3] = 1; } } else{ evenXStack.add(new int[]{robot[i][0],robot[i][2],i}); } } else{ if (robot[i][1] == -1) { if (!oddXStack.isEmpty()) { int[] collidingRobotX = oddXStack.pop(); int time = (robot[i][0]-collidingRobotX[0])/2; collidingTimes[robot[i][2]] = time; collidingTimes[robot[collidingRobotX[2]][2]] = time; robot[i][3] = 1; robot[collidingRobotX[2]][3] = 1; } } else{ oddXStack.add(new int[]{robot[i][0],robot[i][2],i}); } } } evenXStack.clear(); oddXStack.clear(); for(int i=n-1;i>=0;i--){ if(robot[i][3] != 1 && robot[i][1] == 1){ if(robot[i][0]%2 == 0) { if (!evenXStack.isEmpty()) { int[] collidingRobotX = evenXStack.pop(); int time = (robot[i][0]-collidingRobotX[0])/2 + m-robot[i][0]; collidingTimes[robot[i][2]] = time; collidingTimes[robot[collidingRobotX[2]][2]] = time; robot[i][3] = 1; robot[collidingRobotX[2]][3] = 1; } else{ evenXStack.add(new int[]{robot[i][0],robot[i][2],i}); } } else{ if (!oddXStack.isEmpty()) { int[] collidingRobotX = oddXStack.pop(); int time = (robot[i][0]-collidingRobotX[0])/2 + m-robot[i][0]; collidingTimes[robot[i][2]] = time; collidingTimes[robot[collidingRobotX[2]][2]] = time; robot[i][3] = 1; robot[collidingRobotX[2]][3] = 1; } else{ oddXStack.add(new int[]{robot[i][0],robot[i][2],i}); } } } } evenXStack.clear(); oddXStack.clear(); for(int i=0;i<n;i++){ if(robot[i][3] != 1 && robot[i][1] == -1){ if(robot[i][0]%2 == 0) { if (!evenXStack.isEmpty()) { int[] collidingRobotX = evenXStack.pop(); int time = (robot[i][0]-collidingRobotX[0])/2 + collidingRobotX[0]; collidingTimes[robot[i][2]] = time; collidingTimes[robot[collidingRobotX[2]][2]] = time; robot[i][3] = 1; robot[collidingRobotX[2]][3] = 1; } else{ evenXStack.add(new int[]{robot[i][0],robot[i][2],i}); } } else{ if (!oddXStack.isEmpty()) { int[] collidingRobotX = oddXStack.pop(); int time = (robot[i][0]-collidingRobotX[0])/2 + collidingRobotX[0]; collidingTimes[robot[i][2]] = time; collidingTimes[robot[collidingRobotX[2]][2]] = time; robot[i][3] = 1; robot[collidingRobotX[2]][3] = 1; } else{ oddXStack.add(new int[]{robot[i][0],robot[i][2],i}); } } } } evenXStack.clear(); oddXStack.clear(); for(int i=0;i<n;i++){ if(robot[i][3] == 1) continue; if(robot[i][0]%2 == 0) { if (robot[i][1] == 1) { if (!evenXStack.isEmpty()) { int[] collidingRobotX = evenXStack.pop(); int time = (robot[i][0]-collidingRobotX[0])/2 + collidingRobotX[0] + m-robot[i][0]; collidingTimes[robot[i][2]] = time; collidingTimes[robot[collidingRobotX[2]][2]] = time; robot[i][3] = 1; robot[collidingRobotX[2]][3] = 1; } } else{ evenXStack.add(new int[]{robot[i][0],robot[i][2],i}); } } else{ if (robot[i][1] == 1) { if (!oddXStack.isEmpty()) { int[] collidingRobotX = oddXStack.pop(); int time = (robot[i][0]-collidingRobotX[0])/2 + collidingRobotX[0] + m-robot[i][0];; collidingTimes[robot[i][2]] = time; collidingTimes[robot[collidingRobotX[2]][2]] = time; robot[i][3] = 1; robot[collidingRobotX[2]][3] = 1; } } else{ oddXStack.add(new int[]{robot[i][0],robot[i][2],i}); } } } for(int i:collidingTimes){ out.print(i+" "); } out.println(); } out.close(); } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
bcd6e27c170a2a2b840fd926408bad48
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.util.*; import java.io.*; public class _109 { static long m; static long [] res; public static void main(String[] args) { MyScanner sc = new MyScanner(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); m = sc.nextLong(); // solve problem on evens and odds separately long [] p = new long[n]; for (int i = 0; i < n; i++) p[i] = sc.nextInt(); char [] d = new char[n]; for (int i = 0; i < n; i++) d[i] = sc.next().equals("L") ? 'L' : 'R'; ArrayList<Pair> even = new ArrayList<>(); ArrayList<Pair> odd = new ArrayList<>(); for (int i = 0; i < n; i++) { if (p[i] % 2 == 0) { even.add(new Pair(p[i], d[i], i)); } else { odd.add(new Pair(p[i], d[i], i)); } } res = new long[n]; Collections.sort(even, Comparator.comparingLong(x -> x.pos)); Collections.sort(odd, Comparator.comparingLong(x -> x.pos)); solve(even); solve(odd); for (int i = 0; i < n; i++) out.print(res[i] + " "); out.println(); } out.close(); } static void solve(ArrayList<Pair> a) { ArrayDeque<Pair> b = new ArrayDeque<>(); int sz = a.size(); ArrayDeque<Pair> left = new ArrayDeque<>(); for (int i = 0; i < sz; i++) { if (a.get(i).dir == 'R') { b.add(a.get(i)); } else { if (b.size() > 0) { Pair last = b.pollLast(); long ans = (a.get(i).pos - last.pos) / 2; res[last.i] = ans; res[a.get(i).i] = ans; } else { left.add(a.get(i)); } } } while (b.size() >= 2) { Pair second = b.pollLast(); Pair first = b.pollLast(); long to = m - second.pos; long get = first.pos + to; long finish = (m - get) / 2; res[second.i] = res[first.i] = to + finish; } while (left.size() >= 2) { Pair first = left.pollFirst(); Pair second = left.pollFirst(); long to = first.pos; long get = second.pos - to; long finish = get / 2; res[second.i] = res[first.i] = to + finish; } if (left.size() + b.size() == 2) { Pair second = b.pollFirst(); Pair first = left.pollFirst(); long firstPos = first.pos; long secondPos = second.pos; if (firstPos <= m - secondPos) { long f = m - secondPos - firstPos; long time = m - secondPos; time += (m - f) / 2; res[second.i] = res[first.i] = time; } else { long s = m - (firstPos - (m - secondPos)); long time = firstPos; time += s / 2; res[second.i] = res[first.i] = time; } } else { if (left.size() > 0) { Pair last = left.pollLast(); res[last.i] = -1; } if (b.size() > 0) { Pair last = b.pollLast(); res[last.i] = -1; } } } static class Pair { long pos; char dir; int i; Pair(long pos, char dir, int i) { this.pos = pos; this.dir = dir; this.i = i; } } static void sort(int[] a) { ArrayList<Integer> q = new ArrayList<>(); for (int i : a) q.add(i); Collections.sort(q); for (int i = 0; i < a.length; i++) a[i] = q.get(i); } static void sort(long[] a) { ArrayList<Long> q = new ArrayList<>(); for (long i : a) q.add(i); Collections.sort(q); for (int i = 0; i < a.length; i++) a[i] = q.get(i); } //-----------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\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
8cdaa7853f8cce2f41066ec8755b56ae
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.io.*; import java.util.*; import javax.swing.text.DefaultStyledDocument.ElementSpec; /** __ __ ( _) ( _) / / \\ / /\_\_ / / \\ / / | \ \ / / \\ / / |\ \ \ / / , \ , / / /| \ \ / / |\_ /| / / / \ \_\ / / |\/ _ '_| \ / / / \ \\ | / |/ 0 \0\ / | | \ \\ | |\| \_\_ / / | \ \\ | | |/ \.\ o\o) / \ | \\ \ | /\\`v-v / | | \\ | \/ /_| \\_| / | | \ \\ | | /__/_ `-` / _____ | | \ \\ \| [__] \_/ |_________ \ | \ () / [___] ( \ \ |\ | | // | [___] |\| \| / |/ /| [____] \ |/\ / / || ( \ [____ / ) _\ \ \ \| | || \ \ [_____| / / __/ \ / / // | \ [_____/ / / \ | \/ // | / '----| /=\____ _/ | / // __ / / | / ___/ _/\ \ | || (/-(/-\) / \ (/\/\)/ | / | / (/\/\) / / // _________/ / / \____________/ ( @author NTUDragons-Reborn */ public class A{ public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(in, out); out.close(); } // main solver static class Task{ double eps= 0.00000001; static final int MAXN = 10000001; // stores smallest prime factor for every number static int spf[] = new int[MAXN]; Map<Integer,Set<Integer>> dp= new HashMap<>(); // Calculating SPF (Smallest Prime Factor) for every // number till MAXN. // Time Complexity : O(nloglogn) public void sieve() { spf[1] = 1; for (int i=2; i<MAXN; i++) // marking smallest prime factor for every // number to be itself. spf[i] = i; // separately marking spf for every even // number as 2 for (int i=4; i<MAXN; i+=2) spf[i] = 2; for (int i=3; i*i<MAXN; i++) { // checking if i is prime if (spf[i] == i) { // marking SPF for all numbers divisible by i for (int j=i*i; j<MAXN; j+=i) // marking spf[j] if it is not // previously marked if (spf[j]==j) spf[j] = i; } } } // A O(log n) function returning primefactorization // by dividing by smallest prime factor at every step public Set<Integer> getFactorization(int x) { if(dp.containsKey(x)) return dp.get(x); Set<Integer> ret = new HashSet<>(); while (x != 1) { if(spf[x]!=2) ret.add(spf[x]); x = x / spf[x]; } dp.put(x,ret); return ret; } // function to find first index >= x public int lowerIndex(List<Integer> arr, int n, int x) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr.get(mid) >= x) h = mid - 1; else l = mid + 1; } return l; } // function to find last index <= y public int upperIndex(List<Integer> arr, int n, int y) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr.get(mid) <= y) l = mid + 1; else h = mid - 1; } return h; } // function to count elements within given range public int countInRange(List<Integer> arr, int n, int x, int y) { // initialize result int count = 0; count = upperIndex(arr, n, y) - lowerIndex(arr, n, x) + 1; return count; } ArrayList<Tuple>odd = new ArrayList<>(); ArrayList<Tuple>even = new ArrayList<>(); int m; Map<Integer, Integer> result = new HashMap<>(); public void solve(InputReader in, PrintWriter out) { int t = in.nextInt(); while (t-- > 0){ even.clear(); odd.clear(); result.clear(); int n = in.nextInt(); m = in.nextInt(); int[] x = new int[n]; int[] direction = new int[n]; for(int i = 0; i < n; i++) x[i] = in.nextInt(); for(int i = 0; i < n; i++){ direction[i]= in.nextToken().charAt(0)=='L'?-1:1; if (x[i] % 2 == 0){ even.add(new Tuple(x[i], direction[i], i)); } else{ odd.add(new Tuple(x[i], direction[i], i)); } } solveOne(odd); solveOne(even); for (int i = 0; i < n; i++){ if (result.containsKey(i)){ out.print(result.get(i) + " "); } else{ out.print("-1 "); } } out.println(); } } void solveOne(ArrayList<Tuple> arr){ Collections.sort(arr); Stack<Tuple> right = new Stack(); List<Tuple> left = new ArrayList<>(); for (Tuple item : arr){ int pos = item.x; int dir = item.y; int index = item.z; if (dir == -1){ // left; if (right.isEmpty()){ left.add(item); } else{ Tuple top = right.pop(); int time = Math.abs(pos - top.x) / 2; result.put(index, time); result.put(top.z, time); } } else{ // right; right.push(item); } } // process right; while (right.size() >= 2){ Tuple first = right.pop(); Tuple second = right.pop(); int time = m - first.x + (first.x - second.x) / 2; result.put(first.z, time); result.put(second.z, time); } Collections.sort(left); // process left; for (int i = 0; i < left.size() - 1; i += 2){ Tuple first = left.get(i); Tuple second = left.get(i+1); int time = first.x + (second.x - first.x) / 2; result.put(first.z, time); result.put(second.z, time); } if (right.isEmpty() || left.size() % 2 == 0){ return; } Tuple first = right.peek(); Tuple second = left.get(left.size()-1); int time = (2 * m - Math.abs(first.x - second.x)) / 2; result.put(first.z, time); result.put(second.z, time); } public int _gcd(int a, int b) { if(b == 0) { return a; } else { return _gcd(b, a % b); } } } static class Tuple implements Comparable<Tuple>{ int x, y, z; public Tuple(int x, int y, int z){ this.x= x; this.y= y; this.z=z; } @Override public int compareTo(Tuple o){ return this.x-o.x; } } static class Pair implements Comparable<Pair>{ public int x; public int y; public Pair(int x, int y){ this.x= x; this.y= y; } @Override public int compareTo(Pair o) { return this.x-o.x; } } // fast input reader class; static class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); } public String nextToken() { while (st == null || !st.hasMoreTokens()) { String line = null; try { line = br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public double nextDouble(){ return Double.parseDouble(nextToken()); } public long nextLong(){ return Long.parseLong(nextToken()); } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
6d720f5fb4322b69a743dd1b1c809fd5
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.io.*; import java.util.*; public class C { private static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); private static BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out)); private static StringTokenizer st; public static void main(String[] args) throws IOException { st = new StringTokenizer(reader.readLine()); int T = Integer.parseInt(st.nextToken()); for (int t = 0; t < T; t++) { st = new StringTokenizer(reader.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int[] x = new int[n]; int[][] xAndIndex = new int[n][]; st = new StringTokenizer(reader.readLine()); for (int i = 0; i < n; i++) { x[i] = Integer.parseInt(st.nextToken()); xAndIndex[i] = new int[]{x[i], i}; } Arrays.sort(xAndIndex, Comparator.comparing(arr -> arr[0])); int[] perm = new int[n]; for (int i = 0; i < n; i++) { perm[xAndIndex[i][1]] = i; } for (int i = 0; i < n; i++) { x[i] = xAndIndex[i][0]; } String[] dirs = new String[n]; String[] originalDirs = new String[n]; st = new StringTokenizer(reader.readLine()); for (int i = 0; i < n; i++) { originalDirs[i] = st.nextToken(); } for (int i = 0; i < n; i++) { dirs[i] = originalDirs[xAndIndex[i][1]]; } //System.out.println("x: " + Arrays.toString(x)); //System.out.println("dirs: " + Arrays.toString(dirs)); Deque<Integer> evenCoord = new ArrayDeque<>(); Deque<Integer> oddCoord = new ArrayDeque<>(); int[] result = new int[n]; for (int i = 0; i < n; i++) { if (x[i] % 2 == 0) { if (evenCoord.isEmpty() || dirs[i].equals("R") || dirs[evenCoord.peekLast()].equals("L")) { evenCoord.offerLast(i); } else { int prev = evenCoord.pollLast(); int halfDist = (x[i] - x[prev]) / 2; result[prev] = halfDist; result[i] = halfDist; //System.out.println(x[prev] + "-" + x[i] + "-" + halfDist); } } else { if (oddCoord.isEmpty() || dirs[i].equals("R") || dirs[oddCoord.peekLast()].equals("L")) { oddCoord.offerLast(i); } else { int prev = oddCoord.pollLast(); int halfDist = (x[i] - x[prev]) / 2; result[prev] = halfDist; result[i] = halfDist; //System.out.println(x[prev] + "-" + x[i] + "-" + halfDist); } } } fillResult(m, x, dirs, result, evenCoord); fillResult(m, x, dirs, result, oddCoord); //System.out.println("res:" + Arrays.toString(result)); for (int i = 0; i < n; i++) { writer.write(result[perm[i]] + " "); } writer.newLine(); } writer.flush(); } static void fillResult(int m, int[] x, String[] dirs, int[] result, Deque<Integer> coord) { //System.out.println("coord: " + coord); while (coord.size() >= 2) { if (dirs[coord.peekLast()].equals("R")) { int right = coord.pollLast(); if (dirs[coord.peekLast()].equals("R")) { int left = coord.pollLast(); int halfDist = (m + m - x[right] - x[left]) / 2; result[left] = halfDist; result[right] = halfDist; //System.out.println(x[left] + "." + x[right] + "." + halfDist); } else if (coord.size() == 1) { int left = coord.pollFirst(); int halfDist = (m + x[left] + m - x[right]) / 2; result[left] = halfDist; result[right] = halfDist; //System.out.println(x[left] + "." + x[right] + "." + halfDist); } else { coord.offerLast(right); break; } } else { break; } } while (coord.size() >= 2) { if (dirs[coord.peekFirst()].equals("L")) { int left = coord.pollFirst(); if (dirs[coord.peekFirst()].equals("L")) { int right = coord.pollFirst(); int halfDist = (x[left] + x[right]) / 2; result[left] = halfDist; result[right] = halfDist; //System.out.println(x[left] + "+" + x[right] + "+" + halfDist); } else if (coord.size() == 1) { int right = coord.pollLast(); int halfDist = (m + x[left] + m - x[right]) / 2; result[left] = halfDist; result[right] = halfDist; //System.out.println(x[left] + "+" + x[right] + "+" + halfDist); } else { coord.offerFirst(left); break; } } else { break; } } //System.out.println("coord: " + coord); while (!coord.isEmpty()) { result[coord.pollFirst()] = -1; } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output