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
404d28628f9aa85e33ffb324e2aa5be5
train_003.jsonl
1567175700
You are given a weighted tree consisting of $$$n$$$ vertices. Recall that a tree is a connected graph without cycles. Vertices $$$u_i$$$ and $$$v_i$$$ are connected by an edge with weight $$$w_i$$$.You are given $$$m$$$ queries. The $$$i$$$-th query is given as an integer $$$q_i$$$. In this query you need to calculate the number of pairs of vertices $$$(u, v)$$$ ($$$u < v$$$) such that the maximum weight of an edge on a simple path between $$$u$$$ and $$$v$$$ doesn't exceed $$$q_i$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; 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); int n = in.nextInt(); int m = in.nextInt(); int MAX_W = 200_005; ArrayList<HashSet<Pair>> list = new ArrayList<HashSet<Pair>>(); for (int i=0;i<=MAX_W;i++) { HashSet<Pair> add = new HashSet<Pair>(); list.add(add); } for (int i=0;i<n-1;i++) { int u = in.nextInt()-1; int v = in.nextInt()-1; Pair pair = new Pair(Math.min(u, v), Math.max(u, v)); int w = in.nextInt(); list.get(w).add(pair); } UnionFind uf = new UnionFind(n); long[] ans = new long[MAX_W]; for (int i=1;i<MAX_W;i++) { long tmp = ans[i-1]; for (Pair p : list.get(i)) { int u = p.x; int v = p.y; if (uf.root(u) != uf.root(v)) { long minus = (long)uf.size(u)*(uf.size(u)-1)/2+(long)uf.size(v)*(uf.size(v)-1)/2; long plus = (long)(uf.size(u)+uf.size(v))*(uf.size(u)+uf.size(v)-1)/2; tmp += plus-minus; } uf.connect(u, v); } ans[i] = tmp; } StringBuilder sb = new StringBuilder(); for (int i=0;i<m;i++) { int q = in.nextInt(); sb.append(ans[q]); if (i != m-1) sb.append(" "); } out.println(sb); out.close(); } static class 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); } } static class UnionFind { List<Integer> Parent; UnionFind(int N) { Parent = new ArrayList<Integer>(); Integer[] values = new Integer[N]; Arrays.fill(values, -1); Parent.addAll(Arrays.asList(values)); } int root(int A) { if (Parent.get(A) < 0) return A; int root = root(Parent.get(A)); Parent.set(A, root); return root; } int size(int A) { return -Parent.get(root(A)); } boolean connect(int A, int B) { A = root(A); B = root(B); if (A == B) { return false; } if (size(A) < size(B)) { int temp = A; A = B; B = temp; } Parent.set(A, Parent.get(A) + Parent.get(B)); Parent.set(B, A); return true; } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["7 5\n1 2 1\n3 2 3\n2 4 1\n4 5 2\n5 7 4\n3 6 2\n5 2 3 4 1", "1 2\n1 2", "3 3\n1 2 1\n2 3 2\n1 3 2"]
3 seconds
["21 7 15 21 3", "0 0", "1 3 3"]
NoteThe picture shows the tree from the first example:
Java 11
standard input
[ "graphs", "dsu", "divide and conquer", "sortings", "trees" ]
f94165f37e968442fa7f8be051018ad9
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the number of vertices in the tree and the number of queries. Each of the next $$$n - 1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by three integers $$$u_i$$$, $$$v_i$$$ and $$$w_i$$$ — the labels of vertices it connects ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$) and the weight of the edge ($$$1 \le w_i \le 2 \cdot 10^5$$$). It is guaranteed that the given edges form a tree. The last line of the input contains $$$m$$$ integers $$$q_1, q_2, \dots, q_m$$$ ($$$1 \le q_i \le 2 \cdot 10^5$$$), where $$$q_i$$$ is the maximum weight of an edge in the $$$i$$$-th query.
1,800
Print $$$m$$$ integers — the answers to the queries. The $$$i$$$-th value should be equal to the number of pairs of vertices $$$(u, v)$$$ ($$$u &lt; v$$$) such that the maximum weight of an edge on a simple path between $$$u$$$ and $$$v$$$ doesn't exceed $$$q_i$$$. Queries are numbered from $$$1$$$ to $$$m$$$ in the order of the input.
standard output
PASSED
8d84e70078b8751fa5acab931416e1d8
train_003.jsonl
1567175700
You are given a weighted tree consisting of $$$n$$$ vertices. Recall that a tree is a connected graph without cycles. Vertices $$$u_i$$$ and $$$v_i$$$ are connected by an edge with weight $$$w_i$$$.You are given $$$m$$$ queries. The $$$i$$$-th query is given as an integer $$$q_i$$$. In this query you need to calculate the number of pairs of vertices $$$(u, v)$$$ ($$$u &lt; v$$$) such that the maximum weight of an edge on a simple path between $$$u$$$ and $$$v$$$ doesn't exceed $$$q_i$$$.
256 megabytes
import java.util.*; import java.io.*; public class G582 { static ArrayList<Integer> [] adj; public static void main(String [] args) { MyScanner sc = new MyScanner(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int n = sc.nextInt(); int m = sc.nextInt(); adj = new ArrayList[n+1]; for (int i = 1; i <= n; i++)adj[i] = new ArrayList<>(); Edge [] e = new Edge[n-1]; for (int i= 0; i < n - 1; i++) { int a = sc.nextInt(); int b = sc.nextInt(); adj[a].add(b); adj[b].add(a); e[i] = new Edge(a, b, sc.nextInt()); } Arrays.sort(e); int idx = 0; int large = n; int [] q = new int[m]; for (int i = 0; i < m; i++) { q[i] = sc.nextInt(); } long [] ret = new long [200001]; long cur = 0; UF dsu = new UF(n+1); for (int i = 0; i <= 200000; i++) { while (idx < n - 1 && e[idx].val <= i) { int a = dsu.find(e[idx].a); int b = dsu.find(e[idx].b); long first = ((long) dsu.size[a] * (dsu.size[a] - 1)) / 2; long second = ((long) dsu.size[b] * (dsu.size[b] - 1)) / 2; long next = ((long)(dsu.size[a] + dsu.size[b]) * (dsu.size[a] + dsu.size[b] - 1)) / 2; cur += (next - first - second); dsu.union(a, b); idx++; } ret[i] = cur; } for (int i = 0; i < m; i++) out.print(ret[q[i]] + " "); out.close(); } static class Edge implements Comparable<Edge> { int a; int b; int val; Edge(int a , int b, int val) { this.a = a; this.b = b; this.val = val; } @Override public int compareTo(Edge o) { if (val == o.val) { if (a == o.a) return b - o.b; else return a - o.a; } return val - o.val; } } static class UF { private int[] parent; // parent[i] = parent of i private byte[] rank; // rank[i] = rank of subtree rooted at i (never more than 31) private int count; // number of components private int[] size; public UF(int n) { if (n < 0) throw new IllegalArgumentException(); count = n; parent = new int[n]; rank = new byte[n]; size = new int[n]; for (int i = 0; i < n; i++) { parent[i] = i; rank[i] = 0; size[i] = 1; } } public int find(int p) { while (p != parent[p]) { parent[p] = parent[parent[p]]; // path compression by halving p = parent[p]; } return p; } public int count() { return count; } public boolean connected(int p, int q) { return find(p) == find(q); } public void union(int p, int q) { int rootP = find(p); int rootQ = find(q); if (rootP == rootQ) return; // make root of smaller rank point to root of larger rank if (rank[rootP] < rank[rootQ]) { parent[rootP] = rootQ; size[rootQ] = size[rootQ] + size[rootP]; } else if (rank[rootP] > rank[rootQ]) { parent[rootQ] = rootP; size[rootP] = size[rootP] + size[rootQ]; } else { parent[rootQ] = rootP; size[rootP] = size[rootP] + size[rootQ]; rank[rootP]++; } count--; } } //-----------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
["7 5\n1 2 1\n3 2 3\n2 4 1\n4 5 2\n5 7 4\n3 6 2\n5 2 3 4 1", "1 2\n1 2", "3 3\n1 2 1\n2 3 2\n1 3 2"]
3 seconds
["21 7 15 21 3", "0 0", "1 3 3"]
NoteThe picture shows the tree from the first example:
Java 11
standard input
[ "graphs", "dsu", "divide and conquer", "sortings", "trees" ]
f94165f37e968442fa7f8be051018ad9
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the number of vertices in the tree and the number of queries. Each of the next $$$n - 1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by three integers $$$u_i$$$, $$$v_i$$$ and $$$w_i$$$ — the labels of vertices it connects ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$) and the weight of the edge ($$$1 \le w_i \le 2 \cdot 10^5$$$). It is guaranteed that the given edges form a tree. The last line of the input contains $$$m$$$ integers $$$q_1, q_2, \dots, q_m$$$ ($$$1 \le q_i \le 2 \cdot 10^5$$$), where $$$q_i$$$ is the maximum weight of an edge in the $$$i$$$-th query.
1,800
Print $$$m$$$ integers — the answers to the queries. The $$$i$$$-th value should be equal to the number of pairs of vertices $$$(u, v)$$$ ($$$u &lt; v$$$) such that the maximum weight of an edge on a simple path between $$$u$$$ and $$$v$$$ doesn't exceed $$$q_i$$$. Queries are numbered from $$$1$$$ to $$$m$$$ in the order of the input.
standard output
PASSED
571fa6201dd8f925fbc443d9f4774829
train_003.jsonl
1567175700
You are given a weighted tree consisting of $$$n$$$ vertices. Recall that a tree is a connected graph without cycles. Vertices $$$u_i$$$ and $$$v_i$$$ are connected by an edge with weight $$$w_i$$$.You are given $$$m$$$ queries. The $$$i$$$-th query is given as an integer $$$q_i$$$. In this query you need to calculate the number of pairs of vertices $$$(u, v)$$$ ($$$u &lt; v$$$) such that the maximum weight of an edge on a simple path between $$$u$$$ and $$$v$$$ doesn't exceed $$$q_i$$$.
256 megabytes
/* Author: Anthony Ngene Created: 08/09/2020 - 14:17 */ import java.io.*; import java.util.*; public class G { // I've learned that people will forget what you said, people will forget what you did, but people will never forget how you made them feel. - Maya Angelou void solver() throws IOException { int n = in.intNext(), q = in.intNext(); Tuple[] edges = new Tuple[n - 1]; int maxW = 0; for (int i = 0; i < n - 1; i++) { int a = in.intNext(), b = in.intNext(), w = in.intNext(); edges[i] = new Tuple(w, a - 1, b - 1); maxW = max(maxW, w); } UnionFind disjoint = new UnionFind(n); Arrays.sort(edges); int[] queries = in.nextIntArray(q); long[] res = new long[maxW + 1]; int idx = 0; for (int i = 1; i < maxW + 1; i++) { while (idx < n - 1 && edges[idx].a <= i) { disjoint.unify((int)edges[idx].b, (int)edges[idx].c); idx++; } res[i] = disjoint.total; } for (int i = 0; i < q; i++) out.p(res[min(maxW, queries[i])]).p(" "); // out.println(res); } class UnionFind { private final int size; private int groups; private final int[] sizes; private final int[] parents; long total = 0; public int getSize() { return size; } public int getGroups() { return groups; } public int getSize(int p) { return sizes[find(p)]; } public UnionFind(int n) { this.size = this.groups = n; sizes = new int[n]; parents = new int[n]; for (int i = 0; i < n; i++) { parents[i] = i; sizes[i] = 1; } } public int find(int p) { int root = p; while (root != parents[root]) root = parents[root]; while (p != root) { int temp = parents[p]; parents[p] = root; p = temp; } return root; } public boolean connected(int p, int q) { return find(p) == find(q); } public void unify(int p, int q) { int root1 = find(p); int root2 = find(q); if (root1 == root2) return; total -= groupEdgeSum(getSize(root1)); total -= groupEdgeSum(getSize(root2)); if (sizes[root1] < sizes[root2]) { parents[root1] = root2; sizes[root2] += sizes[root1]; } else { parents[root2] = root1; sizes[root1] += sizes[root2]; } total += groupEdgeSum(getSize(find(root1))); groups--; } long groupEdgeSum(long n) { return ((n - 1) * n) / 2; } } // Generated Code Below: // checks: 1. edge cases 2. overflow 3. possible errors (e.g 1/0, arr[out]) 4. time/space complexity private static final FastWriter out = new FastWriter(); private static FastScanner in; static ArrayList<Integer>[] adj; private static long e97 = (long)1e9 + 7; public static void main(String[] args) throws IOException { in = new FastScanner(); new G().solver(); out.close(); } static class FastWriter { private static final int IO_BUFFERS = 128 * 1024; private final StringBuilder out; public FastWriter() { out = new StringBuilder(IO_BUFFERS); } public FastWriter p(Object object) { out.append(object); return this; } public FastWriter p(String format, Object... args) { out.append(String.format(format, args)); return this; } public FastWriter pp(Object... args) { for (Object ob : args) { out.append(ob).append(" "); } out.append("\n"); return this; } public FastWriter pp(int[] args) { for (int ob : args) { out.append(ob).append(" "); } out.append("\n"); return this; } public FastWriter pp(long[] args) { for (long ob : args) { out.append(ob).append(" "); } out.append("\n"); return this; } public FastWriter pp(char[] args) { for (char ob : args) { out.append(ob).append(" "); } out.append("\n"); return this; } public void println(long[] arr) { for(long e: arr) out.append(e).append(" "); out.append("\n"); } public void println(int[] arr) { for(int e: arr) out.append(e).append(" "); out.append("\n"); } public void println(char[] arr) { for(char e: arr) out.append(e).append(" "); out.append("\n"); } public void println(double[] arr) { for(double e: arr) out.append(e).append(" "); out.append("\n"); } public void println(boolean[] arr) { for(boolean e: arr) out.append(e).append(" "); out.append("\n"); } public <T>void println(T[] arr) { for(T e: arr) out.append(e).append(" "); out.append("\n"); } public void println(long[][] arr) { for (long[] row: arr) out.append(Arrays.toString(row)).append("\n"); } public void println(int[][] arr) { for (int[] row: arr) out.append(Arrays.toString(row)).append("\n"); } public void println(char[][] arr) { for (char[] row: arr) out.append(Arrays.toString(row)).append("\n"); } public void println(double[][] arr) { for (double[] row: arr) out.append(Arrays.toString(row)).append("\n"); } public <T>void println(T[][] arr) { for (T[] row: arr) out.append(Arrays.toString(row)).append("\n"); } public FastWriter println(Object object) { out.append(object).append("\n"); return this; } public void toFile(String fileName) throws IOException { BufferedWriter writer = new BufferedWriter(new FileWriter(fileName)); writer.write(out.toString()); writer.close(); } public void close() throws IOException { System.out.print(out); } } static class FastScanner { private InputStream sin = System.in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; public FastScanner(){} public FastScanner(String filename) throws FileNotFoundException { File file = new File(filename); sin = new FileInputStream(file); } private boolean hasNextByte() { if (ptr < buflen) { return true; }else{ ptr = 0; try { buflen = sin.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;} private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;} public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte();} public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while(isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long longNext() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while(true){ if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; }else if(b == -1 || !isPrintableChar(b) || b == ':'){ return minus ? -n : n; }else{ throw new NumberFormatException(); } b = readByte(); } } public int intNext() { long nl = longNext(); if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException(); return (int) nl; } public double doubleNext() { return Double.parseDouble(next());} public long[] nextLongArray(final int n){ final long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = longNext(); return a; } public int[] nextIntArray(final int n){ final int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = intNext(); return a; } public double[] nextDoubleArray(final int n){ final double[] a = new double[n]; for (int i = 0; i < n; i++) a[i] = doubleNext(); return a; } public ArrayList<Integer>[] getAdj(int n) { ArrayList<Integer>[] adj = new ArrayList[n + 1]; for (int i = 1; i <= n; i++) adj[i] = new ArrayList<>(); return adj; } public ArrayList<Integer>[] adjacencyList(int nodes, int edges) throws IOException { return adjacencyList(nodes, edges, false); } public ArrayList<Integer>[] adjacencyList(int nodes, int edges, boolean isDirected) throws IOException { adj = getAdj(nodes); for (int i = 0; i < edges; i++) { int a = intNext(), b = intNext(); adj[a].add(b); if (!isDirected) adj[b].add(a); } return adj; } } static class u { public static int upperBound(long[] array, long obj) { int l = 0, r = array.length - 1; while (r - l >= 0) { int c = (l + r) / 2; if (obj < array[c]) { r = c - 1; } else { l = c + 1; } } return l; } public static int upperBound(ArrayList<Long> array, long obj) { int l = 0, r = array.size() - 1; while (r - l >= 0) { int c = (l + r) / 2; if (obj < array.get(c)) { r = c - 1; } else { l = c + 1; } } return l; } public static int lowerBound(long[] array, long obj) { int l = 0, r = array.length - 1; while (r - l >= 0) { int c = (l + r) / 2; if (obj <= array[c]) { r = c - 1; } else { l = c + 1; } } return l; } public static int lowerBound(ArrayList<Long> array, long obj) { int l = 0, r = array.size() - 1; while (r - l >= 0) { int c = (l + r) / 2; if (obj <= array.get(c)) { r = c - 1; } else { l = c + 1; } } return l; } static <T> T[][] deepCopy(T[][] matrix) { return Arrays.stream(matrix).map(el -> el.clone()).toArray($ -> matrix.clone()); } static int[][] deepCopy(int[][] matrix) { return Arrays.stream(matrix).map(int[]::clone).toArray($ -> matrix.clone()); } static long[][] deepCopy(long[][] matrix) { return Arrays.stream(matrix).map(long[]::clone).toArray($ -> matrix.clone()); } private static void sort(int[][] arr){ Arrays.sort(arr, Comparator.comparingDouble(o -> o[0])); } private static void sort(long[][] arr){ Arrays.sort(arr, Comparator.comparingDouble(o -> o[0])); } private static <T>void rSort(T[] arr) { Arrays.sort(arr, Collections.reverseOrder()); } private static void customSort(int[][] arr) { Arrays.sort(arr, new Comparator<int[]>() { public int compare(int[] a, int[] b) { if (a[0] == b[0]) return Integer.compare(a[1], b[1]); return Integer.compare(a[0], b[0]); } }); } public static int[] swap(int[] arr, int left, int right) { int temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; return arr; } public static int[] reverse(int[] arr, int left, int right) { while (left < right) { int temp = arr[left]; arr[left++] = arr[right]; arr[right--] = temp; } return arr; } public static boolean findNextPermutation(int[] data) { if (data.length <= 1) return false; int last = data.length - 2; while (last >= 0) { if (data[last] < data[last + 1]) break; last--; } if (last < 0) return false; int nextGreater = data.length - 1; for (int i = data.length - 1; i > last; i--) { if (data[i] > data[last]) { nextGreater = i; break; } } data = swap(data, nextGreater, last); data = reverse(data, last + 1, data.length - 1); return true; } public static int biSearch(int[] dt, int target){ int left=0, right=dt.length-1; int mid=-1; while(left<=right){ mid = (right+left)/2; if(dt[mid] == target) return mid; if(dt[mid] < target) left=mid+1; else right=mid-1; } return -1; } public static int biSearchMax(long[] dt, long target){ int left=-1, right=dt.length; int mid=-1; while((right-left)>1){ mid = left + (right-left)/2; if(dt[mid] <= target) left=mid; else right=mid; } return left; } public static int biSearchMaxAL(ArrayList<Integer> dt, long target){ int left=-1, right=dt.size(); int mid=-1; while((right-left)>1){ mid = left + (right-left)/2; if(dt.get(mid) <= target) left=mid; else right=mid; } return left; } private static <T>void fill(T[][] ob, T res){for(int i=0;i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){ ob[i][j] = res; }}} private static void fill(boolean[][] ob,boolean res){for(int i=0;i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){ ob[i][j] = res; }}} private static void fill(int[][] ob, int res){ for(int i=0; i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){ ob[i][j] = res; }}} private static void fill(long[][] ob, long res){ for(int i=0; i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){ ob[i][j] = res; }}} private static void fill(char[][] ob, char res){ for(int i=0; i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){ ob[i][j] = res; }}} private static void fill(double[][] ob, double res){for(int i=0; i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){ ob[i][j] = res; }}} private static void fill(int[][][] ob,int res){for(int i=0;i<ob.length;i++){for(int j=0;j<ob[0].length;j++){for(int k=0;k<ob[0][0].length;k++){ob[i][j][k]=res;}}}} private static void fill(long[][][] ob,long res){for(int i=0;i<ob.length;i++){for(int j=0;j<ob[0].length;j++){for(int k=0;k<ob[0][0].length;k++){ob[i][j][k]=res;}}}} private static <T>void fill(T[][][] ob,T res){for(int i=0;i<ob.length;i++){for(int j=0;j<ob[0].length;j++){for(int k=0;k<ob[0][0].length;k++){ob[i][j][k]=res;}}}} private static void fill_parent(int[] ob){ for(int i=0; i<ob.length; i++) ob[i]=i; } private static boolean same3(long a, long b, long c){ if(a!=b) return false; if(b!=c) return false; if(c!=a) return false; return true; } private static boolean dif3(long a, long b, long c){ if(a==b) return false; if(b==c) return false; if(c==a) return false; return true; } private static double hypotenuse(double a, double b){ return Math.sqrt(a*a+b*b); } private static long factorial(int n) { long ans=1; for(long i=n; i>0; i--){ ans*=i; } return ans; } private static long facMod(int n, long mod) { long ans=1; for(long i=n; i>0; i--) ans = (ans * i) % mod; return ans; } private static long lcm(long m, long n){ long ans = m/gcd(m,n); ans *= n; return ans; } private static long gcd(long m, long n) { if(m < n) return gcd(n, m); if(n == 0) return m; return gcd(n, m % n); } private static boolean isPrime(long a){ if(a==1) return false; for(int i=2; i<=Math.sqrt(a); i++){ if(a%i == 0) return false; } return true; } static long modInverse(long a, long mod) { /* Fermat's little theorem: a^(MOD-1) => 1 Therefore (divide both sides by a): a^(MOD-2) => a^(-1) */ return binpowMod(a, mod - 2, mod); } static long binpowMod(long a, long b, long mod) { long res = 1; while (b > 0) { if (b % 2 == 1) res = (res * a) % mod; a = (a * a) % mod; b /= 2; } return res; } private static int getDigit2(long num){ long cf = 1; int d=0; while(num >= cf){ d++; cf = 1<<d; } return d; } private static int getDigit10(long num){ long cf = 1; int d=0; while(num >= cf){ d++; cf*=10; } return d; } private static boolean isInArea(int y, int x, int h, int w){ if(y<0) return false; if(x<0) return false; if(y>=h) return false; if(x>=w) return false; return true; } private static ArrayList<Integer> generatePrimes(int n) { int[] lp = new int[n + 1]; ArrayList<Integer> pr = new ArrayList<>(); for (int i = 2; i <= n; ++i) { if (lp[i] == 0) { lp[i] = i; pr.add(i); } for (int j = 0; j < pr.size() && pr.get(j) <= lp[i] && i * pr.get(j) <= n; ++j) { lp[i * pr.get(j)] = pr.get(j); } } return pr; } static long nPrMod(int n, int r, long MOD) { long res = 1; for (int i = (n - r + 1); i <= n; i++) { res = (res * i) % MOD; } return res; } static long nCr(int n, int r) { if (r > (n - r)) r = n - r; long ans = 1; for (int i = 1; i <= r; i++) { ans *= n; ans /= i; n--; } return ans; } static long nCrMod(int n, int r, long MOD) { long rFactorial = nPrMod(r, r, MOD); long first = nPrMod(n, r, MOD); long second = binpowMod(rFactorial, MOD-2, MOD); return (first * second) % MOD; } static void printBitRepr(int n) { StringBuilder res = new StringBuilder(); for (int i = 0; i < 32; i++) { int mask = (1 << i); res.append((mask & n) == 0 ? "0" : "1"); } out.println(res); } static String bitString(int n) {return Integer.toString(n);} static int setKthBitToOne(int n, int k) { return (n | (1 << k)); } // zero indexed static int setKthBitToZero(int n, int k) { return (n & ~(1 << k)); } static int invertKthBit(int n, int k) { return (n ^ (1 << k)); } static boolean isPowerOfTwo(int n) { return (n & (n - 1)) == 0; } static HashMap<Character, Integer> counts(String word) { HashMap<Character, Integer> counts = new HashMap<>(); for (int i = 0; i < word.length(); i++) counts.merge(word.charAt(i), 1, Integer::sum); return counts; } static HashMap<Integer, Integer> counts(int[] arr) { HashMap<Integer, Integer> counts = new HashMap<>(); for (int value : arr) counts.merge(value, 1, Integer::sum); return counts; } static HashMap<Long, Integer> counts(long[] arr) { HashMap<Long, Integer> counts = new HashMap<>(); for (long l : arr) counts.merge(l, 1, Integer::sum); return counts; } static HashMap<Character, Integer> counts(char[] arr) { HashMap<Character, Integer> counts = new HashMap<>(); for (char c : arr) counts.merge(c, 1, Integer::sum); return counts; } static long hash(int x, int y) { return x* 1_000_000_000L +y; } static final Random random = new Random(); static void sort(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 void sort(long[] arr) { shuffleArray(arr); Arrays.sort(arr); } static void shuffleArray(long[] arr) { int n = arr.length; for(int i=0; i<n; ++i){ long tmp = arr[i]; int randomPos = i + random.nextInt(n-i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } } static class Tuple implements Comparable<Tuple> { long a; long b; long c; public Tuple(long a, long b) { this.a = a; this.b = b; this.c = 0; } public Tuple(long a, long b, long c) { this.a = a; this.b = b; this.c = c; } public long getA() { return a; } public long getB() { return b; } public long getC() { return c; } public int compareTo(Tuple other) { if (this.a == other.a) { if (this.b == other.b) return Long.compare(this.c, other.c); return Long.compare(this.b, other.b); } return Long.compare(this.a, other.a); } @Override public int hashCode() { return Arrays.deepHashCode(new Long[]{a, b, c}); } @Override public boolean equals(Object o) { if (!(o instanceof Tuple)) return false; Tuple pairo = (Tuple) o; return (this.a == pairo.a && this.b == pairo.b && this.c == pairo.c); } @Override public String toString() { return String.format("(%d %d %d) ", this.a, this.b, this.c); } } private static int abs(int a){ return (a>=0) ? a: -a; } private static int min(int... ins){ int min = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] < min) min = ins[i]; } return min; } private static int max(int... ins){ int max = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] > max) max = ins[i]; } return max; } private static int sum(int... ins){ int total = 0; for (int v : ins) { total += v; } return total; } private static long abs(long a){ return (a>=0) ? a: -a; } private static long min(long... ins){ long min = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] < min) min = ins[i]; } return min; } private static long max(long... ins){ long max = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] > max) max = ins[i]; } return max; } private static long sum(long... ins){ long total = 0; for (long v : ins) { total += v; } return total; } private static double abs(double a){ return (a>=0) ? a: -a; } private static double min(double... ins){ double min = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] < min) min = ins[i]; } return min; } private static double max(double... ins){ double max = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] > max) max = ins[i]; } return max; } private static double sum(double... ins){ double total = 0; for (double v : ins) { total += v; } return total; } }
Java
["7 5\n1 2 1\n3 2 3\n2 4 1\n4 5 2\n5 7 4\n3 6 2\n5 2 3 4 1", "1 2\n1 2", "3 3\n1 2 1\n2 3 2\n1 3 2"]
3 seconds
["21 7 15 21 3", "0 0", "1 3 3"]
NoteThe picture shows the tree from the first example:
Java 11
standard input
[ "graphs", "dsu", "divide and conquer", "sortings", "trees" ]
f94165f37e968442fa7f8be051018ad9
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the number of vertices in the tree and the number of queries. Each of the next $$$n - 1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by three integers $$$u_i$$$, $$$v_i$$$ and $$$w_i$$$ — the labels of vertices it connects ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$) and the weight of the edge ($$$1 \le w_i \le 2 \cdot 10^5$$$). It is guaranteed that the given edges form a tree. The last line of the input contains $$$m$$$ integers $$$q_1, q_2, \dots, q_m$$$ ($$$1 \le q_i \le 2 \cdot 10^5$$$), where $$$q_i$$$ is the maximum weight of an edge in the $$$i$$$-th query.
1,800
Print $$$m$$$ integers — the answers to the queries. The $$$i$$$-th value should be equal to the number of pairs of vertices $$$(u, v)$$$ ($$$u &lt; v$$$) such that the maximum weight of an edge on a simple path between $$$u$$$ and $$$v$$$ doesn't exceed $$$q_i$$$. Queries are numbered from $$$1$$$ to $$$m$$$ in the order of the input.
standard output
PASSED
a9dde6c685bfcc4274ee34027f84834c
train_003.jsonl
1567175700
You are given a weighted tree consisting of $$$n$$$ vertices. Recall that a tree is a connected graph without cycles. Vertices $$$u_i$$$ and $$$v_i$$$ are connected by an edge with weight $$$w_i$$$.You are given $$$m$$$ queries. The $$$i$$$-th query is given as an integer $$$q_i$$$. In this query you need to calculate the number of pairs of vertices $$$(u, v)$$$ ($$$u &lt; v$$$) such that the maximum weight of an edge on a simple path between $$$u$$$ and $$$v$$$ doesn't exceed $$$q_i$$$.
256 megabytes
import java.util.*; import java.io.*; public class Main { static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } static class Edge { int u,v,w; Edge(int u,int v,int w) { this.u=u; this.v=v; this.w=w; } } static class DSU { int n; int par[]; long ans[]; int rank[]; DSU(int n) { this.n=n; rank=new int[n]; par=new int[n]; ans=new long[300000]; for(int i=1;i<n;i++) par[i]=i; Arrays.fill(rank,1); } public int find(int u) { if(par[u]==u) return u; return par[u]=find(par[u]); } public void union(int x,int y,int vert) { x=find(x); y=find(y); if(rank[x]<rank[y]) { par[x]=y; ans[vert]=ans[vert]+1L*rank[x]*rank[y]; rank[y]+=rank[x]; rank[x]=0; } else if(rank[x]>rank[y]) { par[y]=x; ans[vert]=ans[vert]+1L*rank[x]*rank[y]; rank[x]+=rank[y]; rank[y]=0; } else { par[y]=x; ans[vert]+=1L*rank[x]*rank[y]; rank[x]+=rank[y]; rank[y]=0; } } } public static void main(String args[])throws Exception { Reader sc=new Reader(); PrintWriter pw=new PrintWriter(System.out); int n=sc.nextInt(); int m=sc.nextInt(); Edge[] e=new Edge[n-1]; for(int i=0;i<n-1;i++) { int u=sc.nextInt(); int v=sc.nextInt(); int w=sc.nextInt(); if(u>v) { int temp=u; u=v; v=temp; } e[i]=new Edge(u,v,w); } int q[]=new int[m]; for(int i=0;i<m;i++) q[i]=sc.nextInt(); Arrays.sort(e,(e1,e2)->e1.w-e2.w); DSU d=new DSU(n+1); for(int i=0;i<n-1;i++) d.union(e[i].u,e[i].v,e[i].w); for(int i=1;i<=200000;i++) d.ans[i]+=d.ans[i-1]; for(int i=0;i<m;i++) pw.print(d.ans[q[i]]+" "); pw.flush(); pw.close(); } }
Java
["7 5\n1 2 1\n3 2 3\n2 4 1\n4 5 2\n5 7 4\n3 6 2\n5 2 3 4 1", "1 2\n1 2", "3 3\n1 2 1\n2 3 2\n1 3 2"]
3 seconds
["21 7 15 21 3", "0 0", "1 3 3"]
NoteThe picture shows the tree from the first example:
Java 11
standard input
[ "graphs", "dsu", "divide and conquer", "sortings", "trees" ]
f94165f37e968442fa7f8be051018ad9
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the number of vertices in the tree and the number of queries. Each of the next $$$n - 1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by three integers $$$u_i$$$, $$$v_i$$$ and $$$w_i$$$ — the labels of vertices it connects ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$) and the weight of the edge ($$$1 \le w_i \le 2 \cdot 10^5$$$). It is guaranteed that the given edges form a tree. The last line of the input contains $$$m$$$ integers $$$q_1, q_2, \dots, q_m$$$ ($$$1 \le q_i \le 2 \cdot 10^5$$$), where $$$q_i$$$ is the maximum weight of an edge in the $$$i$$$-th query.
1,800
Print $$$m$$$ integers — the answers to the queries. The $$$i$$$-th value should be equal to the number of pairs of vertices $$$(u, v)$$$ ($$$u &lt; v$$$) such that the maximum weight of an edge on a simple path between $$$u$$$ and $$$v$$$ doesn't exceed $$$q_i$$$. Queries are numbered from $$$1$$$ to $$$m$$$ in the order of the input.
standard output
PASSED
f429b8e3d79cdfa157faa1f3e14b7408
train_003.jsonl
1567175700
You are given a weighted tree consisting of $$$n$$$ vertices. Recall that a tree is a connected graph without cycles. Vertices $$$u_i$$$ and $$$v_i$$$ are connected by an edge with weight $$$w_i$$$.You are given $$$m$$$ queries. The $$$i$$$-th query is given as an integer $$$q_i$$$. In this query you need to calculate the number of pairs of vertices $$$(u, v)$$$ ($$$u &lt; v$$$) such that the maximum weight of an edge on a simple path between $$$u$$$ and $$$v$$$ doesn't exceed $$$q_i$$$.
256 megabytes
import java.io.*; import java.util.*; public class d3prac implements Runnable { private boolean console=false; int par[],size[]; long max; public void solve() { int i; int n=in.ni(); int q=in.ni(); edge a[]=new edge[n-1];par=new int[n]; size=new int [n]; long qu[][]=new long[q][3]; for(i=0;i<n;i++) { par[i]=i; size[i]=1; } for(i=0;i<n-1;i++) { int u=in.ni()-1; int v=in.ni()-1; int w=in.ni(); a[i]= new edge(u,v,w); } Arrays.sort(a, (p,r)-> p.w-r.w); for(i=0;i<q;i++) { qu[i][0]=in.ni(); qu[i][1]=i; } Arrays.sort(qu, (p,r)-> (int) (p[0]-r[0])); int k=0; for(i=0;i<q;i++) { while(k<n-1&&a[k].w<=qu[i][0]) { union(a[k].u,a[k].v); k++; } qu[i][2]=max; } Arrays.sort(qu, (p,r)-> (int) (p[1]-r[1])); for(long val[]:qu) { out.print(val[2]+" "); } } public int find(int a) { return (par[a]==a)?a:(par[a]=find(par[a])); } public void union(int a,int b) { a=find(a); b=find(b); if(a==b) return; if(size[a]<size[b]) { int t=a; a=b; b=t; } par[b]=a; max-= calc(size[a]); max-= calc(size[b]); size[a]+=size[b]; max+= calc(size[a]); } long calc(long c) { return c*(c-1)/2; } @Override public void run() { try { init(); } catch (FileNotFoundException e) { e.printStackTrace(); } int t= 1; while (t-->0) { solve(); out.flush(); } } private FastInput in; private PrintWriter out; public static void main(String[] args) throws Exception { new d3prac().run(); } private void init() throws FileNotFoundException { InputStream inputStream = System.in; OutputStream outputStream = System.out; try { if (!console && System.getProperty("user.name").equals("sachan")) { outputStream = new FileOutputStream("/home/sachan/Desktop/output.txt"); inputStream = new FileInputStream("/home/sachan/Desktop/input.txt"); } } catch (Exception ignored) { } out = new PrintWriter(outputStream); in = new FastInput(inputStream); } static class FastInput { InputStream obj; public FastInput(InputStream obj) { this.obj = obj; } byte inbuffer[] = new byte[1024]; int lenbuffer = 0, ptrbuffer = 0; int readByte() { if (lenbuffer == -1) throw new InputMismatchException(); if (ptrbuffer >= lenbuffer) { ptrbuffer = 0; try { lenbuffer = obj.read(inbuffer); } catch (IOException e) { throw new InputMismatchException(); } } if (lenbuffer <= 0) return -1;return inbuffer[ptrbuffer++]; } String ns() { int b = skip();StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { sb.appendCodePoint(b);b = readByte(); }return sb.toString();} int ni() { int num = 0, b;boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true;b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; }b = readByte(); }} 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 * 10L + (b - '0'); } else { return minus ? -num : num; }b = readByte(); } } boolean isSpaceChar(int c) { return (!(c >= 33 && c <= 126)); } int skip() { int b;while ((b = readByte()) != -1 && isSpaceChar(b)) ;return b; } float nf() {return Float.parseFloat(ns());} double nd() {return Double.parseDouble(ns());} char nc() {return (char) skip();} } } class edge { int u,v,w; edge(int u,int v,int w) { this.u=u; this.v=v; this.w=w; } }
Java
["7 5\n1 2 1\n3 2 3\n2 4 1\n4 5 2\n5 7 4\n3 6 2\n5 2 3 4 1", "1 2\n1 2", "3 3\n1 2 1\n2 3 2\n1 3 2"]
3 seconds
["21 7 15 21 3", "0 0", "1 3 3"]
NoteThe picture shows the tree from the first example:
Java 11
standard input
[ "graphs", "dsu", "divide and conquer", "sortings", "trees" ]
f94165f37e968442fa7f8be051018ad9
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the number of vertices in the tree and the number of queries. Each of the next $$$n - 1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by three integers $$$u_i$$$, $$$v_i$$$ and $$$w_i$$$ — the labels of vertices it connects ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$) and the weight of the edge ($$$1 \le w_i \le 2 \cdot 10^5$$$). It is guaranteed that the given edges form a tree. The last line of the input contains $$$m$$$ integers $$$q_1, q_2, \dots, q_m$$$ ($$$1 \le q_i \le 2 \cdot 10^5$$$), where $$$q_i$$$ is the maximum weight of an edge in the $$$i$$$-th query.
1,800
Print $$$m$$$ integers — the answers to the queries. The $$$i$$$-th value should be equal to the number of pairs of vertices $$$(u, v)$$$ ($$$u &lt; v$$$) such that the maximum weight of an edge on a simple path between $$$u$$$ and $$$v$$$ doesn't exceed $$$q_i$$$. Queries are numbered from $$$1$$$ to $$$m$$$ in the order of the input.
standard output
PASSED
a4a2b12506b1a270e3888b281e774054
train_003.jsonl
1567175700
You are given a weighted tree consisting of $$$n$$$ vertices. Recall that a tree is a connected graph without cycles. Vertices $$$u_i$$$ and $$$v_i$$$ are connected by an edge with weight $$$w_i$$$.You are given $$$m$$$ queries. The $$$i$$$-th query is given as an integer $$$q_i$$$. In this query you need to calculate the number of pairs of vertices $$$(u, v)$$$ ($$$u &lt; v$$$) such that the maximum weight of an edge on a simple path between $$$u$$$ and $$$v$$$ doesn't exceed $$$q_i$$$.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws IOException { Scanner s=new Scanner(System.in); int n=s.nextInt(); int m=s.nextInt(); Node ar[]=new Node[n-1]; for(int i=0;i<n-1;i++) { int u=s.nextInt(); int v=s.nextInt(); int w=s.nextInt(); u--; v--; ar[i]=new Node(u,v,w); } Pair br[]=new Pair[m]; for(int i=0;i<m;i++) { br[i]=new Pair(s.nextInt(),i); } Arrays.sort(ar,(a,b)->a.ti-b.ti); Arrays.sort(br,(a,b)->a.fi-b.fi); // for(int i=0;i<n-1;i++) // System.out.println(ar[i].fi+" "+ar[i].si+" "+ar[i].ti); // // for(int i=0;i<m;i++) // System.out.println(br[i].fi+" "+br[i].si); long ans[]=new long[m]; long leader[]=new long[n]; Arrays.fill(leader, 1); DSU dsu=new DSU(n); int j=0; long res=0; for(int i=0;i<m;i++) { while(j<n-1 && ar[j].ti<=br[i].fi) { int u=ar[j].fi; int v=ar[j].si; int w=ar[j].ti; u=dsu.get(u); v=dsu.get(v); if(leader[u]<leader[v]) { long tmp=leader[u]; leader[u]=leader[v]; leader[v]=tmp; } dsu.union(u, v); res-=get(leader[u]); res-=get(leader[v]); leader[u]+=leader[v]; res+=get(leader[u]); // System.out.println("res :"+res+" and j :"+j); j++; } ans[br[i].si]=res; } for(int i=0;i<m;i++) System.out.print(ans[i]+" "); System.out.println(); } private static long get(long u) { // TODO Auto-generated method stub return (u*(u-1))/2; } } class DSU { int parent[]; int rank[]; int totalComponents; public DSU(int n) { parent=new int[n]; rank=new int[n]; for(int i=0;i<n;i++) { parent[i]=i; } totalComponents=n; } int get(int a) { if(a==parent[a]) return a; return parent[a]= get(parent[a]); } void union(int a, int b) { a=this.get(a); b=this.get(b); if(a!=b) { if(rank[a]<rank[b]) { int tmp=rank[a]; rank[a]=rank[b]; rank[b]=tmp; } parent[b]=a; if(rank[a]==rank[b]) rank[a]++; totalComponents--; } } } class Node{ int fi; int si; int ti; public Node(int fi,int si,int ti) { if(fi>si) { this.fi=si; this.si=fi; this.ti=ti; }else { this.fi=fi; this.si=si; this.ti=ti; } } } class Pair{ int fi; int si; public Pair(int fi,int si) { this.fi=fi; this.si=si; } }
Java
["7 5\n1 2 1\n3 2 3\n2 4 1\n4 5 2\n5 7 4\n3 6 2\n5 2 3 4 1", "1 2\n1 2", "3 3\n1 2 1\n2 3 2\n1 3 2"]
3 seconds
["21 7 15 21 3", "0 0", "1 3 3"]
NoteThe picture shows the tree from the first example:
Java 11
standard input
[ "graphs", "dsu", "divide and conquer", "sortings", "trees" ]
f94165f37e968442fa7f8be051018ad9
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the number of vertices in the tree and the number of queries. Each of the next $$$n - 1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by three integers $$$u_i$$$, $$$v_i$$$ and $$$w_i$$$ — the labels of vertices it connects ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$) and the weight of the edge ($$$1 \le w_i \le 2 \cdot 10^5$$$). It is guaranteed that the given edges form a tree. The last line of the input contains $$$m$$$ integers $$$q_1, q_2, \dots, q_m$$$ ($$$1 \le q_i \le 2 \cdot 10^5$$$), where $$$q_i$$$ is the maximum weight of an edge in the $$$i$$$-th query.
1,800
Print $$$m$$$ integers — the answers to the queries. The $$$i$$$-th value should be equal to the number of pairs of vertices $$$(u, v)$$$ ($$$u &lt; v$$$) such that the maximum weight of an edge on a simple path between $$$u$$$ and $$$v$$$ doesn't exceed $$$q_i$$$. Queries are numbered from $$$1$$$ to $$$m$$$ in the order of the input.
standard output
PASSED
0101578e6be7c5517b3c4677c311715a
train_003.jsonl
1567175700
You are given a weighted tree consisting of $$$n$$$ vertices. Recall that a tree is a connected graph without cycles. Vertices $$$u_i$$$ and $$$v_i$$$ are connected by an edge with weight $$$w_i$$$.You are given $$$m$$$ queries. The $$$i$$$-th query is given as an integer $$$q_i$$$. In this query you need to calculate the number of pairs of vertices $$$(u, v)$$$ ($$$u &lt; v$$$) such that the maximum weight of an edge on a simple path between $$$u$$$ and $$$v$$$ doesn't exceed $$$q_i$$$.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws IOException { Scanner s=new Scanner(System.in); int n=s.nextInt(); int m=s.nextInt(); Node ar[]=new Node[n-1]; for(int i=0;i<n-1;i++) { int u=s.nextInt(); int v=s.nextInt(); int w=s.nextInt(); u--; v--; ar[i]=new Node(u,v,w); } Pair br[]=new Pair[m]; for(int i=0;i<m;i++) { br[i]=new Pair(s.nextInt(),i); } Arrays.sort(ar,(a,b)->a.ti-b.ti); Arrays.sort(br,(a,b)->a.fi-b.fi); // for(int i=0;i<n-1;i++) // System.out.println(ar[i].fi+" "+ar[i].si+" "+ar[i].ti); // // for(int i=0;i<m;i++) // System.out.println(br[i].fi+" "+br[i].si); long ans[]=new long[m]; long leader[]=new long[n]; Arrays.fill(leader, 1); DSU dsu=new DSU(n); int j=0; long res=0; for(int i=0;i<m;i++) { while(j<n-1 && ar[j].ti<=br[i].fi) { int u=ar[j].fi; int v=ar[j].si; int w=ar[j].ti; u=dsu.get(u); v=dsu.get(v); // if(leader[u]<leader[v]) { // long tmp=leader[u]; // leader[u]=leader[v]; // leader[v]=tmp; // } dsu.union(u, v); res-=get(leader[u]); res-=get(leader[v]); leader[u]+=leader[v]; res+=get(leader[u]); // System.out.println("res :"+res+" and j :"+j); j++; } ans[br[i].si]=res; } for(int i=0;i<m;i++) System.out.print(ans[i]+" "); System.out.println(); } private static long get(long u) { // TODO Auto-generated method stub return (u*(u-1))/2; } } class DSU { int parent[]; int rank[]; int totalComponents; public DSU(int n) { parent=new int[n]; rank=new int[n]; for(int i=0;i<n;i++) { parent[i]=i; } totalComponents=n; } int get(int a) { if(a==parent[a]) return a; return parent[a]= get(parent[a]); } void union(int a, int b) { a=this.get(a); b=this.get(b); if(a!=b) { if(rank[a]<rank[b]) { int tmp=rank[a]; rank[a]=rank[b]; rank[b]=tmp; } parent[b]=a; if(rank[a]==rank[b]) rank[a]++; totalComponents--; } } } class Node{ int fi; int si; int ti; public Node(int fi,int si,int ti) { if(fi>si) { this.fi=si; this.si=fi; this.ti=ti; }else { this.fi=fi; this.si=si; this.ti=ti; } } } class Pair{ int fi; int si; public Pair(int fi,int si) { this.fi=fi; this.si=si; } }
Java
["7 5\n1 2 1\n3 2 3\n2 4 1\n4 5 2\n5 7 4\n3 6 2\n5 2 3 4 1", "1 2\n1 2", "3 3\n1 2 1\n2 3 2\n1 3 2"]
3 seconds
["21 7 15 21 3", "0 0", "1 3 3"]
NoteThe picture shows the tree from the first example:
Java 11
standard input
[ "graphs", "dsu", "divide and conquer", "sortings", "trees" ]
f94165f37e968442fa7f8be051018ad9
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the number of vertices in the tree and the number of queries. Each of the next $$$n - 1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by three integers $$$u_i$$$, $$$v_i$$$ and $$$w_i$$$ — the labels of vertices it connects ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$) and the weight of the edge ($$$1 \le w_i \le 2 \cdot 10^5$$$). It is guaranteed that the given edges form a tree. The last line of the input contains $$$m$$$ integers $$$q_1, q_2, \dots, q_m$$$ ($$$1 \le q_i \le 2 \cdot 10^5$$$), where $$$q_i$$$ is the maximum weight of an edge in the $$$i$$$-th query.
1,800
Print $$$m$$$ integers — the answers to the queries. The $$$i$$$-th value should be equal to the number of pairs of vertices $$$(u, v)$$$ ($$$u &lt; v$$$) such that the maximum weight of an edge on a simple path between $$$u$$$ and $$$v$$$ doesn't exceed $$$q_i$$$. Queries are numbered from $$$1$$$ to $$$m$$$ in the order of the input.
standard output
PASSED
f5e914ffe32710a769a2efd0e9a879ed
train_003.jsonl
1567175700
You are given a weighted tree consisting of $$$n$$$ vertices. Recall that a tree is a connected graph without cycles. Vertices $$$u_i$$$ and $$$v_i$$$ are connected by an edge with weight $$$w_i$$$.You are given $$$m$$$ queries. The $$$i$$$-th query is given as an integer $$$q_i$$$. In this query you need to calculate the number of pairs of vertices $$$(u, v)$$$ ($$$u &lt; v$$$) such that the maximum weight of an edge on a simple path between $$$u$$$ and $$$v$$$ doesn't exceed $$$q_i$$$.
256 megabytes
import java.util.*; import java.io.*; import java.math.BigInteger; public class Main { static final int mod=(int)1e9+7; static long[] size; static int[] p; static long pairs; public static void main(String[] args) throws Exception { FastReader in=new FastReader(); PrintWriter pw=new PrintWriter(System.out); int n=in.nextInt(); int q=in.nextInt(); size=new long[n+1]; p=new int[n+1]; ArrayList<Integer[]>[] E=new ArrayList[200001]; ArrayList<Integer>[] queries=new ArrayList[200001]; for(int i=1;i<=200000;i++) { E[i]=new ArrayList(); queries[i]=new ArrayList(); } for(int i=1;i<=n;i++) { size[i]=1; p[i]=i; } for(int i=1;i<n;i++) { int u=in.nextInt(); int v=in.nextInt(); int w=in.nextInt(); E[w].add(new Integer[]{u,v}); } for(int i=0;i<q;i++) queries[in.nextInt()].add(i); pairs=0; long[] ans=new long[q]; for(int i=1;i<=200000;i++) { for(Integer[] a:E[i]) union(a[0],a[1]); for(int j:queries[i]) ans[j]=pairs; } for(int i=0;i<q;i++) pw.print(ans[i]+" "); pw.flush(); } static int find(int a) { if(a==p[a]) return a; p[a]=find(p[a]); return p[a]; } static void union(int a,int b) { int c=find(a); int d=find(b); if(c==d) return; pairs+=size[c]*size[d]; if(size[c]>=size[d]) { size[c]+=size[d]; p[d]=c; } else { size[d]+=size[c]; p[c]=d; } } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } public String next() throws IOException { if(st==null || !st.hasMoreElements()) { 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()); } }
Java
["7 5\n1 2 1\n3 2 3\n2 4 1\n4 5 2\n5 7 4\n3 6 2\n5 2 3 4 1", "1 2\n1 2", "3 3\n1 2 1\n2 3 2\n1 3 2"]
3 seconds
["21 7 15 21 3", "0 0", "1 3 3"]
NoteThe picture shows the tree from the first example:
Java 11
standard input
[ "graphs", "dsu", "divide and conquer", "sortings", "trees" ]
f94165f37e968442fa7f8be051018ad9
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the number of vertices in the tree and the number of queries. Each of the next $$$n - 1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by three integers $$$u_i$$$, $$$v_i$$$ and $$$w_i$$$ — the labels of vertices it connects ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$) and the weight of the edge ($$$1 \le w_i \le 2 \cdot 10^5$$$). It is guaranteed that the given edges form a tree. The last line of the input contains $$$m$$$ integers $$$q_1, q_2, \dots, q_m$$$ ($$$1 \le q_i \le 2 \cdot 10^5$$$), where $$$q_i$$$ is the maximum weight of an edge in the $$$i$$$-th query.
1,800
Print $$$m$$$ integers — the answers to the queries. The $$$i$$$-th value should be equal to the number of pairs of vertices $$$(u, v)$$$ ($$$u &lt; v$$$) such that the maximum weight of an edge on a simple path between $$$u$$$ and $$$v$$$ doesn't exceed $$$q_i$$$. Queries are numbered from $$$1$$$ to $$$m$$$ in the order of the input.
standard output
PASSED
4251fba4ff1dcfb77b84401b9fce5f00
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; import java.io.*; public class ConstructingtheArray{ static int n,k; static StringBuilder answer; static HashMap<Integer,Integer> map=new HashMap<>(); public static void main(String[] args) throws IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); answer=new StringBuilder(); PrintWriter out=new PrintWriter(System.out); int t=Integer.parseInt(br.readLine().trim()); while(t-->0){ n=Integer.parseInt(br.readLine().trim()); int[] arr=new int[n+1]; PriorityQueue<pair> pq=new PriorityQueue<>(new ss()); pq.add(new pair(1,n)); for(int i=1;i<=n;i++){ pair curr=pq.poll(); int diff=curr.b-curr.a+1; int mid=0; if(diff%2==0){ mid=(curr.a+curr.b-1)/2; arr[mid]=i; } else{ mid=(curr.a+curr.b)/2; arr[mid]=i; } // System.out.println(Arrays.toString(arr)); pair left=new pair(curr.a,mid-1); pair right=new pair(mid+1,curr.b); if(left.a<=left.b){ // System.out.println(left.a+" L "+left.b); pq.add(left); } if(right.a<=right.b){ // System.out.println(right.a+" R "+right.b); pq.add(right); } } for(int i=1;i<=n;i++){ answer.append(arr[i]+" "); } answer.append("\n"); } out.println(answer); out.close(); } static class pair{ int a,b,c,d; pair(int a,int b){ this.a=a; this.b=b; } pair(int a,int b,int c,int d){ this.a=a; this.b=b; this.c=c; this.d=d; } } static class ss implements Comparator<pair>{ public int compare(pair a,pair b){ int dif1=a.b-a.a; int dif2=b.b-b.a; if(dif1==dif2){ return a.a-b.a; } else{ return dif2-dif1; } } } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
426db2f3e9a34a669743e56e2ee078c9
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class Main{ static long MOD = 998244353L; static long [] fac; static int[][] dir = new int[][]{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; public static void main(String[] args) { MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); // Start writing your solution here. ------------------------------------- int t = sc.nextInt(); //int t = 1; while(t-- > 0) { int n = sc.nextInt(); PriorityQueue <int[]> pq = new PriorityQueue<>((a1, a2) -> a2[1] != a1[1] ? a2[1] - a1[1] : a1[0] - a2[0]); pq.add(new int[]{0, n}); int a[] = new int[n]; int cnt = 1; while(!pq.isEmpty()) { int[] tmp = pq.poll(); int l = tmp[0], r = l + tmp[1] - 1; int mid = (l + r) / 2; a[mid] = cnt++; if(mid > l) pq.add(new int[]{l, mid - l}); if(r > l) pq.add(new int[]{mid + 1, r - mid}); } for(int i = 0; i < n; i ++) out.print(a[i] + " "); out.println(""); } out.close(); } public static long C(int n, int m) { if(m == 0 || m == n) return 1l; if(m > n || m < 0) return 0l; long res = fac[n] * quickPOW((fac[m] * fac[n - m]) % MOD, MOD - 2) % MOD; return res; } public static long quickPOW(long n, long m) { long ans = 1l; while(m > 0) { if(m % 2 == 1) ans = (ans * n) % MOD; n = (n * n) % MOD; m >>= 1; } return ans; } public static int gcd(int a, int b) { if(a % b == 0) return b; return gcd(b, a % b); } public static long gcd(long a, long b) { if(a % b == 0) return b; return gcd(b, a % b); } public static long solve(long x, long[] res){ int n = res.length; long a = x / n; int b = (int)(x % n); return res[n - 1] * a + res[b]; } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------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
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
51d46352b8a5977606f6fc8764a2d20c
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class ar { 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 (final 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 (final IOException e) { e.printStackTrace(); } return str; } } // static boolean[] seen; // static Map<Integer, Integer> map; // static Map<Long, Long> lmap; // static Set<Character> charset; // static Set<Integer> set; // static int[] arr; // static int[][] dp; // static int rem = (int) 1e9 + 7; // static List<List<Integer>> graph; // static int[][] kmv = { { 2, 1 }, { 1, 2 }, { 2, -1 }, { -1, 2 }, { -2, 1 }, { // 1, -2 }, { -1, -2 }, { -2, -1 } }; // static char[] car; // static boolean[] primes; // static int MAX = (int) 1e4 + 1; // static double[] dar; static long[] lar; // static long[][] dlar; // static void Sieve() { // primes = new boolean[MAX]; // primes[0] = true; // primes[1] = true; // for (int i = 2; i * i < MAX; i++) { // if (!primes[i]) { // for (int j = i * i; j < MAX; j += i) { // primes[j] = true; // } // } // } // } // static int[] t; static int func(int[] a, int[] b){ int len1=a[1]-a[0]+1; int len2=b[1]-b[0]+1; if(len1>len2||len2>len1){ return len2-len1; } return a[0]-b[0]; } public static void main(String[] args) throws java.lang.Exception { FastReader scn = new FastReader(); int T = scn.nextInt(); for(int t=0;t<T;t++){ int n=scn.nextInt(); PriorityQueue<int[]> pq = new PriorityQueue<>((a,b)->func(a,b)); pq.add(new int[]{0,n-1}); int[] arr = new int[n]; for(int i=1;i<=n;i++){ int[] sub=pq.poll(); if(sub[0]<0||sub[1]<0||sub[0]>=n||sub[1]>=n)continue; int ind=(sub[0]+sub[1])/2; arr[ind]=i; pq.add(new int[]{sub[0],ind-1}); pq.add(new int[]{ind+1,sub[1]}); } for(int k:arr){ System.out.print(k+" "); } System.out.print("\n"); } } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
4d83b93c117ff8d9ce19db86d38afec4
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; import java.io.*; public class Main { static public class InputIterator{ ArrayList<String> inputLine = new ArrayList<String>(1024); int index = 0; int max; InputIterator(){ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while(true){ String read; try{ read = br.readLine(); }catch(IOException e){ read = null; } if(read != null){ inputLine.add(read); }else{ break; } } max = inputLine.size(); } public boolean hasNext(){return (index < max);} public String next(){ if(hasNext()){ String returnStr = inputLine.get(index); index++; return returnStr; }else{ throw new IndexOutOfBoundsException("これ以上入力はないよ。"); } } } static InputIterator ii = new InputIterator(); static void myout(Object t){System.out.println(t);} static void myerr(Object t){System.err.println(t);} static String next(){return ii.next();} static int nextInt(){return Integer.parseInt(next());} static long nextLong(){return Long.parseLong(next());} static String[] nextStrArray(){return next().split(" ");} static String[] nextCharArray(){return mySplit(next());} static ArrayList<Integer> nextIntArray(){ ArrayList<Integer> ret = new ArrayList<Integer>(); String[] input = nextStrArray(); for(int i = 0; i < input.length; i++){ ret.add(Integer.parseInt(input[i])); } return ret; } static ArrayList<Long> nextLongArray(){ ArrayList<Long> ret = new ArrayList<Long>(); String[] input = nextStrArray(); for(int i = 0; i < input.length; i++){ ret.add(Long.parseLong(input[i])); } return ret; } static String[] mySplit(String str){return str.split("");} static String kaigyoToStr(String[] list){return String.join("\n",list);} static String kaigyoToStr(ArrayList<String> list){return String.join("\n",list);} static String hanSpToStr(String[] list){return String.join(" ",list);} static String hanSpToStr(ArrayList<String> list){return String.join(" ",list);} public static void main(String[] args){ int t = nextInt(); for(int i = 0; i < t; i++){ int N = nextInt(); String[] output = new String[N]; PriorityQueue<Integer[]> pq = new PriorityQueue<>(new originComparator()); int count = 1; Integer[] first = new Integer[2]; first[0] = 1; first[1] = N; pq.add(first); while(pq.size() > 0){ Integer[] tmp = pq.poll(); int L = tmp[0]; int R = tmp[1]; int no; if((tmp[1] - tmp[0] + 1) % 2 == 1){ no = (tmp[0] + tmp[1]) / 2; }else{ no = (tmp[0] + tmp[1] - 1) / 2; } output[no - 1] = String.valueOf(count); count++; if(L == R){ continue; }else if(L + 1 == R){ Integer[] pushQueue = new Integer[2]; pushQueue[0] = R; pushQueue[1] = R; pq.add(pushQueue); }else{ Integer[] pushQueue1 = new Integer[2]; pushQueue1[0] = no + 1; pushQueue1[1] = R; pq.add(pushQueue1); Integer[] pushQueue2 = new Integer[2]; pushQueue2[0] = L; pushQueue2[1] = no - 1; pq.add(pushQueue2); } } myout(hanSpToStr(output)); } } //Method addition frame start public static class originComparator implements Comparator<Integer[]>{ public int compare(Integer[] mae, Integer[] ato){ if(mae[1] - mae[0] == ato[1] - ato[0]){ return mae[0] - ato[0]; }else{ return (ato[1] - ato[0]) - (mae[1] - mae[0]); } } } //Method addition frame end }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
7b7deaa120d6f9c82cdb430332ac06bd
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.awt.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Comparator; import java.util.PriorityQueue; import java.util.Scanner; import java.util.StringTokenizer; public class Recursion { static long dp[][]; static int n; static int a[]; static int ans[]; public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); int pandey=sc.nextInt(); while (pandey-->0) { int n = sc.nextInt(); ans = new int[n]; int x = 1; PriorityQueue<Point> pinky=new PriorityQueue<>(new Comparator<Point>() { @Override public int compare(Point o1, Point o2) { if ((o1.y-o1.x+1)-(o2.y-o2.x+1)==0)return o1.x-o2.x; return -((o1.y-o1.x+1)-(o2.y-o2.x+1)); } }); pinky.add(new Point(0,n-1)); while (!pinky.isEmpty()){ Point p=pinky.poll(); int c=p.x+(p.y-p.x)/2; ans[c]=x++; if (p.x<=c-1){ pinky.add(new Point(p.x,c-1)); } if (c+1<=p.y){ pinky.add(new Point(c+1,p.y)); } } StringBuilder arun=new StringBuilder(); for (int tt:ans)arun.append(tt+" "); System.out.println(arun); } }}
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
bf735f506a6c22eadba9e6db86d3da05
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
//package round642; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import java.util.PriorityQueue; public class D { InputStream is; PrintWriter out; String INPUT = ""; void solve() { for(int T = ni();T > 0;T--)go(); } void go() { int n = ni(); PriorityQueue<int[]> pq = new PriorityQueue<>((x, y) -> { if(x[0] != y[0])return -(x[0] - y[0]); return x[1] - y[1]; }); pq.add(new int[]{n, 0}); int[] ans = new int[n]; int step = 1; while(step <= n){ int[] cur = pq.poll(); ans[cur[1]+(cur[0]-1)/2] = step++; pq.add(new int[]{(cur[0]-1)/2, cur[1]}); pq.add(new int[]{cur[0]-(cur[0]-1)/2-1, cur[1]+(cur[0]-1)/2+1}); } for(int v : ans){ out.print(v + " "); } out.println(); } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new D().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
daea119e649e1f3a973980cbc1cde985
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.Queue; import java.util.*; import java.io.*; public class Constructing_The_Array { 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) { // TODO Auto-generated method stub FastReader t = new FastReader(); // PrintWriter o = new PrintWriter(System.out); Constructing_The_Array obj = new Constructing_The_Array(); obj.solve(); // o.flush(); // o.close(); } class PAIR implements Comparable<PAIR> { int l; int r; int size; PAIR(int l, int r) { this.l = l; this.r = r; this.size = r - l + 1; } public int compareTo(PAIR o) { return o.size - this.size != 0 ? o.size - this.size : this.l - o.l; } } public void solve() { FastReader t = new FastReader(); // PrintWriter o = new PrintWriter(System.out); int test = t.nextInt(); while (test-- > 0) { int n = t.nextInt(); int num = 1; Queue<PAIR> queue = new PriorityQueue<>(); int[] a = new int[n + 1]; // System.out.println(n); queue.add(new PAIR(1, n)); while (!queue.isEmpty()) { PAIR p = queue.remove(); int l = p.l; int r = p.r; int mid = (r + l) / 2; if (l > r) continue; a[(r + l) / 2] = num++; if (((r - l + 1) & 1) == 1) { queue.add(new PAIR(l, mid - 1)); queue.add(new PAIR(mid + 1, r)); } else { queue.add(new PAIR(mid + 1, r)); queue.add(new PAIR(l, mid - 1)); } } for (int i = 1; i <= n; ++i) System.out.print(a[i] + " "); System.out.println(); } // o.flush(); // o.close(); } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
3c0ae84a0c726012ee2a6bd344d7c3bb
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
/*input 6 1 2 3 4 5 6 */ import java.math.*; import java.io.*; import java.util.*; public class Main { static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } static Reader sc=new Reader(); static BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out)); public static void main(String args[])throws IOException { /* * For integer input: int n=inputInt(); * For long input: long n=inputLong(); * For double input: double n=inputDouble(); * For String input: String s=inputString(); * Logic goes here * For printing without space: print(a+""); where a is a variable of any datatype * For printing with space: printSp(a+""); where a is a variable of any datatype * For printing with new line: println(a+""); where a is a variable of any datatype */ int t=inputInt(); while(t-- >0) { int n=inputInt(); int[] a=new int[n+1]; PriorityQueue<int[]>pq=new PriorityQueue<>((ax,b)->ax[2]==b[2]?ax[0]-b[0]:b[2]-ax[2]); int temp[]={1,n,n}; pq.add(temp); for(int i=1;i<=n;i++) { int[] ar= pq.remove(); int l=ar[0]; int r=ar[1]; int mid; //println(l+" "+r+""); if((r-l+1)%2==1) { mid=(l+r)/2; } else { mid=(l+r-1)/2; } a[mid]=i; if(mid-l>0) { pq.add(new int[]{l,mid-1,mid-l}); } if(r-mid>0) pq.add(new int[]{mid+1,r,r-mid}); } for(int i=1;i<=n;i++) { print(a[i]+" "); } println(""); } bw.flush(); bw.close(); } public static int gcd(int a,int b) { if(b==0) return a; return gcd(b,a%b); } public static int inputInt()throws IOException { return sc.nextInt(); } public static long inputLong()throws IOException { return sc.nextLong(); } public static double inputDouble()throws IOException { return sc.nextDouble(); } public static String inputString()throws IOException { return sc.readLine(); } public static void print(String a)throws IOException { bw.write(a); } public static void printSp(String a)throws IOException { bw.write(a+" "); } public static void println(String a)throws IOException { bw.write(a+"\n"); } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
607c41df674605ad85243763ec7bebbd
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.*; public class Main{ static void main() throws Exception{ int n=sc.nextInt(); PriorityQueue<int[]>pq=new PriorityQueue<>((x,y)->y[0]==x[0]?x[1]-y[1]:y[0]-x[0]); pq.add(new int[] {n,0,n-1}); int[]ans=new int[n]; int cur=1; while(!pq.isEmpty()) { int[]curSegment=pq.poll(); int start=curSegment[1],end=curSegment[2]; if(start>end)continue; int mid=(start+end)>>1; ans[mid]=cur++; if(start==end)continue; int len1=(mid-1-start+1),len2=end-(mid+1)+1; pq.add(new int[] {len1,start,mid-1}); pq.add(new int[] {len2,mid+1,end}); } for(int i:ans)pw.print(i+" "); pw.println(); } public static void main(String[] args) throws Exception{ pw=new PrintWriter(System.out); sc = new MScanner(System.in); int tc=sc.nextInt(); while(tc-->0)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
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
4bf2fc1d9d203f99cfb487edce9afdcc
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
/** * * @author Harshwardhan Yadav */ import java.math.*; import java.io.*; import java.util.*; public class Codeforces { /** * @param args the command line arguments */ static class Valueable{ int l,r; Valueable(int l,int r) { this.l=l; this.r=r; } } static class Sortbyroll implements Comparator<Valueable> { // Used for sorting in ascending order of // roll number @Override public int compare(Valueable a,Valueable b) { return a.l-b.l; } } static int findMaxElementIndex(int ar[]) { int index=0; int max=0; int n=ar.length; for(int i=0;i<n;i++) { if(ar[i]>max) { max=ar[i]; index=i; } } return index; } static int findMaxElement(int ar[]) { int max=0; int n=ar.length; for(int i=0;i<n;i++) { if(ar[i]>max) { max=ar[i]; } } return max; } static int binarySearch(int arr[],int value,int start,int end) { int mid=(start+end)/2; int result; if(start<=end) { if(arr[mid]==value) { return mid; } else if(arr[mid]<value) { result=binarySearch(arr, value, mid+1, end); } else{ result=binarySearch(arr, value, start, mid-1); } } else{ return -1; } return result; } 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[] nextIntArray(int n) { int arr[]=new int[n]; for(int i=0;i<n;i++) { arr[i]=Integer.parseInt(next()); } return arr; } Integer[] nextIntegerArray(int n) { Integer arr[]=new Integer[n]; for(Integer i=0;i<n;i++) { arr[i]=Integer.parseInt(next()); } return arr; } long[] nextLongArray(int n) { long arr[]=new long[n]; for(int i=0;i<n;i++) { arr[i]=Long.parseLong(next()); } return arr; } } static int gcd(Integer a,Integer b) { if(b==0) return a; else return gcd(b,a%b); } static boolean checkForPrime(long inputNumber) { boolean isItPrime = true; if(inputNumber <= 1) { isItPrime = false; return isItPrime; } else { if(inputNumber%2==0 && inputNumber==2) { return true; } else if(inputNumber%2==0) { return false; } else{ int check=(int)Math.sqrt(inputNumber); for (int i = 3; i<= check; i+=2) { if ((inputNumber % i) == 0) { isItPrime = false; break; } } } } return isItPrime; } static SortedSet<Valueable> ts=new TreeSet<Valueable>(new Comparator<Valueable>(){ @Override public int compare(Valueable a,Valueable b) { if(a.r-a.l==b.r-b.l) { return a.l-b.l; } else{ return (-1)*((a.r-a.l)-(b.r-b.l)); } } } ); static Valueable[] queue=new Valueable[200000]; static int F=-1,R=-1; static void solve(int arr[],int l,int r,int count) { if(l<=r) { if((r-l+1)%2!=0) { arr[(l+r)/2]=count; if(l<=(l+r)/2-1) ts.add(new Valueable(l,(l+r)/2-1)); if((l+r)/2+1<=r) ts.add(new Valueable((l+r)/2+1,r)); } else{ arr[(l+r-1)/2]=count; if((l+r-1)/2+1<=r) ts.add(new Valueable((l+r-1)/2+1,r)); if(l<=(l+r-1)/2-1) ts.add(new Valueable(l,(l+r-1)/2-1)); } } } static void enqueue(int l,int r) { R++; queue[R]=new Valueable(l,r); if(F==-1) F++; } static Valueable dequeue() { Valueable ob=queue[F]; if(F==R) F=R=-1; else F++; return ob; } public static void main(String[] args) throws UnsupportedEncodingException, IOException { // TODO code application logic here FastReader sc=new FastReader(); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(java.io.FileDescriptor.out), "ASCII"), 512); int t=sc.nextInt(); for(int test=0;test<t;test++) { int n=sc.nextInt(); int[] arr=new int[n]; int count=1,l=0,r=n-1; solve(arr,l,r,count); while(!ts.isEmpty()) { count++; Valueable ob=ts.first(); ts.remove(ob); solve(arr,ob.l,ob.r,count); } for(int i=0;i<n;i++) { out.write(arr[i]+" "); } out.write("\n"); out.flush(); } out.close(); } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
cac000e3a2b7be2b400381e21798411b
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.*; public class Q3 { static Print print; private static class E { int len; int l; E(int i,int j) { len=i; l=j; } } public static void main(String args[]) throws Exception { Scan scan = new Scan(); print = new Print(); int T = scan.scanInt(); while (T-- > 0) { int N=scan.scanInt(); int arr[]=new int[N]; PriorityQueue<E> pq = new PriorityQueue<E>(new Comparator<E>() { public int compare(E e1,E e2) { if(e1.len>e2.len) { return -1; } else if(e1.len<e2.len) { return 1; } else { if(e1.l<e2.l) { return -1; } else { return 1; } } } }); pq.add(new E(N,0)); int counter=1; while(!pq.isEmpty() && counter<=N) { E e=pq.poll(); if(e.len==0) { break; } int index=e.l+e.l+e.len-1; index/=2; arr[index]=counter; if(e.len!=1) { if((e.len&1)==0) { if(arr[e.l]==0) { pq.add(new E((e.len/2)-1,e.l)); } if(arr[index+1]==0) { pq.add(new E(e.len/2,index+1)); } } else { if(arr[e.l]==0) { pq.add(new E(e.len/2,e.l)); } if(arr[index+1]==0) { pq.add(new E(e.len/2,index+1)); } } } counter++; } for(int i:arr) { print.print(i+" "); } print.println(""); } print.close(); } public static class Print { private final BufferedWriter bw; public Print() { this.bw = new BufferedWriter(new OutputStreamWriter(System.out)); } public void print(Object object) throws IOException { bw.append("" + object); } public void println(Object object) throws IOException { print(object); bw.append("\n"); } public void close() throws IOException { bw.close(); } } static class Scan { private byte[] buf = new byte[1024 * 1024 * 4]; private int index; private InputStream in; private int total; public Scan() { in = System.in; } public int scan() throws IOException { if (total < 0) throw new InputMismatchException(); if (index >= total) { index = 0; total = in.read(buf); if (total <= 0) return -1; } return buf[index++]; } public int scanInt() throws IOException { int integer = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { integer *= 10; integer += n - '0'; n = scan(); } else throw new InputMismatchException(); } return neg * integer; } public double scanDouble() throws IOException { double doub = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n) && n != '.') { if (n >= '0' && n <= '9') { doub *= 10; doub += n - '0'; n = scan(); } else throw new InputMismatchException(); } if (n == '.') { n = scan(); double temp = 1; while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { temp /= 10; doub += (n - '0') * temp; n = scan(); } else throw new InputMismatchException(); } } return doub * neg; } public long scanLong() throws IOException { long ret = 0; long c = scan(); while (c <= ' ') { c = scan(); } boolean neg = (c == '-'); if (neg) { c = scan(); } do { ret = ret * 10 + c - '0'; } while ((c = scan()) >= '0' && c <= '9'); if (neg) { return -ret; } return ret; } public String scanString() throws IOException { StringBuilder sb = new StringBuilder(); int n = scan(); while (isWhiteSpace(n)) n = scan(); while (!isWhiteSpace(n) || n == ' ') { sb.append((char) n); n = scan(); } return sb.toString(); } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; return false; } } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
5635bfdcb1686ebfd13bf85609a2f719
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class test { static int INF = 1000000007; public static void main(String[] args) { int test = fs.nextInt(); // int test = 1; for (int cases = 0; cases < test; cases++) { int n = fs.nextInt(); TreeSet<Pair> set = new TreeSet<>(new Comparator<Pair>() { @Override public int compare(Pair o1, Pair o2) { // TODO Auto-generated method stub int l1 = o1.second - o1.first; int l2 = o2.second - o2.first; if (l2 > l1) { return 1; } else if (l1 > l2) { return -1; } else { if (o1.first < o2.first) { return -1; } else { return 1; } } } }); set.add(new Pair(0, n - 1)); int ar[] = new int[n]; int z = 1; while (z <= n) { Pair x = set.first() != null ? set.first() : new Pair(-1, -1); int start = x.first; int end = x.second; set.pollFirst(); int mid = (end + start) / 2; ar[mid] = z; if (start < mid) set.add(new Pair(start, mid - 1)); if (mid < end) set.add(new Pair(mid + 1, end)); ++z; } for (int i : ar) { System.out.print(i + " "); } System.out.println(); } } static class Cpair { char x; int c; Cpair(char x, int c) { this.x = x; this.c = c; } } static long power(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } static long modInverse(long n, long p) { return power(n, p - 2, p); } static long nCrModPFermat(long n, long r, long p) { long ans1 = 1; long i = n; long k = r; while (k > 0) { ans1 = mul(ans1, i, p); i--; k--; } long ans2 = 1; while (r > 0) { ans2 = mul(ans2, r, p); r--; } r = modInverse(ans2, p); ans1 = mul(ans1, r, p); return ans1; } static long facCalc(long total) { long ans = 1; for (long i = 2; i <= total; i++) { ans = mul(ans, i, INF); } return ans; } static long mul(long a, long b, long p) { return ((a % p) * (b % p)) % p; } static void sieve() { boolean prime[] = new boolean[101]; Arrays.fill(prime, true); prime[1] = false; for (int i = 2; i * i <= prime.length - 1; i++) { for (int j = i * i; j <= prime.length - 1; j += i) { prime[j] = false; } } } public static int[] radixSort(int[] f) { return radixSort(f, f.length); } public static int[] radixSort(int[] f, int n) { int[] to = new int[n]; { int[] b = new int[65537]; for (int i = 0; i < n; i++) b[1 + (f[i] & 0xffff)]++; for (int i = 1; i <= 65536; i++) b[i] += b[i - 1]; for (int i = 0; i < n; i++) to[b[f[i] & 0xffff]++] = f[i]; int[] d = f; f = to; to = d; } { int[] b = new int[65537]; for (int i = 0; i < n; i++) b[1 + (f[i] >>> 16)]++; for (int i = 1; i <= 65536; i++) b[i] += b[i - 1]; for (int i = 0; i < n; i++) to[b[f[i] >>> 16]++] = f[i]; int[] d = f; f = to; to = d; } return f; } static void printArray(int ar[]) { System.out.println(Arrays.toString(ar)); } static class Pair { int first, second; public Pair(int first, int second) { this.first = first; this.second = second; } } static class LongPair { long first; long second; LongPair(long a, long b) { this.first = a; this.second = b; } } static long expmodulo(long a, long b, long c) { long x = 1; long y = a; while (b > 0) { if (b % 2 == 1) { x = (x * y) % c; } y = (y * y) % c; // squaring the base b /= 2; } return (long) x % c; } // static int modInverse(int a, int m) { // int m0 = m; // int y = 0, x = 1; // // if (m == 1) // return 0; // // while (a > 1) { // int q = a / m; // int t = m; // m = a % m; // a = t; // t = y; // y = x - q * y; // x = t; // } // if (x < 0) // x += m0; // return x; // } static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } static void sortMyMapusingValues(HashMap<Integer, Integer> hm) { List<Map.Entry<Integer, Integer>> capitalList = new LinkedList<>(hm.entrySet()); Collections.sort(capitalList, new Comparator<Map.Entry<Integer, Integer>>() { public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) { return (o1.getValue()).compareTo(o2.getValue()); } }); HashMap<Integer, Integer> result = new HashMap<>(); for (Map.Entry<Integer, Integer> entry : capitalList) { result.put(entry.getKey(), entry.getValue()); } } static boolean ispowerof2(long num) { if ((num & (num - 1)) == 0) return true; return false; } static void primeFactors(int n) { while (n % 2 == 0) { System.out.print(2 + " "); n /= 2; } for (int i = 3; i <= Math.sqrt(n); i += 2) { while (n % i == 0) { System.out.print(i + " "); n /= i; } } if (n > 2) System.out.print(n); } static boolean isPrime(long n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; long sq = (long) Math.sqrt(n); for (int i = 5; i <= sq; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static class Graph { HashMap<Integer, LinkedList<Integer>> hm = new HashMap<Integer, LinkedList<Integer>>(); private void addVertex(int vertex) { hm.put(vertex, new LinkedList<>()); } private void addEdge(int source, int dest, boolean bi) { if (!hm.containsKey(source)) addVertex(source); if (!hm.containsKey(dest)) addVertex(dest); hm.get(source).add(dest); if (bi) { hm.get(dest).add(source); } } private boolean uniCycle(int i, HashSet<Integer> visited, int parent) { visited.add(i); LinkedList<Integer> list = hm.get(i); Iterator<Integer> it = list.iterator(); while (it.hasNext()) { Integer integer = (Integer) it.next(); if (!visited.contains(integer)) { if (uniCycle(integer, visited, i)) return true; } else if (integer != parent) { return true; } } return false; } private boolean uniCyclic() { HashSet<Integer> visited = new HashSet<Integer>(); Set<Integer> set = hm.keySet(); for (Integer integer : set) { if (!visited.contains(integer)) { if (uniCycle(integer, visited, -1)) { return true; } } } return false; } private boolean isbiCycle(int i, HashSet<Integer> visited, HashSet<Integer> countered) { if (countered.contains(i)) return true; if (visited.contains(i)) return false; visited.add(i); countered.add(i); LinkedList<Integer> list = hm.get(i); Iterator<Integer> it = list.iterator(); while (it.hasNext()) { Integer integer = (Integer) it.next(); if (isbiCycle(integer, visited, countered)) { return true; } } countered.remove(i); return false; } Boolean isReachable(int s, int d, int k) { if (hm.isEmpty()) { return false; } LinkedList<Integer> temp; boolean visited[] = new boolean[k]; LinkedList<Integer> queue = new LinkedList<Integer>(); visited[s] = true; queue.add(s); Iterator<Integer> i; while (queue.size() != 0) { s = queue.poll(); int n; i = hm.get(s).listIterator(); // Get all adjacent vertices of the dequeued vertex s // If a adjacent has not been visited, then mark it // visited and enqueue it while (i.hasNext()) { n = i.next(); // If this adjacent node is the destination node, // then return true if (n == d) return true; // Else, continue to do BFS if (!visited[n]) { visited[n] = true; queue.add(n); } } } // If BFS is complete without visited d return false; } private boolean isbiCyclic() { HashSet<Integer> visited = new HashSet<Integer>(); HashSet<Integer> countered = new HashSet<Integer>(); Set<Integer> set = hm.keySet(); for (Integer integer : set) { if (isbiCycle(integer, visited, countered)) { return true; } } return false; } } static class Node { Node left, right; int data; public Node(int data) { this.data = data; } public void insert(int val) { if (val <= data) { if (left == null) { left = new Node(val); } else { left.insert(val); } } else { if (right == null) { right = new Node(val); } else { right.insert(val); } } } public boolean contains(int val) { if (data == val) { return true; } else if (val < data) { if (left == null) { return false; } else { return left.contains(val); } } else { if (right == null) { return false; } else { return right.contains(val); } } } public void inorder() { if (left != null) { left.inorder(); } System.out.print(data + " "); if (right != null) { right.inorder(); } } public int maxDepth() { if (left == null) return 0; if (right == null) return 0; else { int ll = left.maxDepth(); int rr = right.maxDepth(); if (ll > rr) return (ll + 1); else return (rr + 1); } } public int countNodes() { if (left == null) return 1; if (right == null) return 1; else { return left.countNodes() + right.countNodes() + 1; } } public void preorder() { System.out.print(data + " "); if (left != null) { left.inorder(); } if (right != null) { right.inorder(); } } public void postorder() { if (left != null) { left.inorder(); } if (right != null) { right.inorder(); } System.out.print(data + " "); } public void levelorder(Node node) { LinkedList<Node> ll = new LinkedList<Node>(); ll.add(node); getorder(ll); } public void getorder(LinkedList<Node> ll) { while (!ll.isEmpty()) { Node node = ll.poll(); System.out.print(node.data + " "); if (node.left != null) ll.add(node.left); if (node.right != null) ll.add(node.right); } } } 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 OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } private static final FastReader fs = new FastReader(); private static final OutputWriter op = new OutputWriter(System.out); }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
f91abb5b8e2cb52e629df71ea4330461
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
//note: 0<=|int|<=2 * 10^9 //note: 0<=|long|<= 9 * 10^18 import java.io.*; import java.util.*; public class MyProgram{ static ArrayList<Integer>[] adj; static StringTokenizer st; static BufferedReader br; static class Comp implements Comparator<int[]>{ public int compare(int[] i1, int[] i2){ if(i2[1] - i2[0] == i1[1] - i1[0]){ return Integer.compare(i1[0], i2[0]); } else{ return Integer.compare(i2[1]-i2[0],i1[1]-i1[0]); } } } public static void main(String[] args) throws IOException{ MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); int t = sc.nextInt(); for(int i = 0; i < t; i++){ int n = sc.nextInt(); int[] arr = new int[n]; PriorityQueue<int[]> pq = new PriorityQueue<>(new Comp()); int[] start = {0,n-1}; pq.add(start); int count = 1; while(!pq.isEmpty()){ int[] k = pq.poll(); int left = k[0]; int mid = k[0] + (k[1] - k[0])/2; int right = k[1]; if(right - left == 1){ int[] add = {k[1], k[1]}; pq.add(add); } else if(right - left != 0){ int[] add1 = {k[0], mid - 1}; int[] add2 = {mid+1, k[1]}; pq.add(add1); pq.add(add2); } arr[mid] = count++; } for(int j : arr){ System.out.print(j + " "); } System.out.println(); } out.close(); } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------MyScanner class for faster input---------- public static class MyScanner { 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
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
3a1fb10c7aed7e755e43444bc4c2293b
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.PrintStream; import java.util.PriorityQueue; import java.util.Scanner; /** * Codeforces Problem 1353D */ public class Solution { public static void main(String args[]) { try (Scanner in = new Scanner(System.in); PrintStream out = System.out;) { int t = in.nextInt(); for (int i = 1; i <= t; i++) { String solution = solveNext(in); // out.println("Case #" + i + ": " + solution); out.println(solution); out.flush(); } } System.exit(0); } public static String solveNext(Scanner in) { int n = in.nextInt(); return new Solution(n).solve(); } int n; public Solution(int n) { this.n = n; } private static class Segment implements Comparable<Segment> { int l; int r; int size; public Segment(int l, int r) { this.l = l; this.r = r; this.size = r - l + 1; } @Override public int compareTo(Segment o) { int comp = -Integer.compare(this.size, o.size); if(comp == 0){ return Integer.compare(this.l, o.l); } return comp; } } public String solve() { int curr = 1; PriorityQueue<Segment> queue = new PriorityQueue<>(); queue.add(new Segment(1, this.n)); int[] arr = new int[this.n]; while(!queue.isEmpty()){ Segment next = queue.poll(); int mid = (next.l + next.r) / 2; arr[mid - 1] = curr; curr++; if(mid > next.l){ queue.add(new Segment(next.l, mid - 1)); } if(mid < next.r){ queue.add(new Segment(mid + 1, next.r)); } } StringBuilder sb = new StringBuilder(); for (int i = 0; i < this.n; i++) { if (i > 0) { sb.append(" "); } sb.append(arr[i]); } return sb.toString(); } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
3a15612c4b9f73266e8b984f22e69358
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.*; public class Q3 { static Print print; private static class E { int len; int l; E(int i,int j) { len=i; l=j; } } public static void main(String args[]) throws Exception { Scan scan = new Scan(); print = new Print(); int T = scan.scanInt(); while (T-- > 0) { int N=scan.scanInt(); int arr[]=new int[N]; PriorityQueue<E> pq = new PriorityQueue<E>(new Comparator<E>() { public int compare(E e1,E e2) { if(e1.len>e2.len) { return -1; } else if(e1.len<e2.len) { return 1; } else { if(e1.l<e2.l) { return -1; } else { return 1; } } } }); pq.add(new E(N,0)); int counter=1; while(!pq.isEmpty() && counter<=N) { E e=pq.poll(); if(e.len==0) { break; } int index=e.l+e.l+e.len-1; index/=2; arr[index]=counter; if(e.len!=1) { if((e.len&1)==0) { if(arr[e.l]==0) { pq.add(new E((e.len/2)-1,e.l)); } if(arr[index+1]==0) { pq.add(new E(e.len/2,index+1)); } } else { if(arr[e.l]==0) { pq.add(new E(e.len/2,e.l)); } if(arr[index+1]==0) { pq.add(new E(e.len/2,index+1)); } } } counter++; } for(int i:arr) { print.print(i+" "); } print.println(""); } print.close(); } public static class Print { private final BufferedWriter bw; public Print() { this.bw = new BufferedWriter(new OutputStreamWriter(System.out)); } public void print(Object object) throws IOException { bw.append("" + object); } public void println(Object object) throws IOException { print(object); bw.append("\n"); } public void close() throws IOException { bw.close(); } } static class Scan { private byte[] buf = new byte[1024 * 1024 * 4]; private int index; private InputStream in; private int total; public Scan() { in = System.in; } public int scan() throws IOException { if (total < 0) throw new InputMismatchException(); if (index >= total) { index = 0; total = in.read(buf); if (total <= 0) return -1; } return buf[index++]; } public int scanInt() throws IOException { int integer = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { integer *= 10; integer += n - '0'; n = scan(); } else throw new InputMismatchException(); } return neg * integer; } public double scanDouble() throws IOException { double doub = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n) && n != '.') { if (n >= '0' && n <= '9') { doub *= 10; doub += n - '0'; n = scan(); } else throw new InputMismatchException(); } if (n == '.') { n = scan(); double temp = 1; while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { temp /= 10; doub += (n - '0') * temp; n = scan(); } else throw new InputMismatchException(); } } return doub * neg; } public long scanLong() throws IOException { long ret = 0; long c = scan(); while (c <= ' ') { c = scan(); } boolean neg = (c == '-'); if (neg) { c = scan(); } do { ret = ret * 10 + c - '0'; } while ((c = scan()) >= '0' && c <= '9'); if (neg) { return -ret; } return ret; } public String scanString() throws IOException { StringBuilder sb = new StringBuilder(); int n = scan(); while (isWhiteSpace(n)) n = scan(); while (!isWhiteSpace(n) || n == ' ') { sb.append((char) n); n = scan(); } return sb.toString(); } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; return false; } } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
ce0f7777d9f24a97d0a47a82db05cee5
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; import java.io.*; // import java.lang.*; // import java.math.BigInteger; public class prac { public static int AP; public static int M = 998244353; static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } public static int[] arr; public static int n; // public static long M = 1000000007; public static void main(String[] args) throws IOException{ Reader s = new Reader(); int t = s.nextInt(); while (t-- > 0) { n = s.nextInt(); arr = new int[n + 1]; int l=1,r=n; PriorityQueue<pair> q = new PriorityQueue<pair>(new pairComparator()); q.add(new pair(l,r)); int i=1; while(!q.isEmpty()){ pair tmp = q.poll(); l = tmp.x; r=tmp.y; // System.out.println(tmp.x + " " + tmp.y); if(tmp.x > tmp.y){ continue; } if(i > n){ break; } int m = func(tmp.x,tmp.y,i++); // System.out.println(l + " " + (m - 1) + " " + (m + 1)+" "+r); if(l <= m -1){ q.add(new pair(l,m - 1)); } if(m + 1 <= r){ q.add(new pair(m + 1,r)); } } for(int j=1;j<=n;j++){ System.out.print(arr[j] + " "); } System.out.println(); } } public static int func(int l , int r,int i){ int m = (l + r)/2; arr[m] = i; return m; } } class pair{ int x; int y; pair(int x,int y){ this.x = x; this.y = y; } } class pairComparator implements Comparator<pair>{ public int compare(pair p1, pair p2) { int p1_dist = Math.abs(p1.y - p1.x); int p2_dist = Math.abs(p2.y - p2.x); if(p1_dist < p2_dist){ return 1; } else if(p1_dist > p2_dist){ return -1; } else{ if(p1.x > p2.x){ return 1; } else{ return -1; } } } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
095c06a9d630ec36e9cab96de1bf1c51
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
// Problem: D. Constructing the Array // Contest: Codeforces - Codeforces Round #642 (Div. 3) // URL: http://codeforces.com/problemset/problem/1353/D // Memory Limit: 256 MB // Time Limit: 1000 ms // Powered by CP Editor (https://github.com/cpeditor/cpeditor) import java.io.*; import java.util.*; public class Main { private static PrintWriter pw = new PrintWriter(System.out); private static InputReader sc = new InputReader(); static class Pair{ int first, second; Pair(int first, int second){ this.first = first; this.second = second; } } static class InputReader{ private static BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); private static StringTokenizer tk; private void next()throws IOException{ while(tk == null || !tk.hasMoreTokens()) tk = new StringTokenizer(r.readLine()); } private int nextInt()throws IOException{ next(); return Integer.parseInt(tk.nextToken()); } } public static void main(String args[])throws IOException{ int t = sc.nextInt(); while(t-->0) solve(); pw.flush(); pw.close(); } private static void solve()throws IOException{ int n = sc.nextInt(), cnt = 0, res[] = new int[n]; TreeMap<Integer, TreeSet<Integer>> map = new TreeMap<>(); map.put(n, new TreeSet<>()); map.get(n).add(0); while(!map.isEmpty()){ // pw.println(map); int len = map.lastKey(); TreeSet<Integer> currset = map.get(len); int pos = currset.first(); res[pos+(len-1)/2] = ++cnt; currset.remove(pos); if(currset.isEmpty()) map.remove(len); if(len > 1){ int len2 = len/2, pos2 = pos + len - len2; map.putIfAbsent(len2, new TreeSet<>()); map.get(len2).add(pos2); if(len > 2){ int len1 = (len - 1)/2, pos1 = pos; map.putIfAbsent(len1, new TreeSet<>()); map.get(len1).add(pos1); } } } for(int i = 0; i < n; i++) pw.print(+res[i]+" "); pw.println(); } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
8de7ad46eb582b3fbd99fd2ee062eec0
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws Exception { Reader read = new Reader(); int test = read.nextInt(); while (test-->0){ // System.out.println("Test "+test); ArrayList<range> sorted= new ArrayList<range>(); PriorityQueue<range> pQ = new PriorityQueue<>(); int n =read.nextInt(); long[] arr = new long[n+1]; range ob =new range(1,n,n-1); sorted.add(ob); pQ.add(ob); long i=1; while (!sorted.isEmpty() && i<=n){ // range x =sorted.get(0); // sorted.remove(x); range x = pQ.poll(); int ind = (x.l+x.r)/2; // System.out.println("Index "+ ind); //ind=ind/2; arr[ind]=i; int l= x.l; int r = x.r; int mid = (x.l+x.r)/2; pQ.add(new range(l,mid-1,mid-1-l)); pQ.add(new range(mid+1,r,r-(mid+1))); // Collections.sort(sorted,new sortRange()); // System.out.println(sorted.get(0).l+ " "+sorted.get(0).r); i+=1; } for(int j=1;j<=n;j++){ System.out.print(arr[j]+" "); } System.out.println(); } } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } static double findRoots(int a, int b, int c) { // If a is 0, then equation is not //quadratic, but linear int d = b*b - 4*a*c; double sqrt_val = Math.sqrt(Math.abs(d)); // System.out.println("Roots are real and different \n"); return Math.max((double)(-b + sqrt_val) / (2 * a) , (double)(-b - sqrt_val) / (2 * a)); } // public static String cin() throws Exception { // return br.readLine(); // } // public static String[] cinA() throws Exception { // return br.readLine().split(" "); // } public static String ToString(Long x) { return Long.toBinaryString(x); } public static void cout(String s) { System.out.println(s); } // public static Integer cinI() throws Exception { // return Integer.parseInt(br.readLine()); // } public static int getI(String s) throws Exception { return Integer.parseInt(s); } public static long getL(String s) throws Exception { return Long.parseLong(s); } public static int max(int a, int b) { return Math.max(a, b); } public static void coutI(int x){ System.out.println(String.valueOf(x)); } public static void coutI(long x){ System.out.println(String.valueOf(x)); } // public static Long cinL() throws Exception { // return Long.parseLong(br.readLine()); // } } class range implements Comparable<range>{ int l; int r; int diff; public range(int l,int r,int diff){ this.l = l; this.r=r; this.diff =diff; } public int mid(){ return l+r/2; } public int compareTo(range o){ if(diff==o.diff) return l-o.l; return o.diff-diff; } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
48e06005db2fc23041cd18b2d41ddc3b
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.PriorityQueue; import java.util.StringTokenizer; public class Main { public static void main(String[] args) { InputStream inputStream = System.in; Scanner in = new Main().new Scanner(inputStream); Main solver = new Main(); solver.solve(in); } class Pair implements Comparable<Pair> { int x; int y; public Pair(int a, int b) { x = a; y = b; } public String toString() { return "[" + x + "," + y + "]"; } @Override public int compareTo(Pair o) { if(y-x != o.y-o.x) return -((y-x) - (o.y-o.x)); return x - o.x; } public int getMid() { if((x-y+1) % 2 == 0) return (x+y-1) / 2; else return (x+y) / 2; } public boolean isEven() { return ((x-y+1) % 2 == 0); } } public void solve(Scanner in) { int t = in.ni(); for(int ii = 0; ii < t; ii++) { int n = in.ni(); PriorityQueue<Pair> pq = new PriorityQueue<Pair>(); int[] a = new int[n]; int i = 1; pq.add(new Pair(0, n-1)); while(!pq.isEmpty() && i <= n) { Pair p = pq.poll(); int beg = p.x; int end = p.y; int mid = p.getMid(); a[mid] = i++; if(mid+1 <= end) pq.add(new Pair(mid+1, end)); if(beg <= mid-1) pq.add(new Pair(beg, mid-1)); } for(int f : a) System.out.print(f + " "); System.out.println(); } } class Scanner { BufferedReader br; StringTokenizer in; public Scanner(InputStream inputStream) { br = new BufferedReader(new InputStreamReader(inputStream)); } public String next() { return hasMoreTokens() ? in.nextToken() : null; } public String readLine() { try { return br.readLine(); } catch (Exception e) { e.printStackTrace(); return null; } } boolean hasMoreTokens() { while (in == null || !in.hasMoreTokens()) { String s = readLine(); if (s == null) return false; in = new StringTokenizer(s); } return true; } public String nextString() { return next(); } public int ni() { return Integer.parseInt(nextString()); } public long nl() { return Long.parseLong(nextString()); } public int[] nia(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = ni(); } return a; } } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
5df46bf6ebb0a62a40ebe9b8c30e2832
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.*; public class C642D { static PrintWriter out = new PrintWriter((System.out)); public static void main(String args[]) throws IOException { Reader sc = new Reader(); int t = sc.nextInt(); while (t-- > 0) { int n=sc.nextInt(); solve(n); } out.close(); } public static void solve(int n) { if(n==1) { out.println(1); return; } PriorityQueue<Pair> pq=new PriorityQueue<>(new Sort()); pq.add(new Pair(0,n-1)); int ans[]=new int[n]; int x=1; while(x<=n) { Pair p=pq.poll(); int l=p.l; int r=p.r; int s=p.s; if(s%2==0) { int d=(l+r-1)/2; ans[d]=x; if(l<d) { pq.add(new Pair(l, d - 1)); } if(d<r) { pq.add(new Pair(d + 1, r)); } } else { int d=(l+r)/2; ans[d]=x; if(l<d) { pq.add(new Pair(l, d - 1)); } if(d<r) { pq.add(new Pair(d + 1, r)); } } x++; } for(int d:ans) { out.print(d+" "); } out.println(); } static class Reader { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { try { return br.readLine(); } catch (Exception e) { e.printStackTrace(); } return null; } public boolean hasNext() { String next = null; try { next = br.readLine(); } catch (Exception e) { } if (next == null) { return false; } st = new StringTokenizer(next); return true; } } } class Pair { int l,r; int s; public Pair(int l,int r) { this.l=l; this.r=r; s=r-l+1; } } class Sort implements Comparator<Pair> { public int compare(Pair a,Pair b) { if(a.s==b.s) { return a.l-b.l; } else { return -(a.s-b.s); } } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
35ed311a234f469d0adda582ba60a4da
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
/** * @author vivek */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Queue; import java.util.StringTokenizer; public class Main { private int anInt; private static void solveTC(int __) { /* For Google */ // ans.append("Case #").append(__).append(": "); //code start PriorityQueue<Pair> queue = new PriorityQueue<>(); // Queue<Pair > queue=new LinkedList<>(); int n = scn.nextInt(); int[] array = new int[n]; queue.add(new Pair(0, n - 1)); int i = 1; while (!queue.isEmpty()) { Pair p = queue.remove(); int l = p.l; int r = p.r; if (l > r) { continue; } int mid; if ((r - l + 1) % 2 == 0) { mid = (l + r - 1) / 2; } else { mid = (l + r) / 2; } array[mid] = i; i++; queue.add(new Pair(l, mid - 1)); queue.add(new Pair(mid + 1, r)); } for (int ele : array) { print(ele + " "); } //code end ans.append("\n"); } static class Pair implements Comparable<Pair> { int l, r; public Pair(int l, int r) { this.l = l; this.r = r; } @Override public int compareTo(Pair o) { int diff = (o.r - o.l) - (r - l); if (diff == 0) { return l - o.l; } else { return diff; } } } private static int gcd(int i, int j) { return (j == 0) ? i : gcd(j, i % j); } static void print(Object obj) { ans.append(obj.toString()); } public static void main(String[] args) { scn = new Scanner(); ans = new StringBuilder(); int t = scn.nextInt(); // int t = 1; for (int i = 1; i <= t; i++) { solveTC(i); } System.out.print(ans); } static Scanner scn; static StringBuilder ans; //Fast Scanner static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() { 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[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; i++) { array[i] = nextInt(); } return array; } Integer[] nextIntegerArray(int n) { Integer[] array = new Integer[n]; for (int i = 0; i < n; i++) { array[i] = nextInt(); } return array; } long[] nextLongArray(int n) { long[] array = new long[n]; for (int i = 0; i < n; i++) { array[i] = nextLong(); } return array; } String[] nextStringArray() { return nextLine().split(" "); } String[] nextStringArray(int n) { String[] array = new String[n]; for (int i = 0; i < n; i++) { array[i] = next(); } return array; } } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
695489f2f83268ed1ab5ac32a53ee804
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class cf1353d { static BufferedReader __in; static PrintWriter __out; static StringTokenizer input; public static void main(String[] args) throws IOException { __in = new BufferedReader(new InputStreamReader(System.in)); __out = new PrintWriter(new OutputStreamWriter(System.out)); int t = ri(); while(t --> 0) { int n = ri(), ans[] = new int[n], cnt = 1; PriorityQueue<P> q = new PriorityQueue<>((a, b) -> a.b - a.a == b.b - b.a ? a.a - b.a : (b.b - b.a) - (a.b - a.a)); q.offer(new P(0, n - 1)); while(!q.isEmpty()) { P itv = q.poll(); if(itv.a > itv.b) continue; if((itv.b - itv.a) % 2 == 0) { int mid = (itv.a + itv.b) / 2; ans[mid] = cnt++; q.offer(new P(itv.a, mid - 1)); q.offer(new P(mid + 1, itv.b)); } else { int mid = (itv.a + itv.b - 1) / 2; ans[mid] = cnt++; q.offer(new P(mid + 1, itv.b)); q.offer(new P(itv.a, mid - 1)); } } prln(ans); } close(); } static class P { int a, b; P(int a_, int b_) { a = a_; b = b_; } @Override public String toString() { return "Pair{" + "a = " + a + ", b = " + b + '}'; } public boolean equalsSafe(Object o) { if(this == o) return true; if(o == null || getClass() != o.getClass()) return false; P p = (P)o; return a == p.a && b == p.b; } public boolean equalsUnchecked(Object o) { P p = (P)o; return a == p.a && b == p.b; } @Override public boolean equals(Object o) { return equalsUnchecked(o); } @Override public int hashCode() { return Objects.hash(a, b); } } // references // IBIG = 1e9 + 7 // IRAND ~= 3e8 // IMAX ~= 2e10 // LMAX ~= 9e18 // constants static final int IBIG = 1000000007; static final int IRAND = 327859546; static final int IMAX = 2147483647; static final int IMIN = -2147483648; static final long LMAX = 9223372036854775807L; static final long LMIN = -9223372036854775808L; // util static int minof(int a, int b, int c) {return min(a, min(b, c));} static int minof(int... x) {return x.length == 1 ? x[0] : x.length == 2 ? min(x[0], x[1]) : min(x[0], minstarting(1, x));} static int minstarting(int offset, int... x) {assert x.length > 2; return offset == x.length - 2 ? min(x[offset], x[offset + 1]) : min(x[offset], minstarting(offset + 1, x));} static long minof(long a, long b, long c) {return min(a, min(b, c));} static long minof(long... x) {return x.length == 1 ? x[0] : x.length == 2 ? min(x[0], x[1]) : min(x[0], minstarting(1, x));} static long minstarting(int offset, long... x) {assert x.length > 2; return offset == x.length - 2 ? min(x[offset], x[offset + 1]) : min(x[offset], minstarting(offset + 1, x));} static int maxof(int a, int b, int c) {return max(a, max(b, c));} static int maxof(int... x) {return x.length == 1 ? x[0] : x.length == 2 ? max(x[0], x[1]) : max(x[0], maxstarting(1, x));} static int maxstarting(int offset, int... x) {assert x.length > 2; return offset == x.length - 2 ? max(x[offset], x[offset + 1]) : max(x[offset], maxstarting(offset + 1, x));} static long maxof(long a, long b, long c) {return max(a, max(b, c));} static long maxof(long... x) {return x.length == 1 ? x[0] : x.length == 2 ? max(x[0], x[1]) : max(x[0], maxstarting(1, x));} static long maxstarting(int offset, long... x) {assert x.length > 2; return offset == x.length - 2 ? max(x[offset], x[offset + 1]) : max(x[offset], maxstarting(offset + 1, x));} static int powi(int a, int b) {if(a == 0) return 0; int ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static long powl(long a, int b) {if(a == 0) return 0; long ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static int floori(double d) {return (int)d;} static int ceili(double d) {return (int)ceil(d);} static long floorl(double d) {return (long)d;} static long ceill(double d) {return (long)ceil(d);} // input static void r() throws IOException {input = new StringTokenizer(__in.readLine());} static int ri() throws IOException {return Integer.parseInt(__in.readLine());} static long rl() throws IOException {return Long.parseLong(__in.readLine());} static int[] ria(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()); return a;} static long[] rla(int n) throws IOException {long[] a = new long[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Long.parseLong(input.nextToken()); return a;} static char[] rcha() throws IOException {return __in.readLine().toCharArray();} static String rline() throws IOException {return __in.readLine();} static int rni() throws IOException {input = new StringTokenizer(__in.readLine()); return Integer.parseInt(input.nextToken());} static int ni() {return Integer.parseInt(input.nextToken());} static long rnl() throws IOException {input = new StringTokenizer(__in.readLine()); return Long.parseLong(input.nextToken());} static long nl() {return Long.parseLong(input.nextToken());} // output static void pr(int i) {__out.print(i);} static void prln(int i) {__out.println(i);} static void pr(long l) {__out.print(l);} static void prln(long l) {__out.println(l);} static void pr(double d) {__out.print(d);} static void prln(double d) {__out.println(d);} static void pr(char c) {__out.print(c);} static void prln(char c) {__out.println(c);} static void pr(char[] s) {__out.print(new String(s));} static void prln(char[] s) {__out.println(new String(s));} static void pr(String s) {__out.print(s);} static void prln(String s) {__out.println(s);} static void pr(Object o) {__out.print(o);} static void prln(Object o) {__out.println(o);} static void prln() {__out.println();} static void pryes() {__out.println("yes");} static void pry() {__out.println("Yes");} static void prY() {__out.println("YES");} static void prno() {__out.println("no");} static void prn() {__out.println("No");} static void prN() {__out.println("NO");} static void pryesno(boolean b) {__out.println(b ? "yes" : "no");}; static void pryn(boolean b) {__out.println(b ? "Yes" : "No");} static void prYN(boolean b) {__out.println(b ? "YES" : "NO");} static void prln(int... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static void prln(long... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for(int i = 0; i < n; __out.print(iter.next()), __out.print(' '), ++i); __out.println(iter.next());} static void flush() {__out.flush();} static void close() {__out.close();} }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
362aa384ee46d28a13e9a2051f195f98
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Comparator; import java.util.PriorityQueue; public class SegmentFill { public static void main(String args[]) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); while (t > 0) { t--; int n = Integer.parseInt(br.readLine()); int[] ans = new int[n+1]; PriorityQueue<Segment> segs = new PriorityQueue<>(n + 1, new segSort()); segs.add(new Segment(1, n)); int i = 1; while(!segs.isEmpty()){ Segment x = segs.poll(); int index; if(x.size % 2 != 0) index = (x.l + x.r)/2; else index = (x.l + x.r - 1)/2; ans[index] = i; if(index-x.l > 0) segs.add(new Segment(x.l, index - 1)); if(x.r-index > 0) segs.add(new Segment(index+1, x.r)); i++; } for(int ite = 1; ite <= n; ite++) System.out.print(ans[ite] + " "); System.out.println(); } } } //Index is inclusive class Segment { int l; int r; int size; Segment(int l, int r){ this.l = l; this.r = r; size = (r-l) - 1; } } class segSort implements Comparator<Segment> { // a-b ascending, b-a descending public int compare(Segment a, Segment b) { if(a.size - b.size == 0) return a.l - b.l; return b.size - a.size; } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
73222e5eb951b9754ff2d9d7b065966b
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.PriorityQueue; import java.util.Scanner; public class SolutionD { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int t = scanner.nextInt(), n; for (int l = 0; l < t; l++) { n = scanner.nextInt(); int[] a = new int[n]; PriorityQueue<Entity> priorityQueue = new PriorityQueue<>((e1, e2) -> { if (e1.length != e2.length) { return e2.length - e1.length; } else { return e1.left - e2.left; } }); priorityQueue.add(new Entity(n, 0, n - 1)); int count = 1, mid; Entity e = null; while (!priorityQueue.isEmpty()) { e = priorityQueue.poll(); mid = e.left + (e.right - e.left) / 2; a[mid] = count; if (mid != e.left) { priorityQueue.add(new Entity(mid - e.left, e.left, mid - 1)); } if (mid != e.right) { priorityQueue.add(new Entity(e.right - mid, mid + 1, e.right)); } count++; } for (int i = 0; i < n; i++) { System.out.print(a[i] + " "); } System.out.println(); } scanner.close(); } } class Entity { public int length; public int left; public int right; public Entity(int l, int i, int j) { length = l; left = i; right = j; } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
834dd82a6b07bc6d1cf4739070e4b5ea
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; public class Main implements Runnable { private boolean console=false; private long MOD = 1000_000_007L; private int MAX = 1000_001; private void solve1(){ int n=in.ni(); int[] arr = new int[n+1]; PriorityQueue<Pair> pq = new PriorityQueue<>((a,b) ->{ if(a.y-a.x == b.y-b.x){ if(a.x==b.x) return a.y-b.y; return a.x-b.x; } return (b.y-b.x) - (a.y-a.x); }); pq.add(new Pair(1,n)); int idx=1; while (!pq.isEmpty()){ Pair p = pq.poll(); int mid = (p.x+p.y)/2; arr[mid]=idx; // out.println(p); if(p.x<=mid-1){ pq.add(new Pair(p.x,mid-1)); } if(p.y>=mid+1){ pq.add(new Pair(mid+1,p.y)); } idx++; } for(int i=1;i<=n;++i){ out.print(arr[i]+" "); } out.println(); } class Pair{ int x,y; public Pair(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return "Pair{" + "x=" + x + ", y=" + y + '}'; } } private void solve() { int testCases = 1; testCases = in.ni(); while (testCases-->0){ solve1(); } } private void add(Map<Integer,Integer> map,int key){ map.put(key,map.getOrDefault(key,0)+1); } private void remove(Map<Integer,Integer> map,int key){ if(!map.containsKey(key)) return; map.put(key,map.getOrDefault(key,0)-1); if(map.get(key)==0) map.remove(key); } @Override public void run() { long time = System.currentTimeMillis(); try { init(); } catch (FileNotFoundException e) { e.printStackTrace(); } try { solve(); out.flush(); System.err.println(System.currentTimeMillis()-time); System.exit(0); }catch (Exception e){ e.printStackTrace(); System.exit(1); } } /* -------------------- Templates and Input Classes -------------------------------*/ private FastInput in; private PrintWriter out; public static void main(String[] args) throws Exception { new Main().run(); // new Thread(null, new Main(), "Main", 1 << 27).start(); } private void init() throws FileNotFoundException { InputStream inputStream = System.in; OutputStream outputStream = System.out; try { if (!console && System.getProperty("user.name").equals("puneet")) { outputStream = new FileOutputStream("/home/puneet/Desktop/output.txt"); inputStream = new FileInputStream("/home/puneet/Desktop/input.txt"); } } catch (Exception ignored) { } out = new PrintWriter(outputStream); in = new FastInput(inputStream); } private void maualAssert(int a,int b,int c){ if(a<b || a>c) throw new RuntimeException(); } private void maualAssert(long a,long b,long c){ if(a<b || a>c) throw new RuntimeException(); } private void sort(int[] arr) { List<Integer> list = new ArrayList<>(); for (int object : arr) list.add(object); Collections.sort(list); for (int i = 0; i < list.size(); ++i) arr[i] = list.get(i); } private void sort(long[] arr) { List<Long> list = new ArrayList<>(); for (long object : arr) list.add(object); Collections.sort(list); for (int i = 0; i < list.size(); ++i) arr[i] = list.get(i); } private long ModPow(long x, long y, long MOD) { long res = 1L; x = x % MOD; while (y >= 1L) { if ((y & 1L) > 0) res = (res * x) % MOD; x = (x * x) % MOD; y >>= 1L; } return res; } private int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } private long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } private int[] arrInt(int n){ int[] arr=new int[n];for(int i=0;i<n;++i)arr[i]=in.ni(); return arr; } private long[] arrLong(int n){ long[] arr=new long[n];for(int i=0;i<n;++i)arr[i]=in.nl(); return arr; } static class FastInput { InputStream obj; public FastInput(InputStream obj) { this.obj = obj; } private byte inbuffer[] = new byte[1024]; private int lenbuffer = 0, ptrbuffer = 0; private int readByte() { if (lenbuffer == -1) throw new InputMismatchException(); if (ptrbuffer >= lenbuffer) { ptrbuffer = 0; try { lenbuffer = obj.read(inbuffer); } catch (IOException e) { throw new InputMismatchException(); } } if (lenbuffer <= 0) return -1;return inbuffer[ptrbuffer++]; } 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();} int ni() { int num = 0, b;boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true;b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; }b = readByte(); }} 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 * 10L + (b - '0'); } else { return minus ? -num : num; }b = readByte(); } } private boolean isSpaceChar(int c) { return (!(c >= 33 && c <= 126)); } int skip() { int b;while ((b = readByte()) != -1 && isSpaceChar(b)) ;return b; } float nf() {return Float.parseFloat(ns());} double nd() {return Double.parseDouble(ns());} char nc() {return (char) skip();} } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
8e749c641a60cdce898a1813a9722e9d
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; import java.io.*; import java.nio.file.*; public class segzeros { static FastScanner in; static FastPrinter out; public static void main(String[] uselessScrub) throws Exception { in = new FastScanner(); out = new FastPrinter(); int t=in.nextInt(); for (int i=1; i<=t; i++) { solve(); } out.close(); } public static void solve() throws Exception { int n=in.nextInt(); int[] a=new int[n]; PriorityQueue<int[]> segs = new PriorityQueue<>((int[] x, int[] y) -> y[2]==x[2]?x[0]-y[0]:y[2]-x[2]); segs.add(new int[] {0, n-1, n}); for (int i=1; i<=n; i++) { int[] c=segs.poll(); int x=(c[0]+c[1])/2; a[x]=i; if (c[0]<=x-1) segs.add(new int[] {c[0], x-1, x-c[0]}); if (c[1]>=x+1) segs.add(new int[] {x+1, c[1], c[1]-x}); } for (int i:a) { out.print(i+" "); } out.println(); } private static class FastPrinter { static final char ENDL = '\n'; StringBuilder buf; PrintWriter pw; public FastPrinter() { buf = new StringBuilder(); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); } public FastPrinter(OutputStream stream) { buf = new StringBuilder(); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream))); } public FastPrinter(String fileName) throws Exception { buf = new StringBuilder(); pw = new PrintWriter(new BufferedWriter(new FileWriter(fileName))); } public FastPrinter(StringBuilder buf) { this.buf = buf; } public void print(int a) { buf.append(a); } public void print(long a) { buf.append(a); } public void print(char a) { buf.append(a); } public void print(char[] a) { buf.append(a); } public void print(double a) { buf.append(a); } public void print(String a) { buf.append(a); } public void print(Object a) { buf.append(a.toString()); } public void println() { buf.append(ENDL); } public void println(int a) { buf.append(a); buf.append(ENDL); } public void println(long a) { buf.append(a); buf.append(ENDL); } public void println(char a) { buf.append(a); buf.append(ENDL); } public void println(char[] a) { buf.append(a); buf.append(ENDL); } public void println(double a) { buf.append(a); buf.append(ENDL); } public void println(String a) { buf.append(a); buf.append(ENDL); } public void println(Object a) { buf.append(a.toString()); buf.append(ENDL); } public void close() { pw.print(buf); pw.close(); } public void flush() { pw.print(buf); pw.flush(); buf.setLength(0); } } private static class FastScanner { final private int BUFFER_SIZE = 1 << 10; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public FastScanner() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public FastScanner(InputStream stream) { din = new DataInputStream(stream); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public FastScanner(String fileName) throws IOException { Path p = Paths.get(fileName); buffer = Files.readAllBytes(p); bytesRead = buffer.length; } int[] nextIntArray(int N) throws IOException { int[] arr = new int[N]; for (int i = 0; i < N; i++) arr[i] = nextInt(); return arr; } int[][] nextDoubleIntArray(int n, int m) throws IOException { int[][] arr = new int[n][m]; for (int i=0; i<n; i++) for (int j=0; j<m; j++) arr[i][j]=nextInt(); return arr; } String nextLine() throws IOException { int c = read(); while (c != -1 && isEndline(c)) c = read(); if (c == -1) { return null; } StringBuilder res = new StringBuilder(); do { if (c >= 0) { res.appendCodePoint(c); } c = read(); } while (!isEndline(c)); return res.toString(); } boolean isEndline(int c) { return c == '\n' || c == '\r' || c == -1; } String next() throws Exception { int c = readOutSpaces(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } private int readOutSpaces() throws IOException { while (true) { if (bufferPointer == bytesRead) fillBuffer(); int c = buffer[bufferPointer++]; if (!isSpaceChar(c)) { return c; } } } public void close() throws IOException { if (din == null) return; din.close(); } } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
82e7556ba9740276d7bb010aab05edf7
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.*; public class PAIR implements Comparable<PAIR> { int l; int r; int dif = r-l; PAIR(int l,int r,int dif) { this.l =l; this.r=r; this.dif =dif;} @Override public int compareTo(PAIR p) { if(p.dif-this.dif!=0) {return (p.dif-this.dif);} else { return (this.l-p.l); } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int cases = sc.nextInt(); //boolean flag =true; for(int i=0;i<cases ;i++) { int n=sc.nextInt(); // List<PAIR> list=new ArrayList<PAIR>(); PriorityQueue<PAIR> list = new PriorityQueue<>(); int arr[] = new int[n]; int count=1; list.add(new PAIR(0,n-1,n-1)); while(!list.isEmpty()) { PAIR pa = list.poll(); //list.remove(0); int mid=(pa.l+pa.r)/2; if(pa.r>=pa.l){ arr[mid]=count;} count++; if(pa.r-pa.l>0) { list.add(new PAIR(pa.l, mid - 1, mid - 1 - pa.l)); list.add(new PAIR(mid + 1, pa.r, pa.r - mid - 1)); } //Collections.sort(list); } for(int j=0;j<n;j++) { System.out.print(arr[j]+" "); } System.out.println(""); } /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
d72c37d59fbdc15dd1628ffa807795be
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; public class Main { static class Segment { int l,r; int length; Segment(int l,int r) { this.l=l; this.r=r; this.length=r-l+1; } public String toString() { return this.l+" "+this.r+" "+this.length; } } public static void main(String args[]) { Scanner sc= new Scanner(System.in); int t=sc.nextInt(); while(t-- >0) { PriorityQueue<Segment> pq= new PriorityQueue<>(new Comparator<Segment>(){ public int compare(Segment a,Segment b) { if(a.length==b.length) { if(a.l<b.l) { return -1; } return 1; } return a.length>b.length?-1:1; } }); int n=sc.nextInt(); int arr[]=new int[n+1]; pq.add(new Segment(1,n)); int op=0; while(pq.peek().length>0) { Segment curr=pq.poll(); int l=curr.l,r=curr.r,length=curr.length; int setind= length%2!=0?(l+r)/2:(l+r-1)/2; arr[setind]=++op; pq.add(new Segment(l,setind-1)); pq.add(new Segment(setind+1,r)); } for(int i=1;i<=n;i++) { System.out.print(arr[i]+" "); } System.out.println(""); } } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
16c9c78b6acf90ee2b51a84a13570a1a
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class SolutionC { static BufferedReader input; static StringTokenizer _stk; static String readln() throws IOException { String l = input.readLine(); if (l != null) _stk = new StringTokenizer(l, " "); return l; } static String next() { return _stk.nextToken(); } static int nextInt() { return Integer.parseInt(next()); } static long nextLong() { return Long.parseLong(next()); } static void dbg(Object... o) { System.out.println(Arrays.deepToString(o)); } static PrintWriter output = new PrintWriter(new BufferedWriter( new OutputStreamWriter(System.out))); public static void main(String[] args) throws IOException { Locale.setDefault(Locale.US); input = new BufferedReader(new InputStreamReader(System.in)); readln(); int t = nextInt(); PriorityQueue<Segment> queue = new PriorityQueue<>(Comparator.comparing(Segment::getLen).reversed().thenComparing(Segment::getStart)); for (int testI = 0; testI < t; testI++) { queue.clear(); readln(); int n = nextInt(); int[] a = new int[n]; int cur = 1; queue.add(new Segment(0, n)); while(!queue.isEmpty()) { Segment segment = queue.poll(); if (segment.len == 1) { a[segment.start] = cur++; continue; } int l = segment.start; int r = l + segment.len; int mid; if ((r - l) % 2 == 1) { mid = l + (r - l) / 2; } else { mid = l + (r - l - 1) / 2; } a[mid] = cur++; if (mid != l) { queue.add(new Segment(l, mid - l)); } if (mid != r) { queue.add(new Segment(mid + 1, r - mid - 1)); } } for (int i = 0; i < n; i++) { output.print(a[i]); if (i < n - 1) { output.print(" "); } } if (testI < t - 1) { output.println(); } } output.close(); } private static class Segment { private int start; private int len; public Segment(int start, int len) { this.start = start; this.len = len; } public int getStart() { return start; } public Segment setStart(int start) { this.start = start; return this; } public int getLen() { return len; } public Segment setLen(int len) { this.len = len; return this; } } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
ef587cc5bf799abfa2d9f48af242a4e1
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int test = sc.nextInt(); for(int t = 0; t < test; t++) { int n = sc.nextInt(), value = 1; StringBuffer sb = new StringBuffer(); int[] arr = new int[n]; PriorityQueue<int[]> pq = new PriorityQueue<int[]>((a, b)->{ int rst = (b[1] - b[0]) - (a[1] - a[0]); return rst == 0 ? a[0] - b[0] : rst; }); pq.add(new int[] {0, n - 1}); while(!pq.isEmpty()) { int[] poll = pq.poll(); int s = poll[0], e = poll[1], mid = (s + e) / 2; if(arr[mid] == 0) arr[mid] = value++; if(mid - 1 >= s) pq.add(new int[] {s, mid - 1}); if(mid + 1 <= e) pq.add(new int[] {mid + 1, e}); } for(int i : arr) sb.append(i + " "); System.out.println(sb.toString().trim()); } } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
f969f2b281207651bf103b31e45e4676
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.*; public class D { 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){ int n = sc.nextInt(); PriorityQueue<Pair> q = new PriorityQueue<>(Collections.reverseOrder()); int c = 1; int[] arr = new int[n]; if(n%2==1){ q.add(new Pair((n+1)/2,1,n)); }else{ q.add(new Pair((n)/2,1,n)); } while (!q.isEmpty()){ Pair p = q.poll(); int mid = p.x; int l = p.y; int r = p.z; if(l>r)continue; arr[mid-1]=c++; if((r-mid-1 +1)%2==1){ q.add(new Pair((mid+1+r)/2,mid+1,r)); }else q.add(new Pair((mid+1+r-1)/2,mid+1,r)); if((mid-1-l+1)%2==1){ q.add(new Pair((mid-1+l)/2,l,mid-1)); }else q.add(new Pair((mid-1+l-1)/2,l,mid-1)); } for(int i=0;i<n;i++) pw.print(arr[i] + " "); pw.println(); } pw.flush(); pw.close(); } static class Pair implements Comparable<Pair>{ int x; int y; int z; int d; public Pair(int x,int y,int z){ this.x= x; this.y = y; this.z =z; d = z-y; } public int compareTo(Pair p){ if(this.d==p.d) return Long.compare(p.x,this.x); return Long.compare(this.d,p.d); } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(FileReader r) { br = new BufferedReader(r); } public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
4ed87e8f5f27d8abe06b644a2ff01517
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class arr { static class seg{ int len,a,b; seg(int x,int y){ a=x; b=y; len=y-x+1; } } public static void main (String[] args) throws java.lang.Exception { // your code goes here Scanner sc=new Scanner(System.in); int tt=sc.nextInt(); while(tt-->0){ int n=sc.nextInt(); int[] arr=new int[n]; PriorityQueue<seg> q=new PriorityQueue<>(new Comparator<seg>(){ public int compare(seg fir,seg sec){ if(fir.len==sec.len){ return fir.a-sec.a; } else return sec.len-fir.len; }}); int idx=1; q.add(new seg(0,n-1)); while(q.size()>0){ seg t=q.poll(); int s=t.a; int e=t.b; int diff=t.len; int id=0; if(diff%2==1){ id=(s+e)/2; } else{ id=(s+e-1)/2; } arr[id]=idx++; if(s<=id-1) q.add(new seg(s,id-1)); if(e>=id+1) q.add(new seg(id+1,e)); } for(int ii:arr){ System.out.print(ii+" "); } System.out.println(); } } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
98b77580bc926b8dc0ba48aaf02617fa
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; public class q4 { public static int count; public static class sd implements Comparable<sd>{ int s; int e; public sd(int s,int e) { this.s=s; this.e=e; } @Override public int compareTo(sd arg) { int l1=this.e-this.s+1; int l2=arg.e-arg.s+1; if(l1==l2) { return this.s-arg.s; } return l2-l1; } } public static void solve(int s,int e,int[] arr) { PriorityQueue<sd>order=new PriorityQueue<q4.sd>(); sd first=new sd(s,e); order.add(first); while(!order.isEmpty()) { sd curr=order.remove(); if(curr.s>curr.e) { continue; } s=curr.s; e=curr.e; int mid=(s+e)/2; arr[mid]=count++; if((e-s+1)%2==0) { // add right sd right=new sd(mid+1,e); order.add(right); // add left sd left=new sd(s,mid-1); order.add(left); } else { // add left sd left=new sd(s,mid-1); order.add(left); // add right sd right=new sd(mid+1,e); order.add(right); } } } public static void main(String[] args) { // TODO Auto-generated method stub Scanner s=new Scanner(System.in); int t=s.nextInt(); for(int i=0;i<t;i++) { int n=s.nextInt(); int[] arr=new int[n]; count=1; solve(0,n-1,arr); for(int j=0;j<n;j++) { System.out.print(arr[j]+" "); } System.out.println(); } } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
a71794f785f2edd20334dda80060ac09
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { public static void main (String[] args) throws java.lang.Exception { // your code goes here Scanner input = new Scanner(System.in); int test = input.nextInt(); while(test-->0){ int n = input.nextInt(); PriorityQueue<pair>q = new PriorityQueue<>(new comp()); int arr[] = new int[n]; q.add(new pair(0,n-1)); for(int i =1;i<=n;i++){ pair seg = q.remove(); int mid = (seg.l+seg.r)/2; arr[mid] = i; if(seg.l<mid)q.add(new pair(seg.l,mid-1)); if(mid<seg.r)q.add(new pair(mid+1,seg.r)); } for(int i =0;i<n;i++)System.out.print(arr[i]+" "); System.out.println(); } } } class pair{ int l,r; public pair(int l,int r){ this.l = l; this.r = r; } } class comp implements Comparator<pair>{ public int compare(pair a,pair b){ int seg1 = a.r-a.l+1; int seg2 = b.r - b.l+1; if(seg1<seg2)return 1; if(seg1 == seg2) return a.l>b.l?1:-1; return -1; } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
a0614af463d118b6b5dbdee2c93733d0
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; import java.io.*; public class GFG { public static void main (String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while (t-->0) { int n=sc.nextInt(); int[] arr=new int[n+1]; PriorityQueue<pair> pq=new PriorityQueue<pair>(); pq.add(new pair(1,n)); for(int i=1;i<=n;i++) { pair pr=pq.remove(); int mid=-1; if(pr.left>pr.right) continue; if(pr.total%2==0) mid=(pr.left+pr.right-1)/2; if(pr.total%2!=0) mid=(pr.left+pr.right)/2; arr[mid]=i; pq.add(new pair(pr.left,mid-1)); pq.add(new pair(mid+1,pr.right)); } for(int i=1;i<=n;i++) System.out.print(arr[i]+" "); System.out.println(); } } static class pair implements Comparable<pair> { int left,right,total; pair(int a,int b) {left=a;right=b;total=right-left+1;} @Override public int compareTo(pair p) { if(this.total!=p.total) return p.total-this.total; return this.left-p.right; } } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
9f9f088ef404aeebe9be324491a6121c
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
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. */ /** * * @author user */ import java.util.*; public class Contruct_The_Array { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); int arr[]=new int[n+1]; PriorityQueue<int[]> pq=new PriorityQueue<>(new Comparator<int[]>() { public int compare(int []a,int b[]) { if(a[0]!=b[0]) return b[0]-a[0]; else if(a[1]!=b[1]) { return a[1]-b[1]; } else return a[2]-b[2]; } } ); int cnt=1; pq.add(new int[]{n,1,n}); while(!pq.isEmpty()) { int a[]=pq.poll(); int s=a[1]; int e=a[2]; int mid=(s+e)/2; arr[mid]=cnt++; if(s==e) continue; if(s<mid) pq.add(new int[]{mid-s,s,(mid-1)}); if(mid<e) pq.add(new int[]{e-mid,(mid+1),e}); } for(int i=1;i<=n;i++) System.out.print(arr[i]+" "); System.out.println(""); } } } /* 1 1 2 2 1 3 3 1 2 4 2 4 1 3 5 3 4 1 5 2 6 */
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
e1abe5d8d2a287013cfe1ba9cf5bd002
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Comparator; import java.util.PriorityQueue; public final class ConstructingTheArrayCF { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); while (t-- > 0) { PriorityQueue<Triplet> pq = new PriorityQueue<>(new Comparator<Triplet>() { @Override public int compare(Triplet a, Triplet b) { if (a.first < b.first) return 1; else if (a.first > b.first) return -1; else { if (a.second > b.second) return 1; else return -1; } } }); int n = Integer.parseInt(br.readLine()); int ans[]=new int[n]; int start = 1; pq.add(new Triplet(n, 0, n - 1)); while (!pq.isEmpty()) { Triplet tt = pq.poll(); int mid = 0; if (tt.first % 2 != 0) { mid = (tt.second + tt.third) / 2; } else mid = (tt.second + tt.third - 1) / 2; ans[mid]=start; start++; if(tt.second<=mid-1){ pq.add(new Triplet(mid-tt.second,tt.second,mid-1)); } if(mid+1<=tt.third){ pq.add(new Triplet(tt.third-mid,mid+1,tt.third)); } } for(int ele:ans) System.out.print(ele+" "); System.out.println(); } } } class Triplet { int first; int second; int third; public Triplet(int first,int second,int third){ this.first=first; this.second=second; this.third=third; } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
b11f6e9157b16ba71c359b8a8888d508
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Comparator; import java.util.PriorityQueue; public final class ConstructingTheArrayCF { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); while (t-- > 0) { PriorityQueue<Triplet> pq = new PriorityQueue<>(new Comparator<Triplet>() { @Override public int compare(Triplet a, Triplet b) { if (a.first < b.first) return 1; else if (a.first > b.first) return -1; else { if (a.second > b.second) return 1; else return -1; } } }); int n = Integer.parseInt(br.readLine()); int ans[]=new int[n]; int start = 1; pq.add(new Triplet(n, 0, n - 1)); while (!pq.isEmpty()) { Triplet tt = pq.poll(); int mid = 0; if (tt.first % 2 != 0) { mid = (tt.second + tt.third) / 2; } else mid = (tt.second + tt.third - 1) / 2; ans[mid]=start; start++; if(tt.second<=mid-1){ pq.add(new Triplet(mid-tt.second,tt.second,mid-1)); } if(mid+1<=tt.third){ pq.add(new Triplet(tt.third-mid,mid+1,tt.third)); } } for(int ele:ans) System.out.print(ele+" "); System.out.println(); } } } class Triplet { int first; int second; int third; public Triplet(int first,int second,int third){ this.first=first; this.second=second; this.third=third; } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
7f3b579ad6b8f81538b41b31c53e410e
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; import java.text.*; /** * @author soumitri12 */ /* Name of the class has to be "Main" only if the class is public*/ public class cf1353A { 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 Node { long pp; long a, b; Node(long x, long y) { a = x; b = y; pp = a * b; } } static class Comp implements Comparator<Node> { public int compare(Node o1, Node o2) { if (o1.pp > o2.pp) { return 1; } else { return -1; } } } static int gcd(int x, int y) { if(y==0) return x; else return gcd(y,x%y); } static long mod_pow(long a, long b, long mod) { a%=mod; if(b==0) return 1%mod; if((b&1)==1) return a*(mod_pow(a,b-1,mod))%mod; else { long u=mod_pow(a,b>>1,mod); return (u*u)%mod; } } static long _pow(long a, long b) { if(b==0) return 1; if((b&1)==1) return a*_pow(a,b-1); else { long u=_pow(a,b>>1); return u*u; } } static int modInv(int a, int m) { if(gcd(a,m)!=1) return -999; else return (a%m+m)%m; } static boolean isPowerOfTwo(int x) { return x!=0 && ((x&(x-1)) == 0); } static boolean isprime(int x) { for(int i=2;i<=Math.sqrt(x);i++) { if(x%i==0) return false; } return true; } static boolean prime[]; static final int INT_MAX=1000007; static void sieve() { prime=new boolean[INT_MAX]; Arrays.fill(prime,true); prime[0]=prime[1]=false; for(int i=2;i<=Math.sqrt(INT_MAX);i++) { if(prime[i]) { for(int j=i*2;j<INT_MAX;j+=i) prime[j]=false; } } } static class Pair { int len; Pointers ptr; public Pair(int len,Pointers ptr) { this.len=len; this.ptr=ptr; } } static class Pointers { int l,u; public Pointers(int l,int u) { this.l=l; this.u=u; } } public static void main(String[] args) { FastReader sc=new FastReader(); PrintWriter out=new PrintWriter(System.out); StringBuffer sb=new StringBuffer(); //your code starts here int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); int a[]=new int[n+1]; PriorityQueue<Pair> pq=new PriorityQueue<>(new Comparator<Pair>() { @Override public int compare(Pair p1,Pair p2) { return (p1.len!=p2.len) ? p2.len-p1.len : p1.ptr.l-p2.ptr.l; } }); Pair init=new Pair(n,new Pointers(1,n)); pq.add(init); int k=0; while(!pq.isEmpty()) { Pair curr=pq.poll(); int l=curr.ptr.l,u=curr.ptr.u; int mid=(l+u)/2; a[mid]=++k; if(l<=mid-1) pq.add(new Pair(mid-l,new Pointers(l,mid-1))); if(mid+1<=u) pq.add(new Pair(u-mid,new Pointers(mid+1,u))); } pq.clear(); for(int i=1;i<=n;i++) sb.append(a[i]+" "); } out.println(sb.toString()); out.close(); } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
da3a04a6d42e768582b473113d980d19
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; import java.text.*; /** * @author soumitri12 */ /* Name of the class has to be "Main" only if the class is public*/ public class cf1353A { 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 Node { long pp; long a, b; Node(long x, long y) { a = x; b = y; pp = a * b; } } static class Comp implements Comparator<Node> { public int compare(Node o1, Node o2) { if (o1.pp > o2.pp) { return 1; } else { return -1; } } } static int gcd(int x, int y) { if(y==0) return x; else return gcd(y,x%y); } static long mod_pow(long a, long b, long mod) { a%=mod; if(b==0) return 1%mod; if((b&1)==1) return a*(mod_pow(a,b-1,mod))%mod; else { long u=mod_pow(a,b>>1,mod); return (u*u)%mod; } } static long _pow(long a, long b) { if(b==0) return 1; if((b&1)==1) return a*_pow(a,b-1); else { long u=_pow(a,b>>1); return u*u; } } static int modInv(int a, int m) { if(gcd(a,m)!=1) return -999; else return (a%m+m)%m; } static boolean isPowerOfTwo(int x) { return x!=0 && ((x&(x-1)) == 0); } static boolean isprime(int x) { for(int i=2;i<=Math.sqrt(x);i++) { if(x%i==0) return false; } return true; } static boolean prime[]; static final int INT_MAX=1000007; static void sieve() { prime=new boolean[INT_MAX]; Arrays.fill(prime,true); prime[0]=prime[1]=false; for(int i=2;i<=Math.sqrt(INT_MAX);i++) { if(prime[i]) { for(int j=i*2;j<INT_MAX;j+=i) prime[j]=false; } } } static class Pair { int len; Pointers ptr; public Pair(int len,Pointers ptr) { this.len=len; this.ptr=ptr; } } static class Pointers { int l,u; public Pointers(int l,int u) { this.l=l; this.u=u; } } public static void main(String[] args) { FastReader sc=new FastReader(); PrintWriter out=new PrintWriter(System.out); StringBuffer sb=new StringBuffer(); //your code starts here int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); int a[]=new int[n+1]; PriorityQueue<Pair> pq=new PriorityQueue<>(new Comparator<Pair>() { @Override public int compare(Pair p1,Pair p2) { return (p1.len!=p2.len) ? p2.len-p1.len : p1.ptr.l-p2.ptr.l; } }); Pair init=new Pair(n,new Pointers(1,n)); pq.add(init); int k=0; while(!pq.isEmpty()) { Pair curr=pq.poll(); int l=curr.ptr.l,u=curr.ptr.u; int mid=(l+u)/2; a[mid]=++k; if(l<=mid-1) pq.add(new Pair(mid-l,new Pointers(l,mid-1))); if(mid+1<=u) pq.add(new Pair(u-mid,new Pointers(mid+1,u))); } pq.clear(); for(int i=1;i<=n;i++) sb.append(a[i]+" "); sb.append("\n"); } out.println(sb.toString()); out.close(); } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
396946ba8bf98f067d6d9cea3cd4c830
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Comparator; import java.util.PriorityQueue; import java.util.Scanner; import java.util.stream.Collectors; public class Solution1353D { private static int cnt = 0; public static void main(String[] args) { Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); int T = in.nextInt(); PrintWriter writer = new PrintWriter(System.out); while (T-- > 0) { int n = in.nextInt(); System.out.println(solve(n)); } } private static String solve(int n) { int[] res = new int[n]; cnt = 1; var pq = new PriorityQueue<int[]>((a, b) -> { if (a[1] - a[0] != b[1] - b[0]) { return (b[1] - b[0]) - (a[1] - a[0]); } else { return a[0] - b[0]; } }); pq.add(new int[]{0, n - 1}); while (!pq.isEmpty()) { var poll = pq.poll(); int m = (poll[1] + poll[0])/2; res[m] = cnt++; if (poll[0] <= m - 1) pq.add(new int[]{poll[0], m - 1}); if (m + 1 <= poll[1]) pq.add(new int[]{m + 1, poll[1]}); } return Arrays.stream(res).mapToObj(String::valueOf).collect(Collectors.joining(" ")); } static int[] toArray(String str) { return Arrays.stream(str.split(" ")).mapToInt(Integer::valueOf).toArray(); } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
b1e5d4ead4bc70991cdb26a956c91c9a
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.*; public class Solution{ public static void test_case(BufferedReader in) throws IOException{ int n = Integer.parseInt(in.readLine()); PriorityQueue<int[]> queue = new PriorityQueue<>((a1, a2)->{ if(a1[1]-a1[0]<a2[1]-a2[0]){ return 1; } else if(a1[1]-a1[0]>a2[1]-a2[0]) return -1; else{ if(a1[1]>a2[1]) return 1; else return -1; } }); int[] arr = new int[n]; queue.add(new int[]{0, n-1}); for(int i=0;i<n;i++){ int[] cur = queue.remove(); int l = cur[0], r = cur[1], mid = (l+r)/2; arr[mid] = i+1; if(mid-1-l>=0) queue.add(new int[]{l, mid-1}); if(r-mid-1>=0) queue.add(new int[]{mid+1, r}); } for(int i=0;i<n;i++) System.out.print(arr[i]+" "); System.out.println(); } public static void main(String[] args) throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); //int t = 1; int t = Integer.parseInt(in.readLine()); while(t-->0){ test_case(in); } } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
4db984d4f719206417673e53f995adde
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import java.util.Scanner; public class ConstructingTheArray { public static void main(String[] args) { Scanner in = new Scanner(System.in); int t = in.nextInt(); for(int i = 0; i < t; i++) { int n = in.nextInt(); Map<Integer, Queue<Integer>> map= new HashMap<>(); Queue<Integer> que = new PriorityQueue<>(); que.add(0); map.put(n - 1, que); int[] ans = new int[n]; int curVal = n; int curAction = 1; while(curVal >= 0) { if(map.get(curVal) == null) { curVal--; continue; } Queue<Integer> q = map.get(curVal); int l = q.poll(); int halved = curVal/2; int side2 = l + halved + 1; ans[l + (curVal / 2)] = curAction; if(curVal % 2 == 0) { if(map.get(halved - 1) == null) { Queue<Integer> tmp = new PriorityQueue<>(); tmp.add(l); tmp.add(side2); map.put(halved - 1, tmp); } else { Queue<Integer> tmp = map.get(halved -1); tmp.add(l); tmp.add(side2); } } else { if(map.get(halved - 1) == null) { Queue<Integer> tmp = new PriorityQueue<>(); tmp.add(l); map.put(halved - 1, tmp); } else { Queue<Integer> tmp = map.get(halved -1); tmp.add(l); } if(map.get(halved) == null) { Queue<Integer> tmp = new PriorityQueue<>(); tmp.add(side2); map.put(halved, tmp); } else { Queue<Integer> tmp = map.get(halved); tmp.add(side2); } } if(q.size() == 0) { curVal--; } curAction++; } for(int j = 0; j < n; j++) { System.out.print(ans[j] + " "); } System.out.println(); } } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
46a03075fc4f58589bfb9d5094127fd1
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import java.util.Scanner; public class ConstructingTheArray { public static void main(String[] args) { Scanner in = new Scanner(System.in); int t = in.nextInt(); for(int i = 0; i < t; i++) { int n = in.nextInt(); Map<Integer, Queue<Integer>> map= new HashMap<>(); Queue<Integer> que = new PriorityQueue<>(); que.add(0); map.put(n - 1, que); int[] ans = new int[n]; int curVal = n; int curAction = 1; while(curVal >= 0) { if(map.get(curVal) == null) { curVal--; continue; } Queue<Integer> q = map.get(curVal); int l = q.poll(); int halved = curVal/2; ans[l + halved] = curAction; if(curVal % 2 == 0) { Queue<Integer> tmp = map.getOrDefault(halved - 1, new PriorityQueue<>()); tmp.add(l); tmp.add(l + halved + 1); map.put(halved - 1, tmp); } else { Queue<Integer> tmp1 = map.getOrDefault(halved - 1, new PriorityQueue<>()); tmp1.add(l); map.put(halved - 1, tmp1); Queue<Integer> tmp2 = map.getOrDefault(halved, new PriorityQueue<>()); tmp2.add(l + halved + 1); map.put(halved, tmp2); } if(q.size() == 0) { curVal--; } curAction++; } for(int j = 0; j < n; j++) { System.out.print(ans[j] + " "); } System.out.println(); } } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
960284900a22c33b08ff8c3b9a362cf7
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); StringBuilder sb=new StringBuilder(); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); PriorityQueue<Pair> pq=new PriorityQueue<>(new myComparator()); pq.add(new Pair(n, 1, n)); int ans[]=new int[n]; for( int i=0;i<n;i++) { Pair x=pq.remove(); int index=(x.l+x.r)/2; ans[index-1]=i+1; int new_size=(x.size-1); if(new_size==1) { pq.add(new Pair(new_size, index+1, x.r)); } else{ pq.add(new Pair(index-x.l, x.l,index-1)); pq.add(new Pair(x.r-index, index+1, x.r)); } } for( int x: ans) { sb.append(x+" "); } sb.append("\n"); } System.out.print(sb.toString()); } } class Pair{ int size; int l; int r; Pair( int size, int l, int r) { this.size=size; this.l=l; this.r=r; } } class myComparator implements Comparator<Pair> { public int compare( Pair a, Pair b) { if(a.size==b.size) { return Integer.compare(a.l,b.l); }else return Integer.compare(b.size,a.size); } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
c11e84a9f9694faee9ecafce014eae72
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; import java.io.*; public class ConstructingtheArray { // https://codeforces.com/problemset/problem/1353/D public static void main(String[] args) throws IOException, FileNotFoundException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); //BufferedReader in = new BufferedReader(new FileReader("ConstructingtheArray")); int t = Integer.parseInt(in.readLine()); while (t --> 0) { int n = Integer.parseInt(in.readLine()); PriorityQueue<int[]> a = new PriorityQueue<>( new Comparator<int[]>() { public int compare(int[] x, int[] y) { if (y[0] != x[0]) return y[0]-x[0]; // sort by largest first else return x[1] - y[1]; // if same large, sort by leftmost } }); int[] ans = new int[n]; a.add(new int[] {n, 0, n-1}); // length, l, r int curnum=1; while (a.size() > 0) { int[] cur = a.poll(); if (cur[0] <= 0 || cur[1] < 0 || cur[2] < 0) continue; ans[(cur[1] + cur[2])/2] = curnum; curnum++; if (cur[1] == cur[2]) continue; a.add(new int[] {(cur[1] + cur[2])/2 - cur[1], cur[1], (cur[1] + cur[2])/2 -1}); a.add(new int[] {cur[2] - (cur[2] + cur[1])/2, (cur[2] + cur[1])/2 + 1, cur[2]}); } for (int i=0; i<n; i++) { System.out.print(ans[i] + " "); } System.out.println(); } } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
2e7657db1e23f448aff41e0aaf648140
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; import java.io.*; public class First { public static void main(String[] args) throws IOException { PrintWriter out = new PrintWriter(System.out); Reader.init(System.in); int t = Reader.nextInt(); while (t-->0) { int n = Reader.nextInt(); int[] arr = new int[n+1]; PriorityQueue<int[]> ss = new PriorityQueue<int[]>(new Sorts()); int[] ll = {1,n}; ss.add(ll); int count=1; while (!ss.isEmpty()) { int[] qp = ss.remove(); int mid = (qp[0]+qp[1])/2; arr[mid]=count; count++; if (qp[0]!=mid) { int[] lq = {qp[0],mid-1}; ss.add(lq); } if (qp[1]!=mid) { int[] rq = {mid+1,qp[1]}; ss.add(rq); } } for (int i = 1;i<=n;i++) { out.append(arr[i]+" "); } out.flush(); } } } class Sorts implements Comparator<int[]> { public int compare(int[] a, int[] b) { if (a[1]-a[0]<b[1]-b[0]) { return 1; } else if (a[1]+b[0]==a[0]+b[1] && b[0]<a[0]) return 1; else return -1; } } 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() ) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt( next() ); } static double nextDouble() throws IOException { return Double.parseDouble( next() ); } static long nextLong() throws IOException { return Long.parseLong( next() ); } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
02df5bb0244e9ccbeb9c2834b6610827
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; //import java.io.*; public class PriorityQueueArray { public static void main(String[] args) { Scanner in = new Scanner(System.in); int T; T=in.nextInt(); while((T--)>0) { //code comes here int N=in.nextInt(); int arr[]=new int[(N+1)]; PriorityQueue<CustomDT> priorityQueue=new PriorityQueue<>(); PriorityQueueArray x=new PriorityQueueArray(); priorityQueue.add(x.new CustomDT(1, N)); int count=1; while(!priorityQueue.isEmpty()) { CustomDT temp=priorityQueue.poll(); int mid=(temp.start+(temp.start+temp.length-1) )/2 ; arr[mid ]=count++; int ss=temp.start; int sizz=mid-temp.start; if(sizz>=1) priorityQueue.add(x.new CustomDT(ss,sizz)); ss=mid+1; sizz=temp.start+temp.length-ss; if(sizz>=1) { priorityQueue.add(x.new CustomDT(ss,sizz)); } } for(int i=1;i<=N;i++) { System.out.print(arr[i]+" "); } System.out.println(); // priorityQueue.add(x.new CustomDT(1, 5)); // priorityQueue.add(x.new CustomDT(1, 3)); // priorityQueue.add(x.new CustomDT(1, 6)); // priorityQueue.add(x.new CustomDT(1, 8)); // priorityQueue.add(x.new CustomDT(1, 1)); // priorityQueue.add(x.new CustomDT(2, 5)); // priorityQueue.add(x.new CustomDT(3, 5)); // while(!priorityQueue.isEmpty()) // { // CustomDT obx=priorityQueue.poll(); // System.out.println(obx.start+" "+obx.length); // } } in.close(); } class CustomDT implements Comparable<CustomDT> { int length,start; CustomDT(int start,int length) { this.length=length; this.start=start; } @Override public int compareTo(CustomDT o) { if(this.length>o.length) { return -1; } else if(this.length<o.length) return 1; else { if(this.start<o.start) return -1; else return 1; } } } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
edfcf47fb3320f7a4e6654f9c15a2200
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; import java.io.*; public class D { public static void main(String[] args) { Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(System.in))); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int T = sc.nextInt(); while (T-- > 0) { int N = sc.nextInt(); PriorityQueue<Segment> q = new PriorityQueue<>(); q.add(new Segment(0, N-1)); int[] ans = new int[N]; for (int i = 1; i <= N; i++) { Segment curr = q.poll(); ans[curr.center] = i; if (curr.l != curr.r) { q.add(new Segment(curr.l, curr.center - 1)); q.add(new Segment(curr.center + 1, curr.r)); } } for (int n : ans) out.print(n + " "); out.println(); } sc.close(); out.close(); } static class Segment implements Comparable<Segment> { int l, r, d, center; Segment(int l, int r) { this.l = l; this.r = r; this.d = this.r - this.l; this.center = (this.l + this.r) / 2; } public int compareTo(Segment o) { if (this.d > o.d) return -1; else if (this.d < o.d) return 1; else if (this.l < o.l) return -1; else if (this.l > o.l) return 1; throw new RuntimeException(); } } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
0ee4636c319a5234206a8cd20fbcdb90
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { public static void main (String[] args)throws IOException { try{ //BufferedReader br =new BufferedReader(new InputStreamReader(System.in)); Scanner sc = new Scanner(System.in); // int t=Integer.parseInt(br.readLine()); int t=sc.nextInt(); // int t=1; while(t-->0){ //int n=Integer.parseInt(br.readLine()) int n = sc.nextInt(); //int k = sc.nextInt(); //long d=Long.parseLong(br.readLine()); //String[] s= br.readLine().trim().split(" "); // Map<Integer,Integer> m = new TreeMap<Integer,Integer>(); List<Integer> f = new ArrayList<Integer>(); //List<Integer> s = new ArrayList<Integer>(); //<Integer> v= new Vector<Integer>(); //Set<Integer> s= new HashSet<Integer>(); int a[] = new int[n+1]; // int b[] = new int[n]; PriorityQueue<pair> pq = new PriorityQueue<pair>(new segmentComparator()); pq.add(new pair(1,n)); int l=0,r=0; for(int i=1;i<=n;i++){ // System.out.println(pq); pair p = pq.poll(); l=p.x; r=p.y; int mid = (l+r)/2; a[mid]=i; pq.add(new pair(l,mid-1)); pq.add(new pair(mid+1,r)); } for(int i=1;i<=n;i++) System.out.print(a[i]+" "); System.out.println(); } } catch(Exception e){ } }} class pair{ int x; int y; pair(int a, int b){ x=a; y=b; } } class segmentComparator implements Comparator<pair>{ public int compare(pair p1, pair p2){ int length1 =p1.y-p1.x; int length2 = p2.y-p2.x; if(length1>length2) return -1; else if(length1<length2) return 1; else{ return (p1.x<p2.x) ? -1 : 1; } } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
d6b209e2ffe0da4a05e1edf1e28cad84
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.Comparator; import java.util.PriorityQueue; import java.util.Scanner; public class constructarray { static int val = 1; public static void main(String args[]){ Scanner s = new Scanner(System.in); int tests = s.nextInt(); for(int i=0;i<tests;i++){ solver(s.nextInt()); } } private static void solver(int n){ PriorityQueue<state> pq = new PriorityQueue<state>(new Comparator<state>() { @Override public int compare(state o1, state o2) { if(o1.length==o2.length){ return o1.l-o2.l; } else return o2.length-o1.length; } }); int arr[] = new int[n+1]; pq.add(new state(1,n)); while(!pq.isEmpty()){ state current = pq.poll(); helper(arr,current,pq); } for(int i=1;i<arr.length;i++) System.out.print(arr[i]+" "); System.out.println(); val = 1; } private static void helper(int arr[],state current,PriorityQueue<state>pq){ int l = current.l , r = current.r; if(l>r) return; int mid = l + (r-l)/2; arr[mid] = val++; pq.add(new state(l,mid-1)); pq.add(new state(mid+1,r)); } private static class state{ int l; int r; int length; state(int l,int r){ this.l = l; this.r = r; this.length = r-l+1; } } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
a33a94898b14112888ad4ce539eb219d
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.util.*; public class Task { public static void main(String[] args) throws Exception { new Task().go(); } PrintWriter out; Reader in; BufferedReader br; Task() throws IOException { try { //br = new BufferedReader( new FileReader("input.txt") ); //in = new Reader("input.txt"); in = new Reader("input.txt"); out = new PrintWriter( new BufferedWriter(new FileWriter("output.txt")) ); } catch (Exception e) { //br = new BufferedReader( new InputStreamReader( System.in ) ); in = new Reader(); out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out)) ); } } void go() throws Exception { int t = in.nextInt(); //int t = 1; while (t > 0) { solve(); t--; } out.flush(); out.close(); } int inf = 2000000000; int mod = 1000000007; double eps = 0.000000001; int n; int m; ArrayList<Integer>[] g; void solve() throws IOException { int n = in.nextInt(); PriorityQueue<Segment> q = new PriorityQueue<>(); q.add(new Segment(0, n - 1, 0)); int[] a = new int[n]; int cnt = 1; for (int i = 0; i < n; i++) { Segment seg = q.poll(); int pos = (seg.a + seg.b) / 2; if (seg.len() % 2 == 0) pos = (seg.a + seg.b - 1) / 2; a[pos] = cnt; cnt++; if (seg.a < pos) q.add(new Segment(seg.a, pos - 1, seg.a)); if (seg.b > pos) q.add(new Segment(pos + 1, seg.b, pos + 1)); } for (int i = 0; i < n; i++) out.print(a[i] + " "); out.println(); } static class Segment implements Comparable<Segment> { public final int a; public final int b; public final int i; Segment(int a, int b, int i) { this.a = a; this.b = b; this.i = i; } public int len() { return b - a + 1; } public int compareTo(Segment p) { if (len() == p.len()) return Integer.compare(i, p.i); else return Integer.compare(p.len(), len()); } } static class Pair<A extends Comparable<A>, B extends Comparable<B>> implements Comparable<Pair<A, B>> { public final A a; public final B b; Pair(A a, B b) { this.a = a; this.b = b; } public int compareTo(Pair<A, B> p) { if (!a.equals(p.a)) return a.compareTo(p.a); else return b.compareTo(p.b); } } class Item { int a; int b; int c; Item(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } } class Reader { BufferedReader br; StringTokenizer tok; Reader(String file) throws IOException { br = new BufferedReader( new FileReader(file) ); } Reader() throws IOException { br = new BufferedReader( new InputStreamReader(System.in) ); } String next() throws IOException { while (tok == null || !tok.hasMoreElements()) tok = new StringTokenizer(br.readLine()); return tok.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.valueOf(next()); } long nextLong() throws NumberFormatException, IOException { return Long.valueOf(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.valueOf(next()); } String nextLine() throws IOException { return br.readLine(); } } static class InputReader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public InputReader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public InputReader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
c8ab9858784354db685e70dbffb22f57
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import javax.xml.crypto.dsig.spec.XSLTTransformParameterSpec; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.util.*; public class Main { public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); try (PrintWriter or = new PrintWriter(System.out)) { int t =in.nextInt(); while (t-->0){ int n=in.nextInt(); PriorityQueue<Tempo>a=new PriorityQueue<>(new Comparator<Tempo>() { @Override public int compare(Tempo o1, Tempo o2) { if ((o1.second-o1.first)==(o2.second-o2.first)){ return o1.first-o2.first; } return -((o1.second-o1.first)-(o2.second-o2.first)); } }); a.add(new Tempo(0,n-1)); int[]ans=new int[n]; int p=1; while (p<=n){ Tempo poll = a.poll(); int f=poll.first,s=poll.second; int mid=(f+s)/2; ans[mid]=p++; if (f<=mid-1)a.offer(new Tempo(f,mid-1)); if (mid+1<=s)a.offer(new Tempo(mid+1,s)); } for(int i:ans)or.print(i+" "); or.println(); } } } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) { if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) { f *= 10; } } } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } } class Tempo { int first, second; public Tempo(int first, int second) { this.first = first; this.second = second; } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
8a6e5f0be543a7c9e691510e7a5266ac
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
//package div3; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.Comparator; import java.util.PriorityQueue; import java.util.Scanner; import java.util.StringTokenizer; public class constructArray { static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } static class Segment{ int left; int right; Segment(int l,int r) { this.left = l; this.right = r; } int getLength(){ return -(this.right-this.left+1); } int getRight(){ return right; } } public static void main(String[] args) throws IOException { Reader sc=new Reader(); int t = sc.nextInt(); while (t-->0){ int n = sc.nextInt(); //Comparator<Segment> segmentComparator = Comparator.comparing(Segment::getLength) //.thenComparing(Segment::getRight); PriorityQueue<Segment> pq = new PriorityQueue<>((a, b) -> { if (b.right - b.left - (a.right - a.left) != 0) return b.right - b.left - (a.right - a.left); return a.left - b.left; }); pq.add(new Segment(1,n)); int[] a = new int[n+1]; int index = 1; while(!pq.isEmpty()){ Segment max = pq.poll(); int mid = (max.left+max.right)/2; //System.out.println(mid); a[mid] = index; index+=1; if(mid>max.left) pq.offer(new Segment(max.left,mid-1)); if(mid<max.right) pq.offer(new Segment(mid+1,max.right)); } for(int i=1;i<a.length;i++) System.out.print(a[i]+" "); System.out.println(); } } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
ca779b1d76014bd0d8d25f76445bc21f
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class code { public static void main(String[] args)throws IOException { FastReader sc = new FastReader(); PrintWriter pw = new PrintWriter(System.out); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); PriorityQueue<Edge> pq = new PriorityQueue<>(new Edge()); int arr[] = new int[n + 1]; int mid = 0; pq.add(new Edge(n, 1, n)); int i = 1; while (i <= n) { Edge e = pq.poll(); if (e.size % 2 != 0) mid = (e.l + e.r) / 2; else mid = (e.l + e.r - 1) / 2; arr[mid] = i; i++; int size1 = 0, size2 = 0; if (e.size % 2 != 0) { size1 = e.size / 2; size2 = e.size / 2; } else { size1 = e.size / 2; size2 = e.size / 2 - 1; } pq.add(new Edge(size2, e.l, mid - 1)); pq.add(new Edge(size1, mid + 1, e.r)); //System.out.println("s"); } for (int j = 1; j <= n; j++) { System.out.print(arr[j] + " "); } System.out.println(); } } static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } } class Edge implements Comparator<Edge> { int size, l, r; public Edge() {} public Edge(int s, int ll, int rr) { size = s; l = ll; r = rr; } public int compare(Edge e1, Edge e2) { if (e1.size < e2.size) return 1; if (e1.size == e2.size) { if (e1.l > e2.l) return 1; return -1; } return -1; } } 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
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
2b6f18881f15aeb473f0b8e9dada749e
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; import java.io.*; //import java.lang.*; public class ranjan{ //public static Read cin; public static InputReader cin; public static PrintWriter cout; public static boolean[] visited; public static int node=-1; public static boolean flag; public static final long b = (long)1e9+7; public static int fileread = 0; public static void main(String ...arg) throws IOException { /*console writer*/ cout = new PrintWriter(new BufferedOutputStream(System.out)); /*Debug Reader*/ //Scan cin =new Scan(); if(fileread == 1) { try { //cin = new Read(new FileInputStream(new File("in1.txt"))); cin = new InputReader(new FileInputStream(new File("in1.txt"))); } catch (IOException error){} } else{ //cin = new Read(System.in); cin = new InputReader(System.in); } int t = cin.nextInt(); PriorityQueue<Range> pq = new PriorityQueue<>(new Comparator<Range>(){ @Override public int compare(Range a,Range b) { if(a.len - b.len != 0) { return b.len - a.len; } else return a.l-b.l; } }); while(t-->0) { int n = cin.nextInt(); int[] ans = new int[n]; pq.clear(); pq.add(new Range(0,n-1)); for(int i=1;i<=n;i++) { Range top = pq.peek(); pq.remove(); int index = (int)(top.l + top.r)/2; pq.add(new Range(top.l,index-1)); pq.add(new Range(index+1,top.r)); ans[index] = i; } for(int val:ans) cout.print(val+" "); cout.print("\n"); } cout.close(); } static class Range{ public int l; public int r; public int len; public Range(int a,int b) { this.l = a; this.r = b; this.len = b-a+1; } } public static <K, V> V getOrDefault(HashMap<K,V> map, K key, V defaultValue) { return map.containsKey(key) ? map.get(key) : defaultValue; } public static long mod_pow(long x,long n,long mod) { long res=1; while(n>0) { if((n&1)==1)res=res*x%mod; x=x*x%mod; n>>=1; } return res; } public static int gcd(int n1, int n2) { int r; while (n2 != 0) { r = n1 % n2; n1 = n2; n2 = r; } return n1; } /*public static long lcm(long n1, long n2) { long answer = (n1 * n2) / (gcd(n1, n2)); return answer; }*/ static class InputReader { final InputStream is; final byte[] buf = new byte[1024]; int pos; int size; public InputReader(InputStream is) { this.is = is; } public int nextInt() { int c = read(); while (isWhitespace(c)) c = read(); int sign = 1; if (c == '-') { sign = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = res * 10 + c - '0'; c = read(); } while (!isWhitespace(c)); return res * sign; } int read() { if (size == -1) throw new InputMismatchException(); if (pos >= size) { pos = 0; try { size = is.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (size <= 0) return -1; } return buf[pos++] & 255; } static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } static class RecursionLimiter { public static long maxLevel = 1549; public static void emerge() { if (maxLevel == 0) return; try { throw new IllegalStateException("Too deep, emerging"); } catch (IllegalStateException e) { if (e.getStackTrace().length > maxLevel + 1) throw e; } } } static class Scan { private byte[] buf=new byte[1024]; private int index; private InputStream in; private int total; public Scan() { in=System.in; } public int scan()throws IOException { if(total<0) throw new InputMismatchException(); if(index>=total) { index=0; total=in.read(buf); if(total<=0) return -1; } return buf[index++]; } public int scanInt()throws IOException { int integer=0; int n=scan(); while(isWhiteSpace(n)) n=scan(); int neg=1; if(n=='-') { neg=-1; n=scan(); } while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { integer*=10; integer+=n-'0'; n=scan(); } else throw new InputMismatchException(); } return neg*integer; } public double scanDouble()throws IOException { double doub=0; int n=scan(); while(isWhiteSpace(n)) n=scan(); int neg=1; if(n=='-') { neg=-1; n=scan(); } while(!isWhiteSpace(n)&&n!='.') { if(n>='0'&&n<='9') { doub*=10; doub+=n-'0'; n=scan(); } else throw new InputMismatchException(); } if(n=='.') { n=scan(); double temp=1; while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { temp/=10; doub+=(n-'0')*temp; n=scan(); } else throw new InputMismatchException(); } } return doub*neg; } public String scanString()throws IOException { StringBuilder sb=new StringBuilder(); int n=scan(); while(isWhiteSpace(n)) n=scan(); while(!isWhiteSpace(n)) { sb.append((char)n); n=scan(); } return sb.toString(); } private boolean isWhiteSpace(int n) { if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1) return true; return false; } } } class Read { private BufferedReader br; private StringTokenizer st; public Read(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } 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
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
477f4f5ea1af8608452babc186f20b53
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
/* Author: Anthony Ngene Created: 07/08/2020 - 06:51 */ import java.io.*; import java.util.*; public class D { // He who angers you conquers you. - Elizabeth Kenny public static void main(String[] args) throws IOException { in = new FastScanner(); int cases = in.intNext(); for (int t = 1; t <= cases; t++) { int n = in.intNext(); int[] arr = new int[n]; TreeSet<Tuple> treeSet = new TreeSet<>(); treeSet.add(new Tuple(0, n - 1)); int selected = 0; while (selected < n) { selected++; Tuple node = treeSet.pollLast(); int idx = (node.a + node.b) / 2; arr[idx] = selected; if (idx > node.a) treeSet.add(new Tuple(node.a, idx - 1)); if (idx < node.b) treeSet.add(new Tuple(idx + 1, node.b)); } for (int i: arr) out.p(i).p(" "); out.println(""); } out.close(); } static class Tuple implements Comparable<Tuple> { int a; int b; public Tuple(int a, int b) { this.a = a; this.b = b; } public int getA() { return a; } public int getB() { return b; } public int size() { return this.b - this.a + 1; } public int compareTo(Tuple other) { if (this.size() == other.size()) return Integer.compare(other.b, this.b); return Integer.compare(this.size(), other.size()); } @Override public int hashCode() { return Arrays.deepHashCode(new Integer[]{a, b}); } @Override public boolean equals(Object o) { if (!(o instanceof Tuple)) return false; Tuple pairo = (Tuple) o; return (this.a == pairo.a && this.b == pairo.b); } @Override public String toString() { return String.format("(%d, %d) ", this.a, this.b); } } private static final FastWriter out = new FastWriter(); private static FastScanner in; static ArrayList<Integer>[] adj; private static long e97 = (long)1e9 + 7; static class FastWriter { private static final int IO_BUFFERS = 128 * 1024; private final StringBuilder out; public FastWriter() { out = new StringBuilder(IO_BUFFERS); } public FastWriter p(Object object) { out.append(object); return this; } public FastWriter p(String format, Object... args) { out.append(String.format(format, args)); return this; } public FastWriter pp(Object... args) { for (Object ob : args) { out.append(ob).append(" "); } out.append("\n"); return this; } public FastWriter println(Object object) { out.append(object).append("\n"); return this; } public void toFile(String fileName) throws IOException { BufferedWriter writer = new BufferedWriter(new FileWriter(fileName)); writer.write(out.toString()); writer.close(); } public void close() throws IOException { System.out.print(out); } } static class FastScanner { private InputStream sin = System.in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; public FastScanner(){} public FastScanner(String filename) throws FileNotFoundException { File file = new File(filename); sin = new FileInputStream(file); } private boolean hasNextByte() { if (ptr < buflen) { return true; }else{ ptr = 0; try { buflen = sin.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;} private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;} public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte();} public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while(isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long longNext() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while(true){ if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; }else if(b == -1 || !isPrintableChar(b) || b == ':'){ return minus ? -n : n; }else{ throw new NumberFormatException(); } b = readByte(); } } public int intNext() { long nl = longNext(); if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException(); return (int) nl; } public double doubleNext() { return Double.parseDouble(next());} public long[] nextLongArray(final int n){ final long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = longNext(); return a; } public int[] nextIntArray(final int n){ final int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = intNext(); return a; } public ArrayList<Integer>[] getAdj(int n) { ArrayList<Integer>[] adj = new ArrayList[n + 1]; for (int i = 1; i <= n; i++) adj[i] = new ArrayList<>(); return adj; } public ArrayList<Integer>[] adjacencyList(int n, int m) throws IOException { adj = getAdj(n); for (int i = 0; i < m; i++) { int a = intNext(), b = intNext(); adj[a].add(b); adj[b].add(a); } return adj; } } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
5f54f9f3bc76a1c53fc195019aefd3b1
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.*; public class Main { private static FastReader f = new FastReader(); public static void main(String[] args) { int t = f.nextInt(); while (t-- > 0) { solve(); } } static void solve() { int n = f.nextInt(); int[] ans = new int[n]; PriorityQueue<Pair> que = new PriorityQueue<>(); que.add(new Pair(0,n-1)); int cnt = 1; while (!que.isEmpty()) { Pair now = que.poll(); //System.out.println(now.left+" "+now.right); int place = now.left + (now.right-now.left)/2; ans[place] = cnt; cnt++; if(now.left != place) { que.add(new Pair(now.left, place-1)); } if(now.right != place) { que.add(new Pair(place+1, now.right)); } } StringBuilder sb = new StringBuilder(); for(int i=0;i<n;i++) { sb.append(ans[i]); sb.append(' '); } System.out.println(sb.toString()); } static class Pair implements Comparable<Pair>{ int left; int right; int diff; Pair(int left, int right) { this.left = left; this.right = right; diff = right - left; } @Override public int compareTo(Pair o) { if(diff == o.diff) { return left - o.left; } return o.diff - diff; } } //fast input reader 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
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
d7d78d69187af5143e6ab0a7527afb65
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; public class codeforces { public static void main(String[] args) { Scanner s=new Scanner(System.in); int t=s.nextInt(); for(int k=0;k<t;k++) { int n=s.nextInt(); int start=1,end=n; int temp[]={1,n,n}; PriorityQueue<int[]>pq=new PriorityQueue<>((a,b)->a[2]==b[2]?a[0]-b[0]:b[2]-a[2]); int outArr[]=new int[n+1]; pq.add(temp); int count =1; while(pq.size()>0) { int arr[]=pq.remove(); start=arr[0]; end=arr[1]; int mid=0; if(start==end) { outArr[start]=count++; } else { mid=(start+end)/2; outArr[mid]=count++; if(mid-start>0) pq.add(new int[]{start,mid-1,mid-start}); if(end-mid>0) pq.add(new int[]{mid+1,end,end-mid}); } } for(int i=1;i<=n;i++) System.out.print(outArr[i]+" "); } } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
d942c5fb596a6297dd0fc4b6cd5894ea
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main{ public static void main(String[] args) throws java.lang.Exception{ // BufferedReader scan = new BufferedReader(new InputStreamReader(System.in)); Reader scan = new Reader(); scan.init(System.in); PrintWriter out = new PrintWriter(System.out); int T = scan.nextInt(); for (int o=0;o<T;o++){ int n = scan.nextInt(); PriorityQueue<Point> q = new PriorityQueue(new comp()); int[] arr = new int[n]; q.add(new Point(0,n-1)); int count = 1; while(!q.isEmpty()){ Point A = q.poll(); int mid = A.y-A.x+1; if (mid%2==0){ mid = (A.x+A.y-1)/2; } else{ mid = (A.x+A.y)/2; } arr[mid] = count++; if (mid-1>=A.x){ q.add(new Point(A.x,mid-1)); } if ( mid+1<=A.y){ q.add(new Point(mid+1,A.y)); } } for (int i : arr){ out.print(i+" "); } out.println(); } out.close(); } } class Point{ int x,y; Point(int a,int b){ x = a; y = b; } } class comp implements Comparator<Point>{ public int compare(Point a,Point b){ if (a.y-a.x+1==b.y-b.x+1){ return a.x-b.x; } return (b.y-b.x+1)-(a.y-a.x+1); } } 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() ); } static double nextDouble() throws IOException { return Double.parseDouble( next() ); } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
36d05d6433a16da2ab8d3d786de6bb77
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.PriorityQueue; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; public class Main { static ArrayList<Integer> adj[]; static PrintWriter out = new PrintWriter(System.out); public static long mod; static int [][]notmemo; static int k; static long[] a; static long b[]; static int m; static char c[][]; static class Pair implements Comparable<Pair>{ int a,b; public Pair(int a2,int e ) { a=a2; b=e; } @Override public int compareTo(Pair o) { if(this.b-this.a==o.b-o.a) { if(this.a>o.a) return 1; else return -1; } else if(this.b-this.a>o.b-o.a) return -1; else { return 1; } } } static Pair s1[]; static long s[]; static ArrayList<Pair> adjlist[]; static int n1; static int n2; static int k1; static int k2; static int skip=0; public static void main(String args[]) throws IOException { Scanner sc = new Scanner(System.in); int t=sc.nextInt(); label: while(t-->0) { int n=sc.nextInt(); PriorityQueue<Pair> pq=new PriorityQueue<>(); pq.add(new Pair(0,n-1)); int a[]=new int[n]; for (int i = 0; i <n; i++) { Pair p=pq.poll(); int l=p.a; int r=p.b; int idx=(l+r)/2; a[idx]=i+1; pq.add(new Pair(p.a,idx-1)); pq.add(new Pair(idx+1,p.b)); } for(int x:a) { out.print(x+" "); } out.println(); } out.flush(); } static int reali,realj; static int dx[]= {1,-1,0,0}; static int dy[]= {0,0,1,-1}; static char curchar; public static boolean ddfs(int i, int j, int size) { boolean f=false; for (int k = 0; k < dx.length; k++) { int x=dx[k]+i; int y=dy[k]+j; if(valid(x,y,curchar)) { if(visit[x][y]&&size>=4&&reali==x&&realj==y) { // System.out.println(reali+" "+realj+" "+size); // System.out.println(i+" "+j); // return true; } else if(!visit[x][y]){ visit[x][y]=true; //System.out.println(x+" "+y+" "+size); f|=ddfs(x,y,size+1); } } } return f; } public static boolean valid(int x, int y, char curchar2) { if(x>=n||y>=m||x<0||y<0||c[x][y]!=curchar2) { return false; } return true; } private static long lcm(long a2, long b2) { return (a2*b2)/gcd(a2,b2); } static boolean visit[][]; static Boolean zero[][]; static int small[]; static void dfs(int s, int e) { small[s] = 1; for(int u: adj[s]) { if(u == e) continue; dfs(u ,s); small[s] +=small[u]; } } static int idx=0; static long dpdp[][][][]; static int modd=(int) 1e8; static class Edge implements Comparable<Edge> { int node;long cost; Edge(int a, long b) { node = a; cost = b; } public int compareTo(Edge e){ return Long.compare(cost,e.cost); } } static void sieve(int N) // O(N log log N) { isComposite = new int[N+1]; isComposite[0] = isComposite[1] = 1; // 0 indicates a prime number primes = new ArrayList<Integer>(); for (int i = 2; i <= N; ++i) //can loop till i*i <= N if primes array is not needed O(N log log sqrt(N)) if (isComposite[i] == 0) //can loop in 2 and odd integers for slightly better performance { primes.add(i); if(1l * i * i <= N) for (int j = i * i; j <= N; j += i) // j = i * 2 will not affect performance too much, may alter in modified sieve isComposite[j] = 1; } } static TreeSet<Integer> factors; static ArrayList<Integer> primeFactors(int N) // O(sqrt(N) / ln sqrt(N)) { ArrayList<Integer> factors = new ArrayList<Integer>(); //take abs(N) in case of -ve integers int idx = 0, p = primes.get(idx); while(1l*p * p <= N) { while(N % p == 0) { factors.add(p); N /= p; } p = primes.get(++idx); } if(N != 1) // last prime factor may be > sqrt(N) factors.add(N); // for integers whose largest prime factor has a power of 1 return factors; } static String y; static int nomnom[]; static long fac[]; static boolean f = true; static class SegmentTree { // 1-based DS, OOP int N; // the number of elements in the array as a power of 2 (i.e. after padding) int[] array, sTree, lazy; SegmentTree(int[] in) { array = in; N = in.length - 1; sTree = new int[N << 1]; // no. of nodes = 2*N - 1, we add one to cross out index zero lazy = new int[N << 1]; //build(1, 1, N); } void build(int node, int b, int e) // O(n) { if (b == e) sTree[node] = array[b]; else { int mid = b + e >> 1; build(node << 1, b, mid); build(node << 1 | 1, mid + 1, e); sTree[node] = sTree[node << 1] + sTree[node << 1 | 1]; } } void update_point(int index, int val) // O(log n) { index += N - 1; sTree[index] = val; while(index>1) { index >>= 1; sTree[index] = Math.max(sTree[index<<1] ,sTree[index<<1|1]); } } void update_range(int i, int j, int val) // O(log n) { update_range(1, 1, N, i, j, val); } void update_range(int node, int b, int e, int i, int j, int val) { if (i > e || j < b) return; if (b >= i && e <= j) { sTree[node] += (e - b + 1) * val; lazy[node] += val; } else { int mid = b + e >> 1; propagate(node, b, mid, e); update_range(node << 1, b, mid, i, j, val); update_range(node << 1 | 1, mid + 1, e, i, j, val); sTree[node] = sTree[node << 1] + sTree[node << 1 | 1]; } } void propagate(int node, int b, int mid, int e) { lazy[node << 1] += lazy[node]; lazy[node << 1 | 1] += lazy[node]; sTree[node << 1] += (mid - b + 1) * lazy[node]; sTree[node << 1 | 1] += (e - mid) * lazy[node]; lazy[node] = 0; } int query(int i, int j) { return query(1, 1, N, i, j); } int query(int node, int b, int e, int i, int j) // O(log n) { if (i > e || j < b) return 0; if (b >= i && e <= j) return sTree[node]; int mid = b + e >> 1; // propagate(node, b, mid, e); int q1 = query(node << 1, b, mid, i, j); int q2 = query(node << 1 | 1, mid + 1, e, i, j); return Math.max(q1,q2); } } static long[][] memo; static class UnionFind { int[] p, rank, setSize; int numSets; int max[]; public UnionFind(int N) { p = new int[numSets = N]; rank = new int[N]; setSize = new int[N]; for (int i = 0; i < N; i++) { p[i] = i; setSize[i] = 1; } } public int findSet(int i) { return p[i] == i ? i : (p[i] = findSet(p[i])); } public boolean isSameSet(int i, int j) { return findSet(i) == findSet(j); } public int chunion(int i,int j, int x2) { if (isSameSet(i, j)) return 0; numSets--; int x = findSet(i), y = findSet(j); int z=findSet(x2); p[x]=z;; p[y]=z; return x; } public void unionSet(int i, int j) { if (isSameSet(i, j)) return; numSets--; int x = findSet(i), y = findSet(j); if (rank[x] > rank[y]) { p[y] = x; setSize[x] += setSize[y]; } else { p[x] = y; setSize[y] += setSize[x]; if (rank[x] == rank[y]) rank[y]++; } } public int numDisjointSets() { return numSets; } public int sizeOfSet(int i) { return setSize[findSet(i)]; } } /** * private static void trace(int i, int time) { if(i==n) return; * * * long ans=dp(i,time); * if(time+a[i].t<a[i].burn&&(ans==dp(i+1,time+a[i].t)+a[i].cost)) { * * trace(i+1, time+a[i].t); * * l1.add(a[i].idx); return; } trace(i+1,time); * * } **/ static class incpair implements Comparable<incpair> { int a; long b; int idx; incpair(int a, long dirg, int i) { this.a = a; b = dirg; idx = i; } public int compareTo(incpair e) { return (int) (b - e.b); } } static class decpair implements Comparable<decpair> { int a; long b; int idx; decpair(int a, long dirg, int i) { this.a = a; b = dirg; idx = i; } public int compareTo(decpair e) { return (int) (e.b - b); } } static long allpowers[]; static class Quad implements Comparable<Quad> { int u; int v; char state; int turns; public Quad(int i, int j, char c, int k) { u = i; v = j; state = c; turns = k; } public int compareTo(Quad e) { return (int) (turns - e.turns); } } static long dirg[][]; static Edge[] driver; static int n; static long manhatandistance(long x, long x2, long y, long y2) { return Math.abs(x - x2) + Math.abs(y - y2); } static long fib[]; static long fib(int n) { if (n == 1 || n == 0) { return 1; } if (fib[n] != -1) { return fib[n]; } else return fib[n] = ((fib(n - 2) % mod + fib(n - 1) % mod) % mod); } static class Point implements Comparable<Point>{ long x, y; Point(long counth, long counts) { x = counth; y = counts; } @Override public int compareTo(Point p ) { return Long.compare(p.y*1l*x, p.x*1l*y); } } static long[][] comb; static class Triple implements Comparable<Triple> { int l; int r; long cost; int idx; public Triple(int a, int b, long l1, int l2) { l = a; r = b; cost = l1; idx = l2; } public int compareTo(Triple x) { if (l != x.l || idx == x.idx) return l - x.l; return -idx; } } static TreeSet<Long> primeFactors(long N) // O(sqrt(N) / ln sqrt(N)) { TreeSet<Long> factors = new TreeSet<Long>(); // take abs(N) in case of -ve integers int idx = 0, p = primes.get(idx); while (p * p <= N) { while (N % p == 0) { factors.add((long) p); N /= p; } if (primes.size() > idx + 1) p = primes.get(++idx); else break; } if (N != 1) // last prime factor may be > sqrt(N) factors.add(N); // for integers whose largest prime factor has a power of 1 return factors; } static boolean visited[]; /** * static int bfs(int s) { Queue<Integer> q = new LinkedList<Integer>(); * q.add(s); int count=0; int maxcost=0; int dist[]=new int[n]; dist[s]=0; * while(!q.isEmpty()) { * * int u = q.remove(); if(dist[u]==k) { break; } for(Pair v: adj[u]) { * maxcost=Math.max(maxcost, v.cost); * * * * if(!visited[v.v]) { * * visited[v.v]=true; q.add(v.v); dist[v.v]=dist[u]+1; maxcost=Math.max(maxcost, * v.cost); } } * * } return maxcost; } **/ public static boolean FindAllElements(int n, int k) { int sum = k; int[] A = new int[k]; Arrays.fill(A, 0, k, 1); for (int i = k - 1; i >= 0; --i) { while (sum + A[i] <= n) { sum += A[i]; A[i] *= 2; } } if (sum == n) { return true; } else return false; } static boolean[] vis2; static boolean f2 = false; static long[][] matMul(long[][] a2, long[][] b, int p, int q, int r) // C(p x r) = A(p x q) x (q x r) -- O(p x q x // r) { long[][] C = new long[p][r]; for (int i = 0; i < p; ++i) { for (int j = 0; j < r; ++j) { for (int k = 0; k < q; ++k) { C[i][j] = (C[i][j] + (a2[i][k] % mod * b[k][j] % mod)) % mod; C[i][j] %= mod; } } } return C; } public static int[] schuffle(int[] a2) { for (int i = 0; i < a2.length; i++) { int x = (int) (Math.random() * a2.length); int temp = a2[x]; a2[x] = a2[i]; a2[i] = temp; } return a2; } static int memo1[]; static boolean vis[]; static TreeSet<Integer> set = new TreeSet<Integer>(); static long modPow(long ways, long count, long mod) // O(log e) { ways %= mod; long res = 1; while (count > 0) { if ((count & 1) == 1) res = (res * ways) % mod; ways = (ways * ways) % mod; count >>= 1; } return res % mod; } static long gcd(long ans, long b) { if (b == 0) { return ans; } return gcd(b, ans % b); } static int[] isComposite; static int[] valid; static ArrayList<Integer> primes; static ArrayList<Integer> l1; static TreeSet<Integer> primus = new TreeSet<Integer>(); static void sieveLinear(int N) { int[] lp = new int[N + 1]; //lp[i] = least prime divisor of i for(int i = 2; i <= N; ++i) { if(lp[i] == 0) { primus.add(i); lp[i] = i; } int curLP = lp[i]; for(int p: primus) if(p > curLP || p * i > N) break; else lp[p * i] = i; } } public static long[] schuffle(long[] a2) { for (int i = 0; i < a2.length; i++) { int x = (int) (Math.random() * a2.length); long temp = a2[x]; a2[x] = a2[i]; a2[i] = temp; } return a2; } static int V; static long INF = (long) 1E16; static class Edge2 { int node; long cost; long next; Edge2(int a, int c, Long long1) { node = a; cost = long1; next = c; } } 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 boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } public int[] nxtArr(int n) throws IOException { int[] ans = new int[n]; for (int i = 0; i < n; i++) ans[i] = nextInt(); return ans; } } public static int[] sortarray(int a[]) { schuffle(a); Arrays.sort(a); return a; } public static long[] sortarray(long a[]) { schuffle(a); Arrays.sort(a); return a; } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
a41bbe0a93e122f2eba513698983b46c
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.*; public class Main { private static final boolean N_CASE = true; private void solve() { int n = sc.nextInt(); int[] ans = new int[n]; PriorityQueue<int[]> q = new PriorityQueue<>((x, y) -> { int lx = x[1] - x[0]; int ly = y[1] - y[0]; if (lx == ly) { return x[0] - y[0]; } else { return ly - lx; } }); q.add(new int[] { 0, n - 1 }); int i = 1; while (!q.isEmpty()) { int[] u = q.poll(); int l = u[0]; int r = u[1]; int len = r - l + 1; int mid; if (len % 2 == 1) { mid = (l + r) / 2; } else { mid = (l + r - 1) / 2; } ans[mid] = i; if (l < mid) { q.add(new int[]{l, mid - 1}); } if (r > mid) { q.add(new int[]{mid + 1, r}); } ++i; } out.printArray(ans); } private void run() { int T = N_CASE ? sc.nextInt() : 1; for (int t = 0; t < T; ++t) { solve(); } } private static MyWriter out; private static MyScanner sc; private static class MyScanner { BufferedReader br; StringTokenizer st; private 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()); } int[] nextArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } List<Integer> nextList(int n) { List<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) { list.add(nextInt()); } return list; } } private static class MyWriter extends PrintWriter { private MyWriter(OutputStream outputStream) { super(outputStream); } void printArray(int[] a) { for (int i = 0; i < a.length; ++i) { print(a[i]); print(i == a.length - 1 ? '\n' : ' '); } } void printlnArray(int[] a) { for (int v : a) { println(v); } } void printList(List<Integer> list) { for (int i = 0; i < list.size(); ++i) { print(list.get(i)); print(i == list.size() - 1 ? '\n' : ' '); } } void printlnList(List<Integer> list) { list.forEach(this::println); } } public static void main(String[] args) { out = new MyWriter(new BufferedOutputStream(System.out)); sc = new MyScanner(); new Main().run(); out.close(); } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
b3120eec64777ba64700783467289b9d
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
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; } } public static class Pair { int l; int r; int d; Pair(int l,int r,int d) { this.l=l; this.r=r; this.d=d; } } public static void main(String[] sdf) { FastReader s=new FastReader(); StringBuilder sb=new StringBuilder(); int t=s.nextInt(); for(int o=0;o<t;o++) { int n=s.nextInt(); int[] arr=new int[n+1]; PriorityQueue<Pair> pp=new PriorityQueue(new Comparator<Pair>() { public int compare(Pair p1,Pair p2) { if(p2.d==p1.d) return p1.l-p2.l; else return p2.d-p1.d; } }); pp.add(new Pair(1,n,n)); int vv=1; while(!pp.isEmpty() && vv<=n) { Pair p=pp.poll(); int l=p.l; int r=p.r; //System.out.println(l+" "+r); int dd=r-l+1; int m=0; if(dd%2==0) { m=(l+r-1)/2; arr[m]=vv; } else { m=(l+r)/2; arr[m]=vv; } vv++; if(l!=r) { pp.add(new Pair(l,m-1,m-l)); pp.add(new Pair(m+1,r,r-m)); } } for(int i=1;i<=n;i++) { if(i==n) sb.append(arr[i]+"\n"); else sb.append(arr[i]+" "); } } System.out.println(sb.toString()); } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
9219be6ce26c8bdbefc1f7d65979630b
train_003.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.*; public class psykibaek { public static class aTree implements Comparable<aTree>{ public int start; public int end; public int dist; public aTree(int start, int end){ this.start = start; this.end = end; this.dist = end-start; } public int getDist(){ return dist; } // dist가 큰게 먼저와야 함 // dist가 같다면, start가 작은게 먼저 와야함 @Override public int compareTo(aTree b){ if(this.getDist() > b.getDist()) return -1; else if(this.getDist() == b.getDist()){ if(this.start < b.start) return -1; else return 1; } else return 1; } } public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); int totCase = Integer.parseInt(br.readLine()); while(totCase-- > 0){ int n = Integer.parseInt(br.readLine()); int[] result = new int[n+1]; PriorityQueue<aTree> pq = new PriorityQueue<>(); pq.add(new aTree(1, n)); int k = 1; while(!pq.isEmpty()){ aTree a = pq.peek(); pq.poll(); int newPoint = (a.end + a.start)/2; if(a.start <= newPoint-1) pq.add(new aTree(a.start, newPoint-1)); if(newPoint+1 <= a.end) pq.add(new aTree(newPoint+1, a.end)); result[newPoint] = k; k++; if(isDebug){ System.out.println("start,end: " + a.start + " " + a.end); for (int i = 1; i <= n; i++) { System.out.print(result[i] + " "); } System.out.println(); System.out.println(); } } if(isDebug){ System.out.println("답"); } for (int i = 1; i <= n ; i++) { bw.write(result[i] + " "); } bw.newLine(); } bw.close(); } public static boolean isDebug = false; }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
ddeacf13683e54dd32342ab3a6e3288b
train_003.jsonl
1430411400
The Bad Luck Island is inhabited by three kinds of species: r rocks, s scissors and p papers. At some moments of time two random individuals meet (all pairs of individuals can meet equiprobably), and if they belong to different species, then one individual kills the other one: a rock kills scissors, scissors kill paper, and paper kills a rock. Your task is to determine for each species what is the probability that this species will be the only one to inhabit this island after a long enough period of time.
256 megabytes
import java.io.*; import java.util.Arrays; import java.util.StringTokenizer; import static java.lang.Integer.parseInt; import static java.nio.charset.StandardCharsets.UTF_8; public class Main { public static void main(String[] args) throws IOException { try (BufferedReader in = new BufferedReader(new InputStreamReader(System.in, UTF_8)); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out, UTF_8))) { StringTokenizer tokens = new StringTokenizer(in.readLine()); int r = parseInt(tokens.nextToken()); int s = parseInt(tokens.nextToken()); int p = parseInt(tokens.nextToken()); double[][][] dp = new double[r + 1][s + 1][p + 1]; for (int i = 0; i <= r; i++) { for (int j = 0; j <= s; j++) { Arrays.fill(dp[i][j], -1); } } for (int i = r; i >= 0; i--) { for (int j = s; j >= 0; j--) { for (int k = p; k >= 0; k--) { f(dp, i, j, k); } } } double xr = 0; for (int i = 0; i <= r; i++) { xr += dp[i][0][0]; } double xs = 0; for (int i = 0; i <= s; i++) { xs += dp[0][i][0]; } double xp = 0; for (int i = 0; i <= p; i++) { xp += dp[0][0][i]; } out.write(xr + " " + xs + " " + xp); out.newLine(); } } private static double f(double[][][] dp, int x, int y, int z) { if (x >= dp.length || y >= dp[0].length || z >= dp[0][0].length) { return 0; } else if (x == dp.length - 1 && y == dp[0].length - 1 && z == dp[0][0].length - 1) { return 1; } if (dp[x][y][z] > -1) { return dp[x][y][z]; } dp[x][y][z] = 0; if (x > 0) { dp[x][y][z] += (x * (y + 1.0)) / (x * (y + 1) + (y + 1) * z + x * z) * f(dp, x, y + 1, z); } if (y > 0) { dp[x][y][z] += (y * (z + 1.0)) / (x * y + y * (z + 1) + x * (z + 1)) * f(dp, x, y, z + 1); } if (z > 0) { dp[x][y][z] += ((x + 1.0) * z) / ((x + 1) * y + y * z + (x + 1) * z) * f(dp, x + 1, y, z); } return dp[x][y][z]; } }
Java
["2 2 2", "2 1 2", "1 1 3"]
2 seconds
["0.333333333333 0.333333333333 0.333333333333", "0.150000000000 0.300000000000 0.550000000000", "0.057142857143 0.657142857143 0.285714285714"]
null
Java 8
standard input
[ "dp", "probabilities" ]
35736970c6d629c2764eaf23299e0356
The single line contains three integers r, s and p (1 ≤ r, s, p ≤ 100) — the original number of individuals in the species of rock, scissors and paper, respectively.
1,900
Print three space-separated real numbers: the probabilities, at which the rocks, the scissors and the paper will be the only surviving species, respectively. The answer will be considered correct if the relative or absolute error of each number doesn't exceed 10 - 9.
standard output
PASSED
e2a4190f08755c496421f4ad1cedc9f1
train_003.jsonl
1430411400
The Bad Luck Island is inhabited by three kinds of species: r rocks, s scissors and p papers. At some moments of time two random individuals meet (all pairs of individuals can meet equiprobably), and if they belong to different species, then one individual kills the other one: a rock kills scissors, scissors kill paper, and paper kills a rock. Your task is to determine for each species what is the probability that this species will be the only one to inhabit this island after a long enough period of time.
256 megabytes
import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.IOException; import java.util.StringTokenizer; import java.io.InputStream; import java.io.InputStreamReader; /** * Built using CHelper plug-in * Actual solution is at the top * @author Artyom Korzun */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } } class TaskD { public void solve(int testNumber, FastScanner in, PrintWriter out) { int r = in.nextInt(); int s = in.nextInt(); int p = in.nextInt(); double[][][] dp = new double[r + 1][s + 1][p + 1]; dp[r][s][p] = 1; for (int i = r; i >= 0; i--) { for (int j = s; j >= 0; j--) { for (int k = p; k >= 0; k--) { int all = i * j + i * k + j * k; if (i > 0 && j > 0) dp[i][j - 1][k] += i * j * dp[i][j][k] / all; if (i > 0 && k > 0) dp[i - 1][j][k] += i * k * dp[i][j][k] / all; if (j > 0 && k > 0) dp[i][j][k - 1] += j * k * dp[i][j][k] / all; } } } double rAnswer = 0; for (int i = 1; i <= r; i++) rAnswer += dp[i][0][0]; double sAnswer = 0; for (int i = 1; i <= s; i++) sAnswer += dp[0][i][0]; double pAnswer = 0; for (int i = 1; i <= p; i++) pAnswer += dp[0][0][i]; out.printf("%.12f %.12f %.12f", rAnswer, sAnswer, pAnswer); } } class FastScanner { private final BufferedReader reader; private StringTokenizer tokenizer; public FastScanner(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); } public int nextInt() { return Integer.parseInt(next()); } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(nextLine()); return tokenizer.nextToken(); } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } }
Java
["2 2 2", "2 1 2", "1 1 3"]
2 seconds
["0.333333333333 0.333333333333 0.333333333333", "0.150000000000 0.300000000000 0.550000000000", "0.057142857143 0.657142857143 0.285714285714"]
null
Java 8
standard input
[ "dp", "probabilities" ]
35736970c6d629c2764eaf23299e0356
The single line contains three integers r, s and p (1 ≤ r, s, p ≤ 100) — the original number of individuals in the species of rock, scissors and paper, respectively.
1,900
Print three space-separated real numbers: the probabilities, at which the rocks, the scissors and the paper will be the only surviving species, respectively. The answer will be considered correct if the relative or absolute error of each number doesn't exceed 10 - 9.
standard output
PASSED
74cc81f90336032d19b02a60503e0b4e
train_003.jsonl
1430411400
The Bad Luck Island is inhabited by three kinds of species: r rocks, s scissors and p papers. At some moments of time two random individuals meet (all pairs of individuals can meet equiprobably), and if they belong to different species, then one individual kills the other one: a rock kills scissors, scissors kill paper, and paper kills a rock. Your task is to determine for each species what is the probability that this species will be the only one to inhabit this island after a long enough period of time.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main1 { static class Reader { private InputStream mIs;private byte[] buf = new byte[1024];private int curChar,numChars;public Reader() { this(System.in); }public Reader(InputStream is) { mIs = is;} public int read() {if (numChars == -1) throw new InputMismatchException();if (curChar >= numChars) {curChar = 0;try { numChars = mIs.read(buf);} catch (IOException e) { throw new InputMismatchException();}if (numChars <= 0) return -1; }return buf[curChar++];} public String nextLine(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isEndOfLine(c));return res.toString() ;} public String s(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isSpaceChar(c));return res.toString();} public long l(){int c = read();while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }long res = 0; do{ if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read();}while(!isSpaceChar(c));return res * sgn;} public int i(){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 double d() throws IOException {return Double.parseDouble(s()) ;} public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public int[] arr(int n){int[] ret = new int[n];for (int i = 0; i < n; i++) {ret[i] = i();}return ret;} } /////////////////////////////////////////////////////////////////////////////////////////// // RRRRRRRRR AAA HHH HHH IIIIIIIIIIIII LLL // // RR RRR AAAAA HHH HHH IIIIIIIIIII LLL // // RR RRR AAAAAAA HHH HHH III LLL // // RR RRR AAA AAA HHHHHHHHHHH III LLL // // RRRRRR AAA AAA HHHHHHHHHHH III LLL // // RR RRR AAAAAAAAAAAAA HHH HHH III LLL // // RR RRR AAA AAA HHH HHH IIIIIIIIIII LLLLLLLLLLLL // // RR RRR AAA AAA HHH HHH IIIIIIIIIIIII LLLLLLLLLLLL // /////////////////////////////////////////////////////////////////////////////////////////// public static void main(String[] args)throws IOException { //edtrl PrintWriter out= new PrintWriter(System.out); Reader sc=new Reader(); int r=sc.i();int s=sc.i();int p=sc.i(); double dp[][][]=new double[r+1][p+1][s+1]; dp[r][p][s]=1.0; double ans[]=new double[3]; for(int i=r;i>=0;i--) for(int j=p;j>=0;j--) for(int k=s;k>=0;k--) { if(i*j+j*k+i*k==0) continue; if(i>0) dp[i-1][j][k]+=dp[i][j][k]*i*j/(i*j+j*k+k*i); if(j>0) dp[i][j-1][k]+=dp[i][j][k]*j*k/(i*j+j*k+k*i); if(k>0) dp[i][j][k-1]+=dp[i][j][k]*i*k/(i*j+j*k+k*i); } double sum1=0; for(int i=0;i<=r;i++)sum1+=dp[i][0][0]; out.println(sum1); sum1=0; for(int i=0;i<=s;i++)sum1+=dp[0][0][i]; out.println(sum1); sum1=0; for(int i=0;i<=p;i++)sum1+=dp[0][i][0]; out.println(sum1); out.flush(); } }
Java
["2 2 2", "2 1 2", "1 1 3"]
2 seconds
["0.333333333333 0.333333333333 0.333333333333", "0.150000000000 0.300000000000 0.550000000000", "0.057142857143 0.657142857143 0.285714285714"]
null
Java 8
standard input
[ "dp", "probabilities" ]
35736970c6d629c2764eaf23299e0356
The single line contains three integers r, s and p (1 ≤ r, s, p ≤ 100) — the original number of individuals in the species of rock, scissors and paper, respectively.
1,900
Print three space-separated real numbers: the probabilities, at which the rocks, the scissors and the paper will be the only surviving species, respectively. The answer will be considered correct if the relative or absolute error of each number doesn't exceed 10 - 9.
standard output
PASSED
ccb5e5ef0ed0b155b3e067d697dd0cb0
train_003.jsonl
1430411400
The Bad Luck Island is inhabited by three kinds of species: r rocks, s scissors and p papers. At some moments of time two random individuals meet (all pairs of individuals can meet equiprobably), and if they belong to different species, then one individual kills the other one: a rock kills scissors, scissors kill paper, and paper kills a rock. Your task is to determine for each species what is the probability that this species will be the only one to inhabit this island after a long enough period of time.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int r = scanner.nextInt(); int s = scanner.nextInt(); int p = scanner.nextInt(); double[][][] pr = new double[r+1][][]; for (int i = 0; i <= r; i++) { pr[i] = new double[s+1][]; } for(int i = 0; i <= r; i++) { for (int j = 0; j <= s; j++) { pr[i][j] = new double[p+1]; } } double[][][] ps = new double[r+1][][]; for (int i = 0; i <= r; i++) { ps[i] = new double[s+1][]; } for(int i = 0; i <= r; i++) { for (int j = 0; j <= s; j++) { ps[i][j] = new double[p+1]; } } double[][][] pp = new double[r+1][][]; for (int i = 0; i <= r; i++) { pp[i] = new double[s+1][]; } for(int i = 0; i <= r; i++) { for (int j = 0; j <= s; j++) { pp[i][j] = new double[p+1]; } } for (int i = 0; i <= r; i++) { for (int j = 0; j <= s; j++) { for (int k = 0; k <= p; k++) { if (k == 0 && i != 0) { pr[i][j][k] = 1; } else if (i == 0 || j == 0) { pr[i][j][k] = 0; } else { pr[i][j][k] = i * k * pr[i - 1][j][k] / (i * j + k * j + i * k) + i * j * pr[i][j - 1][k] / (i * j + k * j + i * k) + k * j * pr[i][j][k - 1] / (i * j + k * j + i * k); } if (i == 0 && j != 0) { ps[i][j][k] = 1; } else if (k == 0 || j == 0) { ps[i][j][k] = 0; } else { ps[i][j][k] = i * k * ps[i - 1][j][k] / (i * j + k * j + i * k) + i * j * ps[i][j - 1][k] / (i * j + k * j + i * k) + k * j * ps[i][j][k - 1] / (i * j + k * j + i * k); } if (j == 0 && k != 0) { pp[i][j][k] = 1; } else if (i == 0 || k == 0) { pp[i][j][k] = 0; } else { pp[i][j][k] = i * k * pp[i - 1][j][k] / (i * j + k * j + i * k) + i * j * pp[i][j - 1][k] / (i * j + k * j + i * k) + k * j * pp[i][j][k - 1] / (i * j + k * j + i * k); } } } } System.out.println(pr[r][s][p] + " " +ps[r][s][p] + " " + (1-pr[r][s][p]-ps[r][s][p])); } }
Java
["2 2 2", "2 1 2", "1 1 3"]
2 seconds
["0.333333333333 0.333333333333 0.333333333333", "0.150000000000 0.300000000000 0.550000000000", "0.057142857143 0.657142857143 0.285714285714"]
null
Java 8
standard input
[ "dp", "probabilities" ]
35736970c6d629c2764eaf23299e0356
The single line contains three integers r, s and p (1 ≤ r, s, p ≤ 100) — the original number of individuals in the species of rock, scissors and paper, respectively.
1,900
Print three space-separated real numbers: the probabilities, at which the rocks, the scissors and the paper will be the only surviving species, respectively. The answer will be considered correct if the relative or absolute error of each number doesn't exceed 10 - 9.
standard output
PASSED
cbb7a9d0e6d77df18026abc30f081d66
train_003.jsonl
1430411400
The Bad Luck Island is inhabited by three kinds of species: r rocks, s scissors and p papers. At some moments of time two random individuals meet (all pairs of individuals can meet equiprobably), and if they belong to different species, then one individual kills the other one: a rock kills scissors, scissors kill paper, and paper kills a rock. Your task is to determine for each species what is the probability that this species will be the only one to inhabit this island after a long enough period of time.
256 megabytes
import java.util.*; import java.io.*; import static java.lang.System.in; public class Main { static int k; public static void main(String[] args)throws IOException { Scanner sc = new Scanner(System.in); int r = sc.nextInt(), s = sc.nextInt(), p = sc.nextInt(); double[][][] dp = new double[r+1][s+1][p+1]; dp[r][s][p] = 1.0; for(int i=r;i>=0;i--){ for(int j=s;j>=0;j--){ for(int k=p;k>=0;k--){ if(i==r&&j==s&&k==p||i==0&&s==0&&k==0) continue; double cur = 0; int base = comb2(i+j+1+k); if(j==0&&k==0){ dp[i][0][0] = dp[i][1][0]; continue; } if(k==0&&i==0){ dp[0][j][0] = dp[0][j][1]; continue; } if(i==0&&j==0){ dp[0][0][k] = dp[1][0][k]; continue; } if(i+j+k+1<=1) continue; if(i+1<=r) cur += ((double)k*(i+1))/((double)(base-comb2(i+1)-comb2(j)-comb2(k)))*dp[i+1][j][k]; if(j+1<=s) cur += ((double)i*(j+1))/((double)(base-comb2(i)-comb2(j+1)-comb2(k)))*dp[i][j+1][k]; if(k+1<=p) cur += ((double)j*(k+1))/((double)(base-comb2(i)-comb2(j)-comb2(k+1)))*dp[i][j][k+1]; dp[i][j][k] = cur; } } } double[] res = new double[]{0.0,0.0,0.0}; for(int i=1;i<=r;i++) res[0] += dp[i][0][0]; for(int j=1;j<=s;j++) res[1] += dp[0][j][0]; for(int k=1;k<=p;k++) res[2] += dp[0][0][k]; StringBuilder sb = new StringBuilder(); for(double w:res){ sb.append(w); sb.append(" "); } System.out.println(sb.toString()); } static int comb2(int i){ return i*(i-1)/2; } }
Java
["2 2 2", "2 1 2", "1 1 3"]
2 seconds
["0.333333333333 0.333333333333 0.333333333333", "0.150000000000 0.300000000000 0.550000000000", "0.057142857143 0.657142857143 0.285714285714"]
null
Java 8
standard input
[ "dp", "probabilities" ]
35736970c6d629c2764eaf23299e0356
The single line contains three integers r, s and p (1 ≤ r, s, p ≤ 100) — the original number of individuals in the species of rock, scissors and paper, respectively.
1,900
Print three space-separated real numbers: the probabilities, at which the rocks, the scissors and the paper will be the only surviving species, respectively. The answer will be considered correct if the relative or absolute error of each number doesn't exceed 10 - 9.
standard output
PASSED
827b8d078a7d092fe0ad844f9183d57c
train_003.jsonl
1430411400
The Bad Luck Island is inhabited by three kinds of species: r rocks, s scissors and p papers. At some moments of time two random individuals meet (all pairs of individuals can meet equiprobably), and if they belong to different species, then one individual kills the other one: a rock kills scissors, scissors kill paper, and paper kills a rock. Your task is to determine for each species what is the probability that this species will be the only one to inhabit this island after a long enough period of time.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class BadLuckIsland { static double[][][] dp; static double rocks(int r, int p, int s) { if (r == 0) return 0; if (s == 0 && p == 0) return 1; if (dp[r][p][s] != -1) return dp[r][p][s]; double res = 0, total = r * p + p * s + r * s; if (r > 0 && s > 0) res = rocks(r, p, s - 1) * ((r * s) / total); if (p > 0 && s > 0) res += rocks(r, p - 1, s) * ((p * s) / total); if (r > 0 && p > 0) res += rocks(r - 1, p, s) * ((r * p) / total); return dp[r][p][s] = res; } static double papers(int r, int p, int s) { if (p == 0) return 0; if (r == 0 && s == 0) return 1; if (dp[r][p][s] != -1) return dp[r][p][s]; double res = 0, total = r * p + p * s + r * s; if (r > 0 && s > 0) res = papers(r, p, s - 1) * ((r * s) / total); if (p > 0 && s > 0) res += papers(r, p - 1, s) * ((p * s) / total); if (r > 0 && p > 0) res += papers(r - 1, p, s) * ((r * p) / total); return dp[r][p][s] = res; } static double scissors(int r, int p, int s) { if (s == 0) return 0; if (r == 0 && p == 0) return 1; if (dp[r][p][s] != -1) return dp[r][p][s]; double res = 0, total = r * p + p * s + r * s; if (r > 0 && s > 0) res = scissors(r, p, s - 1) * ((r * s) / total); if (p > 0 && s > 0) res += scissors(r, p - 1, s) * ((p * s) / total); if (r > 0 && p > 0) res += scissors(r - 1, p, s) * ((r * p) / total); return dp[r][p][s] = res; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int r = sc.nextInt(), s = sc.nextInt(), p = sc.nextInt(); dp = new double[r + 1][p + 1][s + 1]; for (int i = 0; i <= r; i++) for (int j = 0; j <= p; j++) Arrays.fill(dp[i][j], -1); double a = rocks(r, p, s); for (int i = 0; i <= r; i++) for (int j = 0; j <= p; j++) Arrays.fill(dp[i][j], -1); double b = papers(r, p, s); for (int i = 0; i <= r; i++) for (int j = 0; j <= p; j++) Arrays.fill(dp[i][j], -1); double c = scissors(r, p, s); System.out.printf("%s %s %s\n", a, c, b); } }
Java
["2 2 2", "2 1 2", "1 1 3"]
2 seconds
["0.333333333333 0.333333333333 0.333333333333", "0.150000000000 0.300000000000 0.550000000000", "0.057142857143 0.657142857143 0.285714285714"]
null
Java 8
standard input
[ "dp", "probabilities" ]
35736970c6d629c2764eaf23299e0356
The single line contains three integers r, s and p (1 ≤ r, s, p ≤ 100) — the original number of individuals in the species of rock, scissors and paper, respectively.
1,900
Print three space-separated real numbers: the probabilities, at which the rocks, the scissors and the paper will be the only surviving species, respectively. The answer will be considered correct if the relative or absolute error of each number doesn't exceed 10 - 9.
standard output
PASSED
6ad32b050221260f26d4841c4311c844
train_003.jsonl
1430411400
The Bad Luck Island is inhabited by three kinds of species: r rocks, s scissors and p papers. At some moments of time two random individuals meet (all pairs of individuals can meet equiprobably), and if they belong to different species, then one individual kills the other one: a rock kills scissors, scissors kill paper, and paper kills a rock. Your task is to determine for each species what is the probability that this species will be the only one to inhabit this island after a long enough period of time.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; /** * Created by Martin on 5/23/2015. */ public class Main { public static void main(String[]args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int R = Integer.parseInt(st.nextToken()); int S = Integer.parseInt(st.nextToken()); int P = Integer.parseInt(st.nextToken()); double dp[][][] = new double[101][101][101]; dp[R][S][P] = 1; for(int r=R;r>=0;r--) { for(int s=S;s>=0;s--) { for(int p=P;p>=0;p--) { double all = r*s + r*p + p*s; if (all == 0) continue; if (r > 0) { dp[r - 1][s][p] += (r * p * dp[r][s][p]) / all; //debug(r-1,s,p,dp[r - 1][s][p]); } if (s > 0) { dp[r][s - 1][p] += (r * s * dp[r][s][p]) / all; //debug(r,s-1,p,dp[r][s-1][p]); } if (p > 0) { dp[r][s][p - 1] += (p * s * dp[r][s][p]) / all; //debug(r,s,p-1,dp[r][s][p-1]); } } } } double rp = 0; for (int i=1;i<=R;i++) rp += dp[i][0][0]; double sp = 0; for (int i=1;i<=S;i++) sp += dp[0][i][0]; double pp = 0; for (int i=1;i<=P;i++) pp += dp[0][0][i]; System.out.println(rp + " " + sp + " " + pp); } public static void debug(Object...args) { System.out.println(Arrays.deepToString(args)); } }
Java
["2 2 2", "2 1 2", "1 1 3"]
2 seconds
["0.333333333333 0.333333333333 0.333333333333", "0.150000000000 0.300000000000 0.550000000000", "0.057142857143 0.657142857143 0.285714285714"]
null
Java 8
standard input
[ "dp", "probabilities" ]
35736970c6d629c2764eaf23299e0356
The single line contains three integers r, s and p (1 ≤ r, s, p ≤ 100) — the original number of individuals in the species of rock, scissors and paper, respectively.
1,900
Print three space-separated real numbers: the probabilities, at which the rocks, the scissors and the paper will be the only surviving species, respectively. The answer will be considered correct if the relative or absolute error of each number doesn't exceed 10 - 9.
standard output
PASSED
4cc74e3b80a1ccf10ecc04b28bb5eb91
train_003.jsonl
1430411400
The Bad Luck Island is inhabited by three kinds of species: r rocks, s scissors and p papers. At some moments of time two random individuals meet (all pairs of individuals can meet equiprobably), and if they belong to different species, then one individual kills the other one: a rock kills scissors, scissors kill paper, and paper kills a rock. Your task is to determine for each species what is the probability that this species will be the only one to inhabit this island after a long enough period of time.
256 megabytes
import java.util.*; public class D540 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int rock = sc.nextInt(); int scissor = sc.nextInt(); int paper = sc.nextInt(); double[][][] dp = new double[105][105][105]; dp[rock][scissor][paper] = 1.0; for (int sum=rock+scissor+paper; sum > 0; sum--) { for (int r = rock; r>=0; r--) { for (int s=scissor; s>=0; s--) { int p = sum - r - s; if (p < 0 || p > paper) continue; if (r==0 && s==0) continue; if (s==0 && p==0) continue; if (p==0 && r==0) continue; int total = (r*s) + (s*p) + (p*r); double curr = dp[r][s][p]; if (r>0) dp[r-1][s][p] += ( (curr * (p*r)*1.0) / (total)); if (s>0) dp[r][s-1][p] += ( (curr * (r*s)*1.0) / (total)); if (p>0) dp[r][s][p-1] += ( (curr * (p*s)*1.0) / (total)); } } } double ansR = 0l, ansS=0l, ansP=0l; for (int i=1; i<=rock;i++) ansR += (dp[i][0][0]); for (int i=1; i<=scissor;i++) ansS += (dp[0][i][0]); for (int i=1; i<=paper;i++) ansP += (dp[0][0][i]); System.out.println(ansR + " " + ansS + " " + ansP); } }
Java
["2 2 2", "2 1 2", "1 1 3"]
2 seconds
["0.333333333333 0.333333333333 0.333333333333", "0.150000000000 0.300000000000 0.550000000000", "0.057142857143 0.657142857143 0.285714285714"]
null
Java 8
standard input
[ "dp", "probabilities" ]
35736970c6d629c2764eaf23299e0356
The single line contains three integers r, s and p (1 ≤ r, s, p ≤ 100) — the original number of individuals in the species of rock, scissors and paper, respectively.
1,900
Print three space-separated real numbers: the probabilities, at which the rocks, the scissors and the paper will be the only surviving species, respectively. The answer will be considered correct if the relative or absolute error of each number doesn't exceed 10 - 9.
standard output
PASSED
fa1845e1a9eb95366c66149ae55198de
train_003.jsonl
1430411400
The Bad Luck Island is inhabited by three kinds of species: r rocks, s scissors and p papers. At some moments of time two random individuals meet (all pairs of individuals can meet equiprobably), and if they belong to different species, then one individual kills the other one: a rock kills scissors, scissors kill paper, and paper kills a rock. Your task is to determine for each species what is the probability that this species will be the only one to inhabit this island after a long enough period of time.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main { PrintWriter out = new PrintWriter(System.out); InputReader ir = new InputReader(System.in); final long kmod = 993960000099397l; double mem[][][][]; void solve() throws IOException{ int r = ir.readInt(); int s = ir.readInt(); int p = ir.readInt(); mem = new double[r + 1][s + 1][p + 1][3]; for(int i = 0; i <= r; i++) { for(int j = 0; j <= s; j++) { for(int k = 0; k <= p; k++) Arrays.fill(mem[i][j][k], -1.0); } } for(int i = 0; i < 3; i++) { if(i == 0) mem[r][s][p][i] = rec0(r, s, p, i); if(i == 1) mem[r][s][p][i] = rec1(r, s, p, i); if(i == 2) mem[r][s][p][i] = rec2(r, s, p, i); out.printf("%.9f ", mem[r][s][p][i]); } out.println(); } double rec1(int r, int s, int p, int id) { if(s == 0) return 0.0; if(p == 0 && r == 0) return 1.0; if(mem[r][s][p][id] != -1) return mem[r][s][p][id]; double tot = r + s + p; double pro = 0; if(r != 0 && s != 0) pro = (r*s*1.0)/(r*s + p*r + s*p) * rec1(r, s- 1, p, id); if(s != 0 && p != 0) pro += (p*s*1.0)/(r*s + p*r + s*p) * rec1(r, s, p - 1, id); if(r != 0 && p != 0) pro += (r*p*1.0)/(r*s + p*r + s*p)* rec1(r - 1, s, p, id); return mem[r][s][p][id] = pro; } double rec2(int r, int s, int p, int id) { if(p == 0) return 0.0; if(s == 0 && r == 0) return 1.0; if(mem[r][s][p][id] != -1) return mem[r][s][p][id]; double tot = r + s + p; double pro = 0; if(r != 0 && s != 0) pro = (r*s*1.0)/(r*s + p*r + s*p) * rec2(r, s- 1, p, id); if(s != 0 && p != 0) pro += (p*s*1.0)/(r*s + p*r + s*p) * rec2(r, s, p - 1, id); if(r != 0 && p != 0) pro += (r*p*1.0)/(r*s + p*r + s*p)* rec2(r - 1, s, p, id); return mem[r][s][p][id] = pro; } double rec0(int r, int s, int p, int id) { if(r == 0) return 0.0; if(p == 0 && s == 0) return 1.0; if(mem[r][s][p][id] != -1) return mem[r][s][p][id]; double tot = r + s + p; double pro = 0; if(r != 0 && s != 0) pro = (r*s*1.0)/(r*s + p*r + s*p) * rec0(r, s- 1, p, id); if(s != 0 && p != 0) pro += (p*s*1.0)/(r*s + p*r + s*p) * rec0(r, s, p - 1, id); if(r != 0 && p != 0) pro += (r*p*1.0)/(r*s + p*r + s*p)* rec0(r - 1, s, p, id); return mem[r][s][p][id] = pro; } void run() throws IOException{ solve(); out.close(); } public static void main(String args[]) throws IOException{ new Main().run(); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public final int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long readLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { 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 double readDouble() { return Double.parseDouble(readString()); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } }
Java
["2 2 2", "2 1 2", "1 1 3"]
2 seconds
["0.333333333333 0.333333333333 0.333333333333", "0.150000000000 0.300000000000 0.550000000000", "0.057142857143 0.657142857143 0.285714285714"]
null
Java 8
standard input
[ "dp", "probabilities" ]
35736970c6d629c2764eaf23299e0356
The single line contains three integers r, s and p (1 ≤ r, s, p ≤ 100) — the original number of individuals in the species of rock, scissors and paper, respectively.
1,900
Print three space-separated real numbers: the probabilities, at which the rocks, the scissors and the paper will be the only surviving species, respectively. The answer will be considered correct if the relative or absolute error of each number doesn't exceed 10 - 9.
standard output
PASSED
f66df9a908c9acf5cb49f5ea043cd2ab
train_003.jsonl
1430411400
The Bad Luck Island is inhabited by three kinds of species: r rocks, s scissors and p papers. At some moments of time two random individuals meet (all pairs of individuals can meet equiprobably), and if they belong to different species, then one individual kills the other one: a rock kills scissors, scissors kill paper, and paper kills a rock. Your task is to determine for each species what is the probability that this species will be the only one to inhabit this island after a long enough period of time.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class utkarsh { InputStream is; PrintWriter out; void solve(){ //Enter code here utkarsh int r = ni(); int s = ni(); int p = ni(); double dp[][][] = new double[r+1][s+1][p+1]; dp[r][s][p] = 1; for(int i = r; i >= 0; i--) { for(int j = s; j >= 0; j--) { for(int k = p; k >= 0; k--) { double n = i * j + j * k + i * k; if(i > 0 && k > 0) dp[i-1][j][k] += dp[i][j][k] * (1.0 * i * k / n); if(j > 0 && i > 0) dp[i][j-1][k] += dp[i][j][k] * (1.0 * i * j / n); if(k > 0 && j > 0) dp[i][j][k-1] += dp[i][j][k] * (1.0 * j * k / n); } } } double ans = 0; for(int i = 1; i <= r; i++) ans += dp[i][0][0]; out.print(ans +" "); ans = 0; for(int i = 1; i <= s; i++) ans += dp[0][i][0]; out.print(ans +" "); ans = 0; for(int i = 1; i <= p; i++) ans += dp[0][0][i]; out.println(ans); } long modpow(long base, long exp, long modulus) { base %= modulus; long result = 1L; while (exp > 0) { if ((exp & 1)==1) result = (result * base) % modulus; base = (base * base) % modulus; exp >>= 1; } return result; } public static void main(String[] args) { new utkarsh().run(); } void run(){ is = System.in; out = new PrintWriter(System.out); solve(); out.flush(); } byte input[] = new byte[1024]; int len = 0, ptr = 0; int readByte(){ if(ptr >= len){ ptr = 0; try{ len = is.read(input); }catch(IOException e){ throw new InputMismatchException(); } if(len <= 0){ return -1; } } return input[ptr++]; } boolean isSpaceChar(int c){ return !( c >= 33 && c <= 126 ); } int skip(){ int b = readByte(); while(b != -1 && isSpaceChar(b)){ b = readByte(); } return b; } char nc(){ return (char)skip(); } String ns(){ int b = skip(); StringBuilder sb = new StringBuilder(); while(!isSpaceChar(b)){ sb.appendCodePoint(b); b=readByte(); } return sb.toString(); } int ni(){ int n = 0,b = readByte(); boolean minus = false; while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')){ b = readByte(); } if(b == '-'){ minus = true; b = readByte(); } if(b == -1){ return -1; } while(b >= '0' && b <= '9'){ n = n * 10 + (b - '0'); b = readByte(); } return minus ? -n : n; } long nl(){ long n = 0L; int b = readByte(); boolean minus = false; while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')){ b = readByte(); } if(b == '-'){ minus = true; b = readByte(); } while(b >= '0' && b <= '9'){ n = n * 10 + (b - '0'); b = readByte(); } return minus ? -n : n; } double nd(){ return Double.parseDouble(ns()); } float nf(){ return Float.parseFloat(ns()); } int[] na(int n){ int a[] = new int[n]; for(int i = 0; i < n; i++){ a[i] = ni(); } return a; } char[] ns(int n){ char c[] = new char[n]; int i,b = skip(); for(i = 0; i < n; i++){ if(isSpaceChar(b)){ break; } c[i] = (char)b; b = readByte(); } return i == n ? c : Arrays.copyOf(c,i); } }
Java
["2 2 2", "2 1 2", "1 1 3"]
2 seconds
["0.333333333333 0.333333333333 0.333333333333", "0.150000000000 0.300000000000 0.550000000000", "0.057142857143 0.657142857143 0.285714285714"]
null
Java 8
standard input
[ "dp", "probabilities" ]
35736970c6d629c2764eaf23299e0356
The single line contains three integers r, s and p (1 ≤ r, s, p ≤ 100) — the original number of individuals in the species of rock, scissors and paper, respectively.
1,900
Print three space-separated real numbers: the probabilities, at which the rocks, the scissors and the paper will be the only surviving species, respectively. The answer will be considered correct if the relative or absolute error of each number doesn't exceed 10 - 9.
standard output
PASSED
8392156453010168075b32bef43375d2
train_003.jsonl
1430411400
The Bad Luck Island is inhabited by three kinds of species: r rocks, s scissors and p papers. At some moments of time two random individuals meet (all pairs of individuals can meet equiprobably), and if they belong to different species, then one individual kills the other one: a rock kills scissors, scissors kill paper, and paper kills a rock. Your task is to determine for each species what is the probability that this species will be the only one to inhabit this island after a long enough period of time.
256 megabytes
import java.util.*; import java.io.*; public class Main { static BufferedReader br; static PrintWriter pr; static StringTokenizer st; public static void main (String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); pr = new PrintWriter(new OutputStreamWriter(System.out)); //br = new BufferedReader(new FileReader("in.txt")); //pr = new PrintWriter(new FileWriter("out.txt")); int r = readInt(); int s = readInt(); int p = readInt(); double[][][] prob = new double[r+1][s+1][p+1]; prob[r][s][p] = 1; for (int i = r; i >= 0; i--) { for (int j = s; j >= 0; j--) { for (int k = p; k >= 0; k--) { double rs = i*j; double sp = j*k; double pr = k*i; double total = rs+sp+pr; // rock if (i > 0 && k > 0) { prob[i-1][j][k] += prob[i][j][k] * (pr/total); // System.out.println((i-1) + " " + j + " " + k + " " + prob[i-1][j][k]); } // scissors if (j > 0 && i > 0) { prob[i][j-1][k] += prob[i][j][k] * (rs/total); // System.out.println(i + " " + (j-1) + " " + k + " " + prob[i][j-1][k]); } // paper if (k > 0 && j > 0) { prob[i][j][k-1] += prob[i][j][k] * (sp/total); // System.out.println(i + " " + j + " " + (k-1) + " " + prob[i][j][k-1]); } } } } double ar = 0; double as = 0; double ap = 0; for (int i = 1; i <= r; i++) ar += prob[i][0][0]; for (int i = 1; i <= s; i++) as += prob[0][i][0]; for (int i = 1; i <= p; i++) ap += prob[0][0][i]; System.out.println(ar + " " + as + " " + ap); pr.close(); } static String next () throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine().trim()); return st.nextToken(); } static long readLong () throws IOException { return Long.parseLong(next()); } static int readInt () throws IOException { return Integer.parseInt(next()); } static double readDouble () throws IOException { return Double.parseDouble(next()); } static char readCharacter () throws IOException { return next().charAt(0); } static String readLine () throws IOException { return br.readLine().trim(); } }
Java
["2 2 2", "2 1 2", "1 1 3"]
2 seconds
["0.333333333333 0.333333333333 0.333333333333", "0.150000000000 0.300000000000 0.550000000000", "0.057142857143 0.657142857143 0.285714285714"]
null
Java 8
standard input
[ "dp", "probabilities" ]
35736970c6d629c2764eaf23299e0356
The single line contains three integers r, s and p (1 ≤ r, s, p ≤ 100) — the original number of individuals in the species of rock, scissors and paper, respectively.
1,900
Print three space-separated real numbers: the probabilities, at which the rocks, the scissors and the paper will be the only surviving species, respectively. The answer will be considered correct if the relative or absolute error of each number doesn't exceed 10 - 9.
standard output
PASSED
6cd32c69ad1f4117c623546dfd5ff4a2
train_003.jsonl
1430411400
The Bad Luck Island is inhabited by three kinds of species: r rocks, s scissors and p papers. At some moments of time two random individuals meet (all pairs of individuals can meet equiprobably), and if they belong to different species, then one individual kills the other one: a rock kills scissors, scissors kill paper, and paper kills a rock. Your task is to determine for each species what is the probability that this species will be the only one to inhabit this island after a long enough period of time.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author aryssoncf */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, OutputWriter out) { try { int r = in.readInt(), s = in.readInt(), p = in.readInt(); double[][][] dp = new double[r + 1][s + 1][p + 1]; dp[r][s][p] = 1; double pr = 0, ps = 0, pp = 0; for (int sum = r + s + p; sum > 0; sum--) { for (int i = 0; i <= r && i <= sum; i++) { for (int j = 0; j <= s && i + j <= sum; j++) { int k = sum - i - j; if (k <= p) { if ((i > 0 && j > 0) || (i > 0 && k > 0) || (j > 0 && k > 0)) { double prob = dp[i][j][k] / (i * j + i * k + j * k); if (i > 0 && j > 0) dp[i][j - 1][k] += i * j * prob; if (i > 0 && k > 0) dp[i - 1][j][k] += i * k * prob; if (k > 0 && j > 0) dp[i][j][k - 1] += j * k * prob; } else if (i > 0) { pr += dp[i][j][k]; } else if (j > 0) { ps += dp[i][j][k]; } else { pp += dp[i][j][k]; } } } } } out.printFormat("%.12f %.12f %.12f\n", pr, ps, pp); } catch (Exception e) { e.printStackTrace(); } } } 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 printFormat(String format, Object... objects) { writer.printf(format, objects); } public void close() { writer.close(); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { boolean isSpaceChar(int ch); } } }
Java
["2 2 2", "2 1 2", "1 1 3"]
2 seconds
["0.333333333333 0.333333333333 0.333333333333", "0.150000000000 0.300000000000 0.550000000000", "0.057142857143 0.657142857143 0.285714285714"]
null
Java 8
standard input
[ "dp", "probabilities" ]
35736970c6d629c2764eaf23299e0356
The single line contains three integers r, s and p (1 ≤ r, s, p ≤ 100) — the original number of individuals in the species of rock, scissors and paper, respectively.
1,900
Print three space-separated real numbers: the probabilities, at which the rocks, the scissors and the paper will be the only surviving species, respectively. The answer will be considered correct if the relative or absolute error of each number doesn't exceed 10 - 9.
standard output
PASSED
41bde32c5b8c38bb583814ae3343b442
train_003.jsonl
1430411400
The Bad Luck Island is inhabited by three kinds of species: r rocks, s scissors and p papers. At some moments of time two random individuals meet (all pairs of individuals can meet equiprobably), and if they belong to different species, then one individual kills the other one: a rock kills scissors, scissors kill paper, and paper kills a rock. Your task is to determine for each species what is the probability that this species will be the only one to inhabit this island after a long enough period of time.
256 megabytes
import java.util.Scanner; public class RPS { static double[][][] cacheR; static double[][][] cacheS; static double[][][] cacheP; static boolean[][][] cached; static int scale = 100; static double get(int r, int s, int p, int whattoget) { // System.out.println("Get " + r + " " + s + " " + p + " " + whattoget); if(!(r > 0 || s > 0 || p > 0)) { // System.out.println("Return 0"); return 0; } if((cached[r][s][p])) { if(whattoget == 0) return cacheR[r][s][p]; else if(whattoget == 1) return cacheS[r][s][p]; else return cacheP[r][s][p]; } if(r == 0 && s > 0) //ps remains { cacheR[r][s][p] = 0; cacheS[r][s][p] = 1; cacheP[r][s][p] = 0; cached[r][s][p] = true; } else if(s == 0 && p > 0) //rp remains { cacheR[r][s][p] = 0; cacheS[r][s][p] = 0; cacheP[r][s][p] = 1; cached[r][s][p] = true; } else if(p == 0 && r > 0) //rs remains { cacheR[r][s][p] = 1; cacheS[r][s][p] = 0; cacheP[r][s][p] = 0; cached[r][s][p] = true; } else { double rp = r*p; double rs = r*s; double ps = p*s; double tot = rp + rs + ps; double rr = (get(r-1,s,p,0)*rp + get(r,s-1,p,0)*rs + get(r,s,p-1,0)*ps)/tot; double ss = (get(r-1,s,p,1)*rp + get(r,s-1,p,1)*rs + get(r,s,p-1,1)*ps)/tot; double pp = (get(r-1,s,p,2)*rp + get(r,s-1,p,2)*rs + get(r,s,p-1,2)*ps)/tot; cacheR[r][s][p] = rr; cacheS[r][s][p] = ss; cacheP[r][s][p] = pp; cached[r][s][p] = true; } if(whattoget == 0) return cacheR[r][s][p]; else if(whattoget == 1) return cacheS[r][s][p]; else return cacheP[r][s][p]; } public static void main(String[] args) { cacheR = new double[scale+1][scale+1][scale+1]; cacheP = new double[scale+1][scale+1][scale+1]; cacheS = new double[scale+1][scale+1][scale+1]; cached = new boolean[scale+1][scale+1][scale+1]; for(int r0 = 0; r0 <= scale; r0++) { for(int s0 = 0; s0 <= scale; s0++) { for(int p0 = 0; p0 <= scale; p0++) { get(r0, s0, p0, 0); } } } // System.out.println("PREP"); Scanner sc = new Scanner(System.in); int r = sc.nextInt(); int s = sc.nextInt(); int p = sc.nextInt(); System.out.println(get(r,s,p,0) + " " + get(r,s,p,1) + " " + get(r,s,p,2)); } }
Java
["2 2 2", "2 1 2", "1 1 3"]
2 seconds
["0.333333333333 0.333333333333 0.333333333333", "0.150000000000 0.300000000000 0.550000000000", "0.057142857143 0.657142857143 0.285714285714"]
null
Java 8
standard input
[ "dp", "probabilities" ]
35736970c6d629c2764eaf23299e0356
The single line contains three integers r, s and p (1 ≤ r, s, p ≤ 100) — the original number of individuals in the species of rock, scissors and paper, respectively.
1,900
Print three space-separated real numbers: the probabilities, at which the rocks, the scissors and the paper will be the only surviving species, respectively. The answer will be considered correct if the relative or absolute error of each number doesn't exceed 10 - 9.
standard output
PASSED
d9873ed3ba3a85eed8192db38a99b378
train_003.jsonl
1430411400
The Bad Luck Island is inhabited by three kinds of species: r rocks, s scissors and p papers. At some moments of time two random individuals meet (all pairs of individuals can meet equiprobably), and if they belong to different species, then one individual kills the other one: a rock kills scissors, scissors kill paper, and paper kills a rock. Your task is to determine for each species what is the probability that this species will be the only one to inhabit this island after a long enough period of time.
256 megabytes
import java.math.*; import java.io.*; import java.util.*; public class Main{ public static void main(String[] args ) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] in = br.readLine().split(" "); int r = Integer.parseInt(in[0]); int s = Integer.parseInt(in[1]); int p = Integer.parseInt(in[2]); int tot = r+p+s; double[][]dpnext = new double[r+1][p+1]; double[][] dpcurr = new double[r+1][p+1]; dpnext[r][p] = 1; for( int d = tot; d >1 ;d--){ dpcurr = dpnext; dpnext = new double[r+1][p+1]; for( int cr = 0; cr <=r; cr++){ for( int cp = 0; cp <=p; cp++){ int cs = d - cp - cr; double prob = dpcurr[cr][cp]; int count = 0; if(cs == 0)count++; if(cp == 0)count++; if(cr == 0)count++; if(count >1){ dpnext[cr][cp] = dpcurr[cr][cp]; continue; } double sl = cr * cs; double pl = cs * cp; double rl = cp * cr; double tl = rl + sl + pl; if(tl == 0 || prob == 0)continue; if(cr !=0){ double cprob = prob * rl/tl; dpnext[cr-1][cp] += cprob; } if(cp !=0){ double cprob = prob * pl/tl; dpnext[cr][cp-1] += cprob; } if(cs !=0){ double cprob = prob * sl/tl; dpnext[cr][cp] += cprob; } } } } double ps = 0; double pr = 0; double pp = 0; for(int i = 1; i <= r;i++) pr+=dpnext[i][0]; for( int i = 1; i <= p;i++) pp+= dpnext[0][i]; ps = 1 - pr - pp; System.out.printf("%.12f %.12f %.12f\n", pr,ps, pp); } }
Java
["2 2 2", "2 1 2", "1 1 3"]
2 seconds
["0.333333333333 0.333333333333 0.333333333333", "0.150000000000 0.300000000000 0.550000000000", "0.057142857143 0.657142857143 0.285714285714"]
null
Java 8
standard input
[ "dp", "probabilities" ]
35736970c6d629c2764eaf23299e0356
The single line contains three integers r, s and p (1 ≤ r, s, p ≤ 100) — the original number of individuals in the species of rock, scissors and paper, respectively.
1,900
Print three space-separated real numbers: the probabilities, at which the rocks, the scissors and the paper will be the only surviving species, respectively. The answer will be considered correct if the relative or absolute error of each number doesn't exceed 10 - 9.
standard output
PASSED
f83f52adbf7db7f260f5f2ad348f348c
train_003.jsonl
1430411400
The Bad Luck Island is inhabited by three kinds of species: r rocks, s scissors and p papers. At some moments of time two random individuals meet (all pairs of individuals can meet equiprobably), and if they belong to different species, then one individual kills the other one: a rock kills scissors, scissors kill paper, and paper kills a rock. Your task is to determine for each species what is the probability that this species will be the only one to inhabit this island after a long enough period of time.
256 megabytes
import java.io.*; import java.util.*; public class bad_luck_island { 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 double nextDouble() { return Double.parseDouble(next()); } } public static void main(String args[])throws IOException { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader sc = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); int R = sc.nextInt(); int S = sc.nextInt(); int P = sc.nextInt(); double [][][][] dp = new double [3][R+1][S+1][P+1]; for (int r = 0; r<= R; r++) { for (int s = 0; s<= S; s++) { for (int p = 0; p<= P; p++) { if (r != 0 && s== 0 && p == 0) dp[0][r][s][p] = 1; else if (s!= 0 && r == 0 && p == 0) dp[1][r][s][p] = 1; else if (p!= 0 && s == 0 && r == 0) dp[2][r][s][p] = 1; else if (p == 0 && r == 0 && s == 0) continue; else { double noWays = r*s + s*p + p*r; for (int i = 0; i< 3; i++) { if (r > 0 && p > 0) dp[i][r][s][p] += r*p*dp[i][r-1][s][p]; if (s > 0 && r > 0) dp[i][r][s][p] += s*r*dp[i][r][s-1][p]; if (s > 0 && p > 0) dp[i][r][s][p] += p*s*dp[i][r][s][p-1]; dp[i][r][s][p] /= noWays; } } } } } out.println(dp[0][R][S][P]+" "+ dp[1][R][S][P]+" "+dp[2][R][S][P]); out.close(); out.flush(); } }
Java
["2 2 2", "2 1 2", "1 1 3"]
2 seconds
["0.333333333333 0.333333333333 0.333333333333", "0.150000000000 0.300000000000 0.550000000000", "0.057142857143 0.657142857143 0.285714285714"]
null
Java 8
standard input
[ "dp", "probabilities" ]
35736970c6d629c2764eaf23299e0356
The single line contains three integers r, s and p (1 ≤ r, s, p ≤ 100) — the original number of individuals in the species of rock, scissors and paper, respectively.
1,900
Print three space-separated real numbers: the probabilities, at which the rocks, the scissors and the paper will be the only surviving species, respectively. The answer will be considered correct if the relative or absolute error of each number doesn't exceed 10 - 9.
standard output
PASSED
5605a909f2289bd6a0bed3783d47cf94
train_003.jsonl
1557414300
This problem is same as the previous one, but has larger constraints.It was a Sunday morning when the three friends Selena, Shiro and Katie decided to have a trip to the nearby power station (do not try this at home). After arriving at the power station, the cats got impressed with a large power transmission system consisting of many chimneys, electric poles, and wires. Since they are cats, they found those things gigantic.At the entrance of the station, there is a map describing the complicated wiring system. Selena is the best at math among three friends. He decided to draw the map on the Cartesian plane. Each pole is now a point at some coordinates $$$(x_i, y_i)$$$. Since every pole is different, all of the points representing these poles are distinct. Also, every two poles are connected with each other by wires. A wire is a straight line on the plane infinite in both directions. If there are more than two poles lying on the same line, they are connected by a single common wire.Selena thinks, that whenever two different electric wires intersect, they may interfere with each other and cause damage. So he wonders, how many pairs are intersecting? Could you help him with this problem?
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.lang.System.*; public class Solver { static line makeLine(segment s) { return new line(new fraction((s.end.y - s.begin.y), (s.end.x - s.begin.x)), new fraction(s.end.y * (s.end.x - s.begin.x) - s.end.x*(s.end.y - s.begin.y),s.end.x - s.begin.x)); } static long gcd(long a, long b) { return a == 0 ? b : (b == 0 ? a : gcd(b % a, a)); } public static void main(String[] args) throws IOException { FastScanner in = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); TreeSet<line> ts = new TreeSet<>(new Comparator<line>() { @Override public int compare(line line, line t1) { int cmp = fraction.compare(line.k,t1.k); if(cmp != 0)return cmp; return fraction.compare(line.b,t1.b); } }); point p[] = new point[n]; TreeSet<line> balyq = new TreeSet<>(new Comparator<line>() { @Override public int compare(line line, line t1) { int cmp = fraction.compare(line.k,t1.k); if(cmp != 0)return cmp; return fraction.compare(line.b,t1.b); } }); TreeMap<fraction,Long>tm = new TreeMap<>(new Comparator<fraction>() { @Override public int compare(fraction o1, fraction o2) { return fraction.compare(o1,o2); } }); for (int i = 0; i < n; i++) { p[i] = new point(in.nextInt(), in.nextInt()); } for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { segment s = new segment(p[i], p[j]); if (s.begin.x == s.end.x) balyq.add(new line(new fraction(1,1), new fraction(s.begin.x,1))); else ts.add(makeLine(new segment(p[i], p[j]))); } } long ans = (long) ts.size() * balyq.size(); for (line q : ts) { tm.put(q.k, tm.getOrDefault(q.k, 0L) + 1); } long left = ts.size() - 1; for (line a : ts) { long now = tm.get(a.k); if (now == 1) tm.remove(a.k); else tm.put(a.k, now - 1); ans += (max(0L, left - tm.getOrDefault(a.k, 0L))); left--; } out.print(ans); out.close(); } } class point { long x, y; public point(long x, long y) { this.x = x; this.y = y; } } class line{ fraction k,b; public line(fraction k, fraction b) { this.k = k; this.b = b; } } class segment { point begin, end; public segment(point begin, point end) { this.begin = begin; this.end = end; } } class fraction { long a, b; fraction(long a, long b) { this.a = a / gcd(a,b); this.b = b / gcd(a,b); } long gcd(long a, long b) { return a == 0 ? b : (b == 0 ? a : gcd(b % a, a)); } static int compare(fraction a, fraction b){ if(a.a != b.a)return Long.compare(a.a,b.a); return Long.compare(a.b,b.b); } } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(s)); } FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } }
Java
["4\n0 0\n1 1\n0 3\n1 2", "4\n0 0\n0 2\n0 4\n2 0", "3\n-1 -1\n1 0\n3 1"]
3 seconds
["14", "6", "0"]
NoteIn the first example: In the second example: Note that the three poles $$$(0, 0)$$$, $$$(0, 2)$$$ and $$$(0, 4)$$$ are connected by a single wire.In the third example:
Java 11
standard input
[ "data structures", "implementation", "geometry", "math" ]
d7d8d91be04f5d9065a0c22e66d11de3
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — the number of electric poles. Each of the following $$$n$$$ lines contains two integers $$$x_i$$$, $$$y_i$$$ ($$$-10^4 \le x_i, y_i \le 10^4$$$) — the coordinates of the poles. It is guaranteed that all of these $$$n$$$ points are distinct.
1,900
Print a single integer — the number of pairs of wires that are intersecting.
standard output
PASSED
6157fd2fb291b32ff5249f916355129a
train_003.jsonl
1547044500
You are given a string $$$s$$$ consisting of exactly $$$n$$$ characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings.Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string such that the number of characters '0' in this string is equal to the number of characters '1', and the number of characters '1' (and '0' obviously) is equal to the number of characters '2').Among all possible balanced ternary strings you have to obtain the lexicographically (alphabetically) smallest.Note that you can neither remove characters from the string nor add characters to the string. Also note that you can replace the given characters only with characters '0', '1' and '2'.It is guaranteed that the answer exists.
256 megabytes
import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.InputMismatchException; public class D1102 { static class Solver { int N, g, a[], f[] = new int[3]; char ch[]; void solve(FastScanner s, PrintWriter out) { g = (N = s.nextInt()) / 3; ch = s.next().toCharArray(); a = new int[N]; for (int i = 0; i < N; i++) f[a[i] = ch[i] - '0']++; for (int i = 0; i < N && f[0] < g; i++) if (a[i] != 0) if (f[a[i]] > g) { f[0]++; f[a[i]]--; a[i] = 0; } for (int i = 0; i < N && f[1] < g; i++) if (a[i] == 2 && f[2] > g) { f[1]++; f[2]--; a[i] = 1; } for (int i = N - 1; i >= 0 && f[2] < g; i--) if (a[i] != 2) if (f[a[i]] > g) { f[2]++; f[a[i]]--; a[i] = 2; } for (int i = N - 1; i >= 0 && f[1] < g; i--) if (a[i] == 0 && f[0] > g) { f[1]++; f[0]--; a[i] = 1; } StringBuilder res = new StringBuilder(); for (int i : a) res.append(i); out.println(res.toString()); } } public static void main(String[] args) { FastScanner s = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); Solver solver = new Solver(); solver.solve(s, out); out.close(); } static int min(int a, int b) { return a < b ? a : b; } static int max(int a, int b) { return a > b ? a : b; } static long min(long a, long b) { return a < b ? a : b; } static long max(long a, long b) { return a > b ? a : b; } static int swap(int a, int b) { return a; } static Object swap(Object a, Object b) { return a; } static String ts(Object... o) { return Arrays.deepToString(o); } static class FastScanner { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastScanner(InputStream stream) { this.stream = stream; } public FastScanner(File f) throws FileNotFoundException { this(new FileInputStream(f)); } public FastScanner(String s) { this.stream = new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8)); } 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++]; } boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } boolean isEndline(int c) { return c == '\n' || c == '\r' || c == -1; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isEndline(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndline(c)); return res.toString(); } // Jacob Garbage public int[] nextIntArray(int N) { int[] ret = new int[N]; for (int i = 0; i < N; i++) ret[i] = this.nextInt(); return ret; } public int[][] next2DIntArray(int N, int M) { int[][] ret = new int[N][]; for (int i = 0; i < N; i++) ret[i] = this.nextIntArray(M); return ret; } public long[] nextLongArray(int N) { long[] ret = new long[N]; for (int i = 0; i < N; i++) ret[i] = this.nextLong(); return ret; } public long[][] next2DLongArray(int N, int M) { long[][] ret = new long[N][]; for (int i = 0; i < N; i++) ret[i] = nextLongArray(M); return ret; } public double[] nextDoubleArray(int N) { double[] ret = new double[N]; for (int i = 0; i < N; i++) ret[i] = this.nextDouble(); return ret; } public double[][] next2DDoubleArray(int N, int M) { double[][] ret = new double[N][]; for (int i = 0; i < N; i++) ret[i] = this.nextDoubleArray(M); return ret; } } }
Java
["3\n121", "6\n000000", "6\n211200", "6\n120110"]
2 seconds
["021", "001122", "211200", "120120"]
null
Java 8
standard input
[ "greedy", "strings" ]
cb852bf0b62d72b3088969ede314f176
The first line of the input contains one integer $$$n$$$ ($$$3 \le n \le 3 \cdot 10^5$$$, $$$n$$$ is divisible by $$$3$$$) — the number of characters in $$$s$$$. The second line contains the string $$$s$$$ consisting of exactly $$$n$$$ characters '0', '1' and '2'.
1,500
Print one string — the lexicographically (alphabetically) smallest balanced ternary string which can be obtained from the given one with minimum number of replacements. Because $$$n$$$ is divisible by $$$3$$$ it is obvious that the answer exists. And it is obvious that there is only one possible answer.
standard output
PASSED
b3ec1d54104fc68c2e4886086606b39d
train_003.jsonl
1547044500
You are given a string $$$s$$$ consisting of exactly $$$n$$$ characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings.Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string such that the number of characters '0' in this string is equal to the number of characters '1', and the number of characters '1' (and '0' obviously) is equal to the number of characters '2').Among all possible balanced ternary strings you have to obtain the lexicographically (alphabetically) smallest.Note that you can neither remove characters from the string nor add characters to the string. Also note that you can replace the given characters only with characters '0', '1' and '2'.It is guaranteed that the answer exists.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Scanner; /** * Built using CHelper plug-in Actual solution is at the top * * @author dima */ 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); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, Scanner in, PrintWriter out) { final int N = in.nextInt(); in.nextLine(); String str = in.nextLine(); int[] count = new int[3]; int[][] suffixCount = new int[3][N]; suffixCount[0][N - 1] = str.charAt(N - 1) == '0' ? 1 : 0; suffixCount[1][N - 1] = str.charAt(N - 1) == '1' ? 1 : 0; suffixCount[2][N - 1] = str.charAt(N - 1) == '2' ? 1 : 0; for (int i = 0; i < N; ++i) { ++count[str.charAt(i) - '0']; } for (int i = N - 2; i >= 0; --i) { for (int j = 0; j < 3; ++j) { suffixCount[j][i] = suffixCount[j][i + 1]; } int idx = str.charAt(i) - '0'; ++suffixCount[idx][i]; } int should = N / 3; int[] seen = new int[3]; for (int i = 0; i < N; ++i) { ++seen[str.charAt(i) - '0']; char c = str.charAt(i); switch (str.charAt(i)) { case '0': if (seen[0] > should) { --seen[0]; if (seen[1] + suffixCount[1][i] < should) { c = '1'; ++seen[1]; } else if (seen[2] + suffixCount[2][i] < should) { c = '2'; ++seen[2]; } } break; case '1': if (seen[1] > should) { /*if (seen[2] >= should) { throw new RuntimeException("We have seen too much 2 here"); }*/ c = '2'; --seen[1]; ++seen[2]; } else if (seen[1] + suffixCount[1][i] - 1 > should) { if (seen[0] + suffixCount[0][i] < should) { c = '0'; --seen[1]; ++seen[0]; } } break; case '2': if (suffixCount[2][i] > should) { if (seen[0] + suffixCount[0][i] < should) { c = '0'; --seen[2]; ++seen[0]; } else { if (count[1] >= should) { throw new RuntimeException("Too many ones in the string??"); } c = '1'; --seen[2]; ++seen[1]; } } } out.print(c); } } } }
Java
["3\n121", "6\n000000", "6\n211200", "6\n120110"]
2 seconds
["021", "001122", "211200", "120120"]
null
Java 8
standard input
[ "greedy", "strings" ]
cb852bf0b62d72b3088969ede314f176
The first line of the input contains one integer $$$n$$$ ($$$3 \le n \le 3 \cdot 10^5$$$, $$$n$$$ is divisible by $$$3$$$) — the number of characters in $$$s$$$. The second line contains the string $$$s$$$ consisting of exactly $$$n$$$ characters '0', '1' and '2'.
1,500
Print one string — the lexicographically (alphabetically) smallest balanced ternary string which can be obtained from the given one with minimum number of replacements. Because $$$n$$$ is divisible by $$$3$$$ it is obvious that the answer exists. And it is obvious that there is only one possible answer.
standard output
PASSED
1b0d2989649e837a134729fef370f750
train_003.jsonl
1547044500
You are given a string $$$s$$$ consisting of exactly $$$n$$$ characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings.Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string such that the number of characters '0' in this string is equal to the number of characters '1', and the number of characters '1' (and '0' obviously) is equal to the number of characters '2').Among all possible balanced ternary strings you have to obtain the lexicographically (alphabetically) smallest.Note that you can neither remove characters from the string nor add characters to the string. Also note that you can replace the given characters only with characters '0', '1' and '2'.It is guaranteed that the answer exists.
256 megabytes
import java.util.Scanner; public class BalancedTernaryString { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); char[] s = scanner.next().toCharArray(); int m = n/3; int[] freq = new int[3]; for (int i = 0; i < n; i++) { freq[s[i] - '0']++; } for (int i = 0; i < n; i++) { if (freq[0] < m) { replace(s, m, freq, i, '0'); } else break; } for (int i = n - 1; i >= 0; i--) { if (freq[2] < m) { replace(s, m, freq, i, '2'); } else break; } if (freq[1] < m) { for (int i = 0; i < n; i++) { if (freq[2] > m) { doFor1(s, freq, i, m, '2'); } else break; } for (int i = n - 1; i >= 0; i--) { if (freq[0] > m) { doFor1(s, freq, i, m, '0'); } else break; } } System.out.println(s); } private static void doFor1(char[] s, int[] freq, int i, int m, char c) { if (s[i] == c) { replace(s, m, freq, i, '1'); } } private static void replace(char[] s, int m, int[] freq, int i, char rep) { if (freq[s[i] - '0'] > m) { freq[s[i] - '0']--; s[i] = rep; freq[s[i] - '0']++; } } }
Java
["3\n121", "6\n000000", "6\n211200", "6\n120110"]
2 seconds
["021", "001122", "211200", "120120"]
null
Java 8
standard input
[ "greedy", "strings" ]
cb852bf0b62d72b3088969ede314f176
The first line of the input contains one integer $$$n$$$ ($$$3 \le n \le 3 \cdot 10^5$$$, $$$n$$$ is divisible by $$$3$$$) — the number of characters in $$$s$$$. The second line contains the string $$$s$$$ consisting of exactly $$$n$$$ characters '0', '1' and '2'.
1,500
Print one string — the lexicographically (alphabetically) smallest balanced ternary string which can be obtained from the given one with minimum number of replacements. Because $$$n$$$ is divisible by $$$3$$$ it is obvious that the answer exists. And it is obvious that there is only one possible answer.
standard output
PASSED
436223386aa5c588c1610406443ad14d
train_003.jsonl
1547044500
You are given a string $$$s$$$ consisting of exactly $$$n$$$ characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings.Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string such that the number of characters '0' in this string is equal to the number of characters '1', and the number of characters '1' (and '0' obviously) is equal to the number of characters '2').Among all possible balanced ternary strings you have to obtain the lexicographically (alphabetically) smallest.Note that you can neither remove characters from the string nor add characters to the string. Also note that you can replace the given characters only with characters '0', '1' and '2'.It is guaranteed that the answer exists.
256 megabytes
import java.io.*; import java.util.*; public class Main { static BufferedReader in; static PrintWriter out; static StringTokenizer tok = new StringTokenizer(""); public static void main(String[] args) throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); new Main().solve(); out.flush(); out.close(); } void solve() throws IOException { int n = nextInt(); int d = n/3; StringBuilder str = new StringBuilder(nextTok()); int[] cnt = new int[3]; for (int i = 0; i < n; i++) { int val = str.charAt(i) - '0'; cnt[val]++; } if (d > cnt[2]) { for (int i = n - 1; cnt[2] < d && i >= 0; i--) { if (cnt[1] > d && str.charAt(i) == '1') { cnt[1]--; cnt[2]++; str.setCharAt(i, '2'); } else if (cnt[0] > d && str.charAt(i) == '0') { cnt[0]--; cnt[2]++; str.setCharAt(i, '2'); } } } if (d > cnt[0]) { for (int i = 0; cnt[0] < d && i < n; i++) { if (cnt[2] > d && str.charAt(i) == '2') { cnt[2]--; cnt[0]++; str.setCharAt(i, '0'); } else if (cnt[1] > d && str.charAt(i) == '1') { cnt[1]--; cnt[0]++; str.setCharAt(i, '0'); } } } if (d > cnt[1]) { if (cnt[2] > d) { for (int i = 0; cnt[1] < d && i < n; i++) { if (str.charAt(i) == '2' && cnt[2] > d) { cnt[2]--; cnt[1]++; str.setCharAt(i, '1'); } } } if (cnt[0] > d) { for (int i = n - 1; cnt[1] < d && i >= 0; i--) { if (str.charAt(i) == '0' && cnt[0] > d) { cnt[0]--; cnt[1]++; str.setCharAt(i, '1'); } } } } out.println(str.toString()); } String nextTok() throws IOException { while (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int nextInt() throws IOException { return Integer.valueOf(nextTok()); } long nextLong() throws IOException { return Long.valueOf(nextTok()); } }
Java
["3\n121", "6\n000000", "6\n211200", "6\n120110"]
2 seconds
["021", "001122", "211200", "120120"]
null
Java 8
standard input
[ "greedy", "strings" ]
cb852bf0b62d72b3088969ede314f176
The first line of the input contains one integer $$$n$$$ ($$$3 \le n \le 3 \cdot 10^5$$$, $$$n$$$ is divisible by $$$3$$$) — the number of characters in $$$s$$$. The second line contains the string $$$s$$$ consisting of exactly $$$n$$$ characters '0', '1' and '2'.
1,500
Print one string — the lexicographically (alphabetically) smallest balanced ternary string which can be obtained from the given one with minimum number of replacements. Because $$$n$$$ is divisible by $$$3$$$ it is obvious that the answer exists. And it is obvious that there is only one possible answer.
standard output
PASSED
5c1e101ed3832e6c426e5b5851d77952
train_003.jsonl
1547044500
You are given a string $$$s$$$ consisting of exactly $$$n$$$ characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings.Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string such that the number of characters '0' in this string is equal to the number of characters '1', and the number of characters '1' (and '0' obviously) is equal to the number of characters '2').Among all possible balanced ternary strings you have to obtain the lexicographically (alphabetically) smallest.Note that you can neither remove characters from the string nor add characters to the string. Also note that you can replace the given characters only with characters '0', '1' and '2'.It is guaranteed that the answer exists.
256 megabytes
import java.util.Scanner; public class B { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); sc.nextLine(); String s = sc.nextLine(); int c = n / 3; int[] arr = new int[3]; int[] ans = new int[n]; int idx = 0; for (char ch : s.toCharArray()) { arr[ch - '0']++; ans[idx++] = ch-'0'; } for (int i = 0; i < arr.length; i++) { if (arr[i] < c) { int[] count = new int[3]; for (int j = 0; j < ans.length; j++) { if (arr[i] == c) break; if (arr[ans[j]] > c) { if (i > ans[j] && count[ans[j]] < c) count[ans[j]]++; else { arr[i]++; arr[ans[j]]--; ans[j] = i; } } } } } for (int an : ans) { System.out.print(an); } } }
Java
["3\n121", "6\n000000", "6\n211200", "6\n120110"]
2 seconds
["021", "001122", "211200", "120120"]
null
Java 8
standard input
[ "greedy", "strings" ]
cb852bf0b62d72b3088969ede314f176
The first line of the input contains one integer $$$n$$$ ($$$3 \le n \le 3 \cdot 10^5$$$, $$$n$$$ is divisible by $$$3$$$) — the number of characters in $$$s$$$. The second line contains the string $$$s$$$ consisting of exactly $$$n$$$ characters '0', '1' and '2'.
1,500
Print one string — the lexicographically (alphabetically) smallest balanced ternary string which can be obtained from the given one with minimum number of replacements. Because $$$n$$$ is divisible by $$$3$$$ it is obvious that the answer exists. And it is obvious that there is only one possible answer.
standard output
PASSED
9f1cd269ebad8c4aa87affe94b6304ec
train_003.jsonl
1547044500
You are given a string $$$s$$$ consisting of exactly $$$n$$$ characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings.Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string such that the number of characters '0' in this string is equal to the number of characters '1', and the number of characters '1' (and '0' obviously) is equal to the number of characters '2').Among all possible balanced ternary strings you have to obtain the lexicographically (alphabetically) smallest.Note that you can neither remove characters from the string nor add characters to the string. Also note that you can replace the given characters only with characters '0', '1' and '2'.It is guaranteed that the answer exists.
256 megabytes
import java.io.*; import java.util.*; public class D { static StringBuilder st = new StringBuilder(); public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt() ; char [] s = sc.next().toCharArray() ; int div = n / 3 ; int [] freq = new int [n] ; for(char c : s)freq[c - '0']++; if(freq[0] < div) for(int i = 0 ; i < n && freq[0] < div;i++) if(s[i] != '0' && freq[s[i] - '0'] > div) { freq[s[i] - '0']--; freq[0]++; s[i] = '0' ; } if(freq[2] < div) for(int i = n - 1 ; i >= 0 && freq[2] < div;i--) if(s[i] == '1' && freq[s[i] - '0'] > div) { freq[1]--; freq[2]++; s[i] = '2' ; } if(freq[2] < div) for(int i = n - 1 ; i >= 0 && freq[2] < div;i--) if(s[i] == '0' && freq[s[i] - '0'] > div) { freq[0]--; freq[2]++; s[i] = '2' ; } if(freq[1] < div) for(int i = 0 ; i < n && freq[1] < div;i++) if(s[i] == '2' && freq[s[i] - '0'] > div) { freq[2]--; freq[1]++; s[i] = '1' ; } if(freq[1] < div) for(int i = n - 1 ; i >= 0 && freq[1] < div;i--) if(s[i] == '0' && freq[s[i] - '0'] > div) { freq[0]--; freq[1]++; s[i] = '1' ; } out.println(s); out.flush(); out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner(InputStream in) { br = new BufferedReader(new InputStreamReader(System.in)); } String next() throws Exception { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws Exception { return Integer.parseInt(next()); } long nextLong() throws Exception { return Long.parseLong(next()); } double nextDouble() throws Exception { return Double.parseDouble(next()); } } static void shuffle(int[] a) { int n = a.length; for (int i = 0; i < n; i++) { int r = i + (int) (Math.random() * (n - i)); int tmp = a[i]; a[i] = a[r]; a[r] = tmp; } } }
Java
["3\n121", "6\n000000", "6\n211200", "6\n120110"]
2 seconds
["021", "001122", "211200", "120120"]
null
Java 8
standard input
[ "greedy", "strings" ]
cb852bf0b62d72b3088969ede314f176
The first line of the input contains one integer $$$n$$$ ($$$3 \le n \le 3 \cdot 10^5$$$, $$$n$$$ is divisible by $$$3$$$) — the number of characters in $$$s$$$. The second line contains the string $$$s$$$ consisting of exactly $$$n$$$ characters '0', '1' and '2'.
1,500
Print one string — the lexicographically (alphabetically) smallest balanced ternary string which can be obtained from the given one with minimum number of replacements. Because $$$n$$$ is divisible by $$$3$$$ it is obvious that the answer exists. And it is obvious that there is only one possible answer.
standard output
PASSED
5fdc1093634db4f28ef079637118fc6f
train_003.jsonl
1547044500
You are given a string $$$s$$$ consisting of exactly $$$n$$$ characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings.Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string such that the number of characters '0' in this string is equal to the number of characters '1', and the number of characters '1' (and '0' obviously) is equal to the number of characters '2').Among all possible balanced ternary strings you have to obtain the lexicographically (alphabetically) smallest.Note that you can neither remove characters from the string nor add characters to the string. Also note that you can replace the given characters only with characters '0', '1' and '2'.It is guaranteed that the answer exists.
256 megabytes
import java.util.*;public class startgame { public static void f0(int a[], int count[],int n) { for(int i=0;i<n;i++) { int x=a[i]; if(count[x]>n/3&&count[0]<n/3) { a[i]=0; count[x]--; count[0]++; } } } public static void f2(int a[], int count[],int n) { for(int i=n-1;i>=0;i--) { int x=a[i]; if(count[x]>n/3&&count[2]<n/3) { a[i]=2; count[x]--; count[2]++; } } } public static void f1(int a[], int count[],int n) { for(int i=0;i<n;i++) { int x=a[i]; if(count[x]>n/3&&count[1]<n/3&&x==2) { a[i]=1; count[x]--; count[1]++; } } for(int i=n-1;i>=0;i--) { int x=a[i]; if(count[x]>n/3&&count[1]<n/3&&x==0) { a[i]=1; count[x]--; count[1]++; } } } public static void main(String args[]) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); String s=sc.next(); int count[]=new int[3]; int a[]=new int[n]; for(int i=0;i<n;i++) { char ch=s.charAt(i); if(ch=='0') { count[0]++; a[i]=0; } if(ch=='1') { count[1]++; a[i]=1; } if(ch=='2') { count[2]++; a[i]=2; } } if(count[0]<n/3) f0(a,count,n); if(count[2]<n/3) f2(a,count,n); if(count[1]<n/3) f1(a,count,n); for(int i=0;i<n;i++) { System.out.print(a[i]); } } }
Java
["3\n121", "6\n000000", "6\n211200", "6\n120110"]
2 seconds
["021", "001122", "211200", "120120"]
null
Java 8
standard input
[ "greedy", "strings" ]
cb852bf0b62d72b3088969ede314f176
The first line of the input contains one integer $$$n$$$ ($$$3 \le n \le 3 \cdot 10^5$$$, $$$n$$$ is divisible by $$$3$$$) — the number of characters in $$$s$$$. The second line contains the string $$$s$$$ consisting of exactly $$$n$$$ characters '0', '1' and '2'.
1,500
Print one string — the lexicographically (alphabetically) smallest balanced ternary string which can be obtained from the given one with minimum number of replacements. Because $$$n$$$ is divisible by $$$3$$$ it is obvious that the answer exists. And it is obvious that there is only one possible answer.
standard output
PASSED
3bc6905658ed2d9bd7fc3629e83a00c1
train_003.jsonl
1547044500
You are given a string $$$s$$$ consisting of exactly $$$n$$$ characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings.Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string such that the number of characters '0' in this string is equal to the number of characters '1', and the number of characters '1' (and '0' obviously) is equal to the number of characters '2').Among all possible balanced ternary strings you have to obtain the lexicographically (alphabetically) smallest.Note that you can neither remove characters from the string nor add characters to the string. Also note that you can replace the given characters only with characters '0', '1' and '2'.It is guaranteed that the answer exists.
256 megabytes
import javafx.util.*; import java.util.*; import java.io.*; import java.math.*; public class Test6 { PrintWriter pw = new PrintWriter(System.out); InputStream is = System.in; Random rnd = new Random(); int a; void run(){ a = ni(); char[] c = ns().toCharArray(); int n = 0, e=0, d=0, z=0; for(char i : c){ if(i=='0') n++; if(i=='1') e++; if(i=='2') d++; } for(int q=0; q<a && n<a/3; q++){ if(c[q]!='0'){ if(c[q]=='1'){ if(e<=a/3) continue; e--; } else{ if(d<=a/3) continue; d--; } n++; c[q] = '0'; } } for(int q=a-1; q>=0 && d<a/3; q--){ if(c[q]=='0' && n>a/3){ n--; d++; c[q] = '2'; } if(c[q]=='1' && e>a/3){ e--; d++; c[q]='2'; } } for(int q=0; q<a && e<a/3; q++){ if(c[q]=='2' && d>a/3){ c[q]='1'; e++; d--; } } for(int q=a-1; q>=0 && e<a/3; q--){ if(c[q]=='0' && n>a/3){ n--; e++; c[q]='1'; } } for(char i : c) pw.print(i); pw.flush(); } public static void main(String[] args) { new Test6().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))) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } }
Java
["3\n121", "6\n000000", "6\n211200", "6\n120110"]
2 seconds
["021", "001122", "211200", "120120"]
null
Java 8
standard input
[ "greedy", "strings" ]
cb852bf0b62d72b3088969ede314f176
The first line of the input contains one integer $$$n$$$ ($$$3 \le n \le 3 \cdot 10^5$$$, $$$n$$$ is divisible by $$$3$$$) — the number of characters in $$$s$$$. The second line contains the string $$$s$$$ consisting of exactly $$$n$$$ characters '0', '1' and '2'.
1,500
Print one string — the lexicographically (alphabetically) smallest balanced ternary string which can be obtained from the given one with minimum number of replacements. Because $$$n$$$ is divisible by $$$3$$$ it is obvious that the answer exists. And it is obvious that there is only one possible answer.
standard output
PASSED
ed5d62c8bab69656051743294767030a
train_003.jsonl
1547044500
You are given a string $$$s$$$ consisting of exactly $$$n$$$ characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings.Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string such that the number of characters '0' in this string is equal to the number of characters '1', and the number of characters '1' (and '0' obviously) is equal to the number of characters '2').Among all possible balanced ternary strings you have to obtain the lexicographically (alphabetically) smallest.Note that you can neither remove characters from the string nor add characters to the string. Also note that you can replace the given characters only with characters '0', '1' and '2'.It is guaranteed that the answer exists.
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; public class D1102 { public static void main(String[] args) throws NumberFormatException, IOException { // BufferedReader br = new BufferedReader(new FileReader("F:/books/input.txt")); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); Integer n = Integer.parseInt(br.readLine()); String s = br.readLine(); int[] x = new int[3]; for(int i=0;i<n;i++) { x[(int)s.charAt(i)-48]++; } x[0] -= n/3; x[1] -= n/3; x[2] -= n/3; int[] y = new int[3]; StringBuilder sb = new StringBuilder(""); for(int i=0;i<n;i++) { int v = (int)s.charAt(i)-48; int tv = v; for(int j=0;j<3;j++) { if(x[j]<0 && x[v]>0 && ((j<v) || (y[v]==n/3) )) { x[j]++; x[v]--; v = j; break; } } y[v]++; sb.append(v); } System.out.println(sb.toString()); } }
Java
["3\n121", "6\n000000", "6\n211200", "6\n120110"]
2 seconds
["021", "001122", "211200", "120120"]
null
Java 8
standard input
[ "greedy", "strings" ]
cb852bf0b62d72b3088969ede314f176
The first line of the input contains one integer $$$n$$$ ($$$3 \le n \le 3 \cdot 10^5$$$, $$$n$$$ is divisible by $$$3$$$) — the number of characters in $$$s$$$. The second line contains the string $$$s$$$ consisting of exactly $$$n$$$ characters '0', '1' and '2'.
1,500
Print one string — the lexicographically (alphabetically) smallest balanced ternary string which can be obtained from the given one with minimum number of replacements. Because $$$n$$$ is divisible by $$$3$$$ it is obvious that the answer exists. And it is obvious that there is only one possible answer.
standard output
PASSED
506a330c613e3503d388841a8ae9d4be
train_003.jsonl
1547044500
You are given a string $$$s$$$ consisting of exactly $$$n$$$ characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings.Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string such that the number of characters '0' in this string is equal to the number of characters '1', and the number of characters '1' (and '0' obviously) is equal to the number of characters '2').Among all possible balanced ternary strings you have to obtain the lexicographically (alphabetically) smallest.Note that you can neither remove characters from the string nor add characters to the string. Also note that you can replace the given characters only with characters '0', '1' and '2'.It is guaranteed that the answer exists.
256 megabytes
import java.util.*; public class D531D3 { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] counts = new int[3]; int[] arr = new int[n]; String s = sc.next(); for(int i=0; i<n; i++) { arr[i] = Integer.valueOf(s.substring(i, i+1)); counts[arr[i]]++; } int[][] change = new int[3][3]; if(counts[0] > n/3) { change[0][2] = counts[1] > n/3? counts[0] -n/3 : counts[0] +counts[1] - 2*n/3; change[0][1] = counts[2] > n/3? counts[0] -n/3 : counts[0] +counts[2] - 2*n/3; } if(counts[1] > n/3) { change[1][2] = counts[0] > n/3? counts[1] -n/3 : counts[1] +counts[0] - 2*n/3; change[1][0] = counts[2] > n/3? counts[1] -n/3 : counts[1] +counts[2] - 2*n/3; } if(counts[2] > n/3) { change[2][0] = counts[1] > n/3? counts[2] -n/3 : counts[2] +counts[1] - 2*n/3; change[2][1] = counts[0] > n/3? counts[2] -n/3 : counts[2] +counts[0] - 2*n/3; } for(int i=0; i<n; i++) { if(arr[i] == 2 && change[2][0] > 0) { arr[i] = 0; change[2][0]--; } if(arr[i] == 2 && change[2][0] <= 0 && change[2][1] >0) { arr[i] = 1; change[2][1]--; } if(arr[i] == 1 && change[1][0] > 0) { arr[i] = 0; change[1][0]--; } } for(int i=n-1; i>=0; i--) { if(arr[i] == 0 && change[0][2] > 0) { arr[i] = 2; change[0][2]--; } if(arr[i] == 0 && change[0][2] <= 0 && change[0][1] > 0) { arr[i] = 1; change[0][1]--; } if(arr[i] == 1 && change[1][2] > 0) { arr[i] = 2; change[1][2]--; } } for(int x: arr) { System.out.print(x); } } }
Java
["3\n121", "6\n000000", "6\n211200", "6\n120110"]
2 seconds
["021", "001122", "211200", "120120"]
null
Java 8
standard input
[ "greedy", "strings" ]
cb852bf0b62d72b3088969ede314f176
The first line of the input contains one integer $$$n$$$ ($$$3 \le n \le 3 \cdot 10^5$$$, $$$n$$$ is divisible by $$$3$$$) — the number of characters in $$$s$$$. The second line contains the string $$$s$$$ consisting of exactly $$$n$$$ characters '0', '1' and '2'.
1,500
Print one string — the lexicographically (alphabetically) smallest balanced ternary string which can be obtained from the given one with minimum number of replacements. Because $$$n$$$ is divisible by $$$3$$$ it is obvious that the answer exists. And it is obvious that there is only one possible answer.
standard output
PASSED
e64c0d554a2a4922d78905021ef09f43
train_003.jsonl
1547044500
You are given a string $$$s$$$ consisting of exactly $$$n$$$ characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings.Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string such that the number of characters '0' in this string is equal to the number of characters '1', and the number of characters '1' (and '0' obviously) is equal to the number of characters '2').Among all possible balanced ternary strings you have to obtain the lexicographically (alphabetically) smallest.Note that you can neither remove characters from the string nor add characters to the string. Also note that you can replace the given characters only with characters '0', '1' and '2'.It is guaranteed that the answer exists.
256 megabytes
// This template code suggested by KT BYTE Computer Science Academy // for use in reading and writing files for USACO problems. // https://content.ktbyte.com/problem.java import java.util.*; import java.io.*; public class BalancedTernaryString { public static void main(String[] args) throws Exception { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int n = in.nextInt(); int[] countNums = new int[3]; int[] nums = new int[n]; String s = in.next(); for (int i = 0; i < n; i++) { int next = Character.getNumericValue(s.charAt(i)); countNums[next]++; nums[i] = next; } int correctNum = n/3; int[] passed = new int[3]; for (int i = 0; i < n; i++) { int cur = nums[i]; if (countNums[cur] <= correctNum) continue; // this is a case where we have more than necessary int lexSmallReplace = 0; for (int j = 0; j < 3; j++) { if (countNums[j] < correctNum) { lexSmallReplace = j; break; } } if (lexSmallReplace < cur) { nums[i] = lexSmallReplace; countNums[lexSmallReplace]++; countNums[cur]--; } else { if (passed[cur] == correctNum) { nums[i] = lexSmallReplace; countNums[lexSmallReplace]++; countNums[cur]--; passed[cur]--; } passed[cur]++; } } for (int i = 0; i < n; i++) { out.print(nums[i]); } out.close(); } }
Java
["3\n121", "6\n000000", "6\n211200", "6\n120110"]
2 seconds
["021", "001122", "211200", "120120"]
null
Java 8
standard input
[ "greedy", "strings" ]
cb852bf0b62d72b3088969ede314f176
The first line of the input contains one integer $$$n$$$ ($$$3 \le n \le 3 \cdot 10^5$$$, $$$n$$$ is divisible by $$$3$$$) — the number of characters in $$$s$$$. The second line contains the string $$$s$$$ consisting of exactly $$$n$$$ characters '0', '1' and '2'.
1,500
Print one string — the lexicographically (alphabetically) smallest balanced ternary string which can be obtained from the given one with minimum number of replacements. Because $$$n$$$ is divisible by $$$3$$$ it is obvious that the answer exists. And it is obvious that there is only one possible answer.
standard output
PASSED
297ec24e58c2f559baf18c4de24d9c4b
train_003.jsonl
1547044500
You are given a string $$$s$$$ consisting of exactly $$$n$$$ characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings.Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string such that the number of characters '0' in this string is equal to the number of characters '1', and the number of characters '1' (and '0' obviously) is equal to the number of characters '2').Among all possible balanced ternary strings you have to obtain the lexicographically (alphabetically) smallest.Note that you can neither remove characters from the string nor add characters to the string. Also note that you can replace the given characters only with characters '0', '1' and '2'.It is guaranteed that the answer exists.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; import java.util.stream.*; import static java.lang.Math.abs; import static java.lang.Math.min; import static java.lang.Math.max; import static java.lang.Math.sqrt; import static java.lang.Integer.signum; @SuppressWarnings("unchecked") public class P1102D { int a []; Deque<Integer> [] dp = new ArrayDeque [3]; void swap(int i, int j) { int p = (i < j) ? dp[i].pollLast() : dp[i].pollFirst(); dp[j].add(p); a[p] = j; } public void run() throws Exception { int n = nextInt(), n3 = n / 3; a = new int [n]; dp[0] = new ArrayDeque(); dp[1] = new ArrayDeque(); dp[2] = new ArrayDeque(); String s = next(); for (int i = 0; i < n; a[i] = s.charAt(i) - '0', dp[a[i]].add(i), i++); while (true) { if ((dp[2].size() > n3) && (dp[0].size() < n3)) { swap(2, 0); } else if ((dp[1].size() > n3) && (dp[0].size() < n3)) { swap(1, 0); } else if ((dp[2].size() > n3) && (dp[1].size() < n3)) { swap(2, 1); } else if ((dp[1].size() > n3) && (dp[2].size() < n3)) { swap(1, 2); } else if ((dp[0].size() > n3) && (dp[2].size() < n3)) { swap(0, 2); } else if ((dp[0].size() > n3) && (dp[1].size() < n3)) { swap(0, 1); } else { break; } } IntStream.of(a).forEach(this::print); } public static void main(String... args) throws Exception { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedOutputStream(System.out)); new P1102D().run(); br.close(); pw.close(); System.err.println("\n[Time : " + (System.currentTimeMillis() - startTime) + " ms]"); } static long startTime = System.currentTimeMillis(); static BufferedReader br; static PrintWriter pw; StringTokenizer stok; String nextToken() throws IOException { while (stok == null || !stok.hasMoreTokens()) { String s = br.readLine(); if (s == null) { return null; } stok = new StringTokenizer(s); } return stok.nextToken(); } void print(byte b) { print("" + b); } void print(int i) { print("" + i); } void print(long l) { print("" + l); } void print(double d) { print("" + d); } void print(char c) { print("" + c); } void print(Object o) { if (o instanceof int[]) { print(Arrays.toString((int [])o)); } else if (o instanceof long[]) { print(Arrays.toString((long [])o)); } else if (o instanceof char[]) { print(Arrays.toString((char [])o)); } else if (o instanceof byte[]) { print(Arrays.toString((byte [])o)); } else if (o instanceof short[]) { print(Arrays.toString((short [])o)); } else if (o instanceof boolean[]) { print(Arrays.toString((boolean [])o)); } else if (o instanceof float[]) { print(Arrays.toString((float [])o)); } else if (o instanceof double[]) { print(Arrays.toString((double [])o)); } else if (o instanceof Object[]) { print(Arrays.toString((Object [])o)); } else { print("" + o); } } void print(String s) { pw.print(s); } void println() { println(""); } void println(byte b) { println("" + b); } void println(int i) { println("" + i); } void println(long l) { println("" + l); } void println(double d) { println("" + d); } void println(char c) { println("" + c); } void println(Object o) { print(o); println(); } void println(String s) { pw.println(s); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } char nextChar() throws IOException { return (char) (br.read()); } String next() throws IOException { return nextToken(); } String nextLine() throws IOException { return br.readLine(); } int [] readInt(int size) throws IOException { int [] array = new int [size]; for (int i = 0; i < size; i++) { array[i] = nextInt(); } return array; } long [] readLong(int size) throws IOException { long [] array = new long [size]; for (int i = 0; i < size; i++) { array[i] = nextLong(); } return array; } double [] readDouble(int size) throws IOException { double [] array = new double [size]; for (int i = 0; i < size; i++) { array[i] = nextDouble(); } return array; } String [] readLines(int size) throws IOException { String [] array = new String [size]; for (int i = 0; i < size; i++) { array[i] = nextLine(); } return array; } int gcd(int a, int b) { if (a == 0) return Math.abs(b); if (b == 0) return Math.abs(a); a = Math.abs(a); b = Math.abs(b); int az = Integer.numberOfTrailingZeros(a), bz = Integer.numberOfTrailingZeros(b); a >>>= az; b >>>= bz; while (a != b) { if (a > b) { a -= b; a >>>= Integer.numberOfTrailingZeros(a); } else { b -= a; b >>>= Integer.numberOfTrailingZeros(b); } } return (a << Math.min(az, bz)); } long gcd(long a, long b) { if (a == 0) return Math.abs(b); if (b == 0) return Math.abs(a); a = Math.abs(a); b = Math.abs(b); int az = Long.numberOfTrailingZeros(a), bz = Long.numberOfTrailingZeros(b); a >>>= az; b >>>= bz; while (a != b) { if (a > b) { a -= b; a >>>= Long.numberOfTrailingZeros(a); } else { b -= a; b >>>= Long.numberOfTrailingZeros(b); } } return (a << Math.min(az, bz)); } void shuffle(int [] a) { Random r = new Random(); for (int i = a.length - 1; i >= 0; i--) { int j = r.nextInt(a.length); int t = a[i]; a[i] = a[j]; a[j] = t; } } void shuffle(long [] a) { Random r = new Random(); for (int i = a.length - 1; i >= 0; i--) { int j = r.nextInt(a.length); long t = a[i]; a[i] = a[j]; a[j] = t; } } void shuffle(Object [] a) { Random r = new Random(); for (int i = a.length - 1; i >= 0; i--) { int j = r.nextInt(a.length); Object t = a[i]; a[i] = a[j]; a[j] = t; } } void flush() { pw.flush(); } void pause() { flush(); System.console().readLine(); } }
Java
["3\n121", "6\n000000", "6\n211200", "6\n120110"]
2 seconds
["021", "001122", "211200", "120120"]
null
Java 8
standard input
[ "greedy", "strings" ]
cb852bf0b62d72b3088969ede314f176
The first line of the input contains one integer $$$n$$$ ($$$3 \le n \le 3 \cdot 10^5$$$, $$$n$$$ is divisible by $$$3$$$) — the number of characters in $$$s$$$. The second line contains the string $$$s$$$ consisting of exactly $$$n$$$ characters '0', '1' and '2'.
1,500
Print one string — the lexicographically (alphabetically) smallest balanced ternary string which can be obtained from the given one with minimum number of replacements. Because $$$n$$$ is divisible by $$$3$$$ it is obvious that the answer exists. And it is obvious that there is only one possible answer.
standard output