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
2823bfde5c413499755e6f0c3ac15d66
train_003.jsonl
1533737100
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!The only thing Mrs. Smith remembered was that any permutation of $$$n$$$ can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.The sequence of $$$n$$$ integers is called a permutation if it contains all integers from $$$1$$$ to $$$n$$$ exactly once.The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS). A subsequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ where $$$1\leq i_1 < i_2 < \ldots < i_k\leq n$$$ is called increasing if $$$a_{i_1} < a_{i_2} < a_{i_3} < \ldots < a_{i_k}$$$. If $$$a_{i_1} > a_{i_2} > a_{i_3} > \ldots > a_{i_k}$$$, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.For example, if there is a permutation $$$[6, 4, 1, 7, 2, 3, 5]$$$, LIS of this permutation will be $$$[1, 2, 3, 5]$$$, so the length of LIS is equal to $$$4$$$. LDS can be $$$[6, 4, 1]$$$, $$$[6, 4, 2]$$$, or $$$[6, 4, 3]$$$, so the length of LDS is $$$3$$$.Note, the lengths of LIS and LDS can be different.So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.*; import java.util.*; import java.util.LinkedList; import java.math.*; import java.lang.*; import java.util.PriorityQueue; import static java.lang.Math.*; @SuppressWarnings("unchecked") public class solution implements Runnable { static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static int min(int a,int b) { if(a>b) { return b; } return a; } public static long max(long a,long b) { if(a>b) { return a; } return b; } static class pair implements Comparable<pair> { int x; int y; pair(int x,int y) { this.x = x; this.y = y; } public int compareTo(pair p) { if(this.x>p.x) { return 1; } else if(this.x<p.x) { return -1; } else { return p.y-this.y; } } } public static void main(String args[]) throws Exception { new Thread(null, new solution(),"Main",1<<26).start(); } public void run() { InputReader sc = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int t1 = 1; while(t1-->0) { int n = sc.nextInt(); int min = n+1; int l = 1; for(int i=2;i<=n;i++) { int val = i+(n+i-1)/i; if(val<min) { min = val; l = i; } } while(n>=l) { for(int i=n-l+1;i<=n;i++) { out.print(i+" "); } n-=l; } for(int i=1;i<=n;i++) { out.print(i+" "); } } out.close(); } }
Java
["4", "2"]
1 second
["3 4 1 2", "2 1"]
NoteIn the first sample, you can build a permutation $$$[3, 4, 1, 2]$$$. LIS is $$$[3, 4]$$$ (or $$$[1, 2]$$$), so the length of LIS is equal to $$$2$$$. LDS can be ony of $$$[3, 1]$$$, $$$[4, 2]$$$, $$$[3, 2]$$$, or $$$[4, 1]$$$. The length of LDS is also equal to $$$2$$$. The sum is equal to $$$4$$$. Note that $$$[3, 4, 1, 2]$$$ is not the only permutation that is valid.In the second sample, you can build a permutation $$$[2, 1]$$$. LIS is $$$[1]$$$ (or $$$[2]$$$), so the length of LIS is equal to $$$1$$$. LDS is $$$[2, 1]$$$, so the length of LDS is equal to $$$2$$$. The sum is equal to $$$3$$$. Note that permutation $$$[1, 2]$$$ is also valid.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
6ea899e915cfc95a43f0e16d6d08cc1e
The only line contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of permutation that you need to build.
1,600
Print a permutation that gives a minimum sum of lengths of LIS and LDS. If there are multiple answers, print any.
standard output
PASSED
fad7fbfb3b1be0acd0d8bf81b1a05120
train_003.jsonl
1533737100
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!The only thing Mrs. Smith remembered was that any permutation of $$$n$$$ can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.The sequence of $$$n$$$ integers is called a permutation if it contains all integers from $$$1$$$ to $$$n$$$ exactly once.The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS). A subsequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ where $$$1\leq i_1 &lt; i_2 &lt; \ldots &lt; i_k\leq n$$$ is called increasing if $$$a_{i_1} &lt; a_{i_2} &lt; a_{i_3} &lt; \ldots &lt; a_{i_k}$$$. If $$$a_{i_1} &gt; a_{i_2} &gt; a_{i_3} &gt; \ldots &gt; a_{i_k}$$$, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.For example, if there is a permutation $$$[6, 4, 1, 7, 2, 3, 5]$$$, LIS of this permutation will be $$$[1, 2, 3, 5]$$$, so the length of LIS is equal to $$$4$$$. LDS can be $$$[6, 4, 1]$$$, $$$[6, 4, 2]$$$, or $$$[6, 4, 3]$$$, so the length of LDS is $$$3$$$.Note, the lengths of LIS and LDS can be different.So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); CThePhoneNumber solver = new CThePhoneNumber(); solver.solve(1, in, out); out.close(); } static class CThePhoneNumber { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int[] p = new int[n]; for (int i = 0; i < n; i++) { p[i] = i + 1; } StringBuilder sb = new StringBuilder(); int k = (int) Math.sqrt(n); for (int i = k - 1; i < n; i += k) { int counter = k; int pos = i; while (counter > 0) { sb.append(p[pos] + " "); counter--; pos--; } } int mod = n % k; if (mod > 0) { int counter = mod; int pos = n - 1; while (counter > 0) { sb.append(p[pos] + " "); counter--; pos--; } } out.println(sb.toString()); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["4", "2"]
1 second
["3 4 1 2", "2 1"]
NoteIn the first sample, you can build a permutation $$$[3, 4, 1, 2]$$$. LIS is $$$[3, 4]$$$ (or $$$[1, 2]$$$), so the length of LIS is equal to $$$2$$$. LDS can be ony of $$$[3, 1]$$$, $$$[4, 2]$$$, $$$[3, 2]$$$, or $$$[4, 1]$$$. The length of LDS is also equal to $$$2$$$. The sum is equal to $$$4$$$. Note that $$$[3, 4, 1, 2]$$$ is not the only permutation that is valid.In the second sample, you can build a permutation $$$[2, 1]$$$. LIS is $$$[1]$$$ (or $$$[2]$$$), so the length of LIS is equal to $$$1$$$. LDS is $$$[2, 1]$$$, so the length of LDS is equal to $$$2$$$. The sum is equal to $$$3$$$. Note that permutation $$$[1, 2]$$$ is also valid.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
6ea899e915cfc95a43f0e16d6d08cc1e
The only line contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of permutation that you need to build.
1,600
Print a permutation that gives a minimum sum of lengths of LIS and LDS. If there are multiple answers, print any.
standard output
PASSED
7ee6a86cef8513a97ffc5ae5bdf2059a
train_003.jsonl
1533737100
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!The only thing Mrs. Smith remembered was that any permutation of $$$n$$$ can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.The sequence of $$$n$$$ integers is called a permutation if it contains all integers from $$$1$$$ to $$$n$$$ exactly once.The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS). A subsequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ where $$$1\leq i_1 &lt; i_2 &lt; \ldots &lt; i_k\leq n$$$ is called increasing if $$$a_{i_1} &lt; a_{i_2} &lt; a_{i_3} &lt; \ldots &lt; a_{i_k}$$$. If $$$a_{i_1} &gt; a_{i_2} &gt; a_{i_3} &gt; \ldots &gt; a_{i_k}$$$, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.For example, if there is a permutation $$$[6, 4, 1, 7, 2, 3, 5]$$$, LIS of this permutation will be $$$[1, 2, 3, 5]$$$, so the length of LIS is equal to $$$4$$$. LDS can be $$$[6, 4, 1]$$$, $$$[6, 4, 2]$$$, or $$$[6, 4, 3]$$$, so the length of LDS is $$$3$$$.Note, the lengths of LIS and LDS can be different.So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
256 megabytes
import java.util.*; import java.io.*; public class codeforces { public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter pw = new PrintWriter(System.out); int n = in.nextInt(); int seg1 = 0, seg2 = 0, mins = 0, smin = 0, min = Integer.MAX_VALUE, m = 0, r = 0; for(int i=0;i<n;i++) { seg1 = n/(i+1) + Math.min(1, n%(i+1)); seg2 = i+1; if(min-seg1-seg2>0) { mins = seg1; smin = seg2; m = n%(i+1); r = Math.min(1, n%(i+1)); min = seg1+seg2; } } n++; for(int i=0;i<smin;i++) { if(m>0) { n = n - mins; for(int j=0;j<mins;j++) pw.print(n+j+" "); } else { n = n - mins + r; for(int j=0;j<mins-r;j++) pw.print(n+j+" "); } m--; } pw.flush(); pw.close(); } static class pair implements Comparable<pair> { Long x, y; pair(long x,long y) { this.x=x; this.y=y; } public int compareTo(pair o) { int result = x.compareTo(o.x); if(result==0) result = y.compareTo(o.y); return result; } public String toString() { return x+" "+y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair)o; return p.x == x && p.y == y ; } return false; } public int hashCode() { return new Long(x).hashCode()*31 + new Long(y).hashCode(); } } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class CodeX { public static void sort(long arr[]) { merge_sort(arr, 0, arr.length - 1); } private static void merge_sort(long A[], long start, long end) { if (start < end) { long mid = (start + end) / 2; merge_sort(A, start, mid); merge_sort(A, mid + 1, end); merge(A, start, mid, end); } } private static void merge(long A[], long start,long mid, long end) { long p = start, q = mid + 1; long Arr[] = new long[(int)(end - start + 1)]; long k = 0; for (int i = (int)start; i <= end; i++) { if (p > mid) Arr[(int)k++] = A[(int)q++]; else if (q > end) Arr[(int)k++] = A[(int)p++]; else if (A[(int)p] < A[(int)q]) Arr[(int)k++] = A[(int)p++]; else Arr[(int)k++] = A[(int)q++]; } for (int i = 0; i < k; i++) { A[(int)start++] = Arr[i]; } } } }
Java
["4", "2"]
1 second
["3 4 1 2", "2 1"]
NoteIn the first sample, you can build a permutation $$$[3, 4, 1, 2]$$$. LIS is $$$[3, 4]$$$ (or $$$[1, 2]$$$), so the length of LIS is equal to $$$2$$$. LDS can be ony of $$$[3, 1]$$$, $$$[4, 2]$$$, $$$[3, 2]$$$, or $$$[4, 1]$$$. The length of LDS is also equal to $$$2$$$. The sum is equal to $$$4$$$. Note that $$$[3, 4, 1, 2]$$$ is not the only permutation that is valid.In the second sample, you can build a permutation $$$[2, 1]$$$. LIS is $$$[1]$$$ (or $$$[2]$$$), so the length of LIS is equal to $$$1$$$. LDS is $$$[2, 1]$$$, so the length of LDS is equal to $$$2$$$. The sum is equal to $$$3$$$. Note that permutation $$$[1, 2]$$$ is also valid.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
6ea899e915cfc95a43f0e16d6d08cc1e
The only line contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of permutation that you need to build.
1,600
Print a permutation that gives a minimum sum of lengths of LIS and LDS. If there are multiple answers, print any.
standard output
PASSED
92a6ab6712b42bc7106eb08230215997
train_003.jsonl
1533737100
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!The only thing Mrs. Smith remembered was that any permutation of $$$n$$$ can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.The sequence of $$$n$$$ integers is called a permutation if it contains all integers from $$$1$$$ to $$$n$$$ exactly once.The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS). A subsequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ where $$$1\leq i_1 &lt; i_2 &lt; \ldots &lt; i_k\leq n$$$ is called increasing if $$$a_{i_1} &lt; a_{i_2} &lt; a_{i_3} &lt; \ldots &lt; a_{i_k}$$$. If $$$a_{i_1} &gt; a_{i_2} &gt; a_{i_3} &gt; \ldots &gt; a_{i_k}$$$, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.For example, if there is a permutation $$$[6, 4, 1, 7, 2, 3, 5]$$$, LIS of this permutation will be $$$[1, 2, 3, 5]$$$, so the length of LIS is equal to $$$4$$$. LDS can be $$$[6, 4, 1]$$$, $$$[6, 4, 2]$$$, or $$$[6, 4, 3]$$$, so the length of LDS is $$$3$$$.Note, the lengths of LIS and LDS can be different.So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
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 prakharjain */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int[] ans = new int[n + 1]; int sqrt = (int) Math.sqrt(n); int cn = n; for (int i = n; i >= 1; i -= sqrt) { for (int j = Math.max(i - sqrt + 1, 1); j <= i; j++) { out.print(j + " "); } } } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void close() { writer.close(); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["4", "2"]
1 second
["3 4 1 2", "2 1"]
NoteIn the first sample, you can build a permutation $$$[3, 4, 1, 2]$$$. LIS is $$$[3, 4]$$$ (or $$$[1, 2]$$$), so the length of LIS is equal to $$$2$$$. LDS can be ony of $$$[3, 1]$$$, $$$[4, 2]$$$, $$$[3, 2]$$$, or $$$[4, 1]$$$. The length of LDS is also equal to $$$2$$$. The sum is equal to $$$4$$$. Note that $$$[3, 4, 1, 2]$$$ is not the only permutation that is valid.In the second sample, you can build a permutation $$$[2, 1]$$$. LIS is $$$[1]$$$ (or $$$[2]$$$), so the length of LIS is equal to $$$1$$$. LDS is $$$[2, 1]$$$, so the length of LDS is equal to $$$2$$$. The sum is equal to $$$3$$$. Note that permutation $$$[1, 2]$$$ is also valid.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
6ea899e915cfc95a43f0e16d6d08cc1e
The only line contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of permutation that you need to build.
1,600
Print a permutation that gives a minimum sum of lengths of LIS and LDS. If there are multiple answers, print any.
standard output
PASSED
9237c28be7dd6bfaf2694a5e3186f729
train_003.jsonl
1533737100
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!The only thing Mrs. Smith remembered was that any permutation of $$$n$$$ can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.The sequence of $$$n$$$ integers is called a permutation if it contains all integers from $$$1$$$ to $$$n$$$ exactly once.The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS). A subsequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ where $$$1\leq i_1 &lt; i_2 &lt; \ldots &lt; i_k\leq n$$$ is called increasing if $$$a_{i_1} &lt; a_{i_2} &lt; a_{i_3} &lt; \ldots &lt; a_{i_k}$$$. If $$$a_{i_1} &gt; a_{i_2} &gt; a_{i_3} &gt; \ldots &gt; a_{i_k}$$$, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.For example, if there is a permutation $$$[6, 4, 1, 7, 2, 3, 5]$$$, LIS of this permutation will be $$$[1, 2, 3, 5]$$$, so the length of LIS is equal to $$$4$$$. LDS can be $$$[6, 4, 1]$$$, $$$[6, 4, 2]$$$, or $$$[6, 4, 3]$$$, so the length of LDS is $$$3$$$.Note, the lengths of LIS and LDS can be different.So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; import java.math.*; /* * Author : joney_000[developer.jaswant@gmail.com] * Algorithm : N/A * Platform : Codeforces * Ref : */ public class A{ private InputStream inputStream ; private OutputStream outputStream ; private FastReader in ; private PrintWriter out ; private final int BUFFER = 100005; private int auxInts[] = new int[BUFFER]; private long auxLongs[] = new long[1]; private double auxDoubles[] = new double[1]; private char auxChars[] = new char[1]; private final long mod = 1000000000+7; private final int INF = Integer.MAX_VALUE; private final long INF_L = Long.MAX_VALUE / 10; public A(){} public A(boolean stdIO)throws FileNotFoundException{ // stdIO = false; if(stdIO){ inputStream = System.in; outputStream = System.out; }else{ inputStream = new FileInputStream("input.txt"); outputStream = new FileOutputStream("output.txt"); } in = new FastReader(inputStream); out = new PrintWriter(outputStream); } void run()throws Exception{ int n = i(); int sqrt = (int)Math.sqrt(n); boolean done[] = new boolean[n + 1]; // out.write("sqrt : "+sqrt+"\n"); for(int i = 1; i <= sqrt + 2; i++){ int st = n - i * sqrt + 1; int end = st + sqrt - 1; for(int j = st; j <= end; j++){ if(j >= 1 && j <= n && !done[j]){ out.write(""+j+" "); done[j] = true; } } } } void clear(){ } long gcd(long a, long b){ if(b == 0)return a; return gcd(b, a % b); } long lcm(long a, long b){ if(a == 0 || b == 0)return 0; return (a * b)/gcd(a, b); } long mulMod(long a, long b, long mod){ if(a == 0 || b == 0)return 0; if(b == 1)return a; long ans = mulMod(a, b/2, mod); ans = (ans * 2) % mod; if(b % 2 == 1)ans = (a + ans)% mod; return ans; } long pow(long a, long b, long mod){ if(b == 0)return 1; if(b == 1)return a; long ans = pow(a, b/2, mod); ans = (ans * ans); if(ans >= mod)ans %= mod; if(b % 2 == 1)ans = (a * ans); if(ans >= mod)ans %= mod; return ans; } // 20*20 nCr Pascal Table long[][] ncrTable(){ long ncr[][] = new long[21][21]; for(int i = 0; i <= 20; i++){ ncr[i][0] = ncr[i][i] = 1L; } for(int j = 0; j <= 20; j++){ for(int i = j + 1; i <= 20; i++){ ncr[i][j] = ncr[i-1][j] + ncr[i-1][j-1]; } } return ncr; } int i()throws Exception{ return in.nextInt(); } long l()throws Exception{ return in.nextLong(); } double d()throws Exception{ return in.nextDouble(); } char c()throws Exception{ return in.nextCharacter(); } String s()throws Exception{ return in.nextLine(); } BigInteger bi()throws Exception{ return in.nextBigInteger(); } private void closeResources(){ out.flush(); out.close(); return; } // IMP: roundoff upto 2 digits // double roundOff = Math.round(a * 100.0) / 100.0; // or // System.out.printf("%.2f", val); // print upto 2 digits after decimal // val = ((long)(val * 100.0))/100.0; public static void main(String[] args) throws java.lang.Exception{ A driver = new A(true); driver.run(); driver.closeResources(); } } class FastReader{ private boolean finished = false; private InputStream stream; private byte[] buf = new byte[4 * 1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public FastReader(InputStream stream){ this.stream = stream; } public int read(){ if (numChars == -1){ throw new InputMismatchException (); } if (curChar >= numChars){ curChar = 0; try{ numChars = stream.read (buf); } catch (IOException e){ throw new InputMismatchException (); } if (numChars <= 0){ return -1; } } return buf[curChar++]; } public int peek(){ if (numChars == -1){ return -1; } if (curChar >= numChars){ curChar = 0; try{ numChars = stream.read (buf); } catch (IOException e){ return -1; } if (numChars <= 0){ return -1; } } return buf[curChar]; } public int nextInt(){ int c = read (); while (isSpaceChar (c)) c = read (); int sgn = 1; if (c == '-'){ sgn = -1; c = read (); } int res = 0; do{ if(c==','){ c = read(); } if (c < '0' || c > '9'){ throw new InputMismatchException (); } res *= 10; res += c - '0'; c = read (); } while (!isSpaceChar (c)); return res * sgn; } public long nextLong(){ int c = read (); while (isSpaceChar (c)) c = read (); int sgn = 1; if (c == '-'){ sgn = -1; c = read (); } long res = 0; do{ if (c < '0' || c > '9'){ throw new InputMismatchException (); } res *= 10; res += c - '0'; c = read (); } while (!isSpaceChar (c)); return res * sgn; } public String nextString(){ int c = read (); while (isSpaceChar (c)) c = read (); StringBuilder res = new StringBuilder (); do{ res.appendCodePoint (c); c = read (); } while (!isSpaceChar (c)); return res.toString (); } public boolean isSpaceChar(int c){ if (filter != null){ return filter.isSpaceChar (c); } return isWhitespace (c); } public static boolean isWhitespace(int c){ return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0(){ StringBuilder buf = new StringBuilder (); int c = read (); while (c != '\n' && c != -1){ if (c != '\r'){ buf.appendCodePoint (c); } c = read (); } return buf.toString (); } public String nextLine(){ String s = readLine0 (); while (s.trim ().length () == 0) s = readLine0 (); return s; } public String nextLine(boolean ignoreEmptyLines){ if (ignoreEmptyLines){ return nextLine (); }else{ return readLine0 (); } } public BigInteger nextBigInteger(){ try{ return new BigInteger (nextString ()); } catch (NumberFormatException e){ throw new InputMismatchException (); } } public char nextCharacter(){ int c = read (); while (isSpaceChar (c)) c = read (); return (char) c; } public double nextDouble(){ int c = read (); while (isSpaceChar (c)) c = read (); int sgn = 1; if (c == '-'){ sgn = -1; c = read (); } double res = 0; while (!isSpaceChar (c) && c != '.'){ if (c == 'e' || c == 'E'){ return res * Math.pow (10, nextInt ()); } if (c < '0' || c > '9'){ throw new InputMismatchException (); } res *= 10; res += c - '0'; c = read (); } if (c == '.'){ c = read (); double m = 1; while (!isSpaceChar (c)){ if (c == 'e' || c == 'E'){ return res * Math.pow (10, nextInt ()); } if (c < '0' || c > '9'){ throw new InputMismatchException (); } m /= 10; res += (c - '0') * m; c = read (); } } return res * sgn; } public boolean isExhausted(){ int value; while (isSpaceChar (value = peek ()) && value != -1) read (); return value == -1; } public String next(){ return nextString (); } public SpaceCharFilter getFilter(){ return filter; } public void setFilter(SpaceCharFilter filter){ this.filter = filter; } public interface SpaceCharFilter{ public boolean isSpaceChar(int ch); } } class Pair implements Comparable<Pair>{ public int a; public int b; public Pair(){ this.a = 0; this.b = 0; } public Pair(int a,int b){ this.a = a; this.b = b; } public int compareTo(Pair p){ if(this.a == p.a){ return this.b - p.b; } return -(this.a - p.a); } @Override public String toString(){ return "a = " + this.a + " b = " + this.b; } }
Java
["4", "2"]
1 second
["3 4 1 2", "2 1"]
NoteIn the first sample, you can build a permutation $$$[3, 4, 1, 2]$$$. LIS is $$$[3, 4]$$$ (or $$$[1, 2]$$$), so the length of LIS is equal to $$$2$$$. LDS can be ony of $$$[3, 1]$$$, $$$[4, 2]$$$, $$$[3, 2]$$$, or $$$[4, 1]$$$. The length of LDS is also equal to $$$2$$$. The sum is equal to $$$4$$$. Note that $$$[3, 4, 1, 2]$$$ is not the only permutation that is valid.In the second sample, you can build a permutation $$$[2, 1]$$$. LIS is $$$[1]$$$ (or $$$[2]$$$), so the length of LIS is equal to $$$1$$$. LDS is $$$[2, 1]$$$, so the length of LDS is equal to $$$2$$$. The sum is equal to $$$3$$$. Note that permutation $$$[1, 2]$$$ is also valid.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
6ea899e915cfc95a43f0e16d6d08cc1e
The only line contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of permutation that you need to build.
1,600
Print a permutation that gives a minimum sum of lengths of LIS and LDS. If there are multiple answers, print any.
standard output
PASSED
3ddb51d3825e8669ccd604e515cdbe4a
train_003.jsonl
1533737100
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!The only thing Mrs. Smith remembered was that any permutation of $$$n$$$ can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.The sequence of $$$n$$$ integers is called a permutation if it contains all integers from $$$1$$$ to $$$n$$$ exactly once.The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS). A subsequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ where $$$1\leq i_1 &lt; i_2 &lt; \ldots &lt; i_k\leq n$$$ is called increasing if $$$a_{i_1} &lt; a_{i_2} &lt; a_{i_3} &lt; \ldots &lt; a_{i_k}$$$. If $$$a_{i_1} &gt; a_{i_2} &gt; a_{i_3} &gt; \ldots &gt; a_{i_k}$$$, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.For example, if there is a permutation $$$[6, 4, 1, 7, 2, 3, 5]$$$, LIS of this permutation will be $$$[1, 2, 3, 5]$$$, so the length of LIS is equal to $$$4$$$. LDS can be $$$[6, 4, 1]$$$, $$$[6, 4, 2]$$$, or $$$[6, 4, 3]$$$, so the length of LDS is $$$3$$$.Note, the lengths of LIS and LDS can be different.So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
256 megabytes
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream st) { this.stream = st; } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } public static void main(String[] args) throws Exception { InputReader in = new InputReader(System.in); int n = in.nextInt(); int target = (int)Math.floor(Math.sqrt(n)); int[] ans = new int[n+1]; //for(int i=n;i>=1;i--) // ans[n - i + 1] = i; int i = n; int j = 1; while(i - target >= 0) { int count = 0; int t = i - target+1; while(count < target) { count++; ans[j] = t; t++; j++; } i = i - target; } if(i > 0) { j = n; while(i > 0) { ans[j] = i; j--;i--; } } for(int k=1;k<=n;k++) System.out.print(ans[k] + " "); System.out.println(); //System.out.println(ans); } }
Java
["4", "2"]
1 second
["3 4 1 2", "2 1"]
NoteIn the first sample, you can build a permutation $$$[3, 4, 1, 2]$$$. LIS is $$$[3, 4]$$$ (or $$$[1, 2]$$$), so the length of LIS is equal to $$$2$$$. LDS can be ony of $$$[3, 1]$$$, $$$[4, 2]$$$, $$$[3, 2]$$$, or $$$[4, 1]$$$. The length of LDS is also equal to $$$2$$$. The sum is equal to $$$4$$$. Note that $$$[3, 4, 1, 2]$$$ is not the only permutation that is valid.In the second sample, you can build a permutation $$$[2, 1]$$$. LIS is $$$[1]$$$ (or $$$[2]$$$), so the length of LIS is equal to $$$1$$$. LDS is $$$[2, 1]$$$, so the length of LDS is equal to $$$2$$$. The sum is equal to $$$3$$$. Note that permutation $$$[1, 2]$$$ is also valid.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
6ea899e915cfc95a43f0e16d6d08cc1e
The only line contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of permutation that you need to build.
1,600
Print a permutation that gives a minimum sum of lengths of LIS and LDS. If there are multiple answers, print any.
standard output
PASSED
a3de52c6471409d5265ef1df4448dce0
train_003.jsonl
1533737100
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!The only thing Mrs. Smith remembered was that any permutation of $$$n$$$ can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.The sequence of $$$n$$$ integers is called a permutation if it contains all integers from $$$1$$$ to $$$n$$$ exactly once.The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS). A subsequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ where $$$1\leq i_1 &lt; i_2 &lt; \ldots &lt; i_k\leq n$$$ is called increasing if $$$a_{i_1} &lt; a_{i_2} &lt; a_{i_3} &lt; \ldots &lt; a_{i_k}$$$. If $$$a_{i_1} &gt; a_{i_2} &gt; a_{i_3} &gt; \ldots &gt; a_{i_k}$$$, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.For example, if there is a permutation $$$[6, 4, 1, 7, 2, 3, 5]$$$, LIS of this permutation will be $$$[1, 2, 3, 5]$$$, so the length of LIS is equal to $$$4$$$. LDS can be $$$[6, 4, 1]$$$, $$$[6, 4, 2]$$$, or $$$[6, 4, 3]$$$, so the length of LDS is $$$3$$$.Note, the lengths of LIS and LDS can be different.So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
256 megabytes
//package Contest502; import java.util.Scanner; public class main502C { public static Scanner enter = new Scanner(System.in); public static void main(String[] args) { int n=enter.nextInt(); int kor = (int)Math.round(Math.sqrt(n)); int tmp=n%kor; int h=n/kor; for (int i = n-tmp+1; i <=n ; i++) { System.out.print(i+" "); } n-=tmp; for (int i = 0; i <h ; i++) { for (int j = n-kor+1; j <=n ; j++) { System.out.print(j+" "); } n-=kor; } } }
Java
["4", "2"]
1 second
["3 4 1 2", "2 1"]
NoteIn the first sample, you can build a permutation $$$[3, 4, 1, 2]$$$. LIS is $$$[3, 4]$$$ (or $$$[1, 2]$$$), so the length of LIS is equal to $$$2$$$. LDS can be ony of $$$[3, 1]$$$, $$$[4, 2]$$$, $$$[3, 2]$$$, or $$$[4, 1]$$$. The length of LDS is also equal to $$$2$$$. The sum is equal to $$$4$$$. Note that $$$[3, 4, 1, 2]$$$ is not the only permutation that is valid.In the second sample, you can build a permutation $$$[2, 1]$$$. LIS is $$$[1]$$$ (or $$$[2]$$$), so the length of LIS is equal to $$$1$$$. LDS is $$$[2, 1]$$$, so the length of LDS is equal to $$$2$$$. The sum is equal to $$$3$$$. Note that permutation $$$[1, 2]$$$ is also valid.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
6ea899e915cfc95a43f0e16d6d08cc1e
The only line contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of permutation that you need to build.
1,600
Print a permutation that gives a minimum sum of lengths of LIS and LDS. If there are multiple answers, print any.
standard output
PASSED
092afac345ec13393edf01a7a6c44b28
train_003.jsonl
1533737100
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!The only thing Mrs. Smith remembered was that any permutation of $$$n$$$ can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.The sequence of $$$n$$$ integers is called a permutation if it contains all integers from $$$1$$$ to $$$n$$$ exactly once.The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS). A subsequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ where $$$1\leq i_1 &lt; i_2 &lt; \ldots &lt; i_k\leq n$$$ is called increasing if $$$a_{i_1} &lt; a_{i_2} &lt; a_{i_3} &lt; \ldots &lt; a_{i_k}$$$. If $$$a_{i_1} &gt; a_{i_2} &gt; a_{i_3} &gt; \ldots &gt; a_{i_k}$$$, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.For example, if there is a permutation $$$[6, 4, 1, 7, 2, 3, 5]$$$, LIS of this permutation will be $$$[1, 2, 3, 5]$$$, so the length of LIS is equal to $$$4$$$. LDS can be $$$[6, 4, 1]$$$, $$$[6, 4, 2]$$$, or $$$[6, 4, 3]$$$, so the length of LDS is $$$3$$$.Note, the lengths of LIS and LDS can be different.So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Scanner; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(); int lis = (int) Math.sqrt(n); int lds = n % lis == 0 ? n / lis : (n / lis + 1); int count = 0; while (lds > 0) { for (int i = count + lis; i > count; i--) { if (i > n) continue; out.print(i + " "); } count = count + lis; lds--; } } } }
Java
["4", "2"]
1 second
["3 4 1 2", "2 1"]
NoteIn the first sample, you can build a permutation $$$[3, 4, 1, 2]$$$. LIS is $$$[3, 4]$$$ (or $$$[1, 2]$$$), so the length of LIS is equal to $$$2$$$. LDS can be ony of $$$[3, 1]$$$, $$$[4, 2]$$$, $$$[3, 2]$$$, or $$$[4, 1]$$$. The length of LDS is also equal to $$$2$$$. The sum is equal to $$$4$$$. Note that $$$[3, 4, 1, 2]$$$ is not the only permutation that is valid.In the second sample, you can build a permutation $$$[2, 1]$$$. LIS is $$$[1]$$$ (or $$$[2]$$$), so the length of LIS is equal to $$$1$$$. LDS is $$$[2, 1]$$$, so the length of LDS is equal to $$$2$$$. The sum is equal to $$$3$$$. Note that permutation $$$[1, 2]$$$ is also valid.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
6ea899e915cfc95a43f0e16d6d08cc1e
The only line contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of permutation that you need to build.
1,600
Print a permutation that gives a minimum sum of lengths of LIS and LDS. If there are multiple answers, print any.
standard output
PASSED
936cab95e21d1b5962f80994086e52d9
train_003.jsonl
1533737100
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!The only thing Mrs. Smith remembered was that any permutation of $$$n$$$ can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.The sequence of $$$n$$$ integers is called a permutation if it contains all integers from $$$1$$$ to $$$n$$$ exactly once.The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS). A subsequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ where $$$1\leq i_1 &lt; i_2 &lt; \ldots &lt; i_k\leq n$$$ is called increasing if $$$a_{i_1} &lt; a_{i_2} &lt; a_{i_3} &lt; \ldots &lt; a_{i_k}$$$. If $$$a_{i_1} &gt; a_{i_2} &gt; a_{i_3} &gt; \ldots &gt; a_{i_k}$$$, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.For example, if there is a permutation $$$[6, 4, 1, 7, 2, 3, 5]$$$, LIS of this permutation will be $$$[1, 2, 3, 5]$$$, so the length of LIS is equal to $$$4$$$. LDS can be $$$[6, 4, 1]$$$, $$$[6, 4, 2]$$$, or $$$[6, 4, 3]$$$, so the length of LDS is $$$3$$$.Note, the lengths of LIS and LDS can be different.So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
256 megabytes
import java.io.*; import java.util.*; public class Task { public static void main(String[] args) throws IOException { 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"); 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 IOException { int t = 1; while (t > 0) { solve(); //out.println(); t--; } out.flush(); out.close(); } int inf = 2000000000; int mod = 1000000007; double eps = 0.000000001; int n; int m; int[] a; ArrayList<Integer>[] g; void solve() throws IOException { int n = in.nextInt(); int d = 1; while (d * d < n) d++; int cur = n; for (int i = 0; i < n;) { for (int j = cur - d + 1; j <= cur; j++) if (j > 0) { out.print(j + " "); i++; } cur -= d; } } int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } class Pair implements Comparable<Pair>{ int a; int b; Pair(int a, int b) { this.a = a; this.b = b; } public int compareTo(Pair p) { if (a > p.a) return 1; if (a < p.a) return -1; if (b > p.b) return 1; if (b < p.b) return -1; return 0; } } 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(); } int[] nextIntArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } ArrayList<Integer>[] nextGraph(int n, int m) throws IOException { ArrayList<Integer>[] g = new ArrayList[n]; for (int i = 0; i < n; i++) g[i] = new ArrayList<>(); for (int i = 0; i < m; i++) { int x = nextInt() - 1; int y = nextInt() - 1; g[x].add(y); g[y].add(x); } return g; } } }
Java
["4", "2"]
1 second
["3 4 1 2", "2 1"]
NoteIn the first sample, you can build a permutation $$$[3, 4, 1, 2]$$$. LIS is $$$[3, 4]$$$ (or $$$[1, 2]$$$), so the length of LIS is equal to $$$2$$$. LDS can be ony of $$$[3, 1]$$$, $$$[4, 2]$$$, $$$[3, 2]$$$, or $$$[4, 1]$$$. The length of LDS is also equal to $$$2$$$. The sum is equal to $$$4$$$. Note that $$$[3, 4, 1, 2]$$$ is not the only permutation that is valid.In the second sample, you can build a permutation $$$[2, 1]$$$. LIS is $$$[1]$$$ (or $$$[2]$$$), so the length of LIS is equal to $$$1$$$. LDS is $$$[2, 1]$$$, so the length of LDS is equal to $$$2$$$. The sum is equal to $$$3$$$. Note that permutation $$$[1, 2]$$$ is also valid.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
6ea899e915cfc95a43f0e16d6d08cc1e
The only line contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of permutation that you need to build.
1,600
Print a permutation that gives a minimum sum of lengths of LIS and LDS. If there are multiple answers, print any.
standard output
PASSED
b99ffd065f3cf1f2d6442e8b68f6b463
train_003.jsonl
1533737100
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!The only thing Mrs. Smith remembered was that any permutation of $$$n$$$ can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.The sequence of $$$n$$$ integers is called a permutation if it contains all integers from $$$1$$$ to $$$n$$$ exactly once.The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS). A subsequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ where $$$1\leq i_1 &lt; i_2 &lt; \ldots &lt; i_k\leq n$$$ is called increasing if $$$a_{i_1} &lt; a_{i_2} &lt; a_{i_3} &lt; \ldots &lt; a_{i_k}$$$. If $$$a_{i_1} &gt; a_{i_2} &gt; a_{i_3} &gt; \ldots &gt; a_{i_k}$$$, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.For example, if there is a permutation $$$[6, 4, 1, 7, 2, 3, 5]$$$, LIS of this permutation will be $$$[1, 2, 3, 5]$$$, so the length of LIS is equal to $$$4$$$. LDS can be $$$[6, 4, 1]$$$, $$$[6, 4, 2]$$$, or $$$[6, 4, 3]$$$, so the length of LDS is $$$3$$$.Note, the lengths of LIS and LDS can be different.So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
256 megabytes
import java.util.*; public class Test { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n= sc.nextInt(); int x= (int)Math.sqrt(n) ; int a[] = new int[n+5]; for(int i=1,o=n,j;i<=n;i+=x) for(j=(int)Math.min(i+x-1,n);j>=i;a[j--]=o--); for(int i=1;i<=n;i++)System.out.print(a[i]+" "); System.out.println(); } }
Java
["4", "2"]
1 second
["3 4 1 2", "2 1"]
NoteIn the first sample, you can build a permutation $$$[3, 4, 1, 2]$$$. LIS is $$$[3, 4]$$$ (or $$$[1, 2]$$$), so the length of LIS is equal to $$$2$$$. LDS can be ony of $$$[3, 1]$$$, $$$[4, 2]$$$, $$$[3, 2]$$$, or $$$[4, 1]$$$. The length of LDS is also equal to $$$2$$$. The sum is equal to $$$4$$$. Note that $$$[3, 4, 1, 2]$$$ is not the only permutation that is valid.In the second sample, you can build a permutation $$$[2, 1]$$$. LIS is $$$[1]$$$ (or $$$[2]$$$), so the length of LIS is equal to $$$1$$$. LDS is $$$[2, 1]$$$, so the length of LDS is equal to $$$2$$$. The sum is equal to $$$3$$$. Note that permutation $$$[1, 2]$$$ is also valid.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
6ea899e915cfc95a43f0e16d6d08cc1e
The only line contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of permutation that you need to build.
1,600
Print a permutation that gives a minimum sum of lengths of LIS and LDS. If there are multiple answers, print any.
standard output
PASSED
17be38aacfbdc2af49b6fcd7ef9b9720
train_003.jsonl
1533737100
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!The only thing Mrs. Smith remembered was that any permutation of $$$n$$$ can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.The sequence of $$$n$$$ integers is called a permutation if it contains all integers from $$$1$$$ to $$$n$$$ exactly once.The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS). A subsequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ where $$$1\leq i_1 &lt; i_2 &lt; \ldots &lt; i_k\leq n$$$ is called increasing if $$$a_{i_1} &lt; a_{i_2} &lt; a_{i_3} &lt; \ldots &lt; a_{i_k}$$$. If $$$a_{i_1} &gt; a_{i_2} &gt; a_{i_3} &gt; \ldots &gt; a_{i_k}$$$, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.For example, if there is a permutation $$$[6, 4, 1, 7, 2, 3, 5]$$$, LIS of this permutation will be $$$[1, 2, 3, 5]$$$, so the length of LIS is equal to $$$4$$$. LDS can be $$$[6, 4, 1]$$$, $$$[6, 4, 2]$$$, or $$$[6, 4, 3]$$$, so the length of LDS is $$$3$$$.Note, the lengths of LIS and LDS can be different.So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
256 megabytes
import java.util.*; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.StringTokenizer; public class problem1017C { public static void main(String[] args) { Scanner console = new Scanner(System.in); PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), true); int n = console.nextInt(); int size = (int)(Math.sqrt(n)); int start = n-size+1; outer: while (true) { for (int i = 0; i<size; i++) { if (start>0) { pw.print(start+" "); start++; } else if (start+size>1) start++; else break outer; } start-=2*size; } pw.close(); } }
Java
["4", "2"]
1 second
["3 4 1 2", "2 1"]
NoteIn the first sample, you can build a permutation $$$[3, 4, 1, 2]$$$. LIS is $$$[3, 4]$$$ (or $$$[1, 2]$$$), so the length of LIS is equal to $$$2$$$. LDS can be ony of $$$[3, 1]$$$, $$$[4, 2]$$$, $$$[3, 2]$$$, or $$$[4, 1]$$$. The length of LDS is also equal to $$$2$$$. The sum is equal to $$$4$$$. Note that $$$[3, 4, 1, 2]$$$ is not the only permutation that is valid.In the second sample, you can build a permutation $$$[2, 1]$$$. LIS is $$$[1]$$$ (or $$$[2]$$$), so the length of LIS is equal to $$$1$$$. LDS is $$$[2, 1]$$$, so the length of LDS is equal to $$$2$$$. The sum is equal to $$$3$$$. Note that permutation $$$[1, 2]$$$ is also valid.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
6ea899e915cfc95a43f0e16d6d08cc1e
The only line contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of permutation that you need to build.
1,600
Print a permutation that gives a minimum sum of lengths of LIS and LDS. If there are multiple answers, print any.
standard output
PASSED
26f9cb722d586d8e55946b161124bf17
train_003.jsonl
1533737100
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!The only thing Mrs. Smith remembered was that any permutation of $$$n$$$ can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.The sequence of $$$n$$$ integers is called a permutation if it contains all integers from $$$1$$$ to $$$n$$$ exactly once.The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS). A subsequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ where $$$1\leq i_1 &lt; i_2 &lt; \ldots &lt; i_k\leq n$$$ is called increasing if $$$a_{i_1} &lt; a_{i_2} &lt; a_{i_3} &lt; \ldots &lt; a_{i_k}$$$. If $$$a_{i_1} &gt; a_{i_2} &gt; a_{i_3} &gt; \ldots &gt; a_{i_k}$$$, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.For example, if there is a permutation $$$[6, 4, 1, 7, 2, 3, 5]$$$, LIS of this permutation will be $$$[1, 2, 3, 5]$$$, so the length of LIS is equal to $$$4$$$. LDS can be $$$[6, 4, 1]$$$, $$$[6, 4, 2]$$$, or $$$[6, 4, 3]$$$, so the length of LDS is $$$3$$$.Note, the lengths of LIS and LDS can be different.So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
256 megabytes
import java.util.Scanner; public class Class1 { public static void main(String[] args) { Scanner input=new Scanner(System.in); int n=input.nextInt(); input.close(); int lim=(int) Math.ceil(Math.sqrt(n)); int[] arr=new int[lim*lim]; for(int i=n-(lim*lim)+1;i<=n;i++) arr[i+(lim*lim)-n-1]=i; for(int i=lim-1;i>=0;i--) { for(int j=0;j<lim;j++) { if(arr[i*lim+j]>0) System.out.print(arr[i*lim+j]+" "); } } } }
Java
["4", "2"]
1 second
["3 4 1 2", "2 1"]
NoteIn the first sample, you can build a permutation $$$[3, 4, 1, 2]$$$. LIS is $$$[3, 4]$$$ (or $$$[1, 2]$$$), so the length of LIS is equal to $$$2$$$. LDS can be ony of $$$[3, 1]$$$, $$$[4, 2]$$$, $$$[3, 2]$$$, or $$$[4, 1]$$$. The length of LDS is also equal to $$$2$$$. The sum is equal to $$$4$$$. Note that $$$[3, 4, 1, 2]$$$ is not the only permutation that is valid.In the second sample, you can build a permutation $$$[2, 1]$$$. LIS is $$$[1]$$$ (or $$$[2]$$$), so the length of LIS is equal to $$$1$$$. LDS is $$$[2, 1]$$$, so the length of LDS is equal to $$$2$$$. The sum is equal to $$$3$$$. Note that permutation $$$[1, 2]$$$ is also valid.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
6ea899e915cfc95a43f0e16d6d08cc1e
The only line contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of permutation that you need to build.
1,600
Print a permutation that gives a minimum sum of lengths of LIS and LDS. If there are multiple answers, print any.
standard output
PASSED
83ff05922ced77dbfa2b3ad1c14328fc
train_003.jsonl
1533737100
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!The only thing Mrs. Smith remembered was that any permutation of $$$n$$$ can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.The sequence of $$$n$$$ integers is called a permutation if it contains all integers from $$$1$$$ to $$$n$$$ exactly once.The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS). A subsequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ where $$$1\leq i_1 &lt; i_2 &lt; \ldots &lt; i_k\leq n$$$ is called increasing if $$$a_{i_1} &lt; a_{i_2} &lt; a_{i_3} &lt; \ldots &lt; a_{i_k}$$$. If $$$a_{i_1} &gt; a_{i_2} &gt; a_{i_3} &gt; \ldots &gt; a_{i_k}$$$, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.For example, if there is a permutation $$$[6, 4, 1, 7, 2, 3, 5]$$$, LIS of this permutation will be $$$[1, 2, 3, 5]$$$, so the length of LIS is equal to $$$4$$$. LDS can be $$$[6, 4, 1]$$$, $$$[6, 4, 2]$$$, or $$$[6, 4, 3]$$$, so the length of LDS is $$$3$$$.Note, the lengths of LIS and LDS can be different.So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.FilterInputStream; import java.io.BufferedInputStream; import java.io.InputStream; /** * @author khokharnikunj8 */ public class Main { public static void main(String[] args) { new Thread(null, new Runnable() { public void run() { new Main().solve(); } }, "1", 1 << 26).start(); } void solve() { InputStream inputStream = System.in; OutputStream outputStream = System.out; ScanReader in = new ScanReader(inputStream); PrintWriter out = new PrintWriter(outputStream); CThePhoneNumber solver = new CThePhoneNumber(); solver.solve(1, in, out); out.close(); } static class CThePhoneNumber { public void solve(int testNumber, ScanReader in, PrintWriter out) { int n = in.scanInt(); int sqrt = (int) Math.sqrt(n); int tt = sqrt; while (true) { for (int i = tt; i >= tt - sqrt + 1; i--) out.print(i + " "); tt += sqrt; if (tt >= n) { for (int i = n; i >= tt - sqrt + 1; i--) out.print(i + " "); break; } } } } static class ScanReader { private byte[] buf = new byte[4 * 1024]; private int index; private BufferedInputStream in; private int total; public ScanReader(InputStream inputStream) { in = new BufferedInputStream(inputStream); } private int scan() { if (index >= total) { index = 0; try { total = in.read(buf); } catch (Exception e) { e.printStackTrace(); } if (total <= 0) return -1; } return buf[index++]; } public int scanInt() { int integer = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { integer *= 10; integer += n - '0'; n = scan(); } } return neg * integer; } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; else return false; } } }
Java
["4", "2"]
1 second
["3 4 1 2", "2 1"]
NoteIn the first sample, you can build a permutation $$$[3, 4, 1, 2]$$$. LIS is $$$[3, 4]$$$ (or $$$[1, 2]$$$), so the length of LIS is equal to $$$2$$$. LDS can be ony of $$$[3, 1]$$$, $$$[4, 2]$$$, $$$[3, 2]$$$, or $$$[4, 1]$$$. The length of LDS is also equal to $$$2$$$. The sum is equal to $$$4$$$. Note that $$$[3, 4, 1, 2]$$$ is not the only permutation that is valid.In the second sample, you can build a permutation $$$[2, 1]$$$. LIS is $$$[1]$$$ (or $$$[2]$$$), so the length of LIS is equal to $$$1$$$. LDS is $$$[2, 1]$$$, so the length of LDS is equal to $$$2$$$. The sum is equal to $$$3$$$. Note that permutation $$$[1, 2]$$$ is also valid.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
6ea899e915cfc95a43f0e16d6d08cc1e
The only line contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of permutation that you need to build.
1,600
Print a permutation that gives a minimum sum of lengths of LIS and LDS. If there are multiple answers, print any.
standard output
PASSED
09244a794e841789b5f67f2360ee2091
train_003.jsonl
1533737100
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!The only thing Mrs. Smith remembered was that any permutation of $$$n$$$ can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.The sequence of $$$n$$$ integers is called a permutation if it contains all integers from $$$1$$$ to $$$n$$$ exactly once.The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS). A subsequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ where $$$1\leq i_1 &lt; i_2 &lt; \ldots &lt; i_k\leq n$$$ is called increasing if $$$a_{i_1} &lt; a_{i_2} &lt; a_{i_3} &lt; \ldots &lt; a_{i_k}$$$. If $$$a_{i_1} &gt; a_{i_2} &gt; a_{i_3} &gt; \ldots &gt; a_{i_k}$$$, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.For example, if there is a permutation $$$[6, 4, 1, 7, 2, 3, 5]$$$, LIS of this permutation will be $$$[1, 2, 3, 5]$$$, so the length of LIS is equal to $$$4$$$. LDS can be $$$[6, 4, 1]$$$, $$$[6, 4, 2]$$$, or $$$[6, 4, 3]$$$, so the length of LDS is $$$3$$$.Note, the lengths of LIS and LDS can be different.So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
256 megabytes
import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.util.*; import java.util.Map.Entry; public class Main { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private PrintWriter pw; private long mod = 1000000 + 3; private StringBuilder ans_sb; private void soln() { int n = nextInt(); int sqrt = (int) Math.sqrt(n); int len = n / sqrt + sqrt; if (n % sqrt != 0) { len++; } int sqrt1 = sqrt + 1; int sqrt2 = sqrt - 1; while (sqrt1 <= n) { int len1 = n / sqrt1 + sqrt1; if (n % sqrt1 != 0) { len1++; } if (len >= len1) { len = len1; sqrt = sqrt1; } sqrt1++; } while (sqrt2 >= 1) { int len1 = n / sqrt2 + sqrt2; if (n % sqrt2 != 0) { len1++; } if (len >= len1) { len = len1; sqrt = sqrt2; } sqrt2--; } // debug(sqrt); // debug(len); // debug(n); if (sqrt * sqrt != n) { int n1 = n % sqrt; for (int i = n - n1 + 1; i <= n; i++) { pw.print(i + " "); } n -= n1; } // debug(n); // debug("yes"); while (n != 0) { for (int i = n - sqrt + 1; i <= n; i++) { pw.print(i + " "); } n -= sqrt; } // int n = nextInt(); // int m = nextInt(); // int q = nextInt(); // int pow = (int) Math.pow(2, n); // int[][] arr = new int[pow][105]; // int[] arr1 = nextIntArray(n); // int[] a1 = new int[pow]; // for(int i=0;i<m;i++) { // String s = nextLine(); // int val = 0; // int pow1 = 1; // for(int j=n-1;j>=0;j--) { // if(s.charAt(j) == '1') { // val += pow1; // } // pow1 = pow1*2; // } // a1[val]++; // } // //debug(a1); // int[] vs = new int[pow]; // for(int i=0;i<pow;i++) { // int j = i; // int kk = 0; // while(j != 0) { // int x = j%2; // if(x == 0) // vs[i] += arr1[n-kk-1]; // j/=2; // kk++; // } // while(kk < n) { // vs[i] += arr1[n-kk-1]; // kk++; // } // } // //debug(vs); // for(int i=0;i<pow;i++) { // for(int j=0;j<=i;j++) { // int xor = (i^j); // int va = vs[xor]; // if(va <= 100) { // if(a1[j] != 0) // arr[i][va]+=a1[j]; // if(a1[i] != 0 && i!=j) // arr[j][va]+=a1[i]; // //debug(i+" "+j+" "+va); // } // } // } // //debug(arr); // for(int i=0;i<pow;i++) { // for(int j=1;j<=100;j++) { // arr[i][j] += arr[i][j-1]; // } // } // while(q-- > 0) { // String[] s = nextLine().split(" "); // int k = Integer.parseInt(s[1]); // int val = 0; // int pow1 = 1; // for(int j=0;j<n;j++) { // if(s[0].charAt(j) == '1') { // val += pow1; // } // pow1 = pow1*2; // } // pw.println(arr[val][k]); // } } private String solveEqn(long a, long b) { long x = 0, y = 1, lastx = 1, lasty = 0, temp; while (b != 0) { long q = a / b; long r = a % b; a = b; b = r; temp = x; x = lastx - q * x; lastx = temp; temp = y; y = lasty - q * y; lasty = temp; } return lastx + " " + lasty; } private void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } private long pow(long a, long b, long c) { if (b == 0) return 1; long p = pow(a, b / 2, c); p = (p * p) % c; return (b % 2 == 0) ? p : (a * p) % c; } private long gcd(long n, long l) { if (l == 0) return n; return gcd(l, n % l); } public static void main(String[] args) throws Exception { new Thread(null, new Runnable() { @Override public void run() { new Main().solve(); } }, "1", 1 << 26).start(); // new Main().solve(); } public StringBuilder solve() { InputReader(System.in); /* * try { InputReader(new FileInputStream("C:\\Users\\hardik\\Desktop\\in.txt")); * } catch(FileNotFoundException e) {} */ pw = new PrintWriter(System.out); // ans_sb = new StringBuilder(); soln(); pw.close(); // System.out.println(ans_sb); return ans_sb; } public void InputReader(InputStream stream1) { stream = stream1; } private boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } private int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } private int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } private long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } private String nextToken() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private 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(); } private int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } private long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } private void pArray(int[] arr) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); return; } private void pArray(long[] arr) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); return; } private boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } private char nextChar() { int c = read(); while (isSpaceChar(c)) c = read(); char c1 = (char) c; while (!isSpaceChar(c)) c = read(); return c1; } private interface SpaceCharFilter { public boolean isSpaceChar(int ch); } }
Java
["4", "2"]
1 second
["3 4 1 2", "2 1"]
NoteIn the first sample, you can build a permutation $$$[3, 4, 1, 2]$$$. LIS is $$$[3, 4]$$$ (or $$$[1, 2]$$$), so the length of LIS is equal to $$$2$$$. LDS can be ony of $$$[3, 1]$$$, $$$[4, 2]$$$, $$$[3, 2]$$$, or $$$[4, 1]$$$. The length of LDS is also equal to $$$2$$$. The sum is equal to $$$4$$$. Note that $$$[3, 4, 1, 2]$$$ is not the only permutation that is valid.In the second sample, you can build a permutation $$$[2, 1]$$$. LIS is $$$[1]$$$ (or $$$[2]$$$), so the length of LIS is equal to $$$1$$$. LDS is $$$[2, 1]$$$, so the length of LDS is equal to $$$2$$$. The sum is equal to $$$3$$$. Note that permutation $$$[1, 2]$$$ is also valid.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
6ea899e915cfc95a43f0e16d6d08cc1e
The only line contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of permutation that you need to build.
1,600
Print a permutation that gives a minimum sum of lengths of LIS and LDS. If there are multiple answers, print any.
standard output
PASSED
08e32330f2014c29378a79f092bf7334
train_003.jsonl
1533737100
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!The only thing Mrs. Smith remembered was that any permutation of $$$n$$$ can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.The sequence of $$$n$$$ integers is called a permutation if it contains all integers from $$$1$$$ to $$$n$$$ exactly once.The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS). A subsequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ where $$$1\leq i_1 &lt; i_2 &lt; \ldots &lt; i_k\leq n$$$ is called increasing if $$$a_{i_1} &lt; a_{i_2} &lt; a_{i_3} &lt; \ldots &lt; a_{i_k}$$$. If $$$a_{i_1} &gt; a_{i_2} &gt; a_{i_3} &gt; \ldots &gt; a_{i_k}$$$, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.For example, if there is a permutation $$$[6, 4, 1, 7, 2, 3, 5]$$$, LIS of this permutation will be $$$[1, 2, 3, 5]$$$, so the length of LIS is equal to $$$4$$$. LDS can be $$$[6, 4, 1]$$$, $$$[6, 4, 2]$$$, or $$$[6, 4, 3]$$$, so the length of LDS is $$$3$$$.Note, the lengths of LIS and LDS can be different.So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; public class DivCmb_502C { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter printer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int n = Integer.parseInt(reader.readLine()); int sqrt = (int) Math.sqrt(n); ArrayList<Integer> build = new ArrayList<Integer>(); int rem = n % sqrt; for (int i = rem - 1; i >= 0; i--) { build.add(n - i); } for (int i = n / sqrt - 1; i >= 0; i--) { for (int j = 0; j < sqrt; j++) { build.add(i * sqrt + j + 1); } } for (int i : build) { printer.print(i + " "); } printer.println(); printer.close(); } }
Java
["4", "2"]
1 second
["3 4 1 2", "2 1"]
NoteIn the first sample, you can build a permutation $$$[3, 4, 1, 2]$$$. LIS is $$$[3, 4]$$$ (or $$$[1, 2]$$$), so the length of LIS is equal to $$$2$$$. LDS can be ony of $$$[3, 1]$$$, $$$[4, 2]$$$, $$$[3, 2]$$$, or $$$[4, 1]$$$. The length of LDS is also equal to $$$2$$$. The sum is equal to $$$4$$$. Note that $$$[3, 4, 1, 2]$$$ is not the only permutation that is valid.In the second sample, you can build a permutation $$$[2, 1]$$$. LIS is $$$[1]$$$ (or $$$[2]$$$), so the length of LIS is equal to $$$1$$$. LDS is $$$[2, 1]$$$, so the length of LDS is equal to $$$2$$$. The sum is equal to $$$3$$$. Note that permutation $$$[1, 2]$$$ is also valid.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
6ea899e915cfc95a43f0e16d6d08cc1e
The only line contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of permutation that you need to build.
1,600
Print a permutation that gives a minimum sum of lengths of LIS and LDS. If there are multiple answers, print any.
standard output
PASSED
96049e09e1ad6e66cdaa84b300d72e9c
train_003.jsonl
1533737100
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!The only thing Mrs. Smith remembered was that any permutation of $$$n$$$ can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.The sequence of $$$n$$$ integers is called a permutation if it contains all integers from $$$1$$$ to $$$n$$$ exactly once.The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS). A subsequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ where $$$1\leq i_1 &lt; i_2 &lt; \ldots &lt; i_k\leq n$$$ is called increasing if $$$a_{i_1} &lt; a_{i_2} &lt; a_{i_3} &lt; \ldots &lt; a_{i_k}$$$. If $$$a_{i_1} &gt; a_{i_2} &gt; a_{i_3} &gt; \ldots &gt; a_{i_k}$$$, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.For example, if there is a permutation $$$[6, 4, 1, 7, 2, 3, 5]$$$, LIS of this permutation will be $$$[1, 2, 3, 5]$$$, so the length of LIS is equal to $$$4$$$. LDS can be $$$[6, 4, 1]$$$, $$$[6, 4, 2]$$$, or $$$[6, 4, 3]$$$, so the length of LDS is $$$3$$$.Note, the lengths of LIS and LDS can be different.So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
256 megabytes
// No sorceries shall prevail. // import java.util.*; import javafx.util.*; import java.io.*; public class InVoker { //Variables static long mod = 1000000007; static long mod2 = 998244353; static FastReader inp= new FastReader(); static PrintWriter out= new PrintWriter(System.out); public static void main(String args[]) { InVoker g=new InVoker(); g.main(); out.close(); } //Main void main() { int n=inp.nextInt(); int k=1; for(;k*k<n;k++) { } //out.println(k); for(int i=0;i<n/k;i++) { for(int j=0;j<k;j++) { out.print(((i+1)*k-j) +" "); } } for(int i=0;i<n%k;i++) { out.print((n-i) +" "); } } /********************************************************************************************************************************************************************************************************* * ti;. .:,:i: :,;;itt;. fDDEDDEEEEEEKEEEEEKEEEEEEEEEEEEEEEEE###WKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWWWWWWWW#WWWWWKKKKKEE :,:. f::::. .,ijLGDDDDDDDEEEEEEE* *ti;. .:,:i: .:,;itt;: GLDEEGEEEEEEEEEEEEEEEEEEDEEEEEEEEEEE#W#WEKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWWWWWWWWWWWKKKKKKG. .::. f:,...,ijLGDDDDDDDDEEEEEE * *ti;. .:,:i: :,;;iti, :fDDEEEEEEEEEEEEEEEKEEEEDEEEEEEEEEEEW##WEEEKKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWWWWWWWWWWWWKKKKKKEG .::. .f,::,ijLGDDDDDDDDEEEEEE * *ti;. .:,:i: .,,;iti;. LDDEEEEEEEEEEKEEEEWEEEDDEEEEEEEEEEE#WWWEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWWWWWWWWKKKKKEDj .::. .:L;;ijfGDDDDDDDDDEEEEE * *ti;. .:,:i: .:,;;iii:LLDEEEEEEEEEEEKEEEEEEEEDEEEEEEEEEEEW#WWEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKWWKWWWWWWWWWWWWWWKKKKKKKEL .::. .:;LijLGGDDDDDDDDEEEEE * *ti;. .:,:;: :,;;ittfDEEEEEEEEEEEEEEEEKEEEGEEEEEEEEEEEKWWWEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWWWWKKKKKKKELj .::. :,;jffGGDDDDDDDDDEEEE * *ti;. .:,:i: .,;;tGGDEEEEEEEEEEEKEEEKEEEDEEEEEEEEEEEEWWWEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWWKWWWWWWKKKKKKKEEL .::. .:;itDGGDDDDDDDDDEEEE * *ti;. .:::;: :;ifDEEEEEEEEEEEEKEEEKEEEEEEEEEEEEEEEWWWEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKW#WWWKKKKKKKKEEf .::. :,itfGEDDDDDDDDDDDEE * *ti;. .:::;: :GGEEEEEEEEEEEKEKEEKEEEEEEEEEEEEEEEEWWEEEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKW#WKKKKKKKKKEEDG .::. .,;jfLGKDLDDDDDDEEDD * *ti;. .:::;: fDEEEEEEKKKKKKKKKEKEEEEEEEEEEEEEEE#WEEEEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKW#KKKKKKKKKKEEf .:::. .,;tfLGDEDDDDDDDDEEE * *ti;. :::;: fDEEEEEEKKKKKKKKKKWKEEEEEEEEEEEEEEEWKEEEEEEEEEEEEEEEEEEEEKEKKKKKKKKKKKKKKKKKKKKKKKKKKKKW##KKKKKKKKKEEft :::. .,;tfLGDDDKDDDDDDDDD * *ti;. .::;: fDEEEEEEKKKKKKKWKKKKKEEEEEEEEEEEEE#WEEWEEEEEDEEDEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKW#WKKKKKKKKEEGG :,:. .,;tfLGGDDDKDDDDDDDD * *ti;. .:.;: tGDEEEEKKKKKKKKKKKKKKKKKEEEEEEEEEEEWEEKWEEEEEEEDEEEEEEEEEEEEEEKEKKKKKKKKKKKKKKKKKKKKKKKKKKWWWKKKKKKKEEDf :::. .,;tfLGGDDDDEDDDDDDD * *ti;. .::;: fDEEEEEKKKKKKKKKKKWKKKKKKKKEEEEEEEWWEEWEEEEEEEEEEEEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKW##KKKKKKKEEEft.::. .,;tfLGGDDDDDDEDDDDD * *ti;. .:.;: tGDEEEKKKKKKKKKKKKKKKKKKKKKKEKEEEEE#EEWWEEEEEEEEEEEEEEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKW#WKKKKKKEEEGD:::. .,;tfLGGDDDDDDDEDDDD * *ti;. .:.,. LDEEEEKKKKKKKKKKWKWKKKKKKKKKKKKEEEKWEKW#EEEEEEEEEEEEEEEEKEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKW##KKKKKKEEEEf,,:. .,;tfLGGDDDDDDDDEDDD * *ti;. ..:.,. LGDEEEEKKKKKKKKKKWKKKKKKKKKKKKKKKKKWEEW#WEEEEEEEEEEEEEEEKEEEEEEEEEEEEEEEEEEEKEKKKKKKKKKKKKKKKK##KKKKKEEEEEfi;,. .,;tfLGGDDDDDDDDDKDD * *tt;. .:.,: jDEEEEKKKKKKKKKKWWKKKKKKKKKKKKKKKKKWKE#WWEEEEEEEEEEEEEEWEEEEEEEEEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKWWKKKKEEEEDfG;,: .,;tfLGGDDDDDDDDDDKD * *tii,. .:.,. tGDEEEEKKKKKKKKKKWWWKKKKKKKKKKKKKKKWKKWWWKEEEEEEEEEEEEEKEEEEEEEEEEEEEEEEEEEEEEEEEEEEEKKKKKKKKKKKW#KKKKEEEEDGGi;,. .,;tfLGGDDDDDDDDDDDE * *ti;;,:. .:.,: fDEEEEKKKKKKKKKKKWKKKKKKKKKKKKKKKKKWEK#WWKEEEEEEEEEEEEDEEEEEEEEEEEEEEGEEEEEEEEEEEEEEEEEEEKKKKKKKWWKKEEEEEEDDf;;;,. .,;tfLGGDDDDDDDDDDDD * *tii;,,:.. ...,. ;LEEEEEKKKKKKWKKKKWKKKKKKKKKKKKKKKKKEKKW#WEEEEEEEEEEEEEjEEEEEEEEEKEEEEGEEEEEEEEEKEEEEEEEEEEEEEEEEE#WKEEEEEEDDf;;;;,: .,itfLGGDDDDDDDDDDDD * *ti;,,,,,:. ...,. LDEEEEKKKKKKKKKKKWWWKKKKKKKKKKKKKKKWKK#W#WEEEEEEEEEEEDDLEEEEEEEEEWEEEEDEEEEEEEEEKEEEEEEEEEEEEEEEEEWWEEEEEEEDDfj,,,,,:. .,itfGGGDDDDDDDDDDDD * *tii,,,,::::. ...,: .fDEEEEKKKKKKWKKKKWWWKKKKKKKKKKKKKKKEKKW#WWEEEEEEEEEEEKiKEEKEEEEEEWEEEEDEEEEEEEEEEEEEEEEEEEEEEEEEEEWWEEEEEEEDDLD:::,,,:. .,ijfGGGDDDDDDDDDDDD * *ti;:::::::::.. .:.,: LDEEEEKKKKKKKWKKKKWWKKKKKKKKKKKKKKKKtKKWWWWKEEEEEEEEEDiiDEEEEEEEEWWEEEEEEDEEEEEEEEEEEEEEEEEEEEEEEEEEWKEEEEEDDDGL:. .:,,,: .,ijLGGGDDDDDDDDDDDD * *tt;. .::::::::.. ...,: :fDEEEKKKKKKKKKKKKWW#KKKKKKKKKKKKKKKKfKKWWWWKEEEEEEEEDti,DEKEEEEEEWWEEEDEEEEEEEEEKEEEEEEEEEEEEEDEEEEE#WEEEEEGGDGf:. .:,;,:. .,ijLGGDDDDDDDDDDDDD * *tt;. .:::::::.. ...,: GDEEEKKKKKKKKWKKKKWWWKKKWKKKKKKKWWWKDEKLWWWWKKEEEEEEDEi,LDEEEEEEEEWWEEEEEEEEEEEEEEEEEEEEEEEEEDEDEEEEEW#EEEEDDDDGf,. :,,,:...,ijLGGGDDDDDDDDDDDD * *tt;. .....::::.. ...,: fDEEEKKKKKKKKWKKKKWWWWKKKWKKKKKKKKKKfWKiWWW#KKEEEEEEEi;.EDfEEEDEEiWWEEEEEEEEEEEEDGKEEEEEEEEEEDEEEEEEEWWEEEEDDDGGLi. .,;,:::,ijLGGGDDDDDDDDDDDD * *tt;. ....:::::. ...,. iDEEEEKKKKKKKKWKKWKWWWWWKKWWWKKKKKKKKtWKt#WWWKKEEEEEDji..DDKDDEDEGiWKEEEEEEEEEEDDEjEEEEEEEEEEEDEEEEEEEKWKEEDDDDGGff. .:,;,,;ijLGGGDDDDDDDDDDDD * *tt;. ....::::.. .:.,: .LDEEEKKKKKKKKKKKKWWWWKWWWWWWWWWWKKKKWtKKiDWWWKKKEEEEKi:..DEDDDDDDiiWKEEEEEEEEEEDDEijDEEEEEKEEEEEEEEEEEEWWEEGDDDGGLG. .:,;;iijLGGGDDDDDDDDDDDD * *tt;. .....:::.. ...,. .fEEEEKKKKKKKKWKKKKWWWWWWWWWWWWWWKWKKKiKDiLWWWWKEEEEEi,..fD:DDDDDti;WEEEEEEEEEEKDDi:iDDEEEEWEEEEEEEEEEEE#WEEGDDDDGGG. :,iitjLGGGDDDDDDDDDDDD * *tti. .....:::.. ...,. GDEEEKKKKKKKKKWKKKWWW#WWWWWWWWWWWKWKKjiEjitWWWKKWEEEDi...DDLDDDDji;;WEEEEEEEEEEEDEj.iDDEEEEWEEEEEEEEEEEEWWEEDDDDDDGf. .,;tjfLGGDDDDDDDDDDDD * *tti. ....::::.. ...,. fEEEKKKKKKKKKKKKKKKW#WWWWWWWWWWWWWWWWtiEiiiWWWKKEWKEi....D.EDDDEi;.fWEEEEEEEEEEDDfL.;EDDEEEWEEEEEEEEEEEEWWEEEDDDDDGf. :;ijfLGGDDDDDDDDDDDD * *tti. ....::::.. ...,. LDEEEKKKKKKKKKKKKKKWWWWWWWWWWWWWWWW####WKiiiWWWKKKEEK,...:E:DDDEii..GWEEEEEEEEDWDDiL.,KDDEEEWEEEEEEEEEEEEWWKEEDDDDDGf: .,itfLGGDDDDDDDDDDDD * *tti. .....:::.. ...,. fDEEEKKKKKKKKKWKKKKWWWWWWWWWWWWW########WLiiWWWKKKEEjD...G,DDDDi;...EWEEEEEEEEDKDEii..LDDEEEWEEEEEEEEEEEEWWWEEDDDDDGfi .,;tfLGGGDDDDDDDDDDD * *tti. .....:::.. ...,. iGEEEKKKKKKKKKKWKKKKWWWWWWWWWWWW###########KiWWWKKEEE,.D..D.DDDii:...KKEEEEEEEEEDDj:...tEDEEEWEEEEEEEEEEEEWWWEEEDDDDDLL .,;tjLLGGDDDDDDDDDDD * *tti. ....::::......:. LEEEKKKKKKKKKKWWKKKWWW#KWWWWWWWW#####W####W##KWWKKEEL..:D.jjDDi;,....KKEEEEEEEDfDDi...:iKDEEEWKEEEEEEEEEEEWWWEEEEDDDDLG .,;tjLLGGDDDDDDDDDDD * *tti. ...::::::..,. :GEEEKKKKKKKKKKKKWWWWW##WWWWWWWWW##WKWK#W#W####WWKEEK.....G.DDti,.....KKEEEEEEDWGDf.,...iKDEEEWWEEEEEEEEEEEW#WEEEEEDDDGL .,;tjLLGGDDDDDDDDDDD * *tti. ....::::::,. GDEEKKKKKKKKKKKKKWWWW###WWWWWWWWWW#WWWK###W#####WKEKK.....jDDL;;......KKEEEEEEEEEDi.f...;KDEEEWWEEEEEEEEEEEWWWWEEEEEDDGf .,;tjLLGGDDDDDDDDDDD * *tti. ....:::,,. .LEEEKKKKKWKKKKKWWWWWW###WWWWWWWWWW#WWKW#WW##W#WWWKEKD:....:DD:;......;KEEEEEEEKiDD..f...,KKEEEWWEEEEEEEEEEEWWWWEEEEEDDDf .:;tjLLGGGDDDDDDDDDD * *tti. ...::,,,:. GDEEKKKKKKKKKKKKWWWWWWW#WWWWWWWWWWW#KjKWWWWWWWWWWWWEK.j,..;fD.;.......fKEEEEEDKG:Di..,....DKEEEWWEEEEEEKEKKKWWWWEEEEEEDDf .:;tjLLGGDDDDDDDDDDD * *jti. ...::,,,,:. .fEEEKKKKKWKKKKKKWWWWWWW#WWWWWWWWWWK#KKKWWWWWWWWWWWWWK..f:.:G.,:.......EKEEEEEKK;:E:.......fKEEEWWKEKEKKKKKKKW#WWEEEEEEDDf: .,;tfLLGGDDDDDDDDDDD * *tti. ...:,,,;;,: iDEEKKKKKWKKKKKKKWWWWWWW#WWWWWWWWWWK#WDKWWKKWWWWWWWWWE..;G:G..,........KKEEEEEKi.Gi..:.....tKEEKWWWKKKKKKKKKKW##WKEEEEEEDfi .,;tfLLGGGDDDDDDDDDD * *tti. ....::,,;;;,LEEKKKKKKWKKKKKWWWWWWW###WWWWWWWWWWKWWDKWEEEWKKWWWWWKKj.:LG..;.........EKEEEEKG;.G...;.....;KKEKWWWKKKKKKKKKKW##WWKEEEEEDfL .,;tfLGGGDDDDDDDDDDD * *jti. ...::::,;ijDEEKKKKKWKKKKKKWKWWWWW##WWWWWWWWWWWKK#KKGDGDWEEWKKWKKGE,.i;.:.........:EKEEEKE;.:L...j.....,KWEKWWWKKKKKKKKKK####WKKEEEEDLG .,;tfLGGGGDDDDDDDDDD * *jti. ...:...,,;GEEKKKKKWWKKKKKWWWWWWWW###WWWWWWWWWKKKWWKiLGGEDEDEKGKKiEG..;...........jKEEEKK;:.G....,.....:KKEWWWWKKKKKKKWKK####WKKKKEEEGL .,;tfLGGGGDDDDDDDDDD * *jti. ...:. .:,GEEKKKKKWKKKKKWWWWWWWW####WWWWWWWWWKKKWWKii;fDLGDK: EEi:E:.............EKEEKK;;..L...........KKKWWWWKKKKKKKWKK####WKKKWKEEDf .,;tfGGGGDDDDDDDDDDD * *jti. ...:. ,EEKKKKKWWKKKKKWWWWWWWWW###WWWWWWWWKKKKfWWLt;i,. fi EG..D:.............EKEKK;;..t....:.......KWKWWWWKKKKKKKWKK####WKKKWEEEDf:. .,;tfGGGGDDDDDDDDDDD * *jti. ...:. GEEKKKKKWKKKKKWWWWWWWWW####WWWWWWWKKKKKt;KKEfff .;t.................KKKKi;:..GtGGfG.......KWWWWWWKKKKKKKWKK###WWWKKKKEEEf,,: .,;tfGGGGDDDDDDDDDDD * *jti. ...:. GEKKKKKWWKKKKKWWWWWWWWWW##WWWWWWWKKKKKKt;EiKKKK, ...t................jEKKG;;..,.....,LGi....KWWWWWWKKKKKKWKKKW####WKKKKKEEL,,,:. .,;tfGGGDDDDDDDDDDDD * *jti. ...:. .GEEKKKKKWKKKKKWWWWWWWWWW###WWWWWWWKKKKKKtiE::tGG........................EEEj;;...,.........:D..DKWWWWWWKKKKK#KKW###W#WKKKKKEEfj:,,,:. .,;tfGGGDDDDDDDDDDDD * *jti. ...:. DEKKKKKWWKKKKKWWWWWWWWW####WWWWWWWKKKKKKiiE:::.::.......................EEi;;...j.....f......:iDKWWWWWWKKKKK#WW######WKKKKKEELG :,,,,:. .,;tfGGGDDDDDDDDDDDD * *jti. ...:. fEEKKKKWWKKKKWWWWWWWWWWW###WWWWWWWWKKKKKK;tE::..........................DD;.;,.::......;........EWWWWWWWKKKKW#WW#####WWKKKWKKELG .:,,,:::,;tfGGGDDDDDDDDDDDD * *jti. ...:. .DEKEKKKWWKKKKWWWWWWWWWWW###WWWWWWWWKKKKKE,iD::..........................D..,;.,;tLffi...........DWDWWWW#KKKWWWWW#####W#KKKWKEEGL .:,;,,,;tfGGGDDDDDDDDDDDD * *jti. ...:. ;EEKKKKWWKKKKKWWWWWW#WWWW####WWWWWWKKKKKEL:iD:..........................j ..;..;;:.....i,........DKtWWWWWKKWWWWWW#####WWWKKKEKEDf .:,;;;itfGGGDDDDDDDDDDDD * *jti. ...:. DEKKKKKWWKKKKWWWWWWW#WWWW####WWWWWWKKKKKEj:iG...............................:....................GKiWWWWWKKWW#WWW######WWKKKKKEEf .,;iitfGGGDDDDDDDDDDDD * *jti. ...:.:EKKKKKWWKKKKKWWWWWWW#WWW#####WWWWWKWKKKKEi:if:.................................iEKEKKKKKKDj......DKiWWWWWKWK##WW#######WWKKK:KEEL .:;itfGGGDDDDDDDDDDDD * *jji. ...:,DEEKKKWWWKWKKWWWWWWWWWWWW#####WWWWWWWKKKKEi:it..................................j. KKKKKKKKKKKf..DKiWWWWWKWW##WW#######WWKKK,KEEf .,;tfGGGDDDDDDDDDDDD * *jji. ..L:iDEEKKKWWKKKKKWWWWWWWWWWWW#####WWWWWKWKKKKKi.i;.................................. . KKKWWWWWWWWK..DGiWWWWWKK##WWW#####W#WWKKKjEKEL, .:;tfGGGDDDDDDDDDDDD * *jji. .f:::EEEKKKWWWKKKKKWWWWWWWWWWWW#####WWWWWKWKKKKK;.i,.................................:: KKEKWWWWWWfWK..EiiWWWWWKWW#WW##########KKKD,KELj .:;tfGGDDDDDDDDDDDDD * *jji. .t::::,DEEKKKWWKKKKWWWWWWWWW#WWWW#####WWWWKKWKKKEK;.i:.................................GDDEEEKKKWWWWWtWWD.E;iWWWWWW###WW#########WWKKK.EEDG .:;tfGGGDDDDDDDDDDDD * *jji. . j..::::EKEKKKWWWKKKKWWWWWWWWW#WWW######WWWWKKWKKKEK;.t:.................................ELLEDDEEEWWWWEtWK,.KiiWWWWWW###W##########WWKKK:EEEG .;tjfLLGDDDDDDDDDDDDDDD * *jji. i.::::::,EEEKKWWWKKKKKWWWWWWWWW#WWW#####WWWWWKWKKKKEE,.t..................................DfiEGDDDEEKKKttKWG.KiiWWWWW##WWW##########WWKKK:fEEL ,fGGGDDDDDDDDEEEDDDDDDDDDD * *jji. .;:..:::::DEEEKKWWWKKKKKWWWWWWWWW#WWWW####WWWWWWWKKKKED,.t..................................ifjDDGGEGDKK.ttKKE.DiWWWWW###WW##########WWWKKK:.KELiLGGGGDDDDDDDDDDDDEEEDDDDDDD * *jji. i.:.::::::,KEEKKWWWKKKKKKWWWWWWWWW#WWWW####WWWWWWWKKKKEL:.j..................................GGf,;ifLLED .iiKKi:fWWWWWW##W#W##########WWWKKK:.KKLGGDDDDDDDDDDDDDDDDEDDEEDDDDD * *jji. .j:.::::::::EEEKKKWWWKKKKKKWWWWWWWW##WWW#####WWWWWWWKKKKKf:.f..................................:EEfftf .,. ;iE,..jWWWWWWW###W############WWKKK,:KKGDDDDDDDDDDDDDDDDDDDDDDDEDDDD * *jji. .:.::::::::,,EEEKKWWWKKKKKKKWWWWWWWW##WWW#####WWWWWWWKKKKKt..G....................................EEELL; .j....tKWWWWWWW################WWWKKtfGKGEDDDDDDDDDDDDDDDDDDDDDDDEEDD * *jji. :...:::::::,,jEEKKWWWWKKKKKKWWWWWWWWW##KWW#####KWWWWWWKKKKEi..D....................................:jEEE.........;KKWWWWWWWW#WW##W##########WWKKDLGKEKDDDDDDDDDDDDDDDDDDDDDDDDDED * *jji. i:.::::::::,,,EEEKKWWWWKKKKKWWWWWWWWWW##WWW#####WWWWWWWKKKKKi..D......................................:::::......,KKKWWWWWWWWW#####W########WWWKKKGGKKEGGGGGGGGDDDDDDDDDDDDDDDDDDE * *jji. i..:::::::::,,tEEKKWWWWKKKKKWWWWWWWWWWW##WW######WWWWWWWKKKKKi..D......................................::::......:EKKKWWWWWWWWWWW##WW########W#WKKWGGKKGGGGGGGGGGGGGGGDDDDDDDDDDDDD * *jji. .:::::::::::,,,EEEKKWWWWKKKKKWWWWWWWWWWW##WW#####WWWWWWWWKKKKKi..D....................................:::::::::..tELii;KWWWWWWWWWW##WW######WWWWWWKWGGGKGGGGGGGGGGGGGGGGGGGGGGGGGGDG * *jjt. :.::::::::,,,,fEEKKWWWWKKKKKKWWWWWWWWWW###WW####WWWWWWW#WKKKKKi..D....................................:::::::.:.,;;;;;;,KKWWWWWWWWW#WW########WWWKKWGGGKGGGGGGGGGGGGGGGGGGGGGGGGGGGG * *jji. ;.::::::::,,,,;EEEKWWWWWKKKKKWWWWWWWWWWWW##WW###WKWWWWWK#WKKKKKi..G......................................:::::::,;;;;:...KKKWWWWWWWWWKWW#######WWWWKKGLGKDGGGGGGLLGGGGGGGGGGGGGGGGGGG * *jjt. f.:::::::::,,,,fEEKKWWWWWKKKKKWWWWWWWWWWW###WW##WKKWWWWWW#WKKKKK;.jt........i.............................:::::::;j;;....:E.KKKWWWWWWWKWW#####W#WWWWKKLLGWEEGGGGGLGGGGGGGGGGGGGGGGGGGG * *jjt. ...:::::::,,,,,;DEEKWWWWWKKKKKWWWWWWWWWWWW####WWWKKKWWWWWWWWKKKKK;.E;.........t.............................:::::ii;;.....D...KKWWWWWWWKWW#####WWEWWWKKGGGEKKGGGGGLGGGGGGGGGGGGGLGGGGGG * *fji. ;.:::::::,,,,,;LEEKKWWWWWKKKKKWWWWWWWWWWWW####KWKKKKWWWWWWWWKKKKKi.D;..........j.............................:::tt;,.....:.....KKWWWWWWKWWWW##WWWGWWWKKGGGGKEGGGGGGGGGGGGGGGGGGGLLGGGGL * *fji. t::::::::,,,,,,;EEEKWWWWWKKKKKKKWWWWWWWWWWW##WKWKKKKKWWWWWWWWKKKKKi:D;............j...........................::LL;,.............KKWWWWWKWWWWWWWWWGWWWKKGGGGKGGGGGGGGGGGGGGGGGGGGLLGGGGL * *fjt: .:::::::,,,,,,,DEEKWWWWWWKKKKKKKWWWWWWWWWWWWKKWKKKKKKWWWWK#WWKKKKWitE;........... ............................:G;;:...............KKKWWKKWWWWWWWWWGWWWKKGGGGWGGGGGGGGGGGGGGGGGGGGGGGGGGL * *fjji;:. .f:::::::,,,,,,,;EEEKWWWWWWKKKKKKWWWWWWWWWWWKKKKKKKKKKKWWKWWWWWKKKKWGKD;........................................L;;..................DKKWKKWWWWWWWWWGWWWKKDGGGKDGGGGGGGGGGGGGGGGGGGGGGGGGG * *fjjtii;,:. :::::::,,,,,,,;EEEKWWWWWWKKKKKKWWWWWWWWWWKKKKKKKKKKKKWWWWWW#WWKKKKWiEj;......................................:i,;....,...............;KKEKWWWWWWWWWGKWWKKDDGGDEGGGDGGGGGDGGGGGGGGGGGGGGGG * *fjtiiiii;;:. j::::::,,,,,,,;;EEEKWWWWW#KKKKKWWWWWWWWWKKKKKKWKKKKKKKWWWWWWWWWKKKKWtEL;:....................................;;;:...,;j................:KEEWWWWWWWWWDDWWKKDDDDDKDDDDDDDDDDDDDDDGGGGGGGGGGG * *fjti;;iiii;;,:::::::,,,,,,,,;EEEKWWWWWWWKKKKWWWWWWWWKKKKKKKWKKKKKKKWWWWWWW#W#KKKKWEEii;...................................f;:....,;L...................EEKWWWWWWWWDDWWKKDDDDDKEDDDDDDDDDDDDDDDDDDDDDGGGG * *fjt,,,;;;;ii;f::::::,,,,,,,;;EEKWWWWWWWKKKKKWWWKWWKKKKKKKKKKKKKKKKKWWWWWWW#W#KKKKWKEij;:...............................:G;,.....,;f....................:tKKWWWWWWWDDWWKKDDDDDKKDDDDDDDDDDDDDDDDDDDDDDDDD * *jjt. ..:,;;;;,::::,,,,,,,,;;GEEWWWWWWWWKKKKWKKWKKKKKKKKKKKKKKKKKKKKWWWWWWW#W#KKKKWEDi;j;............................,Li;L;;;..,;;f........................KKKKWWWKDDWWKKDDDGDKKGGGGGGGGDGDDDDDDDDDDDDDDD * *fjt. .:,,,:::::,,,,,,,;;;EEKWWWWWWWKKKKKKWKKKKKKKKKKKKKKKKKKKKKWKKKWKW##W#KKKKWEti;;G;........................tEEEL;;;;;;;;;;L..........................DKKKKKEDDWWKEDGftiLE;;;;itjLGGGGGGDDDDDDDDDDD * *fjt. .j::::,,,,,,,;;;DEEWWWWWWWWKKKKWKKKKKKKKKKKKKKKKKKKKKKKWKKWWWK##W#KKKKKEii;;;L;...................iDEEEEEEKKi;j;;;;jD.....:......................,KKKKDGGEKKE:::::;E::::::::::,tLGGDDDDDDDDDD * *fjt. .;:::,,,,,,,;;;;EEKWWWWWWWWKWKKKKKKKKKKKKKKKWKKKKKKKKKKWKKWWWW#WW#KKKKKKii;;;;f;.............:tDEEEEEKKKKKKKKEti;;;L...............................EEKf;:iKKE::::::E::::::::::::::ifDDDDDDDDD * *fjt: :::,,,,,,,,;;;DEEWWWWWWWWWEKKKKKKKKKKKKKKKKKKKKKKKKKKWWKKWWWW####KKKKKEiii;;;;f,.........iDEEEEKKKKKKKKKKKKKKKf;iG......i..........................fK::::KKE::::::E::::::::::::::::,tGGDDDDD * *fjt: t:::,,,,,,;;;;iDEKWWWWWWKEKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWKKWWWW####WKKKKLiii;;;;;L,....,Li;EDEEEEKKKKKKKKKKKKKKKKiG......;:...........................:i:::KKE:::::,E,::::::::::::::::::iGDDDD * *jjt. f::,,,,,,,;;;;GEEWWWWKEEKEKKKKKKKKKKKKKKKKWKKKKKKKKKKKWWKWWWWW###WWKKKKiii;;;;;;;G,;L;;iiEEEEEEEKKKKKKKKKKKKKWWKE......;t.........:....................j::KEE:,::,,D,,::::,,,,,,:::::::::tDDD * *fjt:. ,::,,,,,,,;;;;EEWWKEEEEEEKKKKKKKKKKKKKKKKWKKKKKKKKKKKWWKKWWWWW#W#KKKKKKiiiiii;;;;;i;;iiiEEKEEKKWKKKKKKKWKKKKKWWWGi;...;t......,;;;;,....................:,EEE,,,,,,D,,,,,,,,,,,,,,,,::,::::tG * *fjt:. ,::,,,,,,,;;;;DEKEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWWW#W#KKKKKKiiiii;;i;;;;;iiiKKKEKKKKWWKWWWWWWKKKKWWWWW;;;:;L.....;;;;;;;;;....................,KEE,,,,,,E,,,,,,,,,,,,,,,,,,,,,,,,; * *fjt:. f:,,,,,,,;;;;jEDEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWW#W##KKKKKKiiiiiiii;i;;iiiEKKKKKKKKWKWWWWWWWWKKKWWWWWKi;;i.....,jEEfGi;;;;;...................EED,,,,,,E,,,,,,,,,,,,,,,,,,,,,,,,, * *fjt:. .f::,,,,,,;;jEEDEEEEEEEEEEKKKKKKKKKKKKKKKWKKKKKKKKKKKKKWWWKWWWWW###KKKKKLiiiiiiiiiiiiiiEEKKKKKKKKWWWWWWWWWWWWKWWWWWWGi;i;,..;jDDDKEGi;;;;;;:................EED,,,,,,D,,,,,,,,,,,,,,,,,,,,,,,,, * *fjt:. .. ;::,,,,,;;EDDEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWKKW#WW####KWKKKiiiiiiiiiiiiijKKKKKKKKKKWWWWWWWWWWWWWWWWWWWWWt;i;;;;i;DDDDDDGi;;;;;;;;:.............EDf;,,,;,G;;;;;;;;;;;;;;;,,,,,,,,,, * *fjt:......:,,,,,,;LDDDEEEEEEEEEEEKKKKKKKKKKKKKKKKWKKKKKKKKKKKKKWWWWKWWWW####KKKKKiiiiiiiiiiijKEKKWKKKKKKKWWWWWWWWWWWWWWWWWWWWWWiLiii;i;DEEEEDDE;i;;;;;;;;;:..........EDi,;;;;;L;;;;;;;;;;;;;;;;;;,,,,,,, * *fjt:......:,,,,,;EDDDEEKEEEEEEEEEKKKKKKKKKKKKKKKWKKKKKKKKKKKKKKWWWWKKWWW##W#KWKKWEiiiiiijGKKKKKWWKKKKKKKKWWWWWWWWWWWWWWWWWWWWWWKi;iiiiDDEEEEEEDEi;;;;;;;;;;;;;,:.....ED;;;;;;;j;;;;;;;;;;;;;;;;;;;;;;;,, * *fjt:.....t,,,,,;DDDDEEEKEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWWKKKWWWW##WKWKKWKiiiKKKKKKKKKWWKKKKKKKKWWWWWWWWWWWWWWW#WWWWWWWWWiiiiifLEEEEEEEEDi;i;;;;;;;;;;;;.....DD;;;;;;;i;;;;;;;;;;;;;;;;;;;;;;;;; * *fjt:.....G,,,,,GDDDEEEEEEEEEEEEKKKKKKKKKKKKKKKKWKKKKKKKKKKKKKKKWWWKKKWWW###WKWKKWKitKKKKKKKKKWKKKKKKKKKKWWWWWWWWWWWWWW###WWWWWWWWEiiiiiiiEEEEEEEEDGiiii;;;;;;;;;.....GD;;;;;;;i;;;;;;;;;;;;;;;;;;;;;;;;; * *fjt:.....L,,,,;GDDDEEEEEEEEEEKEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWDGWWW###KKWWKWKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWW####WWWWWWWWWiiiiiiiiEEEEEEEEEEDi;i;;;;;;;;.....Lj;;;;;;i;iiiiii;;;;;;ii;;;;;;;;;;; * ***********************************************************************************************************************************************************************************************************/ // Classes static class Edge implements Comparable<Edge>{ int l,r; Edge(){} Edge(int l,int r){ this.l=l; this.r=r; } @Override public int compareTo(Edge e) { return (l-e.l)!=0?l-e.l:r-e.r; } } static class Segment implements Comparable<Segment> { long l, r, initialIndex; Segment () {} Segment (long l_, long r_, long d_) { this.l = l_; this.r = r_; this.initialIndex = d_; } @Override public int compareTo(Segment o) { return (int)((l - o.l) !=0 ? l-o.l : initialIndex - o.initialIndex); } } 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 s=""; try { s=br.readLine(); } catch (IOException e) { e.printStackTrace(); } return s; } } // Functions static long gcd(long a, long b) { return b==0?a:gcd(b,a%b); } static int gcd(int a, int b) { return b==0?a:gcd(b,a%b); } void reverse(long[] A,int l,int r) { int i=l,j=r-1; while(i<j) { long t=A[i]; A[i]=A[j]; A[j]=t; i++;j--; } } void reverse(int[] A,int l,int r) { int i=l,j=r-1; while(i<j) { int t=A[i]; A[i]=A[j]; A[j]=t; i++;j--; } } //Input Arrays static void input(long a[], int n) { for(int i=0;i<n;i++) { a[i]=inp.nextLong(); } } static void input(int a[], int n) { for(int i=0;i<n;i++) { a[i]=inp.nextInt(); } } static void input(String s[],int n) { for(int i=0;i<n;i++) { s[i]=inp.next(); } } static void input(int a[][], int n, int m) { for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { a[i][j]=inp.nextInt(); } } } static void input(long a[][], int n, int m) { for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { a[i][j]=inp.nextLong(); } } } }
Java
["4", "2"]
1 second
["3 4 1 2", "2 1"]
NoteIn the first sample, you can build a permutation $$$[3, 4, 1, 2]$$$. LIS is $$$[3, 4]$$$ (or $$$[1, 2]$$$), so the length of LIS is equal to $$$2$$$. LDS can be ony of $$$[3, 1]$$$, $$$[4, 2]$$$, $$$[3, 2]$$$, or $$$[4, 1]$$$. The length of LDS is also equal to $$$2$$$. The sum is equal to $$$4$$$. Note that $$$[3, 4, 1, 2]$$$ is not the only permutation that is valid.In the second sample, you can build a permutation $$$[2, 1]$$$. LIS is $$$[1]$$$ (or $$$[2]$$$), so the length of LIS is equal to $$$1$$$. LDS is $$$[2, 1]$$$, so the length of LDS is equal to $$$2$$$. The sum is equal to $$$3$$$. Note that permutation $$$[1, 2]$$$ is also valid.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
6ea899e915cfc95a43f0e16d6d08cc1e
The only line contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of permutation that you need to build.
1,600
Print a permutation that gives a minimum sum of lengths of LIS and LDS. If there are multiple answers, print any.
standard output
PASSED
51396af15d2b023776d969c64e0f193b
train_003.jsonl
1533737100
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!The only thing Mrs. Smith remembered was that any permutation of $$$n$$$ can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.The sequence of $$$n$$$ integers is called a permutation if it contains all integers from $$$1$$$ to $$$n$$$ exactly once.The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS). A subsequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ where $$$1\leq i_1 &lt; i_2 &lt; \ldots &lt; i_k\leq n$$$ is called increasing if $$$a_{i_1} &lt; a_{i_2} &lt; a_{i_3} &lt; \ldots &lt; a_{i_k}$$$. If $$$a_{i_1} &gt; a_{i_2} &gt; a_{i_3} &gt; \ldots &gt; a_{i_k}$$$, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.For example, if there is a permutation $$$[6, 4, 1, 7, 2, 3, 5]$$$, LIS of this permutation will be $$$[1, 2, 3, 5]$$$, so the length of LIS is equal to $$$4$$$. LDS can be $$$[6, 4, 1]$$$, $$$[6, 4, 2]$$$, or $$$[6, 4, 3]$$$, so the length of LDS is $$$3$$$.Note, the lengths of LIS and LDS can be different.So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main3 { 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;} } // |----| /\ | | ----- | // | / / \ | | | | // |--/ /----\ |----| | | // | \ / \ | | | | // | \ / \ | | ----- ------- static int n; static PrintWriter out; public static void rec(int start1,int value) { int val=start1-(int)Math.sqrt(value); for(int i=0;i<n;i++) { if(i%(int)Math.sqrt(value)==0) { val+=2*(int)Math.sqrt(value); if(val>n) val=n; out.print(val+" "); val--; } else { out.print(val+" "); val--; } } } public static void main(String[] args)throws IOException { out= new PrintWriter(System.out); Reader sc=new Reader(); n=sc.i(); rec(0,n); out.flush(); } }
Java
["4", "2"]
1 second
["3 4 1 2", "2 1"]
NoteIn the first sample, you can build a permutation $$$[3, 4, 1, 2]$$$. LIS is $$$[3, 4]$$$ (or $$$[1, 2]$$$), so the length of LIS is equal to $$$2$$$. LDS can be ony of $$$[3, 1]$$$, $$$[4, 2]$$$, $$$[3, 2]$$$, or $$$[4, 1]$$$. The length of LDS is also equal to $$$2$$$. The sum is equal to $$$4$$$. Note that $$$[3, 4, 1, 2]$$$ is not the only permutation that is valid.In the second sample, you can build a permutation $$$[2, 1]$$$. LIS is $$$[1]$$$ (or $$$[2]$$$), so the length of LIS is equal to $$$1$$$. LDS is $$$[2, 1]$$$, so the length of LDS is equal to $$$2$$$. The sum is equal to $$$3$$$. Note that permutation $$$[1, 2]$$$ is also valid.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
6ea899e915cfc95a43f0e16d6d08cc1e
The only line contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of permutation that you need to build.
1,600
Print a permutation that gives a minimum sum of lengths of LIS and LDS. If there are multiple answers, print any.
standard output
PASSED
f2757993476cde802a03e7d43f88c5ad
train_003.jsonl
1533737100
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!The only thing Mrs. Smith remembered was that any permutation of $$$n$$$ can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.The sequence of $$$n$$$ integers is called a permutation if it contains all integers from $$$1$$$ to $$$n$$$ exactly once.The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS). A subsequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ where $$$1\leq i_1 &lt; i_2 &lt; \ldots &lt; i_k\leq n$$$ is called increasing if $$$a_{i_1} &lt; a_{i_2} &lt; a_{i_3} &lt; \ldots &lt; a_{i_k}$$$. If $$$a_{i_1} &gt; a_{i_2} &gt; a_{i_3} &gt; \ldots &gt; a_{i_k}$$$, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.For example, if there is a permutation $$$[6, 4, 1, 7, 2, 3, 5]$$$, LIS of this permutation will be $$$[1, 2, 3, 5]$$$, so the length of LIS is equal to $$$4$$$. LDS can be $$$[6, 4, 1]$$$, $$$[6, 4, 2]$$$, or $$$[6, 4, 3]$$$, so the length of LDS is $$$3$$$.Note, the lengths of LIS and LDS can be different.So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
256 megabytes
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.InputMismatchException; import java.util.List; public class Main { private static final int MAXN = 5000; private static final String NO = "NO"; private static final String YES = "YES"; InputStream is; PrintWriter out; String INPUT = ""; private static final long MOD = 1000000007L; void solve() { int n = ni(); int k = (int) Math.sqrt(n); if (k * k < n) k++; for (int c = n - k; c > -k; c -= k) { for (int i = 1; i <= k; i++) if (c + i > 0) out.append(" " + (c + i)); } } long power(long a, long b) { long x = 1, y = a; while (b > 0) { if (b % 2 != 0) { x = (x * y) % MOD; } y = (y * y) % MOD; b /= 2; } return x % MOD; } private long gcd(long a, long b) { while (a != 0) { long tmp = b % a; b = a; a = tmp; } return b; } void run() throws Exception { is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); if (!INPUT.isEmpty()) tr(System.currentTimeMillis() - s + "ms"); } public static void main(String[] args) throws Exception { new Main().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private boolean vis[]; 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) { if (!(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 List<Integer> na2(int n) { List<Integer> a = new ArrayList<Integer>(); for (int i = 0; i < n; i++) a.add(ni()); return a; } private int[][] na(int n, int m) { int[][] a = new int[n][]; for (int i = 0; i < n; i++) a[i] = na(m); 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(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nl(); return a; } private long nl() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private static void tr(Object... o) { System.out.println(Arrays.deepToString(o)); } public class Pair<K, V> { /** * Key of this <code>Pair</code>. */ private K key; /** * Gets the key for this pair. * * @return key for this pair */ public K getKey() { return key; } /** * Value of this this <code>Pair</code>. */ private V value; /** * Gets the value for this pair. * * @return value for this pair */ public V getValue() { return value; } /** * Creates a new pair * * @param key The key for this pair * @param value The value to use for this pair */ public Pair(K key, V value) { this.key = key; this.value = value; } /** * <p> * <code>String</code> representation of this <code>Pair</code>. * </p> * * <p> * The default name/value delimiter '=' is always used. * </p> * * @return <code>String</code> representation of this <code>Pair</code> */ @Override public String toString() { return key + "=" + value; } /** * <p> * Generate a hash code for this <code>Pair</code>. * </p> * * <p> * The hash code is calculated using both the name and the value of the * <code>Pair</code>. * </p> * * @return hash code for this <code>Pair</code> */ @Override public int hashCode() { // name's hashCode is multiplied by an arbitrary prime number (13) // in order to make sure there is a difference in the hashCode between // these two parameters: // name: a value: aa // name: aa value: a return key.hashCode() * 13 + (value == null ? 0 : value.hashCode()); } /** * <p> * Test this <code>Pair</code> for equality with another <code>Object</code>. * </p> * * <p> * If the <code>Object</code> to be tested is not a <code>Pair</code> or is * <code>null</code>, then this method returns <code>false</code>. * </p> * * <p> * Two <code>Pair</code>s are considered equal if and only if both the names and * values are equal. * </p> * * @param o the <code>Object</code> to test for equality with this * <code>Pair</code> * @return <code>true</code> if the given <code>Object</code> is equal to this * <code>Pair</code> else <code>false</code> */ @Override public boolean equals(Object o) { if (this == o) return true; if (o instanceof Pair) { Pair pair = (Pair) o; if (key != null ? !key.equals(pair.key) : pair.key != null) return false; if (value != null ? !value.equals(pair.value) : pair.value != null) return false; return true; } return false; } } }
Java
["4", "2"]
1 second
["3 4 1 2", "2 1"]
NoteIn the first sample, you can build a permutation $$$[3, 4, 1, 2]$$$. LIS is $$$[3, 4]$$$ (or $$$[1, 2]$$$), so the length of LIS is equal to $$$2$$$. LDS can be ony of $$$[3, 1]$$$, $$$[4, 2]$$$, $$$[3, 2]$$$, or $$$[4, 1]$$$. The length of LDS is also equal to $$$2$$$. The sum is equal to $$$4$$$. Note that $$$[3, 4, 1, 2]$$$ is not the only permutation that is valid.In the second sample, you can build a permutation $$$[2, 1]$$$. LIS is $$$[1]$$$ (or $$$[2]$$$), so the length of LIS is equal to $$$1$$$. LDS is $$$[2, 1]$$$, so the length of LDS is equal to $$$2$$$. The sum is equal to $$$3$$$. Note that permutation $$$[1, 2]$$$ is also valid.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
6ea899e915cfc95a43f0e16d6d08cc1e
The only line contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of permutation that you need to build.
1,600
Print a permutation that gives a minimum sum of lengths of LIS and LDS. If there are multiple answers, print any.
standard output
PASSED
1809bb22d59d988036508180c22816ed
train_003.jsonl
1533737100
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!The only thing Mrs. Smith remembered was that any permutation of $$$n$$$ can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.The sequence of $$$n$$$ integers is called a permutation if it contains all integers from $$$1$$$ to $$$n$$$ exactly once.The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS). A subsequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ where $$$1\leq i_1 &lt; i_2 &lt; \ldots &lt; i_k\leq n$$$ is called increasing if $$$a_{i_1} &lt; a_{i_2} &lt; a_{i_3} &lt; \ldots &lt; a_{i_k}$$$. If $$$a_{i_1} &gt; a_{i_2} &gt; a_{i_3} &gt; \ldots &gt; a_{i_k}$$$, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.For example, if there is a permutation $$$[6, 4, 1, 7, 2, 3, 5]$$$, LIS of this permutation will be $$$[1, 2, 3, 5]$$$, so the length of LIS is equal to $$$4$$$. LDS can be $$$[6, 4, 1]$$$, $$$[6, 4, 2]$$$, or $$$[6, 4, 3]$$$, so the length of LDS is $$$3$$$.Note, the lengths of LIS and LDS can be different.So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
256 megabytes
import java.io.*; import java.util.*; public class C1017 { static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(int[] array) { for (int i = 0; i < array.length; i++) { if (i != 0) writer.print(' '); writer.print(array[i]); } } public void printLine(int[] array) { print(array); writer.println(); } public void close() { writer.close(); } } static class Pair { int value; int index; Pair(int value, int index) { this.value = value; this.index = index; } } static class MyComparator implements Comparator<Pair> { @Override public int compare(Pair p1, Pair p2) { if (p1.value != p2.value) return p1.value - p2.value; return p1.index - p2.index; } } static int bsearch(int[] arr, int k) { int start = 0; int end = arr.length - 1; while (start < end) { int mid = start + (end-start) / 2; if (arr[mid] == k) { return mid; } else if (arr[mid] < k) { start = mid+1; } else { end = mid - 1; } } return start; } public static void main(String[] args) { OutputStream outputStream = System.out; OutputWriter out = new OutputWriter(outputStream); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); Scanner sc= new Scanner(System.in); int n = sc.nextInt(); int[] arr = new int[n]; if (n==1) arr[0] = 1; else if (n==2) { arr[0] = 2; arr[1] = 1; } else if (n ==3) { arr[0] = 3; arr[1] = 1; arr[2] = 2; } else { int[] temparr = new int[320]; for (int i=1; i<=320; i++) { temparr[i-1] = i*i; } //for (int i=0; i<=10; i++) System.out.println(temparr[i]); int index = bsearch(temparr, n); //System.out.println(index); Stack<Integer> stack = new Stack<>(); if (temparr[index] == n) { int x = (int)Math.sqrt(n); //System.out.println("Yo"); int idx = 1; int times = 1; for (int i=0; i<n; i++) { if (times != 1 && times % (int)Math.sqrt(n) == 1) { x = (int)Math.sqrt(n) * (++idx); times = 1; } times++; //System.out.println("x="+x); stack.push(x); x -= 1; } for (int i=0; i<n; i++) { arr[i] = stack.pop(); } } else { //index--; if (index>0 && temparr[index]>n) index--; int remainingCount = n % (int)Math.sqrt(temparr[index]); //System.out.println("Remaining:" + remainingCount); int x = (int)Math.sqrt(n); //System.out.println("index="+index); //System.out.println("Yo"); int idx = 1; int times = 1; for (int i=0; i<n-remainingCount; i++) { //System.out.println("Yo"+i); if (times != 1 && times % (int)Math.sqrt(n) == 1) { x = (int)Math.sqrt(n) * (++idx); times = 1; } times++; //System.out.println("x="+x); stack.push(x); x -= 1; } x = n; while (remainingCount>0) { stack.push(x); x--; remainingCount--; } for (int i=0; i<n; i++) { arr[i] = stack.pop(); } } } //int n = in.readInt(); //int[] temparr = IOUtils.readIntArray(in, n); //int[] rating = new int[n]; out.printLine(arr); out.close(); } }
Java
["4", "2"]
1 second
["3 4 1 2", "2 1"]
NoteIn the first sample, you can build a permutation $$$[3, 4, 1, 2]$$$. LIS is $$$[3, 4]$$$ (or $$$[1, 2]$$$), so the length of LIS is equal to $$$2$$$. LDS can be ony of $$$[3, 1]$$$, $$$[4, 2]$$$, $$$[3, 2]$$$, or $$$[4, 1]$$$. The length of LDS is also equal to $$$2$$$. The sum is equal to $$$4$$$. Note that $$$[3, 4, 1, 2]$$$ is not the only permutation that is valid.In the second sample, you can build a permutation $$$[2, 1]$$$. LIS is $$$[1]$$$ (or $$$[2]$$$), so the length of LIS is equal to $$$1$$$. LDS is $$$[2, 1]$$$, so the length of LDS is equal to $$$2$$$. The sum is equal to $$$3$$$. Note that permutation $$$[1, 2]$$$ is also valid.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
6ea899e915cfc95a43f0e16d6d08cc1e
The only line contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of permutation that you need to build.
1,600
Print a permutation that gives a minimum sum of lengths of LIS and LDS. If there are multiple answers, print any.
standard output
PASSED
a0b514da755b0d9239f56a2e7b9b689d
train_003.jsonl
1533737100
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!The only thing Mrs. Smith remembered was that any permutation of $$$n$$$ can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.The sequence of $$$n$$$ integers is called a permutation if it contains all integers from $$$1$$$ to $$$n$$$ exactly once.The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS). A subsequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ where $$$1\leq i_1 &lt; i_2 &lt; \ldots &lt; i_k\leq n$$$ is called increasing if $$$a_{i_1} &lt; a_{i_2} &lt; a_{i_3} &lt; \ldots &lt; a_{i_k}$$$. If $$$a_{i_1} &gt; a_{i_2} &gt; a_{i_3} &gt; \ldots &gt; a_{i_k}$$$, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.For example, if there is a permutation $$$[6, 4, 1, 7, 2, 3, 5]$$$, LIS of this permutation will be $$$[1, 2, 3, 5]$$$, so the length of LIS is equal to $$$4$$$. LDS can be $$$[6, 4, 1]$$$, $$$[6, 4, 2]$$$, or $$$[6, 4, 3]$$$, so the length of LDS is $$$3$$$.Note, the lengths of LIS and LDS can be different.So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
256 megabytes
import java.util.*; import java.io.*; public class TaskC { FastScanner in; public void solve() throws IOException { int n = in.nextInt(); int min = n + 1; int k = 1; for (int i = 2; i <= n; i++) { int x = i + n / i; if (n % i != 0) { x++; } if (x < min) { min = x; k = i; } } int m = n / k; if (n % k != 0) { m++; } for (int i = m - 1; i >= 0; i--) { for (int j = 1; j <= k; j++) { if (i * k + j > n) { break; } System.out.print((i * k + j) + " "); } } } public void run() throws IOException { in = new FastScanner(); solve(); } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } } public static void main(String[] arg) throws IOException { new TaskC().run(); } }
Java
["4", "2"]
1 second
["3 4 1 2", "2 1"]
NoteIn the first sample, you can build a permutation $$$[3, 4, 1, 2]$$$. LIS is $$$[3, 4]$$$ (or $$$[1, 2]$$$), so the length of LIS is equal to $$$2$$$. LDS can be ony of $$$[3, 1]$$$, $$$[4, 2]$$$, $$$[3, 2]$$$, or $$$[4, 1]$$$. The length of LDS is also equal to $$$2$$$. The sum is equal to $$$4$$$. Note that $$$[3, 4, 1, 2]$$$ is not the only permutation that is valid.In the second sample, you can build a permutation $$$[2, 1]$$$. LIS is $$$[1]$$$ (or $$$[2]$$$), so the length of LIS is equal to $$$1$$$. LDS is $$$[2, 1]$$$, so the length of LDS is equal to $$$2$$$. The sum is equal to $$$3$$$. Note that permutation $$$[1, 2]$$$ is also valid.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
6ea899e915cfc95a43f0e16d6d08cc1e
The only line contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of permutation that you need to build.
1,600
Print a permutation that gives a minimum sum of lengths of LIS and LDS. If there are multiple answers, print any.
standard output
PASSED
ad941979e26cf53472e5e8bc30a6902f
train_003.jsonl
1533737100
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!The only thing Mrs. Smith remembered was that any permutation of $$$n$$$ can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.The sequence of $$$n$$$ integers is called a permutation if it contains all integers from $$$1$$$ to $$$n$$$ exactly once.The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS). A subsequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ where $$$1\leq i_1 &lt; i_2 &lt; \ldots &lt; i_k\leq n$$$ is called increasing if $$$a_{i_1} &lt; a_{i_2} &lt; a_{i_3} &lt; \ldots &lt; a_{i_k}$$$. If $$$a_{i_1} &gt; a_{i_2} &gt; a_{i_3} &gt; \ldots &gt; a_{i_k}$$$, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.For example, if there is a permutation $$$[6, 4, 1, 7, 2, 3, 5]$$$, LIS of this permutation will be $$$[1, 2, 3, 5]$$$, so the length of LIS is equal to $$$4$$$. LDS can be $$$[6, 4, 1]$$$, $$$[6, 4, 2]$$$, or $$$[6, 4, 3]$$$, so the length of LDS is $$$3$$$.Note, the lengths of LIS and LDS can be different.So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
256 megabytes
import java.io.*; import java.lang.annotation.Retention; import java.util.*; import java.math.BigInteger; import java.util.Map.Entry; import static java.lang.Math.*; public class C extends PrintWriter { int inc(int... p) { int n = p.length; int[] d = new int[n]; int max = 1; for (int i = 0; i < n; i++) { d[i] = 1; for (int j = 0; j < i; j++) { if (p[j] < p[i]) { d[i] = max(d[i], d[j] + 1); } } max = max(max, d[i]); } return max; } int dec(int... p) { int n = p.length; int[] d = new int[n]; int max = 1; for (int i = 0; i < n; i++) { d[i] = 1; for (int j = 0; j < i; j++) { if (p[j] > p[i]) { d[i] = max(d[i], d[j] + 1); } } max = max(max, d[i]); } return max; } int[] solve(int n) { int minVal = 0; int minSum = 2 * (n + 3); for (int lis = 1; lis <= n; lis++) { int q = n / lis; int r = n % lis; int lds = q + ((r > 0) ? 1 : 0); int cur = lis + lds; if (cur < minSum) { minSum = cur; minVal = lis; } } int lis = minVal; int q = n / lis; int r = n % lis; int lds = q + ((r > 0) ? 1 : 0); int x = lis - r, y = r; if (r == 0) { x = lis; y = 0; } int p = 0; int[] ans = new int[n]; int s = 0; while (--x >= 0) { int len = q; for (int i = len; i >= 1; i--) { ans[s++] = p + i; } p += len; } while (--y >= 0) { int len = q + 1; for (int i = len; i >= 1; i--) { ans[s++] = p + i; } p += len; } return ans; } // // int[] bf(int n) { // int[] ans = new int[n]; // int min = 2 * (n + 3); // // for (Permutation p = new Permutation(n); p != null; p = p.next()) { // int cur = inc(p.toArray()) + dec(p.toArray()); // // if (cur < min) { // min = cur; // ans = p.toArray(); // } // } // return ans; // // } void run() { int n = nextInt(); int[] p = solve(n); for (int i = 0; i < n; i++) { print(p[i]); print(' '); } // println(); // println(inc(p) + dec(p)); // int[] q = bf(n); // for (int i = 0; i < n; i++) { // print(q[i]); // print(' '); // } // println(); // println(inc(q) + dec(q)); // flush(); } boolean skip() { while (hasNext()) { next(); } return true; } int[][] nextMatrix(int n, int m) { int[][] matrix = new int[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) matrix[i][j] = nextInt(); return matrix; } String next() { while (!tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(nextLine()); return tokenizer.nextToken(); } boolean hasNext() { while (!tokenizer.hasMoreTokens()) { String line = nextLine(); if (line == null) { return false; } tokenizer = new StringTokenizer(line); } return true; } int[] nextArray(int n) { int[] array = new int[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; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { try { return reader.readLine(); } catch (IOException err) { return null; } } public C(OutputStream outputStream) { super(outputStream); } static BufferedReader reader; static StringTokenizer tokenizer = new StringTokenizer(""); static Random rnd = new Random(); static boolean OJ; public static void main(String[] args) throws IOException { OJ = System.getProperty("ONLINE_JUDGE") != null; C solution = new C(System.out); if (OJ) { reader = new BufferedReader(new InputStreamReader(System.in)); solution.run(); } else { reader = new BufferedReader(new FileReader(new File(C.class.getName() + ".txt"))); long timeout = System.currentTimeMillis(); while (solution.hasNext()) { solution.run(); solution.println(); solution.println("----------------------------------"); } solution.println("time: " + (System.currentTimeMillis() - timeout)); } solution.close(); reader.close(); } }
Java
["4", "2"]
1 second
["3 4 1 2", "2 1"]
NoteIn the first sample, you can build a permutation $$$[3, 4, 1, 2]$$$. LIS is $$$[3, 4]$$$ (or $$$[1, 2]$$$), so the length of LIS is equal to $$$2$$$. LDS can be ony of $$$[3, 1]$$$, $$$[4, 2]$$$, $$$[3, 2]$$$, or $$$[4, 1]$$$. The length of LDS is also equal to $$$2$$$. The sum is equal to $$$4$$$. Note that $$$[3, 4, 1, 2]$$$ is not the only permutation that is valid.In the second sample, you can build a permutation $$$[2, 1]$$$. LIS is $$$[1]$$$ (or $$$[2]$$$), so the length of LIS is equal to $$$1$$$. LDS is $$$[2, 1]$$$, so the length of LDS is equal to $$$2$$$. The sum is equal to $$$3$$$. Note that permutation $$$[1, 2]$$$ is also valid.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
6ea899e915cfc95a43f0e16d6d08cc1e
The only line contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of permutation that you need to build.
1,600
Print a permutation that gives a minimum sum of lengths of LIS and LDS. If there are multiple answers, print any.
standard output
PASSED
ff234f09a879e2105d0583f4ba179628
train_003.jsonl
1533737100
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!The only thing Mrs. Smith remembered was that any permutation of $$$n$$$ can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.The sequence of $$$n$$$ integers is called a permutation if it contains all integers from $$$1$$$ to $$$n$$$ exactly once.The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS). A subsequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ where $$$1\leq i_1 &lt; i_2 &lt; \ldots &lt; i_k\leq n$$$ is called increasing if $$$a_{i_1} &lt; a_{i_2} &lt; a_{i_3} &lt; \ldots &lt; a_{i_k}$$$. If $$$a_{i_1} &gt; a_{i_2} &gt; a_{i_3} &gt; \ldots &gt; a_{i_k}$$$, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.For example, if there is a permutation $$$[6, 4, 1, 7, 2, 3, 5]$$$, LIS of this permutation will be $$$[1, 2, 3, 5]$$$, so the length of LIS is equal to $$$4$$$. LDS can be $$$[6, 4, 1]$$$, $$$[6, 4, 2]$$$, or $$$[6, 4, 3]$$$, so the length of LDS is $$$3$$$.Note, the lengths of LIS and LDS can be different.So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
256 megabytes
import java.io.*; import java.math.*; import java.text.*; import java.util.*; import java.util.regex.*; public class Solution { static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream st) { this.stream = st; } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } static class node implements Comparable<node> { int p; long c; node(int a1,long a2) { p=a1; c=a2; } public int compareTo(node n1) { if(this.c>n1.c) { return 1; } else if(this.c<n1.c) { return -1; } return 0; } } static class party { ArrayList<Long> cost; party() { cost=new ArrayList<Long>(); } } public static void main(String[] args) throws IOException { InputReader in=new InputReader(System.in); int n=in.nextInt(); int[] ar=new int[n]; int min=Integer.MAX_VALUE; int size=-1; int cost=0; for(int s=1;s<=n;s++) { if(n%s==0) { cost=s+(n/s); } else { cost=s+(n/s)+1; } if(cost<min) { min=cost; size=s; } } //System.out.println(size); if(n%size==0) { int max=n; for(int i=0;i<=n-size;i+=size) { for(int j=size-1;j>=0;j--) { ar[i+j]=max; max--; } } } else { int max=n; for(int i=0;i<n-size;i+=size) { for(int j=size-1;j>=0;j--) { ar[i+j]=max; max--; } } for(int i=n-1;i>=((n/size)*size);i--) { ar[i]=max; max--; } } for(int x=0;x<n;x++) { System.out.print(ar[x]+" "); } } }
Java
["4", "2"]
1 second
["3 4 1 2", "2 1"]
NoteIn the first sample, you can build a permutation $$$[3, 4, 1, 2]$$$. LIS is $$$[3, 4]$$$ (or $$$[1, 2]$$$), so the length of LIS is equal to $$$2$$$. LDS can be ony of $$$[3, 1]$$$, $$$[4, 2]$$$, $$$[3, 2]$$$, or $$$[4, 1]$$$. The length of LDS is also equal to $$$2$$$. The sum is equal to $$$4$$$. Note that $$$[3, 4, 1, 2]$$$ is not the only permutation that is valid.In the second sample, you can build a permutation $$$[2, 1]$$$. LIS is $$$[1]$$$ (or $$$[2]$$$), so the length of LIS is equal to $$$1$$$. LDS is $$$[2, 1]$$$, so the length of LDS is equal to $$$2$$$. The sum is equal to $$$3$$$. Note that permutation $$$[1, 2]$$$ is also valid.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
6ea899e915cfc95a43f0e16d6d08cc1e
The only line contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of permutation that you need to build.
1,600
Print a permutation that gives a minimum sum of lengths of LIS and LDS. If there are multiple answers, print any.
standard output
PASSED
da7cc03d828e3488bc776cf098e35116
train_003.jsonl
1533737100
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!The only thing Mrs. Smith remembered was that any permutation of $$$n$$$ can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.The sequence of $$$n$$$ integers is called a permutation if it contains all integers from $$$1$$$ to $$$n$$$ exactly once.The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS). A subsequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ where $$$1\leq i_1 &lt; i_2 &lt; \ldots &lt; i_k\leq n$$$ is called increasing if $$$a_{i_1} &lt; a_{i_2} &lt; a_{i_3} &lt; \ldots &lt; a_{i_k}$$$. If $$$a_{i_1} &gt; a_{i_2} &gt; a_{i_3} &gt; \ldots &gt; a_{i_k}$$$, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.For example, if there is a permutation $$$[6, 4, 1, 7, 2, 3, 5]$$$, LIS of this permutation will be $$$[1, 2, 3, 5]$$$, so the length of LIS is equal to $$$4$$$. LDS can be $$$[6, 4, 1]$$$, $$$[6, 4, 2]$$$, or $$$[6, 4, 3]$$$, so the length of LDS is $$$3$$$.Note, the lengths of LIS and LDS can be different.So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
256 megabytes
//package sudo_plac; import java.util.*; public class phone_number { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int b=Integer.MAX_VALUE; int lm=n; int fact=0; int en=0; for(int i=1;i<=Math.sqrt(lm);i++) { //System.out.println(i+" "+lm/i+" "+(i+1+lm/i)+" "+b); if(lm%i==0) { if(b>(i+lm/i)) { b=i+n/i; fact=i; en=n/i; } } else { if(b>i+1+(lm/i)) { b=i+n/i+1; fact=i; en=lm/i+1; } } } String s=""; int t=0; while(t<en) { String tmp=""; //System.out.println(fact*t+" "+fact*(t+1)); for(int i=fact*t;i<fact*(t+1);i++) { if(i<n) tmp=tmp+(i+1)+" "; } s=tmp+s; t++; } System.out.println(s); } }
Java
["4", "2"]
1 second
["3 4 1 2", "2 1"]
NoteIn the first sample, you can build a permutation $$$[3, 4, 1, 2]$$$. LIS is $$$[3, 4]$$$ (or $$$[1, 2]$$$), so the length of LIS is equal to $$$2$$$. LDS can be ony of $$$[3, 1]$$$, $$$[4, 2]$$$, $$$[3, 2]$$$, or $$$[4, 1]$$$. The length of LDS is also equal to $$$2$$$. The sum is equal to $$$4$$$. Note that $$$[3, 4, 1, 2]$$$ is not the only permutation that is valid.In the second sample, you can build a permutation $$$[2, 1]$$$. LIS is $$$[1]$$$ (or $$$[2]$$$), so the length of LIS is equal to $$$1$$$. LDS is $$$[2, 1]$$$, so the length of LDS is equal to $$$2$$$. The sum is equal to $$$3$$$. Note that permutation $$$[1, 2]$$$ is also valid.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
6ea899e915cfc95a43f0e16d6d08cc1e
The only line contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of permutation that you need to build.
1,600
Print a permutation that gives a minimum sum of lengths of LIS and LDS. If there are multiple answers, print any.
standard output
PASSED
6bae6dcc20c9d06adda3bb1e759510f3
train_003.jsonl
1533737100
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!The only thing Mrs. Smith remembered was that any permutation of $$$n$$$ can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.The sequence of $$$n$$$ integers is called a permutation if it contains all integers from $$$1$$$ to $$$n$$$ exactly once.The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS). A subsequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ where $$$1\leq i_1 &lt; i_2 &lt; \ldots &lt; i_k\leq n$$$ is called increasing if $$$a_{i_1} &lt; a_{i_2} &lt; a_{i_3} &lt; \ldots &lt; a_{i_k}$$$. If $$$a_{i_1} &gt; a_{i_2} &gt; a_{i_3} &gt; \ldots &gt; a_{i_k}$$$, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.For example, if there is a permutation $$$[6, 4, 1, 7, 2, 3, 5]$$$, LIS of this permutation will be $$$[1, 2, 3, 5]$$$, so the length of LIS is equal to $$$4$$$. LDS can be $$$[6, 4, 1]$$$, $$$[6, 4, 2]$$$, or $$$[6, 4, 3]$$$, so the length of LDS is $$$3$$$.Note, the lengths of LIS and LDS can be different.So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
256 megabytes
/** * Created by Baelish on 8/8/2018. */ import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; public class C { public static void main(String[] args) throws Exception { FastReader in = new FastReader(System.in); PrintWriter pw = new PrintWriter(System.out); int n = in.nextInt(); int a = (int) Math.ceil(Math.sqrt(n)); List<List<Integer>> ans = new ArrayList<>(); int idx = 1; for (int i = 0; i < a; ++i) { List<Integer> tmp = new ArrayList<>(); for (int j = 0; j < a && idx <= n; ++j) { tmp.add(idx++); } ans.add(tmp); } Collections.reverse(ans); for (List<Integer> v : ans){ for (int x : v) { pw.print(x + " "); } } pw.println(); pw.close(); } static <T>List<T>[] genList(int n){ List<T> list[] = new List[n]; for(int i = 0; i < n; i++) list[i] = new ArrayList<T>(); return list; } static void debug(Object... obj) { System.err.println(Arrays.deepToString(obj)); } static class FastReader { static final int ints[] = new int[128]; InputStream is; private byte[] inbuf = new byte[1024]; private int lenbuf = 0, ptrbuf = 0; public FastReader(InputStream is) { for (int i = '0'; i <= '9'; i++) ints[i] = i - '0'; this.is = is; } public 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++]; } public boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } public int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } public String next() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public int nextInt() { 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 << 3) + (num << 1) + ints[b]; } else { return minus ? -num : num; } b = readByte(); } } public long nextLong() { 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 << 3) + (num << 1) + ints[b]; } else { return minus ? -num : num; } b = readByte(); } } public double nextDouble() { return Double.parseDouble(next()); } /* public char nextChar() { return (char)skip(); }*/ public char[] next(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 buff[] = new char[1005]; public char[] nextCharArray(){ int b = skip(), p = 0; while(!(isSpaceChar(b))){ buff[p++] = (char)b; b = readByte(); } return Arrays.copyOf(buff, p); }*/ } }
Java
["4", "2"]
1 second
["3 4 1 2", "2 1"]
NoteIn the first sample, you can build a permutation $$$[3, 4, 1, 2]$$$. LIS is $$$[3, 4]$$$ (or $$$[1, 2]$$$), so the length of LIS is equal to $$$2$$$. LDS can be ony of $$$[3, 1]$$$, $$$[4, 2]$$$, $$$[3, 2]$$$, or $$$[4, 1]$$$. The length of LDS is also equal to $$$2$$$. The sum is equal to $$$4$$$. Note that $$$[3, 4, 1, 2]$$$ is not the only permutation that is valid.In the second sample, you can build a permutation $$$[2, 1]$$$. LIS is $$$[1]$$$ (or $$$[2]$$$), so the length of LIS is equal to $$$1$$$. LDS is $$$[2, 1]$$$, so the length of LDS is equal to $$$2$$$. The sum is equal to $$$3$$$. Note that permutation $$$[1, 2]$$$ is also valid.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
6ea899e915cfc95a43f0e16d6d08cc1e
The only line contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of permutation that you need to build.
1,600
Print a permutation that gives a minimum sum of lengths of LIS and LDS. If there are multiple answers, print any.
standard output
PASSED
b5c1d883d023a00d75adaf687a1b61a2
train_003.jsonl
1533737100
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!The only thing Mrs. Smith remembered was that any permutation of $$$n$$$ can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.The sequence of $$$n$$$ integers is called a permutation if it contains all integers from $$$1$$$ to $$$n$$$ exactly once.The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS). A subsequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ where $$$1\leq i_1 &lt; i_2 &lt; \ldots &lt; i_k\leq n$$$ is called increasing if $$$a_{i_1} &lt; a_{i_2} &lt; a_{i_3} &lt; \ldots &lt; a_{i_k}$$$. If $$$a_{i_1} &gt; a_{i_2} &gt; a_{i_3} &gt; \ldots &gt; a_{i_k}$$$, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.For example, if there is a permutation $$$[6, 4, 1, 7, 2, 3, 5]$$$, LIS of this permutation will be $$$[1, 2, 3, 5]$$$, so the length of LIS is equal to $$$4$$$. LDS can be $$$[6, 4, 1]$$$, $$$[6, 4, 2]$$$, or $$$[6, 4, 3]$$$, so the length of LDS is $$$3$$$.Note, the lengths of LIS and LDS can be different.So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
256 megabytes
import java.util.Scanner; public class ThePhoneumber { public static void main(String[] args) { // TODO Auto-generated method stub Scanner s = new Scanner(System.in); int n = s.nextInt(); StringBuilder sb = new StringBuilder(); int rem = (int) Math.sqrt(n); int l =1,r = rem; while(n>=l) { for(int i=r;i>=l;i--) { System.out.print(i+" "); } l+=rem; r+=rem; if(r>n) { r = n; } } } }
Java
["4", "2"]
1 second
["3 4 1 2", "2 1"]
NoteIn the first sample, you can build a permutation $$$[3, 4, 1, 2]$$$. LIS is $$$[3, 4]$$$ (or $$$[1, 2]$$$), so the length of LIS is equal to $$$2$$$. LDS can be ony of $$$[3, 1]$$$, $$$[4, 2]$$$, $$$[3, 2]$$$, or $$$[4, 1]$$$. The length of LDS is also equal to $$$2$$$. The sum is equal to $$$4$$$. Note that $$$[3, 4, 1, 2]$$$ is not the only permutation that is valid.In the second sample, you can build a permutation $$$[2, 1]$$$. LIS is $$$[1]$$$ (or $$$[2]$$$), so the length of LIS is equal to $$$1$$$. LDS is $$$[2, 1]$$$, so the length of LDS is equal to $$$2$$$. The sum is equal to $$$3$$$. Note that permutation $$$[1, 2]$$$ is also valid.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
6ea899e915cfc95a43f0e16d6d08cc1e
The only line contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of permutation that you need to build.
1,600
Print a permutation that gives a minimum sum of lengths of LIS and LDS. If there are multiple answers, print any.
standard output
PASSED
e8bcae5bd373ff7df0e8ff5bc1450b3b
train_003.jsonl
1533737100
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!The only thing Mrs. Smith remembered was that any permutation of $$$n$$$ can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.The sequence of $$$n$$$ integers is called a permutation if it contains all integers from $$$1$$$ to $$$n$$$ exactly once.The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS). A subsequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ where $$$1\leq i_1 &lt; i_2 &lt; \ldots &lt; i_k\leq n$$$ is called increasing if $$$a_{i_1} &lt; a_{i_2} &lt; a_{i_3} &lt; \ldots &lt; a_{i_k}$$$. If $$$a_{i_1} &gt; a_{i_2} &gt; a_{i_3} &gt; \ldots &gt; a_{i_k}$$$, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.For example, if there is a permutation $$$[6, 4, 1, 7, 2, 3, 5]$$$, LIS of this permutation will be $$$[1, 2, 3, 5]$$$, so the length of LIS is equal to $$$4$$$. LDS can be $$$[6, 4, 1]$$$, $$$[6, 4, 2]$$$, or $$$[6, 4, 3]$$$, so the length of LDS is $$$3$$$.Note, the lengths of LIS and LDS can be different.So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
256 megabytes
import java.util.Scanner; public class CF1017C { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int k = (int)(Math.sqrt(n)); for (int i = 1; i <= n / k; i++) { for (int a = 0; a < k; a++) { System.out.print((k * i - a) + " "); } } for (int i = n; i > n / k * k; i--){ System.out.print(i + " "); } } }
Java
["4", "2"]
1 second
["3 4 1 2", "2 1"]
NoteIn the first sample, you can build a permutation $$$[3, 4, 1, 2]$$$. LIS is $$$[3, 4]$$$ (or $$$[1, 2]$$$), so the length of LIS is equal to $$$2$$$. LDS can be ony of $$$[3, 1]$$$, $$$[4, 2]$$$, $$$[3, 2]$$$, or $$$[4, 1]$$$. The length of LDS is also equal to $$$2$$$. The sum is equal to $$$4$$$. Note that $$$[3, 4, 1, 2]$$$ is not the only permutation that is valid.In the second sample, you can build a permutation $$$[2, 1]$$$. LIS is $$$[1]$$$ (or $$$[2]$$$), so the length of LIS is equal to $$$1$$$. LDS is $$$[2, 1]$$$, so the length of LDS is equal to $$$2$$$. The sum is equal to $$$3$$$. Note that permutation $$$[1, 2]$$$ is also valid.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
6ea899e915cfc95a43f0e16d6d08cc1e
The only line contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of permutation that you need to build.
1,600
Print a permutation that gives a minimum sum of lengths of LIS and LDS. If there are multiple answers, print any.
standard output
PASSED
7232c9a8225a374356e29ccd874232ab
train_003.jsonl
1581257100
Guy-Manuel and Thomas have an array $$$a$$$ of $$$n$$$ integers [$$$a_1, a_2, \dots, a_n$$$]. In one step they can add $$$1$$$ to any element of the array. Formally, in one step they can choose any integer index $$$i$$$ ($$$1 \le i \le n$$$) and do $$$a_i := a_i + 1$$$.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make $$$a_1 + a_2 +$$$ $$$\dots$$$ $$$+ a_n \ne 0$$$ and $$$a_1 \cdot a_2 \cdot$$$ $$$\dots$$$ $$$\cdot a_n \ne 0$$$.
256 megabytes
import java.util.Scanner; public class Nonzero { public static int sumOfArrayElements(int[] a) { int sum = 0; for (int i = 0; i < a.length; i++) { sum += a[i]; } return sum; } public static int zeroCounter(int[] a) { int counter = 0; for (int i = 0; i < a.length; i++) { if(a[i]==0) counter++; } return counter; } public static void Solver(int[] a) { if(sumOfArrayElements(a)+zeroCounter(a) == 0) System.out.println(zeroCounter(a) + 1); else System.out.println(zeroCounter(a)); } public static void main(String[] args) { Scanner input = new Scanner(System.in); int testCases = input.nextInt(); for (int i = 0; i < testCases; i++) { int[] a; int lengthOfArr = input.nextInt(); a = new int[lengthOfArr]; for (int j = 0; j < lengthOfArr; j++) { a[j] = input.nextInt(); } Solver(a); } } }
Java
["4\n3\n2 -1 -1\n4\n-1 0 0 1\n2\n-1 2\n3\n0 -2 1"]
1 second
["1\n2\n0\n2"]
NoteIn the first test case, the sum is $$$0$$$. If we add $$$1$$$ to the first element, the array will be $$$[3,-1,-1]$$$, the sum will be equal to $$$1$$$ and the product will be equal to $$$3$$$.In the second test case, both product and sum are $$$0$$$. If we add $$$1$$$ to the second and the third element, the array will be $$$[-1,1,1,1]$$$, the sum will be equal to $$$2$$$ and the product will be equal to $$$-1$$$. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding $$$1$$$ twice to the first element the array will be $$$[2,-2,1]$$$, the sum will be $$$1$$$ and the product will be $$$-4$$$.
Java 8
standard input
[ "implementation", "math" ]
1ffb08fe61cdf90099c82162b8353b1f
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-100 \le a_i \le 100$$$) — elements of the array .
800
For each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.
standard output
PASSED
24172a2f96e5d8aa1a2966c018139b0a
train_003.jsonl
1581257100
Guy-Manuel and Thomas have an array $$$a$$$ of $$$n$$$ integers [$$$a_1, a_2, \dots, a_n$$$]. In one step they can add $$$1$$$ to any element of the array. Formally, in one step they can choose any integer index $$$i$$$ ($$$1 \le i \le n$$$) and do $$$a_i := a_i + 1$$$.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make $$$a_1 + a_2 +$$$ $$$\dots$$$ $$$+ a_n \ne 0$$$ and $$$a_1 \cdot a_2 \cdot$$$ $$$\dots$$$ $$$\cdot a_n \ne 0$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; import java.util.StringTokenizer; public class code { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { FastReader sc=new FastReader(); PrintWriter pw=new PrintWriter(System.out); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); int arr[]=new int[n]; int sum=0,count=0; for(int i=0;i<n;i++) { arr[i]=sc.nextInt(); sum+=arr[i]; if(arr[i]==0) count++; } if(sum+count==0) count++; System.out.println(count); } } }
Java
["4\n3\n2 -1 -1\n4\n-1 0 0 1\n2\n-1 2\n3\n0 -2 1"]
1 second
["1\n2\n0\n2"]
NoteIn the first test case, the sum is $$$0$$$. If we add $$$1$$$ to the first element, the array will be $$$[3,-1,-1]$$$, the sum will be equal to $$$1$$$ and the product will be equal to $$$3$$$.In the second test case, both product and sum are $$$0$$$. If we add $$$1$$$ to the second and the third element, the array will be $$$[-1,1,1,1]$$$, the sum will be equal to $$$2$$$ and the product will be equal to $$$-1$$$. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding $$$1$$$ twice to the first element the array will be $$$[2,-2,1]$$$, the sum will be $$$1$$$ and the product will be $$$-4$$$.
Java 8
standard input
[ "implementation", "math" ]
1ffb08fe61cdf90099c82162b8353b1f
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-100 \le a_i \le 100$$$) — elements of the array .
800
For each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.
standard output
PASSED
150949a6fba1cfc2e4e53c53de5dca7c
train_003.jsonl
1581257100
Guy-Manuel and Thomas have an array $$$a$$$ of $$$n$$$ integers [$$$a_1, a_2, \dots, a_n$$$]. In one step they can add $$$1$$$ to any element of the array. Formally, in one step they can choose any integer index $$$i$$$ ($$$1 \le i \le n$$$) and do $$$a_i := a_i + 1$$$.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make $$$a_1 + a_2 +$$$ $$$\dots$$$ $$$+ a_n \ne 0$$$ and $$$a_1 \cdot a_2 \cdot$$$ $$$\dots$$$ $$$\cdot a_n \ne 0$$$.
256 megabytes
import java.util.*; public class Problem1300A { public static void main(String[] args) { Scanner in = new Scanner(System.in); int testCases, arrlength; testCases = in.nextInt(); for (int i = 0; i < testCases; i++) { int Sum = 0, Counter = 0, minStep; arrlength = in.nextInt(); int arr[] = new int[arrlength]; for (int j = 0; j < arrlength; j++) { arr[j] = in.nextInt(); if (arr[j] == 0) { Counter++; } Sum += arr[j]; } if (Counter == 0) { //means no zeros at array, So product is non zero. if (Sum == 0) { System.out.println("1"); } else { System.out.println("0"); } } else { minStep = Counter; //no.of zeros at array befor conversion [0 => 1] Sum += Counter; //total sum at array after adding no.of zeros to previous sum if (Sum == 0) { System.out.println(minStep + 1); } else { System.out.println(minStep); } } } } }
Java
["4\n3\n2 -1 -1\n4\n-1 0 0 1\n2\n-1 2\n3\n0 -2 1"]
1 second
["1\n2\n0\n2"]
NoteIn the first test case, the sum is $$$0$$$. If we add $$$1$$$ to the first element, the array will be $$$[3,-1,-1]$$$, the sum will be equal to $$$1$$$ and the product will be equal to $$$3$$$.In the second test case, both product and sum are $$$0$$$. If we add $$$1$$$ to the second and the third element, the array will be $$$[-1,1,1,1]$$$, the sum will be equal to $$$2$$$ and the product will be equal to $$$-1$$$. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding $$$1$$$ twice to the first element the array will be $$$[2,-2,1]$$$, the sum will be $$$1$$$ and the product will be $$$-4$$$.
Java 8
standard input
[ "implementation", "math" ]
1ffb08fe61cdf90099c82162b8353b1f
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-100 \le a_i \le 100$$$) — elements of the array .
800
For each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.
standard output
PASSED
6d60a28bc3153ee1dee1f601bc0c14f9
train_003.jsonl
1581257100
Guy-Manuel and Thomas have an array $$$a$$$ of $$$n$$$ integers [$$$a_1, a_2, \dots, a_n$$$]. In one step they can add $$$1$$$ to any element of the array. Formally, in one step they can choose any integer index $$$i$$$ ($$$1 \le i \le n$$$) and do $$$a_i := a_i + 1$$$.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make $$$a_1 + a_2 +$$$ $$$\dots$$$ $$$+ a_n \ne 0$$$ and $$$a_1 \cdot a_2 \cdot$$$ $$$\dots$$$ $$$\cdot a_n \ne 0$$$.
256 megabytes
// @author Hassan_Kaka import java.util.Scanner; public class NonZero_1300A { public static void main(String[] args) { Scanner input = new Scanner(System.in); int counter = 0; int sum = 0; int arrNumbers[]; int arrLen; int numberOfCases = input.nextInt(); for (int f = 0; f < numberOfCases; f++) { counter = 0; sum = 0; arrLen = input.nextInt(); arrNumbers = new int[arrLen]; for (int i = 0; i < arrLen; i++) { arrNumbers[i] = input.nextInt(); if (arrNumbers[i] == 0) { arrNumbers[i] +=1; counter++; } sum += arrNumbers[i]; } if (sum == 0){ counter++; } System.out.println(counter); } } }
Java
["4\n3\n2 -1 -1\n4\n-1 0 0 1\n2\n-1 2\n3\n0 -2 1"]
1 second
["1\n2\n0\n2"]
NoteIn the first test case, the sum is $$$0$$$. If we add $$$1$$$ to the first element, the array will be $$$[3,-1,-1]$$$, the sum will be equal to $$$1$$$ and the product will be equal to $$$3$$$.In the second test case, both product and sum are $$$0$$$. If we add $$$1$$$ to the second and the third element, the array will be $$$[-1,1,1,1]$$$, the sum will be equal to $$$2$$$ and the product will be equal to $$$-1$$$. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding $$$1$$$ twice to the first element the array will be $$$[2,-2,1]$$$, the sum will be $$$1$$$ and the product will be $$$-4$$$.
Java 8
standard input
[ "implementation", "math" ]
1ffb08fe61cdf90099c82162b8353b1f
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-100 \le a_i \le 100$$$) — elements of the array .
800
For each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.
standard output
PASSED
000dff796bb71de8155b453a94c3abb9
train_003.jsonl
1581257100
Guy-Manuel and Thomas have an array $$$a$$$ of $$$n$$$ integers [$$$a_1, a_2, \dots, a_n$$$]. In one step they can add $$$1$$$ to any element of the array. Formally, in one step they can choose any integer index $$$i$$$ ($$$1 \le i \le n$$$) and do $$$a_i := a_i + 1$$$.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make $$$a_1 + a_2 +$$$ $$$\dots$$$ $$$+ a_n \ne 0$$$ and $$$a_1 \cdot a_2 \cdot$$$ $$$\dots$$$ $$$\cdot a_n \ne 0$$$.
256 megabytes
import java.util.Scanner; /** * * @author Hp */ public class Force2 { /** * @param args the command line arguments */ static Scanner input = new Scanner(System.in); public static void main(String[] args) { //ـــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــ int ar; int sum=0; int count=0; int product=1; long t= input.nextLong(); for ( long i = 0; i < t; i++) { // System.out.println("Enter Array Size"); int size = input.nextInt(); long [] arr=new long [size] ; for (ar = 0; ar <size ; ar++) { arr[ar] = input.nextInt(); if (arr[ar]!=0) { sum+=arr[ar]; product*= arr[ar]; } else { count++; arr[ar]++; sum+=arr[ar]; } } if (sum==0) { // sum++; count++; } System.out.println(count); count=0; sum=0; } } }
Java
["4\n3\n2 -1 -1\n4\n-1 0 0 1\n2\n-1 2\n3\n0 -2 1"]
1 second
["1\n2\n0\n2"]
NoteIn the first test case, the sum is $$$0$$$. If we add $$$1$$$ to the first element, the array will be $$$[3,-1,-1]$$$, the sum will be equal to $$$1$$$ and the product will be equal to $$$3$$$.In the second test case, both product and sum are $$$0$$$. If we add $$$1$$$ to the second and the third element, the array will be $$$[-1,1,1,1]$$$, the sum will be equal to $$$2$$$ and the product will be equal to $$$-1$$$. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding $$$1$$$ twice to the first element the array will be $$$[2,-2,1]$$$, the sum will be $$$1$$$ and the product will be $$$-4$$$.
Java 8
standard input
[ "implementation", "math" ]
1ffb08fe61cdf90099c82162b8353b1f
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-100 \le a_i \le 100$$$) — elements of the array .
800
For each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.
standard output
PASSED
37faa9267a9b560dd55bb3745f0596b7
train_003.jsonl
1581257100
Guy-Manuel and Thomas have an array $$$a$$$ of $$$n$$$ integers [$$$a_1, a_2, \dots, a_n$$$]. In one step they can add $$$1$$$ to any element of the array. Formally, in one step they can choose any integer index $$$i$$$ ($$$1 \le i \le n$$$) and do $$$a_i := a_i + 1$$$.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make $$$a_1 + a_2 +$$$ $$$\dots$$$ $$$+ a_n \ne 0$$$ and $$$a_1 \cdot a_2 \cdot$$$ $$$\dots$$$ $$$\cdot a_n \ne 0$$$.
256 megabytes
//import java.io.BufferedReader; //import java.io.IOException; //import java.io.InputStreamReader; //import java.util.*; //import java.math.*; // // //public class Codeforces { // public static String[] longestCommonSubsequence(String str1, String str2,int ind) { // // Write your code here. // int n=str1.length(); // int m=str2.length(); // StringBuilder b=new StringBuilder(); // for(int i=0;i<n && ind<m;i++) // { // if(str1.charAt(i)==str2.charAt(ind)) // { // b.append(str1.charAt(i)); // ind++; // } // } // return new String[]{b.toString(),Integer.toString(ind)}; // // } // public static void main(String[] args) throws IOException { // Scanner s = new Scanner(System.in); //// int t=s.nextInt(); //// for(int i=0;i<t;i++) //// { // int n=s.nextInt(); // double[] arr=new double[n]; //// double sum=0; // for(int i=0;i<n;i++) // { // arr[i]=s.nextInt(); //// sum+=arr[i]; // } // for(int i=0;i<n;) // { // double sum=arr[i]; // int start=i,end=-1; // double min=arr[i]; // // for(int j=i+1;j<n;j++) // { // sum+=arr[j]; // double val=sum/(j-i+1); // if(val<min) // { // min=val; // end=j; // } // } // if(end!=-1) // { // for(int j=start;j<=end;j++) // { // arr[j]=min; // } // i=end+1; // } // else // { // i++; // } // // } // //// while(true) { //// double subSum = sum; //// //// //// int start = -1, end = -1; //// int l = 0, r = arr.length - 1; //// double min=arr[l]; //// while (l < r) { //// double val = ((double) subSum) / (r - l + 1); //// min=arr[l]; //// if (val < min) { //// start = l; //// end = r; //// subSum -= arr[r]; //// r--; //// min=val; //// //// } else { //// subSum -= arr[l]; //// l++; //// min=arr[l]; //// } //// } //// //// if (start == -1) { //// break; //// } //// int sum1=0; ////// System.out.println(start+" "+end); //// for(int j=start;j<=end;j++) //// { //// sum1+=arr[j]; //// } //// double a=((double)sum1)/(end-start+1); //// for(int i=start;i<=end;i++) //// { //// arr[i]=a; //// } //// sum=0; //// for(double i:arr) //// { //// sum+=i; //// } //// //// } // for(double i:arr) // { // System.out.println(i); // } //// double[] ans=new double[n]; //// for(int i=0;i<n;i++) //// { //// ans[i]=arr[i]; //// } //// for(Pair p:list) //// { //// int sum1=0; //// for(int i=p.start;i<=p.end;i++) //// { //// sum1+=arr[i]; //// } //// double a=((double)sum1)/(p.end-p.start+1); //// for(int i=p.start;i<=p.end;i++) //// { //// ans[i]=a; //// } //// } // //// System.out.println(); // // // //// } // // // } //} // //class Pair //{ // int start,end; // Pair(int start,int end) // { // this.start=start; // this.end=end; // } //} import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; import java.math.*; public class Codeforces { public static String[] longestCommonSubsequence(String str1, String str2,int ind) { // Write your code here. int n=str1.length(); int m=str2.length(); StringBuilder b=new StringBuilder(); for(int i=0;i<n && ind<m;i++) { if(str1.charAt(i)==str2.charAt(ind)) { b.append(str1.charAt(i)); ind++; } } return new String[]{b.toString(),Integer.toString(ind)}; } public static void main(String[] args) throws IOException { 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]; int prod=1; int sum=0; int count_z=0; for(int j=0;j<n;j++) { arr[j]=s.nextInt(); if(arr[j]==0) { count_z++; } prod*=arr[j]; sum+=arr[j]; } int ans=count_z; sum+=count_z; if(sum==0) { ans++; } System.out.println(ans); } } }
Java
["4\n3\n2 -1 -1\n4\n-1 0 0 1\n2\n-1 2\n3\n0 -2 1"]
1 second
["1\n2\n0\n2"]
NoteIn the first test case, the sum is $$$0$$$. If we add $$$1$$$ to the first element, the array will be $$$[3,-1,-1]$$$, the sum will be equal to $$$1$$$ and the product will be equal to $$$3$$$.In the second test case, both product and sum are $$$0$$$. If we add $$$1$$$ to the second and the third element, the array will be $$$[-1,1,1,1]$$$, the sum will be equal to $$$2$$$ and the product will be equal to $$$-1$$$. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding $$$1$$$ twice to the first element the array will be $$$[2,-2,1]$$$, the sum will be $$$1$$$ and the product will be $$$-4$$$.
Java 8
standard input
[ "implementation", "math" ]
1ffb08fe61cdf90099c82162b8353b1f
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-100 \le a_i \le 100$$$) — elements of the array .
800
For each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.
standard output
PASSED
8dc429e7cb53a755574da37a6d1975d7
train_003.jsonl
1581257100
Guy-Manuel and Thomas have an array $$$a$$$ of $$$n$$$ integers [$$$a_1, a_2, \dots, a_n$$$]. In one step they can add $$$1$$$ to any element of the array. Formally, in one step they can choose any integer index $$$i$$$ ($$$1 \le i \le n$$$) and do $$$a_i := a_i + 1$$$.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make $$$a_1 + a_2 +$$$ $$$\dots$$$ $$$+ a_n \ne 0$$$ and $$$a_1 \cdot a_2 \cdot$$$ $$$\dots$$$ $$$\cdot a_n \ne 0$$$.
256 megabytes
import java.io.*; import java.util.*; public class A { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static FastReader s = new FastReader(); static PrintWriter out = new PrintWriter(System.out); private static int[] rai(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = s.nextInt(); } return arr; } private static int[][] rai(int n, int m) { int[][] arr = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { arr[i][j] = s.nextInt(); } } return arr; } private static long[] ral(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = s.nextLong(); } return arr; } private static long[][] ral(int n, int m) { long[][] arr = new long[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { arr[i][j] = s.nextLong(); } } return arr; } private static int ri() { return s.nextInt(); } private static long rl() { return s.nextLong(); } private static String rs() { return s.next(); } static int gcd(int a,int b) { if(b==0) { return a; } return gcd(b,a%b); } public static void main(String[] args) { StringBuilder ans = new StringBuilder(); int t = ri(); // int t=1; while (t-- > 0) { int n=ri(); int[] arr=rai(n); int sum=0; int z=0; for(int i:arr) { sum+=i; if(i==0) { z++; } } sum+=z; int count=z; if(sum==0) { count++; } ans.append(count).append("\n"); } out.print(ans.toString()); out.flush(); } }
Java
["4\n3\n2 -1 -1\n4\n-1 0 0 1\n2\n-1 2\n3\n0 -2 1"]
1 second
["1\n2\n0\n2"]
NoteIn the first test case, the sum is $$$0$$$. If we add $$$1$$$ to the first element, the array will be $$$[3,-1,-1]$$$, the sum will be equal to $$$1$$$ and the product will be equal to $$$3$$$.In the second test case, both product and sum are $$$0$$$. If we add $$$1$$$ to the second and the third element, the array will be $$$[-1,1,1,1]$$$, the sum will be equal to $$$2$$$ and the product will be equal to $$$-1$$$. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding $$$1$$$ twice to the first element the array will be $$$[2,-2,1]$$$, the sum will be $$$1$$$ and the product will be $$$-4$$$.
Java 8
standard input
[ "implementation", "math" ]
1ffb08fe61cdf90099c82162b8353b1f
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-100 \le a_i \le 100$$$) — elements of the array .
800
For each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.
standard output
PASSED
15f05abcf12f505f39522e0ef317f1da
train_003.jsonl
1581257100
Guy-Manuel and Thomas have an array $$$a$$$ of $$$n$$$ integers [$$$a_1, a_2, \dots, a_n$$$]. In one step they can add $$$1$$$ to any element of the array. Formally, in one step they can choose any integer index $$$i$$$ ($$$1 \le i \le n$$$) and do $$$a_i := a_i + 1$$$.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make $$$a_1 + a_2 +$$$ $$$\dots$$$ $$$+ a_n \ne 0$$$ and $$$a_1 \cdot a_2 \cdot$$$ $$$\dots$$$ $$$\cdot a_n \ne 0$$$.
256 megabytes
import java.util.*; import java.io.*; import java.lang.Math; import java.time.*; //100 //0 0 -60 0 20 0 -85 0 0 0 -88 -77 83 0 10 0 98 0 1 68 0 0 0 0 0 0 -46 -95 0 -63 0 0 0 41 5 21 -60 0 -23 0 32 61 0 0 67 -87 73 -88 0 0 0 56 0 27 0 0 0 0 -42 -49 59 0 -74 -34 0 0 42 0 0 0 55 -36 -59 0 0 94 0 0 -58 54 0 2 67 0 0 0 100 0 45 73 -54 54 0 94 0 0 -1 -12 -40 -59 public class non_zero { public static void main(String[] args) { //Instant start = Instant.now(); Scanner scan = new Scanner(System.in); int t = scan.nextInt(); for (int i = 0; i < t; i++) { int n = scan.nextInt(); int[] array = new int[n]; int sum = 0; int changes = 0; int product = 1; for (int j = 0; j < n; j++) { int num = scan.nextInt(); if (num == 0) { num++; changes++; } array[j] = num; sum = sum + num; //product = product*num; } Arrays.sort(array); int pos = -1; for (int j = 0; j < n; j++) { if (array[j] > 0) { pos = j; break; } } // System.out.println("pos = " + pos); // System.out.println("product = " + product); // for (int val: array) { // System.out.print(val + " "); // } // System.out.println(); while (sum == 0 || product == 0) { //int val = array[pos]; //System.out.print(sum + ";" + product + "_"); array[pos]++; sum++; changes++; } System.out.println(changes); } // Instant end = Instant.now(); // Duration timeElapsed = Duration.between(start, end); // System.out.println("Time taken: "+ timeElapsed.toMillis() +" milliseconds"); } }
Java
["4\n3\n2 -1 -1\n4\n-1 0 0 1\n2\n-1 2\n3\n0 -2 1"]
1 second
["1\n2\n0\n2"]
NoteIn the first test case, the sum is $$$0$$$. If we add $$$1$$$ to the first element, the array will be $$$[3,-1,-1]$$$, the sum will be equal to $$$1$$$ and the product will be equal to $$$3$$$.In the second test case, both product and sum are $$$0$$$. If we add $$$1$$$ to the second and the third element, the array will be $$$[-1,1,1,1]$$$, the sum will be equal to $$$2$$$ and the product will be equal to $$$-1$$$. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding $$$1$$$ twice to the first element the array will be $$$[2,-2,1]$$$, the sum will be $$$1$$$ and the product will be $$$-4$$$.
Java 8
standard input
[ "implementation", "math" ]
1ffb08fe61cdf90099c82162b8353b1f
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-100 \le a_i \le 100$$$) — elements of the array .
800
For each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.
standard output
PASSED
9ab8fb08876b3ddde3e0c60b5dad3719
train_003.jsonl
1581257100
Guy-Manuel and Thomas have an array $$$a$$$ of $$$n$$$ integers [$$$a_1, a_2, \dots, a_n$$$]. In one step they can add $$$1$$$ to any element of the array. Formally, in one step they can choose any integer index $$$i$$$ ($$$1 \le i \le n$$$) and do $$$a_i := a_i + 1$$$.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make $$$a_1 + a_2 +$$$ $$$\dots$$$ $$$+ a_n \ne 0$$$ and $$$a_1 \cdot a_2 \cdot$$$ $$$\dots$$$ $$$\cdot a_n \ne 0$$$.
256 megabytes
import java.util.*; public class mohammad { public static void main (String[]args) { Scanner U = new Scanner (System.in); int t = U.nextInt(); while(t!=0){ int n = U.nextInt(); int[] a = new int[n]; int sum = 0, c =0; for(int i=0 ; i<n ; i++){ a[i] = U.nextInt(); if(a[i]==0){ a[i]++; c++;} sum+=a[i]; } if(sum==0){ sum++; c++;} if(sum!=0) System.out.println(c); t--; } } }
Java
["4\n3\n2 -1 -1\n4\n-1 0 0 1\n2\n-1 2\n3\n0 -2 1"]
1 second
["1\n2\n0\n2"]
NoteIn the first test case, the sum is $$$0$$$. If we add $$$1$$$ to the first element, the array will be $$$[3,-1,-1]$$$, the sum will be equal to $$$1$$$ and the product will be equal to $$$3$$$.In the second test case, both product and sum are $$$0$$$. If we add $$$1$$$ to the second and the third element, the array will be $$$[-1,1,1,1]$$$, the sum will be equal to $$$2$$$ and the product will be equal to $$$-1$$$. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding $$$1$$$ twice to the first element the array will be $$$[2,-2,1]$$$, the sum will be $$$1$$$ and the product will be $$$-4$$$.
Java 8
standard input
[ "implementation", "math" ]
1ffb08fe61cdf90099c82162b8353b1f
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-100 \le a_i \le 100$$$) — elements of the array .
800
For each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.
standard output
PASSED
c62331a6cab2440e6e17940974ff5884
train_003.jsonl
1581257100
Guy-Manuel and Thomas have an array $$$a$$$ of $$$n$$$ integers [$$$a_1, a_2, \dots, a_n$$$]. In one step they can add $$$1$$$ to any element of the array. Formally, in one step they can choose any integer index $$$i$$$ ($$$1 \le i \le n$$$) and do $$$a_i := a_i + 1$$$.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make $$$a_1 + a_2 +$$$ $$$\dots$$$ $$$+ a_n \ne 0$$$ and $$$a_1 \cdot a_2 \cdot$$$ $$$\dots$$$ $$$\cdot a_n \ne 0$$$.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class DynamicProgramming { public static void main(String[] args) { Scanner scn = new Scanner(System.in); int n = scn.nextInt(); for (int i = 0; i < n; i++){ int size = scn.nextInt(); int[] arr = new int[size]; for(int j = 0 ; j < size ; j++) arr[j] = scn.nextInt(); fun(arr); } } public static void fun(int[] arr) { Arrays.sort(arr); int sum = 0; int cz = 0; for(int ele : arr){ if(ele == 0) cz++; sum += ele; } if(sum == 0){ if(cz == 0){ System.out.println("1"); }else{ System.out.println(cz); } }else{ if(cz == 0){ System.out.println("0"); }else{ if(sum + cz != 0) System.out.println(cz); else System.out.println(cz + 1); } } } }
Java
["4\n3\n2 -1 -1\n4\n-1 0 0 1\n2\n-1 2\n3\n0 -2 1"]
1 second
["1\n2\n0\n2"]
NoteIn the first test case, the sum is $$$0$$$. If we add $$$1$$$ to the first element, the array will be $$$[3,-1,-1]$$$, the sum will be equal to $$$1$$$ and the product will be equal to $$$3$$$.In the second test case, both product and sum are $$$0$$$. If we add $$$1$$$ to the second and the third element, the array will be $$$[-1,1,1,1]$$$, the sum will be equal to $$$2$$$ and the product will be equal to $$$-1$$$. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding $$$1$$$ twice to the first element the array will be $$$[2,-2,1]$$$, the sum will be $$$1$$$ and the product will be $$$-4$$$.
Java 8
standard input
[ "implementation", "math" ]
1ffb08fe61cdf90099c82162b8353b1f
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-100 \le a_i \le 100$$$) — elements of the array .
800
For each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.
standard output
PASSED
f50ac584872bfe715245a73571f4bcf5
train_003.jsonl
1581257100
Guy-Manuel and Thomas have an array $$$a$$$ of $$$n$$$ integers [$$$a_1, a_2, \dots, a_n$$$]. In one step they can add $$$1$$$ to any element of the array. Formally, in one step they can choose any integer index $$$i$$$ ($$$1 \le i \le n$$$) and do $$$a_i := a_i + 1$$$.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make $$$a_1 + a_2 +$$$ $$$\dots$$$ $$$+ a_n \ne 0$$$ and $$$a_1 \cdot a_2 \cdot$$$ $$$\dots$$$ $$$\cdot a_n \ne 0$$$.
256 megabytes
import java.io.IOException; import java.util.Scanner; public class Solutions { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for(int i =0; i < t; i++) { int n = sc.nextInt(); int []a = new int[100]; int p = 1; int s = 0; int cntz = 0; for(int j = 0; j < n; j++) { a[j] = sc.nextInt(); p = p * a[j]; s += a[j]; if(a[j] == 0) cntz++; } int res = cntz; if(s + cntz == 0) { res++; } System.out.println(res); } sc.close(); } }
Java
["4\n3\n2 -1 -1\n4\n-1 0 0 1\n2\n-1 2\n3\n0 -2 1"]
1 second
["1\n2\n0\n2"]
NoteIn the first test case, the sum is $$$0$$$. If we add $$$1$$$ to the first element, the array will be $$$[3,-1,-1]$$$, the sum will be equal to $$$1$$$ and the product will be equal to $$$3$$$.In the second test case, both product and sum are $$$0$$$. If we add $$$1$$$ to the second and the third element, the array will be $$$[-1,1,1,1]$$$, the sum will be equal to $$$2$$$ and the product will be equal to $$$-1$$$. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding $$$1$$$ twice to the first element the array will be $$$[2,-2,1]$$$, the sum will be $$$1$$$ and the product will be $$$-4$$$.
Java 8
standard input
[ "implementation", "math" ]
1ffb08fe61cdf90099c82162b8353b1f
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-100 \le a_i \le 100$$$) — elements of the array .
800
For each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.
standard output
PASSED
9d9f51f89009526531935c92ea620fbc
train_003.jsonl
1581257100
Guy-Manuel and Thomas have an array $$$a$$$ of $$$n$$$ integers [$$$a_1, a_2, \dots, a_n$$$]. In one step they can add $$$1$$$ to any element of the array. Formally, in one step they can choose any integer index $$$i$$$ ($$$1 \le i \le n$$$) and do $$$a_i := a_i + 1$$$.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make $$$a_1 + a_2 +$$$ $$$\dots$$$ $$$+ a_n \ne 0$$$ and $$$a_1 \cdot a_2 \cdot$$$ $$$\dots$$$ $$$\cdot a_n \ne 0$$$.
256 megabytes
import java.util.*; /** * * @author Razan */ public class JavaApplication64 { /** * @param args the command line arguments */ //import java.util.Scanner; /** * * @author Razan */ //import java.util.Scanner; /** * * @author Razan */ //import java.util.Scanner; /** * * @author Razan */ static class NewClass20 { Scanner s = new Scanner(System.in); // Scanner ss = new Scanner(System.in); int n = s.nextInt(); // int t; int[] a; int pro = 1; int i; int countS = 1; int countP = 1;int count ; List l=new ArrayList(); public void ss() { for (int ii = 0; ii < n; ii++) { count=0; int t = s.nextInt(); a = new int[t]; for (i = 0; i < t; i++) { a[i] = s.nextInt(); } for (i = 0; i < a.length; i++) { //System.out.println(a[i]); // sum += a[i]; // pro *= a[i]; System.out.println("pro"+pro); if (a[i] == 0) { a[i] = a[i] + 1; count++; } } int sum = 0; // System.out.println("count"+count); for (i = 0; i < a.length; i++) { // System.out.println(a[i]); sum += a[i]; } // System.out.println("sum"+sum); while (sum == 0) { count++; //System.out.println("countS"+countS); sum = sum + count; } if (sum != 0) { l.add(count); } } for(i=0;i<l.size();i++){ System.out.println(l.get(i)); } // System.out.println("count"+countS); //if(count+sum!=0&&pro*count>=0){ // System.out.println(count); //break; // } } } public static void main(String[] args) { // TODO code application logic here NewClass20 n = new NewClass20(); n.ss(); } }
Java
["4\n3\n2 -1 -1\n4\n-1 0 0 1\n2\n-1 2\n3\n0 -2 1"]
1 second
["1\n2\n0\n2"]
NoteIn the first test case, the sum is $$$0$$$. If we add $$$1$$$ to the first element, the array will be $$$[3,-1,-1]$$$, the sum will be equal to $$$1$$$ and the product will be equal to $$$3$$$.In the second test case, both product and sum are $$$0$$$. If we add $$$1$$$ to the second and the third element, the array will be $$$[-1,1,1,1]$$$, the sum will be equal to $$$2$$$ and the product will be equal to $$$-1$$$. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding $$$1$$$ twice to the first element the array will be $$$[2,-2,1]$$$, the sum will be $$$1$$$ and the product will be $$$-4$$$.
Java 8
standard input
[ "implementation", "math" ]
1ffb08fe61cdf90099c82162b8353b1f
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-100 \le a_i \le 100$$$) — elements of the array .
800
For each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.
standard output
PASSED
bf7d2bbc3c7a4ecf5df09149e68806c5
train_003.jsonl
1581257100
Guy-Manuel and Thomas have an array $$$a$$$ of $$$n$$$ integers [$$$a_1, a_2, \dots, a_n$$$]. In one step they can add $$$1$$$ to any element of the array. Formally, in one step they can choose any integer index $$$i$$$ ($$$1 \le i \le n$$$) and do $$$a_i := a_i + 1$$$.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make $$$a_1 + a_2 +$$$ $$$\dots$$$ $$$+ a_n \ne 0$$$ and $$$a_1 \cdot a_2 \cdot$$$ $$$\dots$$$ $$$\cdot a_n \ne 0$$$.
256 megabytes
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.List; import java.util.Scanner; import java.util.stream.Collectors; public class _p001300A { static public void main(final String[] args) throws java.io.IOException { p001300A._main(args); } //begin p001300A.java static private class p001300A extends Solver{public p001300A(){nameIn="p001300A.in" ;singleTest=false;}int n;int[]a;@Override protected void solve(){int s=0;int res =0;for(int i=0;i<n;i++){if(a[i]==0){a[i]++;res++;}s+=a[i];}if(s==0){res++;}pw.println (res);}@Override public void readInput()throws IOException{n=sc.nextInt();sc.nextLine ();a=Arrays.stream(sc.nextLine().trim().split("\\s+")).mapToInt(Integer::valueOf ).toArray();}static public void _main(String[]args)throws IOException{new p001300A ().run();}} //end p001300A.java //begin net/leksi/contest/Solver.java static private abstract class Solver{protected String nameIn=null;protected String nameOut=null;protected boolean singleTest=false;protected boolean preprocessDebug =false;protected boolean doNotPreprocess=false;protected Scanner sc=null;protected PrintWriter pw=null;private void process()throws IOException{if(!singleTest){int t=lineToIntArray()[0];while(t-->0){readInput();solve();}}else{readInput();solve( );}}abstract protected void readInput()throws IOException;abstract protected void solve()throws IOException;protected int[]lineToIntArray()throws IOException{return Arrays.stream(sc.nextLine().trim().split("\\s+")).mapToInt(Integer::valueOf).toArray ();}protected long[]lineToLongArray()throws IOException{return Arrays.stream(sc.nextLine ().trim().split("\\s+")).mapToLong(Long::valueOf).toArray();}protected String intArrayToString (final int[]a){return Arrays.stream(a).mapToObj(Integer::toString).collect(Collectors .joining(" "));}protected String longArrayToString(final long[]a){return Arrays.stream (a).mapToObj(Long::toString).collect(Collectors.joining(" "));}protected List<Long> longArrayToList(final long[]a){return Arrays.stream(a).mapToObj(Long::valueOf).collect (Collectors.toList());}protected List<Integer>intArrayToList(final int[]a){return Arrays.stream(a).mapToObj(Integer::valueOf).collect(Collectors.toList());}protected List<Long>intArrayToLongList(final int[]a){return Arrays.stream(a).mapToObj(Long ::valueOf).collect(Collectors.toList());}protected void run()throws IOException{ try{try(FileInputStream fis=new FileInputStream(nameIn);PrintWriter pw0=select_output ();){sc=new Scanner(fis);pw=pw0;process();}}catch(IOException ex){try(PrintWriter pw0=select_output();){sc=new Scanner(System.in);pw=pw0;process();}}}private PrintWriter select_output()throws FileNotFoundException{if(nameOut !=null){return new PrintWriter (nameOut);}return new PrintWriter(System.out);}} //end net/leksi/contest/Solver.java }
Java
["4\n3\n2 -1 -1\n4\n-1 0 0 1\n2\n-1 2\n3\n0 -2 1"]
1 second
["1\n2\n0\n2"]
NoteIn the first test case, the sum is $$$0$$$. If we add $$$1$$$ to the first element, the array will be $$$[3,-1,-1]$$$, the sum will be equal to $$$1$$$ and the product will be equal to $$$3$$$.In the second test case, both product and sum are $$$0$$$. If we add $$$1$$$ to the second and the third element, the array will be $$$[-1,1,1,1]$$$, the sum will be equal to $$$2$$$ and the product will be equal to $$$-1$$$. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding $$$1$$$ twice to the first element the array will be $$$[2,-2,1]$$$, the sum will be $$$1$$$ and the product will be $$$-4$$$.
Java 8
standard input
[ "implementation", "math" ]
1ffb08fe61cdf90099c82162b8353b1f
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-100 \le a_i \le 100$$$) — elements of the array .
800
For each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.
standard output
PASSED
a8e3a79592982ec6310d133582d4c89b
train_003.jsonl
1581257100
Guy-Manuel and Thomas have an array $$$a$$$ of $$$n$$$ integers [$$$a_1, a_2, \dots, a_n$$$]. In one step they can add $$$1$$$ to any element of the array. Formally, in one step they can choose any integer index $$$i$$$ ($$$1 \le i \le n$$$) and do $$$a_i := a_i + 1$$$.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make $$$a_1 + a_2 +$$$ $$$\dots$$$ $$$+ a_n \ne 0$$$ and $$$a_1 \cdot a_2 \cdot$$$ $$$\dots$$$ $$$\cdot a_n \ne 0$$$.
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.stream.Collectors; public class _p001300A { static public void main(final String[] args) throws java.io.IOException { p001300A._main(args); } //begin p001300A.java static private class p001300A{static public void _main(String[]args)throws IOException {new Solver(){{{nameIn="p001300A.in";singleTest=false;}}@Override public void process (BufferedReader br,PrintWriter pw)throws IOException{int n=readIntArray(br)[0];int []a=readIntArray(br);solve(n,a,pw);}private void solve(int n,int[]a,PrintWriter pw ){int s=0;int res=0;for(int i=0;i<n;i++){if(a[i]==0){a[i]++;res++;}s+=a[i];}if(s ==0){res++;}pw.println(res);}}.run();}} //end p001300A.java //begin net/leksi/contest/Solver.java static private abstract class Solver{protected String nameIn=null;protected String nameOut=null;protected boolean singleTest=false;protected boolean preprocessDebug =false;protected boolean doNotPreprocess=false;private void preProcess(final BufferedReader br,final PrintWriter pw)throws IOException{if(!singleTest){int t=Integer.valueOf (br.readLine().trim());while(t-->0){process(br,pw);}}else{process(br,pw);}}abstract public void process(final BufferedReader br,final PrintWriter pw)throws IOException ;protected int[]readIntArray(final BufferedReader br)throws IOException{return Arrays .stream(br.readLine().trim().split("\\s+")).mapToInt(v->Integer.valueOf(v)).toArray ();}protected long[]readLongArray(final BufferedReader br)throws IOException{return Arrays.stream(br.readLine().trim().split("\\s+")).mapToLong(v->Long.valueOf(v)).toArray ();}protected String readString(final BufferedReader br)throws IOException{return br.readLine().trim();}protected String intArrayToString(final int[]a){return Arrays .stream(a).mapToObj(v->Integer.toString(v)).collect(Collectors.joining(" "));}protected String longArrayToString(final long[]a){return Arrays.stream(a).mapToObj(v->Long .toString(v)).collect(Collectors.joining(" "));}public void run()throws IOException {try{try(FileReader fr=new FileReader(nameIn);BufferedReader br=new BufferedReader (fr);PrintWriter pw=select_output();){preProcess(br,pw);}}catch(Exception ex){try (InputStreamReader fr=new InputStreamReader(System.in);BufferedReader br=new BufferedReader (fr);PrintWriter pw=select_output();){preProcess(br,pw);}}}private PrintWriter select_output ()throws FileNotFoundException{if(nameOut !=null){return new PrintWriter(nameOut );}return new PrintWriter(System.out);}} //end net/leksi/contest/Solver.java }
Java
["4\n3\n2 -1 -1\n4\n-1 0 0 1\n2\n-1 2\n3\n0 -2 1"]
1 second
["1\n2\n0\n2"]
NoteIn the first test case, the sum is $$$0$$$. If we add $$$1$$$ to the first element, the array will be $$$[3,-1,-1]$$$, the sum will be equal to $$$1$$$ and the product will be equal to $$$3$$$.In the second test case, both product and sum are $$$0$$$. If we add $$$1$$$ to the second and the third element, the array will be $$$[-1,1,1,1]$$$, the sum will be equal to $$$2$$$ and the product will be equal to $$$-1$$$. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding $$$1$$$ twice to the first element the array will be $$$[2,-2,1]$$$, the sum will be $$$1$$$ and the product will be $$$-4$$$.
Java 8
standard input
[ "implementation", "math" ]
1ffb08fe61cdf90099c82162b8353b1f
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-100 \le a_i \le 100$$$) — elements of the array .
800
For each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.
standard output
PASSED
989090317f639ed973990594936a3b74
train_003.jsonl
1581257100
Guy-Manuel and Thomas have an array $$$a$$$ of $$$n$$$ integers [$$$a_1, a_2, \dots, a_n$$$]. In one step they can add $$$1$$$ to any element of the array. Formally, in one step they can choose any integer index $$$i$$$ ($$$1 \le i \le n$$$) and do $$$a_i := a_i + 1$$$.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make $$$a_1 + a_2 +$$$ $$$\dots$$$ $$$+ a_n \ne 0$$$ and $$$a_1 \cdot a_2 \cdot$$$ $$$\dots$$$ $$$\cdot a_n \ne 0$$$.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String [] args) { Scanner input = new Scanner(System.in); int t = input.nextInt(); for(int i = 0 ; i < t ; i++) { int n = input.nextInt(); int sum = 0; long product = 0; int countZeros = 0; for(int j = 0 ; j < n ; j++){ int a = input.nextInt(); sum += a; product *= a; if(a == 0) countZeros++; } System.out.println(sum + countZeros == 0 ? countZeros + 1 : countZeros); } } }
Java
["4\n3\n2 -1 -1\n4\n-1 0 0 1\n2\n-1 2\n3\n0 -2 1"]
1 second
["1\n2\n0\n2"]
NoteIn the first test case, the sum is $$$0$$$. If we add $$$1$$$ to the first element, the array will be $$$[3,-1,-1]$$$, the sum will be equal to $$$1$$$ and the product will be equal to $$$3$$$.In the second test case, both product and sum are $$$0$$$. If we add $$$1$$$ to the second and the third element, the array will be $$$[-1,1,1,1]$$$, the sum will be equal to $$$2$$$ and the product will be equal to $$$-1$$$. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding $$$1$$$ twice to the first element the array will be $$$[2,-2,1]$$$, the sum will be $$$1$$$ and the product will be $$$-4$$$.
Java 8
standard input
[ "implementation", "math" ]
1ffb08fe61cdf90099c82162b8353b1f
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-100 \le a_i \le 100$$$) — elements of the array .
800
For each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.
standard output
PASSED
a8eebef3df5037d87968df145d1519a5
train_003.jsonl
1581257100
Guy-Manuel and Thomas have an array $$$a$$$ of $$$n$$$ integers [$$$a_1, a_2, \dots, a_n$$$]. In one step they can add $$$1$$$ to any element of the array. Formally, in one step they can choose any integer index $$$i$$$ ($$$1 \le i \le n$$$) and do $$$a_i := a_i + 1$$$.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make $$$a_1 + a_2 +$$$ $$$\dots$$$ $$$+ a_n \ne 0$$$ and $$$a_1 \cdot a_2 \cdot$$$ $$$\dots$$$ $$$\cdot a_n \ne 0$$$.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String [] args) { Scanner input = new Scanner(System.in); int t = input.nextInt(); for(int i = 0 ; i < t ; i++) { int n = input.nextInt(); int [] a = new int [n]; int sum = 0; long product = 0; int countZeros = 0; for(int j = 0 ; j < n ; j++){ a[j] = input.nextInt(); sum += a[j]; product *= a[j]; if(a[j] == 0) countZeros++; } System.out.println(sum + countZeros == 0 ? countZeros + 1 : countZeros); } } }
Java
["4\n3\n2 -1 -1\n4\n-1 0 0 1\n2\n-1 2\n3\n0 -2 1"]
1 second
["1\n2\n0\n2"]
NoteIn the first test case, the sum is $$$0$$$. If we add $$$1$$$ to the first element, the array will be $$$[3,-1,-1]$$$, the sum will be equal to $$$1$$$ and the product will be equal to $$$3$$$.In the second test case, both product and sum are $$$0$$$. If we add $$$1$$$ to the second and the third element, the array will be $$$[-1,1,1,1]$$$, the sum will be equal to $$$2$$$ and the product will be equal to $$$-1$$$. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding $$$1$$$ twice to the first element the array will be $$$[2,-2,1]$$$, the sum will be $$$1$$$ and the product will be $$$-4$$$.
Java 8
standard input
[ "implementation", "math" ]
1ffb08fe61cdf90099c82162b8353b1f
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-100 \le a_i \le 100$$$) — elements of the array .
800
For each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.
standard output
PASSED
0cce92d8745db9bd6204b137f85a86d9
train_003.jsonl
1581257100
Guy-Manuel and Thomas have an array $$$a$$$ of $$$n$$$ integers [$$$a_1, a_2, \dots, a_n$$$]. In one step they can add $$$1$$$ to any element of the array. Formally, in one step they can choose any integer index $$$i$$$ ($$$1 \le i \le n$$$) and do $$$a_i := a_i + 1$$$.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make $$$a_1 + a_2 +$$$ $$$\dots$$$ $$$+ a_n \ne 0$$$ and $$$a_1 \cdot a_2 \cdot$$$ $$$\dots$$$ $$$\cdot a_n \ne 0$$$.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String [] args) { Scanner input = new Scanner(System.in); int t = input.nextInt(); for(int i = 0 ; i < t ; i++) { int n = input.nextInt(); int [] a = new int [n]; int sum = 0; long product = 0; int countZeros = 0; for(int j = 0 ; j < n ; j++){ a[j] = input.nextInt(); sum += a[j]; product *= a[j]; if(a[j] == 0) countZeros++; } if(sum + countZeros == 0) System.out.println(countZeros + 1); else System.out.println(countZeros); } } }
Java
["4\n3\n2 -1 -1\n4\n-1 0 0 1\n2\n-1 2\n3\n0 -2 1"]
1 second
["1\n2\n0\n2"]
NoteIn the first test case, the sum is $$$0$$$. If we add $$$1$$$ to the first element, the array will be $$$[3,-1,-1]$$$, the sum will be equal to $$$1$$$ and the product will be equal to $$$3$$$.In the second test case, both product and sum are $$$0$$$. If we add $$$1$$$ to the second and the third element, the array will be $$$[-1,1,1,1]$$$, the sum will be equal to $$$2$$$ and the product will be equal to $$$-1$$$. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding $$$1$$$ twice to the first element the array will be $$$[2,-2,1]$$$, the sum will be $$$1$$$ and the product will be $$$-4$$$.
Java 8
standard input
[ "implementation", "math" ]
1ffb08fe61cdf90099c82162b8353b1f
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-100 \le a_i \le 100$$$) — elements of the array .
800
For each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.
standard output
PASSED
826a53e99eb0b45e0cca5540f9e9cf13
train_003.jsonl
1581257100
Guy-Manuel and Thomas have an array $$$a$$$ of $$$n$$$ integers [$$$a_1, a_2, \dots, a_n$$$]. In one step they can add $$$1$$$ to any element of the array. Formally, in one step they can choose any integer index $$$i$$$ ($$$1 \le i \le n$$$) and do $$$a_i := a_i + 1$$$.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make $$$a_1 + a_2 +$$$ $$$\dots$$$ $$$+ a_n \ne 0$$$ and $$$a_1 \cdot a_2 \cdot$$$ $$$\dots$$$ $$$\cdot a_n \ne 0$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class NonZero { public static void main(String[] args) throws NumberFormatException, IOException { InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); int T = Integer.parseInt(br.readLine()); for (int i = 0; i < T; i++) { int n = Integer.parseInt(br.readLine()); String[] as = br.readLine().split(" "); int[] A = new int[n]; for (int j = 0; j < n; j++) { A[j] = Integer.parseInt(as[j]); } System.out.println(getMinChange(A, n)); } br.close(); } private static int getMinChange(int[] A, int n) { int cz = 0; int sum = 0; for (int i = 0; i < n; i++) { sum += A[i]; cz += A[i] == 0 ? 1 : 0; } return cz + ((sum == -cz) ? 1 : 0); } }
Java
["4\n3\n2 -1 -1\n4\n-1 0 0 1\n2\n-1 2\n3\n0 -2 1"]
1 second
["1\n2\n0\n2"]
NoteIn the first test case, the sum is $$$0$$$. If we add $$$1$$$ to the first element, the array will be $$$[3,-1,-1]$$$, the sum will be equal to $$$1$$$ and the product will be equal to $$$3$$$.In the second test case, both product and sum are $$$0$$$. If we add $$$1$$$ to the second and the third element, the array will be $$$[-1,1,1,1]$$$, the sum will be equal to $$$2$$$ and the product will be equal to $$$-1$$$. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding $$$1$$$ twice to the first element the array will be $$$[2,-2,1]$$$, the sum will be $$$1$$$ and the product will be $$$-4$$$.
Java 8
standard input
[ "implementation", "math" ]
1ffb08fe61cdf90099c82162b8353b1f
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-100 \le a_i \le 100$$$) — elements of the array .
800
For each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.
standard output
PASSED
e0fe9367104bf12628ca11b03750ce77
train_003.jsonl
1581257100
Guy-Manuel and Thomas have an array $$$a$$$ of $$$n$$$ integers [$$$a_1, a_2, \dots, a_n$$$]. In one step they can add $$$1$$$ to any element of the array. Formally, in one step they can choose any integer index $$$i$$$ ($$$1 \le i \le n$$$) and do $$$a_i := a_i + 1$$$.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make $$$a_1 + a_2 +$$$ $$$\dots$$$ $$$+ a_n \ne 0$$$ and $$$a_1 \cdot a_2 \cdot$$$ $$$\dots$$$ $$$\cdot a_n \ne 0$$$.
256 megabytes
/* -> Written by <- ----------- |J_O_B_E_E_L| |___________| | ___ | | (^_^) | | /( | )\ | |____|_|____| */ import java.lang.reflect.Array; import java.util.*; import java.io.*; import java.lang.*; import java.math.*; import java.util.Map.*; public class Test { static PrintWriter pw=new PrintWriter(System.out); public static void main(String[] args) throws IOException, InterruptedException { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0){ long sum=0,count=0; int x=sc.nextInt(); while(x-->0){ int y=sc.nextInt(); if(y==0)count++; sum+=y; } pw.println(sum+count==0 ? count+1:count); } pw.flush(); pw.close(); } }
Java
["4\n3\n2 -1 -1\n4\n-1 0 0 1\n2\n-1 2\n3\n0 -2 1"]
1 second
["1\n2\n0\n2"]
NoteIn the first test case, the sum is $$$0$$$. If we add $$$1$$$ to the first element, the array will be $$$[3,-1,-1]$$$, the sum will be equal to $$$1$$$ and the product will be equal to $$$3$$$.In the second test case, both product and sum are $$$0$$$. If we add $$$1$$$ to the second and the third element, the array will be $$$[-1,1,1,1]$$$, the sum will be equal to $$$2$$$ and the product will be equal to $$$-1$$$. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding $$$1$$$ twice to the first element the array will be $$$[2,-2,1]$$$, the sum will be $$$1$$$ and the product will be $$$-4$$$.
Java 8
standard input
[ "implementation", "math" ]
1ffb08fe61cdf90099c82162b8353b1f
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-100 \le a_i \le 100$$$) — elements of the array .
800
For each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.
standard output
PASSED
9922298ce4856e2ed70998a5f3008f74
train_003.jsonl
1581257100
Guy-Manuel and Thomas have an array $$$a$$$ of $$$n$$$ integers [$$$a_1, a_2, \dots, a_n$$$]. In one step they can add $$$1$$$ to any element of the array. Formally, in one step they can choose any integer index $$$i$$$ ($$$1 \le i \le n$$$) and do $$$a_i := a_i + 1$$$.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make $$$a_1 + a_2 +$$$ $$$\dots$$$ $$$+ a_n \ne 0$$$ and $$$a_1 \cdot a_2 \cdot$$$ $$$\dots$$$ $$$\cdot a_n \ne 0$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; import java.util.TreeSet; public class Q2 { public static void main(String[] args) { YScanner in = new YScanner(); int t = in.nextInt(); for(int i = 0;i<t;i++) { int n = in.nextInt(); int[] arr = new int[n]; int zero = 0; int sum = 0; for(int j = 0;j<n;j++) { arr[j] = in.nextInt(); if(arr[j]==0) zero++; sum+=arr[j]; } if(sum+zero==0) System.out.println(zero+1); else System.out.println(zero); } } } class YScanner { BufferedReader br ; StringTokenizer st; public YScanner() { br = new BufferedReader(new InputStreamReader(System.in)); st = null; } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); }}
Java
["4\n3\n2 -1 -1\n4\n-1 0 0 1\n2\n-1 2\n3\n0 -2 1"]
1 second
["1\n2\n0\n2"]
NoteIn the first test case, the sum is $$$0$$$. If we add $$$1$$$ to the first element, the array will be $$$[3,-1,-1]$$$, the sum will be equal to $$$1$$$ and the product will be equal to $$$3$$$.In the second test case, both product and sum are $$$0$$$. If we add $$$1$$$ to the second and the third element, the array will be $$$[-1,1,1,1]$$$, the sum will be equal to $$$2$$$ and the product will be equal to $$$-1$$$. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding $$$1$$$ twice to the first element the array will be $$$[2,-2,1]$$$, the sum will be $$$1$$$ and the product will be $$$-4$$$.
Java 8
standard input
[ "implementation", "math" ]
1ffb08fe61cdf90099c82162b8353b1f
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-100 \le a_i \le 100$$$) — elements of the array .
800
For each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.
standard output
PASSED
0c3923a68f88b15b6fdf3c2031279482
train_003.jsonl
1581257100
Guy-Manuel and Thomas have an array $$$a$$$ of $$$n$$$ integers [$$$a_1, a_2, \dots, a_n$$$]. In one step they can add $$$1$$$ to any element of the array. Formally, in one step they can choose any integer index $$$i$$$ ($$$1 \le i \le n$$$) and do $$$a_i := a_i + 1$$$.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make $$$a_1 + a_2 +$$$ $$$\dots$$$ $$$+ a_n \ne 0$$$ and $$$a_1 \cdot a_2 \cdot$$$ $$$\dots$$$ $$$\cdot a_n \ne 0$$$.
256 megabytes
import java.util.Scanner; public class nonzero { public static void main(String[] args) { Scanner sc=new Scanner (System.in); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); int ar[]=new int[n]; int z=0; for(int i=0;i<n;i++) { ar[i]=sc.nextInt(); if(ar[i]==0) { ++z; ar[i]=1; } } int w=0; for(int i=0;i<n;i++) { w=w+ar[i]; } if(w==0) { z=z+Math.abs(w-0)+1; } System.out.println(z); } } }
Java
["4\n3\n2 -1 -1\n4\n-1 0 0 1\n2\n-1 2\n3\n0 -2 1"]
1 second
["1\n2\n0\n2"]
NoteIn the first test case, the sum is $$$0$$$. If we add $$$1$$$ to the first element, the array will be $$$[3,-1,-1]$$$, the sum will be equal to $$$1$$$ and the product will be equal to $$$3$$$.In the second test case, both product and sum are $$$0$$$. If we add $$$1$$$ to the second and the third element, the array will be $$$[-1,1,1,1]$$$, the sum will be equal to $$$2$$$ and the product will be equal to $$$-1$$$. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding $$$1$$$ twice to the first element the array will be $$$[2,-2,1]$$$, the sum will be $$$1$$$ and the product will be $$$-4$$$.
Java 8
standard input
[ "implementation", "math" ]
1ffb08fe61cdf90099c82162b8353b1f
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-100 \le a_i \le 100$$$) — elements of the array .
800
For each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.
standard output
PASSED
063652fd90cb6dbcef5575654e087085
train_003.jsonl
1581257100
Guy-Manuel and Thomas have an array $$$a$$$ of $$$n$$$ integers [$$$a_1, a_2, \dots, a_n$$$]. In one step they can add $$$1$$$ to any element of the array. Formally, in one step they can choose any integer index $$$i$$$ ($$$1 \le i \le n$$$) and do $$$a_i := a_i + 1$$$.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make $$$a_1 + a_2 +$$$ $$$\dots$$$ $$$+ a_n \ne 0$$$ and $$$a_1 \cdot a_2 \cdot$$$ $$$\dots$$$ $$$\cdot a_n \ne 0$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author EDGE */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task618A solver = new Task618A(); solver.solve(1, in, out); out.close(); } static class Task618A { public void solve(int testNumber, FastReader in, PrintWriter out) { int t = in.nextInt(); while (t-- > 0) { int n = in.nextInt(); int pos = 0, neg = 0, ze = 0; int pos_s = 0, neg_s = 0; for (int i = 0; i < n; i++) { int te = in.nextInt(); if (te == 0) { ze++; } else pos_s += te; } int ans = 0; if (ze > 0) ans += ze; pos_s += ans; if (pos_s == 0) ans += 1; out.println(ans); } } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader(InputStream inputStream) { br = new BufferedReader(new InputStreamReader(inputStream)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["4\n3\n2 -1 -1\n4\n-1 0 0 1\n2\n-1 2\n3\n0 -2 1"]
1 second
["1\n2\n0\n2"]
NoteIn the first test case, the sum is $$$0$$$. If we add $$$1$$$ to the first element, the array will be $$$[3,-1,-1]$$$, the sum will be equal to $$$1$$$ and the product will be equal to $$$3$$$.In the second test case, both product and sum are $$$0$$$. If we add $$$1$$$ to the second and the third element, the array will be $$$[-1,1,1,1]$$$, the sum will be equal to $$$2$$$ and the product will be equal to $$$-1$$$. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding $$$1$$$ twice to the first element the array will be $$$[2,-2,1]$$$, the sum will be $$$1$$$ and the product will be $$$-4$$$.
Java 8
standard input
[ "implementation", "math" ]
1ffb08fe61cdf90099c82162b8353b1f
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-100 \le a_i \le 100$$$) — elements of the array .
800
For each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.
standard output
PASSED
1bf74149b88e97e23fb2dc1e69e9bab7
train_003.jsonl
1581257100
Guy-Manuel and Thomas have an array $$$a$$$ of $$$n$$$ integers [$$$a_1, a_2, \dots, a_n$$$]. In one step they can add $$$1$$$ to any element of the array. Formally, in one step they can choose any integer index $$$i$$$ ($$$1 \le i \le n$$$) and do $$$a_i := a_i + 1$$$.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make $$$a_1 + a_2 +$$$ $$$\dots$$$ $$$+ a_n \ne 0$$$ and $$$a_1 \cdot a_2 \cdot$$$ $$$\dots$$$ $$$\cdot a_n \ne 0$$$.
256 megabytes
import java.io.*; import java.util.*; public class utkarsh { public static void main(String[] args) { new utkarsh().run(); } BufferedReader br; PrintWriter out; long mod = (long) (1e9 + 7), inf = (long) (3e18); void solve() { int t = ni(); while(t-- > 0) { int n = ni(); int a[] = new int[n]; int ans = 0; for(int i = 0; i < n; i++) { a[i] = ni(); if(a[i] == 0) { a[i]++; ans++; } } long sum = 0; for(int x : a) sum += x; if(sum == 0) ans++; out.println(ans); } } // -------- I/O Template ------------- char nc() { return ns().charAt(0); } String nLine() { try { return br.readLine(); } catch(IOException e) { return "-1"; } } double nd() { return Double.parseDouble(ns()); } long nl() { return Long.parseLong(ns()); } int ni() { return Integer.parseInt(ns()); } int[] na(int n) { int a[] = new int[n]; for(int i = 0; i < n; i++) a[i] = ni(); return a; } StringTokenizer ip; String ns() { if(ip == null || !ip.hasMoreTokens()) { try { ip = new StringTokenizer(br.readLine()); } catch(IOException e) { throw new InputMismatchException(); } } return ip.nextToken(); } void run() { try { if (System.getProperty("ONLINE_JUDGE") == null) { br = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } else { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } } catch (FileNotFoundException e) { System.out.println(e); } solve(); out.flush(); } }
Java
["4\n3\n2 -1 -1\n4\n-1 0 0 1\n2\n-1 2\n3\n0 -2 1"]
1 second
["1\n2\n0\n2"]
NoteIn the first test case, the sum is $$$0$$$. If we add $$$1$$$ to the first element, the array will be $$$[3,-1,-1]$$$, the sum will be equal to $$$1$$$ and the product will be equal to $$$3$$$.In the second test case, both product and sum are $$$0$$$. If we add $$$1$$$ to the second and the third element, the array will be $$$[-1,1,1,1]$$$, the sum will be equal to $$$2$$$ and the product will be equal to $$$-1$$$. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding $$$1$$$ twice to the first element the array will be $$$[2,-2,1]$$$, the sum will be $$$1$$$ and the product will be $$$-4$$$.
Java 8
standard input
[ "implementation", "math" ]
1ffb08fe61cdf90099c82162b8353b1f
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-100 \le a_i \le 100$$$) — elements of the array .
800
For each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.
standard output
PASSED
b6a5af7ffcc41f2c633569fef5a940a9
train_003.jsonl
1581257100
Guy-Manuel and Thomas have an array $$$a$$$ of $$$n$$$ integers [$$$a_1, a_2, \dots, a_n$$$]. In one step they can add $$$1$$$ to any element of the array. Formally, in one step they can choose any integer index $$$i$$$ ($$$1 \le i \le n$$$) and do $$$a_i := a_i + 1$$$.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make $$$a_1 + a_2 +$$$ $$$\dots$$$ $$$+ a_n \ne 0$$$ and $$$a_1 \cdot a_2 \cdot$$$ $$$\dots$$$ $$$\cdot a_n \ne 0$$$.
256 megabytes
import java.io.*; import java.util.*; public class utkarsh { BufferedReader br; PrintWriter out; long mod = (long) (1e9 + 7), inf = (long) (3e18); void solve() { int t = ni(); while(t-- > 0) { int n = ni(); int a[] = new int[n]; int ans = 0; for(int i = 0; i < n; i++) { a[i] = ni(); if(a[i] == 0) { a[i]++; ans++; } } long sum = 0; for(int x : a) sum += x; if(sum == 0) ans++; out.println(ans); } } long mp(long b, long e) { long r = 1; while(e > 0) { if( (e&1) == 1 ) r = (r * b) % mod; b = (b * b) % mod; e >>= 1; } return r; } // -------- I/O Template ------------- char nc() { return ns().charAt(0); } String nLine() { try { return br.readLine(); } catch(IOException e) { return "-1"; } } double nd() { return Double.parseDouble(ns()); } long nl() { return Long.parseLong(ns()); } int ni() { return Integer.parseInt(ns()); } StringTokenizer ip; String ns() { if(ip == null || !ip.hasMoreTokens()) { try { ip = new StringTokenizer(br.readLine()); } catch(IOException e) { throw new InputMismatchException(); } } return ip.nextToken(); } void run() { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.flush(); } public static void main(String[] args) { new utkarsh().run(); } }
Java
["4\n3\n2 -1 -1\n4\n-1 0 0 1\n2\n-1 2\n3\n0 -2 1"]
1 second
["1\n2\n0\n2"]
NoteIn the first test case, the sum is $$$0$$$. If we add $$$1$$$ to the first element, the array will be $$$[3,-1,-1]$$$, the sum will be equal to $$$1$$$ and the product will be equal to $$$3$$$.In the second test case, both product and sum are $$$0$$$. If we add $$$1$$$ to the second and the third element, the array will be $$$[-1,1,1,1]$$$, the sum will be equal to $$$2$$$ and the product will be equal to $$$-1$$$. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding $$$1$$$ twice to the first element the array will be $$$[2,-2,1]$$$, the sum will be $$$1$$$ and the product will be $$$-4$$$.
Java 8
standard input
[ "implementation", "math" ]
1ffb08fe61cdf90099c82162b8353b1f
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-100 \le a_i \le 100$$$) — elements of the array .
800
For each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.
standard output
PASSED
0c23d14255daf44dd7c31385464fb36b
train_003.jsonl
1581257100
Guy-Manuel and Thomas have an array $$$a$$$ of $$$n$$$ integers [$$$a_1, a_2, \dots, a_n$$$]. In one step they can add $$$1$$$ to any element of the array. Formally, in one step they can choose any integer index $$$i$$$ ($$$1 \le i \le n$$$) and do $$$a_i := a_i + 1$$$.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make $$$a_1 + a_2 +$$$ $$$\dots$$$ $$$+ a_n \ne 0$$$ and $$$a_1 \cdot a_2 \cdot$$$ $$$\dots$$$ $$$\cdot a_n \ne 0$$$.
256 megabytes
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)); int test = Integer.parseInt(br.readLine()); for(int t = 0; t < test; t++){ int n = Integer.parseInt(br.readLine()); String[] a = br.readLine().split(" "); int[] arr = new int[n]; for(int i = 0; i < n; i++){ arr[i] = Integer.parseInt(a[i]); } long sum = 0; int prod = 1; for(int i = 0; i < n; i++){ sum += arr[i]; prod *= arr[i]; } int c = 0; if(prod == 0 && sum == 0){ for(int i = 0; i < n; i++){ if(arr[i] == 0){ arr[i]++; c++; } } sum = 0; for(int i = 0; i < n; i++){ sum += arr[i]; } if(sum == 0) c++; } else if(sum == 0 && prod != 0){ c = 1; } else if(prod == 0 && sum != 0){ for(int i = 0; i < n; i++){ if(arr[i] == 0){ arr[i]++; c++; } } sum = 0; for(int i = 0; i < n; i++){ sum += arr[i]; } if(sum == 0) c++; } System.out.println(c); } } }
Java
["4\n3\n2 -1 -1\n4\n-1 0 0 1\n2\n-1 2\n3\n0 -2 1"]
1 second
["1\n2\n0\n2"]
NoteIn the first test case, the sum is $$$0$$$. If we add $$$1$$$ to the first element, the array will be $$$[3,-1,-1]$$$, the sum will be equal to $$$1$$$ and the product will be equal to $$$3$$$.In the second test case, both product and sum are $$$0$$$. If we add $$$1$$$ to the second and the third element, the array will be $$$[-1,1,1,1]$$$, the sum will be equal to $$$2$$$ and the product will be equal to $$$-1$$$. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding $$$1$$$ twice to the first element the array will be $$$[2,-2,1]$$$, the sum will be $$$1$$$ and the product will be $$$-4$$$.
Java 8
standard input
[ "implementation", "math" ]
1ffb08fe61cdf90099c82162b8353b1f
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-100 \le a_i \le 100$$$) — elements of the array .
800
For each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.
standard output
PASSED
045c2d6a2ae8467ac44190199cd77863
train_003.jsonl
1581257100
Guy-Manuel and Thomas have an array $$$a$$$ of $$$n$$$ integers [$$$a_1, a_2, \dots, a_n$$$]. In one step they can add $$$1$$$ to any element of the array. Formally, in one step they can choose any integer index $$$i$$$ ($$$1 \le i \le n$$$) and do $$$a_i := a_i + 1$$$.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make $$$a_1 + a_2 +$$$ $$$\dots$$$ $$$+ a_n \ne 0$$$ and $$$a_1 \cdot a_2 \cdot$$$ $$$\dots$$$ $$$\cdot a_n \ne 0$$$.
256 megabytes
import java.lang.reflect.Array; import java.util.Arrays; import java.util.Collections; import java.util.Scanner; public class ct1{ public static void main(String[] args) { Scanner inp = new Scanner(System.in); int x = inp.nextInt(); while (x-->0){ int n = inp.nextInt(); int[] a = new int[n]; int sum=0, res=0; for(int i=0; i<n ; i++){ a[i] = inp.nextInt(); if(a[i]==0) { res++; a[i]++; } sum+=a[i]; } if(sum == 0){ System.out.println(res+1); } else System.out.println(res); } } }
Java
["4\n3\n2 -1 -1\n4\n-1 0 0 1\n2\n-1 2\n3\n0 -2 1"]
1 second
["1\n2\n0\n2"]
NoteIn the first test case, the sum is $$$0$$$. If we add $$$1$$$ to the first element, the array will be $$$[3,-1,-1]$$$, the sum will be equal to $$$1$$$ and the product will be equal to $$$3$$$.In the second test case, both product and sum are $$$0$$$. If we add $$$1$$$ to the second and the third element, the array will be $$$[-1,1,1,1]$$$, the sum will be equal to $$$2$$$ and the product will be equal to $$$-1$$$. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding $$$1$$$ twice to the first element the array will be $$$[2,-2,1]$$$, the sum will be $$$1$$$ and the product will be $$$-4$$$.
Java 8
standard input
[ "implementation", "math" ]
1ffb08fe61cdf90099c82162b8353b1f
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-100 \le a_i \le 100$$$) — elements of the array .
800
For each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.
standard output
PASSED
8e275a217e12d5f1e9a53aa90d617c87
train_003.jsonl
1581257100
Guy-Manuel and Thomas have an array $$$a$$$ of $$$n$$$ integers [$$$a_1, a_2, \dots, a_n$$$]. In one step they can add $$$1$$$ to any element of the array. Formally, in one step they can choose any integer index $$$i$$$ ($$$1 \le i \le n$$$) and do $$$a_i := a_i + 1$$$.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make $$$a_1 + a_2 +$$$ $$$\dots$$$ $$$+ a_n \ne 0$$$ and $$$a_1 \cdot a_2 \cdot$$$ $$$\dots$$$ $$$\cdot a_n \ne 0$$$.
256 megabytes
import java.util.*; public class V { public static void main(String args[]) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); for(int x=0;x<t;x++) { int g=sc.nextInt(); int a=0; int b=0; for(int y=0;y<g;y++) { int p=sc.nextInt(); if(p==0) { a++; } b+=p; } if(b+a==0) { a++; } System.out.println(a); } } }
Java
["4\n3\n2 -1 -1\n4\n-1 0 0 1\n2\n-1 2\n3\n0 -2 1"]
1 second
["1\n2\n0\n2"]
NoteIn the first test case, the sum is $$$0$$$. If we add $$$1$$$ to the first element, the array will be $$$[3,-1,-1]$$$, the sum will be equal to $$$1$$$ and the product will be equal to $$$3$$$.In the second test case, both product and sum are $$$0$$$. If we add $$$1$$$ to the second and the third element, the array will be $$$[-1,1,1,1]$$$, the sum will be equal to $$$2$$$ and the product will be equal to $$$-1$$$. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding $$$1$$$ twice to the first element the array will be $$$[2,-2,1]$$$, the sum will be $$$1$$$ and the product will be $$$-4$$$.
Java 8
standard input
[ "implementation", "math" ]
1ffb08fe61cdf90099c82162b8353b1f
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-100 \le a_i \le 100$$$) — elements of the array .
800
For each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.
standard output
PASSED
2616c99a01a6c4a5d25e5cbf40db7e88
train_003.jsonl
1581257100
Guy-Manuel and Thomas have an array $$$a$$$ of $$$n$$$ integers [$$$a_1, a_2, \dots, a_n$$$]. In one step they can add $$$1$$$ to any element of the array. Formally, in one step they can choose any integer index $$$i$$$ ($$$1 \le i \le n$$$) and do $$$a_i := a_i + 1$$$.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make $$$a_1 + a_2 +$$$ $$$\dots$$$ $$$+ a_n \ne 0$$$ and $$$a_1 \cdot a_2 \cdot$$$ $$$\dots$$$ $$$\cdot a_n \ne 0$$$.
256 megabytes
import java.util.Scanner; public class A_1300 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner s= new Scanner(System.in); int t = s.nextInt(); outer: for(int tt =0;tt<t;tt++) { int n = s.nextInt(); int[] a = new int[n]; int sum = 0,prod = 1,pc=0; int i=0; for( i=0;i<n;i++) { a[i]= s.nextInt(); sum+=a[i]; if(a[i] == 0) pc++; prod*=a[i]; } if(pc == 0 && sum == 0) { pc=1; }else if(sum == -pc){ pc++; } System.out.println(pc); } } }
Java
["4\n3\n2 -1 -1\n4\n-1 0 0 1\n2\n-1 2\n3\n0 -2 1"]
1 second
["1\n2\n0\n2"]
NoteIn the first test case, the sum is $$$0$$$. If we add $$$1$$$ to the first element, the array will be $$$[3,-1,-1]$$$, the sum will be equal to $$$1$$$ and the product will be equal to $$$3$$$.In the second test case, both product and sum are $$$0$$$. If we add $$$1$$$ to the second and the third element, the array will be $$$[-1,1,1,1]$$$, the sum will be equal to $$$2$$$ and the product will be equal to $$$-1$$$. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding $$$1$$$ twice to the first element the array will be $$$[2,-2,1]$$$, the sum will be $$$1$$$ and the product will be $$$-4$$$.
Java 8
standard input
[ "implementation", "math" ]
1ffb08fe61cdf90099c82162b8353b1f
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-100 \le a_i \le 100$$$) — elements of the array .
800
For each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.
standard output
PASSED
500da8dfe9d3544084a9a49fabbc8f4f
train_003.jsonl
1581257100
Guy-Manuel and Thomas have an array $$$a$$$ of $$$n$$$ integers [$$$a_1, a_2, \dots, a_n$$$]. In one step they can add $$$1$$$ to any element of the array. Formally, in one step they can choose any integer index $$$i$$$ ($$$1 \le i \le n$$$) and do $$$a_i := a_i + 1$$$.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make $$$a_1 + a_2 +$$$ $$$\dots$$$ $$$+ a_n \ne 0$$$ and $$$a_1 \cdot a_2 \cdot$$$ $$$\dots$$$ $$$\cdot a_n \ne 0$$$.
256 megabytes
import java.util.*; public class NonZero { public static Scanner scn = new Scanner(System.in); public static void main(String[] args) { int t = scn.nextInt(); while(t-->0) { int n = scn.nextInt(); int[] a = new int[n]; int p = 1 ; int s = 0 ; int b = 0; int count1 =0 ; int count2 = 0 ; int count3 =0 ; int count4 = 0; for(int i=0;i<n;i++) { a[i] = scn.nextInt(); if(a[i]==0) { count2++; } if(a[i]== -1) { count3++; } if(a[i] == 1) { count4++; } s += a[i] ; } /*if(s==0 && count2==0 ) { System.out.println("1"); } else if(s>0 && count2>0) { System.out.println(count2); } else if(s==0 && count2>0) { System.out.println(count2); } else if(s+count2 == 0) { System.out.println("2"); } else { System.out.println("0"); }*/ int d = s + count2 ; if(d == 0) { System.out.println(count2 + 1); } else { System.out.println(count2); } } } }
Java
["4\n3\n2 -1 -1\n4\n-1 0 0 1\n2\n-1 2\n3\n0 -2 1"]
1 second
["1\n2\n0\n2"]
NoteIn the first test case, the sum is $$$0$$$. If we add $$$1$$$ to the first element, the array will be $$$[3,-1,-1]$$$, the sum will be equal to $$$1$$$ and the product will be equal to $$$3$$$.In the second test case, both product and sum are $$$0$$$. If we add $$$1$$$ to the second and the third element, the array will be $$$[-1,1,1,1]$$$, the sum will be equal to $$$2$$$ and the product will be equal to $$$-1$$$. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding $$$1$$$ twice to the first element the array will be $$$[2,-2,1]$$$, the sum will be $$$1$$$ and the product will be $$$-4$$$.
Java 8
standard input
[ "implementation", "math" ]
1ffb08fe61cdf90099c82162b8353b1f
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-100 \le a_i \le 100$$$) — elements of the array .
800
For each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.
standard output
PASSED
fe7a668b9df0ad08f1efbe542d0d8f99
train_003.jsonl
1508151900
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ 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); D876 solver = new D876(); solver.solve(1, in, out); out.close(); } static class D876 { public void solve(int testNumber, FastScanner s, PrintWriter out) { int N = s.nextInt(); int[] p = s.nextIntArray(N); boolean[] placed = new boolean[N + 1]; int rear = 0; out.print(1); for (int i = 0; i < N; i++) { placed[p[i]] = true; while (placed[N - rear]) rear++; out.print(" "); out.print(1 + (i + 1 - rear)); } out.println(); } } 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; } 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; } public int nextInt() { return Integer.parseInt(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 int[] nextIntArray(int N) { int[] ret = new int[N]; for (int i = 0; i < N; i++) ret[i] = this.nextInt(); return ret; } } }
Java
["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"]
1 second
["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"]
NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Java 8
standard input
[ "two pointers", "dsu", "implementation", "sortings", "trees" ]
b97eeaa66e91bbcc3b5e616cb480c7af
The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
1,500
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
standard output
PASSED
1b655490f9a7cc4498f000a5b64b7d47
train_003.jsonl
1508151900
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
512 megabytes
import java.io.BufferedInputStream; import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Scanner; public class D { // 21:30- public static void main(String[] args) throws IOException { Scanner sc = new Scanner(new BufferedInputStream(System.in)); BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(System.out)); int n = sc.nextInt(); boolean[] coins = new boolean[n]; int last = n; wr.write(1 + " "); for (int i = 0; i < n; i++) { int p = sc.nextInt(); coins[p - 1] = true; while (last - 1 >= 0 && coins[last - 1]) last--; wr.write((1 + (i + 1) - (n - last)) + " "); } wr.close(); } }
Java
["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"]
1 second
["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"]
NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Java 8
standard input
[ "two pointers", "dsu", "implementation", "sortings", "trees" ]
b97eeaa66e91bbcc3b5e616cb480c7af
The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
1,500
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
standard output
PASSED
e8874c85b7f9d98c5e189feede92efc5
train_003.jsonl
1508151900
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.*; import java.util.stream.Collectors; public class Main { private static IO io = new IO(); public static void main(String[] args)throws IOException { int n = io.getInt(), cl = n - 1, xs = 0; List<Integer> ls = io.getIntegerArray(n), ans = new ArrayList<>(); int[] arr = new int[n]; ans.add(1); for (int l : ls) { l--; xs++; if (l == cl) { arr[cl] = 1; while (cl >= 0 && arr[cl] == 1) cl--; } else arr[l] = 1; ans.add(xs - (n - 1 - cl) + 1); } System.out.println(Utils.join(ans, " ")); } } class IO { private BufferedReader br = null; private StringTokenizer st = null; public IO() { this(System.in); } public IO(InputStream is) { this.br = new BufferedReader(new InputStreamReader(is)); } public List<String> getStringArray(int n) throws IOException { if (n == 0) return new ArrayList<>(); if (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); List<String> res = new ArrayList<>(); for (int i = 0; i < n; i++) { if (!st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); res.add(st.nextToken()); } return res; } public String getString() throws IOException { List<String> res = this.getStringArray(1); return res.size() == 0 ? "" : res.get(0); } public List<Integer> getIntegerArray(int n) throws IOException { if (n == 0) return new ArrayList<>(); List<String> res = getStringArray(n); return res.stream().map(Integer::parseInt).collect(Collectors.toList()); } public Integer getInt() throws IOException { List<Integer> res = this.getIntegerArray(1); return res.size() == 0 ? 0 : res.get(0); } public List<Long> getLongArray(int n) throws IOException { if (n == 0) return new ArrayList<>(); List<String> res = getStringArray(n); return res.stream().map(Long::parseLong).collect(Collectors.toList()); } public Long getLong() throws IOException { List<Long> res = this.getLongArray(1); return res.size() == 0 ? 0L : res.get(0); } public List<Double> getDoubleArray(int n) throws IOException { if (n == 0) return new ArrayList<>(); List<String> res = getStringArray(n); return res.stream().map(Double::parseDouble).collect(Collectors.toList()); } public Double getDouble() throws IOException { List<Double> res = this.getDoubleArray(1); return res.size() == 0 ? 0.0 : res.get(0); } } class Utils { static int[][] fourDirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; static int[][] eightDirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1}}; static int modAdd(long a, long b) { return (int) ((a + b) % 1000000007); } static int modMul(long a, long b) { return (int) ((a * b) % 1000000007); } static int modSub(long a, long b) { return (int) ((a - b + 1000000007) % 1000000007); } public static List<Integer> sieve(int n) { boolean b[] = new boolean[n + 1]; List<Integer> ans = new ArrayList<>(); Arrays.fill(b, true); for (int i = 2; i <= n; i++) { if (b[i]) { ans.add(i); for (int j = i * i; j >= 0 && j <= n; j += i) { b[j] = false; } } } return ans; } public static boolean isPrime(long n) { long sqrt = (long) Math.sqrt(n); for (int i = 2; i <= sqrt; i++) { if (n % i == 0) return false; } return true; } public static long mod(long n) { if (n > 0) return n % 1000000007; return (n + 2000000014) % 1000000007; } public static boolean isSqr(long n) { int sqrt = (int) Math.sqrt(n); return n == (long) sqrt * sqrt; } public static boolean inRange(long i, long l, long h) { return i >= l && i <= h; } public static boolean isValid(int i, int j, int n, int m) { return i >= 0 && j >= 0 && i < n && j < m; } public static void swap(List<Integer> ls, int i, int j) { int temp = ls.get(i); ls.set(i, ls.get(j)); ls.set(j, temp); } public static long gcd(long a, long b) { if (a < b) return gcd(b, a); else if (a == b || b == 0) return a; else { return gcd(b, a % b); } } public static long subSum(long[] pre, int l, int h) { return l == 0 ? pre[h] : pre[h] - pre[l - 1]; } public static void ifPrint(boolean test, Object ifValue, Object elseValue) { System.out.println(test ? ifValue : elseValue); } public static void print(Character delim, Object... a) { List<String> top = new ArrayList<>(); for (Object aa : a) top.add(aa == null ? "null" : aa.toString()); System.out.println(join(top, delim.toString())); } public static void print(Object... a) { print(' ', a); } public static <T extends Comparable<T>> int lowerBound(T[] arr, int l, int h, T key) { while (l < h) { int mid = (l + h) / 2; if (arr[mid].compareTo(key) < 0) l = mid + 1; else h = mid; } return arr[l].compareTo(key) >= 0 ? l : -1; } public static <T extends Comparable<T>> int upperBound(T[] arr, int l, int h, T key) { while (l < h) { int mid = (l + h) / 2; if (arr[mid].compareTo(key) < 0) l = mid + 1; else if (arr[mid].compareTo(key) == 0) l = mid; else h = mid; if (h == l + 1) break; } return arr[l].compareTo(key) >= 0 ? l : -1; } public static <T> String join(List<T> ls) { return join(ls, " "); } public static <T> String join(List<T> ls, String delim) { StringJoiner sj = new StringJoiner(delim); for (T a : ls) sj.add(a.toString()); return sj.toString(); } public static <T> void print2DArray(List<List<T>> mat) { for (List<T> m : mat) { System.out.println("{ " + join(m, ", ") + " }"); } } public static <T> void reverseArrray(T[] arr, int l, int h) { while (l < h) { T temp = arr[l]; arr[l] = arr[h]; arr[h] = temp; l++; h--; } } }
Java
["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"]
1 second
["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"]
NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Java 8
standard input
[ "two pointers", "dsu", "implementation", "sortings", "trees" ]
b97eeaa66e91bbcc3b5e616cb480c7af
The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
1,500
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
standard output
PASSED
89e69a760c42b658706deb8dec25d663
train_003.jsonl
1508151900
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
512 megabytes
import java.io.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.*; import java.io.IOException; import java.io.InputStream; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collector; import java.util.stream.Collectors; import java.util.stream.IntStream; public class Main { public static void main(String[] args) { File file = new File("in.txt"); File fileOut = new File("out.txt"); InputStream inputStream = null; OutputStream outputStream = null; // try {inputStream= new FileInputStream(file);} catch (FileNotFoundException ex){return;}; // try {outputStream= new FileOutputStream(fileOut);} catch (FileNotFoundException ex){return;}; inputStream = System.in; outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(1, in, out); out.close(); } } class Task { public void solve(int testNumber, InputReader in, PrintWriter out) { Integer n = in.nextInt(); boolean[] ones = new boolean[n]; Integer rightMostZero = n-1; Integer oneCount = 0; out.print(1 + " "); for(int i=0; i<n-1; i++){ Integer insert = in.nextInt()-1; ones[insert] = true; oneCount++; while(ones[rightMostZero]){ rightMostZero--; } Integer onesOnTheLeft = oneCount - (n-1 - rightMostZero); out.print(onesOnTheLeft + 1 + " "); } out.print(1 + " "); } } 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 String nextLine(){ try { return reader.readLine(); } catch (IOException e){ throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } class Pair<F, S> { public final F first; public final S second; public Pair(F first, S second) { this.first = first; this.second = second; } @Override public boolean equals(Object o) { if (!(o instanceof Pair)) { return false; } Pair<?, ?> p = (Pair<?, ?>) o; return Objects.equals(p.first, first) && Objects.equals(p.second, second); } @Override public int hashCode() { return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode()); } @Override public String toString() { return "(" + first + ", " + second + ')'; } } class IntPair extends Pair<Integer, Integer>{ public IntPair(Integer first, Integer second){ super(first, second); } }
Java
["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"]
1 second
["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"]
NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Java 8
standard input
[ "two pointers", "dsu", "implementation", "sortings", "trees" ]
b97eeaa66e91bbcc3b5e616cb480c7af
The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
1,500
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
standard output
PASSED
06d9f165fc1ca1ffb6dc6be9b327e4fd
train_003.jsonl
1508151900
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
512 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Stack; import java.util.StringTokenizer; import java.util.Vector; public class n1 { public static int diff(boolean[]q){ for(int i=1;i<=q.length;i++){ boolean work=false; for(int j=0;j<q.length-1;j++){ if(q[j]&&!q[j+1]){ work=true; q[j+1]=true; q[j]=false; } } if(!work){ return i; } } return -1; } public static void main(String[]usdhzgv) throws Exception, IOException{ BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); PrintWriter out=new PrintWriter(System.out); /*String s="11111110"; boolean[]q=new boolean[s.length()]; for(int i=0;i<s.length();i++){ q[i]=s.charAt(i)=='1'; } *///System.out.println(diff(q)); int n=Integer.parseInt(in.readLine()); int[]q=new int[n]; StringTokenizer st=new StringTokenizer(in.readLine()); for(int i=0;i<n;i++){ q[i]=Integer.parseInt(st.nextToken())-1; } boolean[]data=new boolean[n]; int p=data.length; int c=1; out.print(c+" "); for(int i=0;i<n;i++){ c++; int po=q[i]; data[po]=true; if(po==p-1){ for(int j=po;j>=0;j--){ if(data[j]){ p--; c--; }else{ break; } } } out.print(c+" "); } out.close(); } }
Java
["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"]
1 second
["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"]
NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Java 8
standard input
[ "two pointers", "dsu", "implementation", "sortings", "trees" ]
b97eeaa66e91bbcc3b5e616cb480c7af
The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
1,500
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
standard output
PASSED
227d3a829351f818ab5ffd56e38f09ce
train_003.jsonl
1508151900
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class D { public static void main(String[] args){ FastScanner scan = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int n = scan.nextInt(); int[] p = scan.nextIntArray(n); boolean[] v = new boolean[n+2]; int[] f = new int[n+2]; for(int i = 0; i <= n; i++) f[i] = i; out.print("1 "); for(int i = 0; i < n; i++) { v[p[i]] = true; if(v[p[i]-1]) f[find(p[i]-1, f)] = find(p[i], f); if(v[p[i]+1]) f[find(p[i], f)] = find(p[i]+1, f); int lo = 1, hi = n; for(int bs = 0; bs < 50; bs++) { int mid = (lo+hi)>>1; if(find(mid, f) == n) hi = mid; else lo = mid; } int res = i+2-(n-hi); if(hi != n || v[n]) res--; out.print(res+" "); } out.close(); } static int find(int at, int[] f) { if(f[at] == at) return at; return f[at] = find(f[at], f); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { try { br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(br.readLine()); } catch (Exception e){e.printStackTrace();} } public String next() { if (st.hasMoreTokens()) return st.nextToken(); try {st = new StringTokenizer(br.readLine());} catch (Exception e) {e.printStackTrace();} return st.nextToken(); } public int nextInt() {return Integer.parseInt(next());} public long nextLong() {return Long.parseLong(next());} public double nextDouble() {return Double.parseDouble(next());} public String nextLine() { String line = ""; if(st.hasMoreTokens()) line = st.nextToken(); else try {return br.readLine();}catch(IOException e){e.printStackTrace();} while(st.hasMoreTokens()) line += " "+st.nextToken(); return line; } public int[] nextIntArray(int n) { int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextLongArray(int n){ long[] a = new long[n]; for(int i = 0; i < n; i++) a[i] = nextLong(); return a; } public double[] nextDoubleArray(int n){ double[] a = new double[n]; for(int i = 0; i < n; i++) a[i] = nextDouble(); return a; } public char[][] nextGrid(int n, int m){ char[][] grid = new char[n][m]; for(int i = 0; i < n; i++) grid[i] = next().toCharArray(); return grid; } } }
Java
["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"]
1 second
["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"]
NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Java 8
standard input
[ "two pointers", "dsu", "implementation", "sortings", "trees" ]
b97eeaa66e91bbcc3b5e616cb480c7af
The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
1,500
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
standard output
PASSED
9c0da6b9b93bc9aa4889e9f52259f276
train_003.jsonl
1508151900
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
512 megabytes
import java.io.*; import java.util.StringTokenizer; public class D { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); int[] p = new int[n]; boolean[] done = new boolean[n]; int nxt = n - 1; out.print(1); for(int i = 0; i < n; i++) { done[sc.nextInt() - 1] = true; while(nxt >= 0 && done[nxt]) nxt--; int inPlace = n - 1 - nxt; out.print(" " + (i + 2 - inPlace)); } out.flush(); out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } Scanner(String f) throws FileNotFoundException { br = new BufferedReader(new FileReader(f)); } String next() throws IOException { while(st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } } }
Java
["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"]
1 second
["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"]
NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Java 8
standard input
[ "two pointers", "dsu", "implementation", "sortings", "trees" ]
b97eeaa66e91bbcc3b5e616cb480c7af
The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
1,500
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
standard output
PASSED
be3e1d4a35a12d15015f4e29298bd0d0
train_003.jsonl
1508151900
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
512 megabytes
/** * DA-IICT * Author : PARTH PATEL */ import java.io.*; import java.math.*; import java.util.*; import static java.util.Arrays.fill; import static java.lang.Math.*; import static java.util.Arrays.sort; import static java.util.Collections.sort; public class D876 { public static int mod = 1000000007; static FasterScanner in = new FasterScanner(); static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { int n=in.nextInt(); out.print("1 "); int[] arr=new int[n+1]; int rightpointer=n; int marked=0; for(int i=1;i<=n;i++) { int x=in.nextInt(); arr[x]=1; marked++; while(arr[rightpointer]==1) { rightpointer--; marked--; } out.print((marked+1)+" "); } out.close(); } /////////////////SEGMENT TREE (BUILD-UPDATE-QUERY)///////////////////////////// /////////////////UPDATE FOLLOWING METHODS AS PER NEED////////////////////////// /* public static void buildsegmenttree(int node,int start,int end) { if(start==end) { // Leaf node will have a single element segmenttree[node]=arr[start]; } else { int mid=start+(end-start)/2; // Recurse on the left child buildsegmenttree(2*node, start, mid); // Recurse on the right child buildsegmenttree(2*node+1, mid+1, end); // Internal node will have the sum of both of its children segmenttree[node]=segmenttree[2*node]+segmenttree[2*node+1]; } } public static void updatesegmenttree(int node,int start,int end,int idx,int val) { if(start==end) { //Leaf Node arr[idx]+=val; segmenttree[node]+=val; } else { int mid=start+(end-start)/2; if(start<=idx && idx<=mid) { // If idx is in the left child, recurse on the left child updatesegmenttree(2*node, start, mid, idx, val); } else { // if idx is in the right child, recurse on the right child updatesegmenttree(2*node+1, mid+1, end, idx, val); } // Internal node will have the sum of both of its children segmenttree[node]=segmenttree[2*node]+segmenttree[2*node+1]; } } public static long querysegmenttree(int node,int start,int end,int l,int r) { if(r<start || end<l) { // range represented by a node is completely outside the given range return 0; } if(l <= start && end <= r) { // range represented by a node is completely inside the given range return segmenttree[node]; } // range represented by a node is partially inside and partially outside the given range int mid=start+(end-start)/2; long leftchild=querysegmenttree(2*node, start, mid, l, r); long rightchild=querysegmenttree(2*node+1, mid+1, end, l, r); return (leftchild+rightchild); } */ public static long pow(long x, long n, long mod) { long res = 1; for (long p = x; n > 0; n >>= 1, p = (p * p) % mod) { if ((n & 1) != 0) { res = (res * p % mod); } } return res; } public static long gcd(long n1, long n2) { long 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 FasterScanner { private byte[] buf = new byte[1024]; private int curChar; private int snumChars; public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = System.in.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 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 nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"]
1 second
["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"]
NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Java 8
standard input
[ "two pointers", "dsu", "implementation", "sortings", "trees" ]
b97eeaa66e91bbcc3b5e616cb480c7af
The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
1,500
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
standard output
PASSED
6b868f897de39cb686754ad870645cf1
train_003.jsonl
1508151900
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Stack; import java.util.StringTokenizer; public class C { public static void main(String[] args) throws NumberFormatException, IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); boolean [] b = new boolean[n]; int lastO = n-1; out.print(1); for (int i = 0; i < n; i++) { int p = sc.nextInt()-1; b[p] = true; while(lastO >= 0 && b[lastO]) lastO--; out.print(" " + (i+2-(n-1-lastO))); } out.flush(); out.close(); } static class Scanner { BufferedReader bf; StringTokenizer st; public Scanner() { bf = new BufferedReader(new InputStreamReader(System.in)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(bf.readLine()); return st.nextToken(); } public int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); } public double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } public long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } } }
Java
["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"]
1 second
["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"]
NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Java 8
standard input
[ "two pointers", "dsu", "implementation", "sortings", "trees" ]
b97eeaa66e91bbcc3b5e616cb480c7af
The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
1,500
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
standard output
PASSED
5a76885d684a4b02af12db323ea21a12
train_003.jsonl
1508151900
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
512 megabytes
import java.util.*; import java.io.*; import java.lang.Math.*; public class MainA { static int mod = (int) 1e9 + 7; static int prime[]=new int[100000+1]; public static void main(String[] args) throws java.lang.Exception { InputReader in = new InputReader(System.in); PrintWriter out=new PrintWriter(System.out); int n=in.nextInt(); int aft[]=new int[n+2]; int bef[]=new int[n+2]; for(int i=0;i<=n+1;i++){aft[i]=i+1;bef[i]=i-1;} int flag=0; out.print(1+" "); for(int i=0;i<n;i++) { int x=in.nextInt(); if(x==n)flag=1; aft[bef[x]]=aft[x]; bef[aft[x]]=bef[x]; if(flag==1) { int rem=i+1-(n-bef[n+1]); out.print((rem+1)+" "); } else { out.print((i+2)+" "); } //for(int j=0;j<=n+1;j++)out.print(aft[j]+" "+bef[j]+" "+j+" "); //out.println(); } out.close(); } static class Pairs implements Comparable<Pairs> { int x; int y; int z; Pairs(int a, int b, int c) { x = a; y = b; z=c; } @Override public boolean equals(Object o) { Pairs other=(Pairs)o; return x==other.x && y==other.y; } @Override public int compareTo(Pairs o) { // TODO Auto-generated method stub if(x==o.x) return Integer.compare(y,o.y); else return Integer.compare(x,o.x); } @Override public int hashCode() { return Objects.hash(x,y); } } public static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } public static boolean isPal(String s) { for (int i = 0, j = s.length() - 1; i <= j; i++, j--) { if (s.charAt(i) != s.charAt(j)) return false; } return true; } public static String rev(String s) { StringBuilder sb = new StringBuilder(s); sb.reverse(); return sb.toString(); } public static long gcd(long x, long y) { if (y == 0) return x; if (x % y == 0) return y; else return gcd(y, x % y); } public static int gcd(int x, int y) { if(y==0) return x; if (x % y == 0) return y; else return gcd(y, x % y); } public static long gcdExtended(long a, long b, long[] x) { if (a == 0) { x[0] = 0; x[1] = 1; return b; } long[] y = new long[2]; long gcd = gcdExtended(b % a, a, y); x[0] = y[1] - (b / a) * y[0]; x[1] = y[0]; return gcd; } public static long max(long a, long b) { if (a > b) return a; else return b; } public static long min(long a, long b) { if (a > b) return b; else return a; } public static long[][] mul(long a[][], long b[][]) { long c[][] = new long[2][2]; c[0][0] = a[0][0] * b[0][0] + a[0][1] * b[1][0]; c[0][1] = a[0][0] * b[0][1] + a[0][1] * b[1][1]; c[1][0] = a[1][0] * b[0][0] + a[1][1] * b[1][0]; c[1][1] = a[1][0] * b[0][1] + a[1][1] * b[1][1]; return c; } public static long[][] pow(long n[][], long p, long m) { long result[][] = new long[2][2]; result[0][0] = 1; result[0][1] = 0; result[1][0] = 0; result[1][1] = 1; if (p == 0) return result; if (p == 1) return n; while (p != 0) { if (p % 2 == 1) result = mul(result, n); //System.out.println(result[0][0]); for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { if (result[i][j] >= m) result[i][j] %= m; } } p >>= 1; n = mul(n, n); // System.out.println(1+" "+n[0][0]+" "+n[0][1]+" "+n[1][0]+" "+n[1][1]); for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { if (n[i][j] >= m) n[i][j] %= m; } } } return result; } public static long pow(long n,long p, long m) { long result=1; if(p==0)return 1; if(p==1)return n%m; while(p!=0) { if(p%2==1)result=(result*n)%m; p >>=1; n=(n*n)%m; } return result; } public static int pow(int n, int p) { int result = 1; if (p == 0) return 1; if (p == 1) return n; while (p != 0) { if (p % 2 == 1) result *= n; p >>= 1; n *= n; } return result; } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public long[] nextLongArray(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"]
1 second
["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"]
NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Java 8
standard input
[ "two pointers", "dsu", "implementation", "sortings", "trees" ]
b97eeaa66e91bbcc3b5e616cb480c7af
The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
1,500
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
standard output
PASSED
13d19fc39b1399140e28050616d6a271
train_003.jsonl
1508151900
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
512 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 coderfoces */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int a[] = new int[n]; int last = n - 1; out.print("1 "); for (int i = 0; i < n; i++) { a[in.nextInt() - 1]++; while (last >= 0 && a[last] != 0) { last--; } out.print(i + 2 - (n - 1 - last) + " "); } } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void close() { writer.close(); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"]
1 second
["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"]
NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Java 8
standard input
[ "two pointers", "dsu", "implementation", "sortings", "trees" ]
b97eeaa66e91bbcc3b5e616cb480c7af
The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
1,500
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
standard output
PASSED
025d7203702599468c645c7aa97b7f5c
train_003.jsonl
1508151900
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
512 megabytes
import java.io.*; import java.util.*; import java.math.*; import jdk.nashorn.internal.runtime.arrays.ArrayLikeIterator; //package acm_practice; /** * * @author ghost */ public class Round_441 { public static void main(String args[]) { //File file= new File("COMPLETE_FILE_PATH"); //InputStream is = new FileInputStream(file); //InputReader in = new InputReader(is); InputReader in = new InputReader(System.in); PrintWriter out= new PrintWriter(System.out); int t=1; Task solver=new Task(); solver.solve(t,in,out); out.flush(); out.close(); } static class Task { long mod = 1000000007; public void solve(int testNumber, InputReader in,PrintWriter out){ int n= in.nextInt(); int[] arr= new int[n+1]; Arrays.fill(arr,0); int last_Zero=n; int num_one=0; out.print((num_one+1)+" "); for(int i=0;i<n;i++){ int index= in.nextInt(); if(index<last_Zero){ num_one++; arr[index]=1; } else if(index==last_Zero){ while(arr[--last_Zero]!=0){ num_one--; } } out.print((num_one+1)+" "); } } int LOG2(long item){ int count=0; while(item>1){ item>>=1;count++; } return count; } long gcd(long a, long b) { a = Math.abs(a); b = Math.abs(b); return BigInteger.valueOf(a).gcd(BigInteger.valueOf(b)).longValue(); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String next() { return readString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } private static void pa(Object... o) { System.out.println(Arrays.deepToString(o)); } } }
Java
["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"]
1 second
["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"]
NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Java 8
standard input
[ "two pointers", "dsu", "implementation", "sortings", "trees" ]
b97eeaa66e91bbcc3b5e616cb480c7af
The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
1,500
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
standard output
PASSED
f0fedf8086f12c6eee7bcbfff3b0aeaa
train_003.jsonl
1508151900
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class D { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); int N = 1; while(N < n) N <<= 1; //padding int[] in = new int[N + 1]; SegmentTree t = new SegmentTree(in); boolean[] taken = new boolean[n+1]; int pointer = n; pw.print(1); for (int i = 0; i < n; i++) { int val = sc.nextInt(); taken[val] = true; t.update_range(val, n, 1); while(taken[pointer]) pointer--; if(pointer == 0) { pw.println(" " + 1); break; } pw.print(" " + (t.query(pointer, pointer)+1)); } pw.flush(); pw.close(); } static class SegmentTree { 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]; // modify base case 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]; // modify merging } } void update_point(int index, int val) // O(log n) { index += N - 1; sTree[index] += val; // base case while(index>1) { index >>= 1; sTree[index] = sTree[index<<1] + sTree[index<<1|1]; // merging } } 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; // how value node carrying is modified lazy[node] += val; // lazy value for node } 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]; // merging } } // modify 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; // base case 1 if(b>= i && e <= j) return sTree[node]; // base case 2 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 q1 + q2; // merging } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public boolean ready() throws IOException {return br.ready();} } }
Java
["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"]
1 second
["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"]
NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Java 8
standard input
[ "two pointers", "dsu", "implementation", "sortings", "trees" ]
b97eeaa66e91bbcc3b5e616cb480c7af
The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
1,500
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
standard output
PASSED
92394bf665d876cd1324b9e64d4d2b53
train_003.jsonl
1508151900
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
512 megabytes
import java.io.*; import java.math.*; import java.util.*; import java.util.stream.*; @SuppressWarnings("unchecked") public class P876D { public void run() throws Exception { print("1"); TreeSet<Integer> p = new TreeSet(); for (int n = nextInt(), i = n; i > 0; i--) { p.add(nextInt()); while ((p.size() > 0) && (p.last() == n)) { p.pollLast(); n--; } print(" " + (p.size() + 1)); } while (p.size() > 0) { print(" " + (p.size() + 1)); p.pollLast(); } } public static void main(String... args) throws Exception { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedOutputStream(System.out)); new P876D().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)); } }
Java
["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"]
1 second
["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"]
NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Java 8
standard input
[ "two pointers", "dsu", "implementation", "sortings", "trees" ]
b97eeaa66e91bbcc3b5e616cb480c7af
The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
1,500
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
standard output
PASSED
7b58c01b3e67426f5a922505c88f7133
train_003.jsonl
1508151900
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
512 megabytes
import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; import java.util.ArrayList; public class D { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Solver solver = new Solver(); solver.solve(1, in, out); out.close(); } static class Solver { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); boolean[] closed = new boolean[n + 1]; out.print("1 "); int last = n; for (int i = 1 ; i <= n ; i++) { int x = in.nextInt(); closed[x] = true; while (last > 0 && closed[last]) last -= 1; out.print((1 + i - (n - last)) + " "); } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public float nextFloat() { return Float.parseFloat(next()); } } }
Java
["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"]
1 second
["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"]
NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Java 8
standard input
[ "two pointers", "dsu", "implementation", "sortings", "trees" ]
b97eeaa66e91bbcc3b5e616cb480c7af
The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
1,500
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
standard output
PASSED
8c83366533d916b7226448bd0d6fe1f0
train_003.jsonl
1508151900
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
512 megabytes
import java.util.*; import java.io.*; import java.math.*; import java.lang.*; public class Main { private static FastReader sc = new FastReader(System.in); private static OutputWriter out = new OutputWriter(System.out); public static void main(String[] args) throws Exception { int n = sc.nextInt(); int unFilled = n; int done = 0; boolean[] isPlaced = new boolean[n + 1]; out.print(1 + " "); for (int i = 0; i < n; i++) { int x = sc.nextInt(); isPlaced[x] = true; while (isPlaced[unFilled]) { unFilled--; done++; } out.print((i + 1 - done + 1) + " "); } out.close(); } } class FastReader { private boolean finished = false; private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public FastReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int peek() { if (numChars == -1) { return -1; } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { return -1; } if (numChars <= 0) { return -1; } } return buf[curChar]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c == ',') { c = read(); } if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0() { StringBuilder buf = new StringBuilder(); int c = read(); while (c != '\n' && c != -1) { if (c != '\r') { buf.appendCodePoint(c); } c = read(); } return buf.toString(); } public String nextLine() { String s = readLine0(); while (s.trim().length() == 0) s = readLine0(); return s; } public String nextLine(boolean ignoreEmptyLines) { if (ignoreEmptyLines) { return nextLine(); } else { return readLine0(); } } public BigInteger nextBigInteger() { try { return new BigInteger(nextString()); } catch (NumberFormatException e) { throw new InputMismatchException(); } } public char nextCharacter() { int c = read(); while (isSpaceChar(c)) c = read(); return (char) c; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') { return res * Math.pow(10, nextInt()); } if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') { return res * Math.pow(10, nextInt()); } if (c < '0' || c > '9') { throw new InputMismatchException(); } m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public boolean isExhausted() { int value; while (isSpaceChar(value = peek()) && value != -1) read(); return value == -1; } public String next() { return nextString(); } public SpaceCharFilter getFilter() { return filter; } public void setFilter(SpaceCharFilter filter) { this.filter = filter; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } 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(); } }
Java
["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"]
1 second
["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"]
NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Java 8
standard input
[ "two pointers", "dsu", "implementation", "sortings", "trees" ]
b97eeaa66e91bbcc3b5e616cb480c7af
The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
1,500
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
standard output
PASSED
fce93308df28827ec8cdaaf9f8a4eaff
train_003.jsonl
1508151900
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.FileNotFoundException; import java.io.File; import java.util.StringTokenizer; import java.io.Writer; import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); D solver = new D(); solver.solve(1, in, out); out.close(); } static class D extends SimpleSavingChelperSolution { public void solve(int testNumber, InputReader in, OutputWriter out) { wrapSolve(testNumber, in, out); } public void solve(int testNumber) { int n = in.nextInt(); out.print(1 + " "); Node root = new Node(0, n); for (int totalSum = 1; totalSum <= n; totalSum++) { root.add(in.nextInt() - 1); int l = 0; int r = n + 1; while (r - l > 1) { int m = (l + r) / 2; int x = root.sum(n - m, n); if (x == m) { l = m; } else { r = m; } } out.print((totalSum - l + 1) + " "); // out.println(root.sum(0, n)); } } class Node { int l; int r; int m; int sum; Node cl; Node cr; Node(int l, int r) { this.l = l; this.r = r; m = (l + r) / 2; sum = 0; if (r - l > 1) { cl = new Node(l, m); cr = new Node(m, r); } } void add(int x) { sum++; if (r - l > 1) { if (x < m) { cl.add(x); } else { cr.add(x); } } } int sum(int ll, int rr) { if (ll == l && rr == r) { return sum; } int ans = 0; if (ll < m) { ans += cl.sum(ll, Math.min(m, rr)); } if (rr > m) { ans += cr.sum(Math.max(m, ll), rr); } return ans; } } } static class InputReader { private BufferedReader br; private StringTokenizer in; public InputReader(String fileName) { try { br = new BufferedReader(new FileReader(fileName)); } catch (IOException e) { throw new RuntimeException(e); } } public InputReader(InputStream inputStream) { br = new BufferedReader(new InputStreamReader(inputStream)); } private boolean hasMoreTokens() { while (in == null || !in.hasMoreTokens()) { String s = nextLine(); if (s == null) { return false; } in = new StringTokenizer(s); } return true; } public String nextString() { return hasMoreTokens() ? in.nextToken() : null; } public String nextLine() { try { in = null; return br.readLine(); } catch (Exception e) { e.printStackTrace(); return null; } } public int nextInt() { return Integer.parseInt(nextString()); } } static class OutputWriter extends PrintWriter { public void close() { super.close(); } public OutputWriter(String fileName) throws FileNotFoundException { super(fileName); } public OutputWriter(OutputStream outputStream) { super(outputStream); } public OutputWriter(Writer writer) { super(writer); } } static abstract class SimpleSavingChelperSolution extends SavingChelperSolution { public String processOutputPreCheck(int testNumber, String output) { return output; } public String processOutputPostCheck(int testNumber, String output) { return output; } } static abstract class SavingChelperSolution { protected int testNumber; public InputReader in; public OutputWriter out; private OutputWriter toFile; private boolean local = new File("chelper.properties").exists(); public OutputWriter debug; { if (local) { debug = new OutputWriter(System.out); } else { debug = new OutputWriter(new OutputStream() { public void write(int b) { } }); } } public SavingChelperSolution() { try { toFile = new OutputWriter("last_test_output.txt"); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } public abstract void solve(int testNumber); public abstract String processOutputPreCheck(int testNumber, String output); public abstract String processOutputPostCheck(int testNumber, String output); public void wrapSolve(int testNumber, InputReader in, OutputWriter out) { this.testNumber = testNumber; ByteArrayOutputStream substituteOutContents = new ByteArrayOutputStream(); OutputWriter substituteOut = new OutputWriter(substituteOutContents); this.in = in; this.out = substituteOut; solve(testNumber); substituteOut.flush(); String result = substituteOutContents.toString(); result = processOutputPreCheck(testNumber, result); out.print(result); out.flush(); if (local) { debug.flush(); result = processOutputPostCheck(testNumber, result); toFile.print(result); toFile.flush(); } } } }
Java
["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"]
1 second
["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"]
NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Java 8
standard input
[ "two pointers", "dsu", "implementation", "sortings", "trees" ]
b97eeaa66e91bbcc3b5e616cb480c7af
The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
1,500
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
standard output
PASSED
5f48894d5b9926d70457f00936e73282
train_003.jsonl
1508151900
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.*; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; public class Main2 { static long mod = 1000000007L; static FastScanner scanner; static long m; static long k; public static void main(String[] args) { scanner = new FastScanner(); int n = scanner.nextInt(); int[] a = scanner.nextIntArray(n); int[] visited = new int[n]; int cnt = 0; int toCheck = n - 1; StringBuilder builder = new StringBuilder(); builder.append("1 "); for (int i = 0; i < n; i++) { int current = a[i] - 1; visited[current] = 1; cnt++; if (current == toCheck) { while (cnt > 0 && visited[toCheck] == 1) { cnt--; toCheck--; } } builder.append(cnt + 1).append(' '); } System.out.println(builder.toString()); } static int calcDigits(int x) { int sum = 0; while (x > 0) { sum += (x % 10); x = x/ 10; } return sum; } static int ask(int i, int j) { System.out.println("? " + i + " " + j); System.out.flush(); return scanner.nextInt(); } static class Pt{ long x, y; public Pt(long x, long y) { this.x = x; this.y = y; } } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } String nextLine() { try { return br.readLine(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(); } } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } int[] nextIntArray(int n) { int[] res = new int[n]; for (int i = 0; i < n; i++) res[i] = nextInt(); return res; } long[] nextLongArray(int n) { long[] res = new long[n]; for (int i = 0; i < n; i++) res[i] = nextLong(); return res; } String[] nextStringArray(int n) { String[] res = new String[n]; for (int i = 0; i < n; i++) res[i] = nextToken(); return res; } } static class PrefixSums { long[] sums; public PrefixSums(long[] sums) { this.sums = sums; } public long sum(int fromInclusive, int toExclusive) { if (fromInclusive > toExclusive) throw new IllegalArgumentException("Wrong sum"); return sums[toExclusive] - sums[fromInclusive]; } public static PrefixSums of(int[] ar) { long[] sums = new long[ar.length + 1]; for (int i = 1; i <= ar.length; i++) { sums[i] = sums[i - 1] + ar[i - 1]; } return new PrefixSums(sums); } public static PrefixSums of(long[] ar) { long[] sums = new long[ar.length + 1]; for (int i = 1; i <= ar.length; i++) { sums[i] = sums[i - 1] + ar[i - 1]; } return new PrefixSums(sums); } } static class ADUtils { static void sort(int[] ar) { Random rnd = ThreadLocalRandom.current(); for (int i = ar.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); // Simple swap int a = ar[index]; ar[index] = ar[i]; ar[i] = a; } Arrays.sort(ar); } static void sort(long[] ar) { Random rnd = ThreadLocalRandom.current(); for (int i = ar.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); // Simple swap long a = ar[index]; ar[index] = ar[i]; ar[i] = a; } Arrays.sort(ar); } } static class MathUtils { static long modpow(long b, long e, long m) { long result = 1; while (e > 0) { if ((e & 1) == 1) { /* multiply in this bit's contribution while using modulus to keep * result small */ result = (result * b) % m; } b = (b * b) % m; e >>= 1; } return result; } static long submod(long x, long y, long m) { return (x - y + m) % m; } } }
Java
["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"]
1 second
["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"]
NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Java 8
standard input
[ "two pointers", "dsu", "implementation", "sortings", "trees" ]
b97eeaa66e91bbcc3b5e616cb480c7af
The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
1,500
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
standard output
PASSED
4ee53871a03ff1019e55fe49a17e7bac
train_003.jsonl
1508151900
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
512 megabytes
import java.io.DataInputStream; import java.io.PrintWriter; import java.io.FileInputStream; import java.io.IOException; 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[201]; // 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 void main(String[] args) throws IOException { Reader s=new Reader();PrintWriter pw=new PrintWriter(System.out); int n=s.nextInt(); int ans[]=new int[n+1]; boolean fill[]=new boolean[n];int id=n-1; for(int i=0;i<n-1;i++){ int x=s.nextInt(); if(x-1==id){ for(int j=id-1;j>=0;j--){if(!fill[j]){id=j;break;}} } ans[i+1]=i+1-(n-1-id);fill[x-1]=true; }for(int i=0;i<=n;i++)pw.write(ans[i]+1+" "); pw.flush();pw.close(); } }
Java
["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"]
1 second
["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"]
NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Java 8
standard input
[ "two pointers", "dsu", "implementation", "sortings", "trees" ]
b97eeaa66e91bbcc3b5e616cb480c7af
The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
1,500
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
standard output
PASSED
aa976b1d5a0ff7cb27235a901ff6e179
train_003.jsonl
1508151900
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; public class Yo { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(in.readLine()); int[] arr = new int[n]; String[] line = in.readLine().split("\\s+"); for(int i=0; i<n; i++) { arr[i] = Integer.parseInt(line[i])-1; } boolean[] taken = new boolean[n]; // init first taken PrintWriter out = new PrintWriter(System.out); out.print(1 + " "); int cur = n-1; int moves = 0; for(int i=0; i<n; i++) { if(arr[i] == cur) { cur--; while(cur != -1 && taken[cur]) { cur--; moves--; } } else { moves++; taken[arr[i]] = true; } out.print((moves + 1) + " "); } out.close(); } }
Java
["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"]
1 second
["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"]
NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Java 8
standard input
[ "two pointers", "dsu", "implementation", "sortings", "trees" ]
b97eeaa66e91bbcc3b5e616cb480c7af
The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
1,500
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
standard output
PASSED
87b23ea6e4dc910225dc8869c4e9dead
train_003.jsonl
1508151900
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Solution { public static void main(String[] args) { InputReader in = new InputReader(); PrintWriter out = new PrintWriter(System.out); Thread th = new Thread(null, new Runnable(){public void run(){new Task1().solve(in, out);}},"Task1",1<<24); try{ th.start(); th.join(); } catch(InterruptedException e){} out.close(); } static class Task1 { static final int MOD = 1000000007; long[] tree; public void solve(InputReader in, PrintWriter out){ int n = in.nextInt(); int[] p = new int[n]; TreeSet<Integer> zeros = new TreeSet<Integer>(); for(int i=0; i<n; i++){ zeros.add(i); p[i] = in.nextInt(); } tree = new long[n+1]; for(int i=0; i<n; i++) updateTree(tree, i, 0); out.print(1+" "); for(int i=0; i<n-1; i++){ updateTree(tree, p[i]-1, 1); zeros.remove(p[i]-1); int pos = zeros.last(); out.print((getSum(tree, pos)+1)+" "); } out.println(1); } static long getSum(long[] tree, int index){ index++; long ans = 0; while(index>0){ ans += tree[index]; index -= index&(-index); } return ans; } static void updateTree(long[] tree, int index, long value){ index++; while(index<tree.length){ tree[index] += value; index += index&(-index); } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader() { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { String s=null; try{ s = reader.readLine(); } catch(IOException e){ throw new RuntimeException(e); } return s; } public String nextParagraph() { String line=null; String ans = ""; try{ while ((line = reader.readLine()) != null) { ans += line; } } catch(IOException e){ throw new RuntimeException(e); } return ans; } } }
Java
["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"]
1 second
["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"]
NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Java 8
standard input
[ "two pointers", "dsu", "implementation", "sortings", "trees" ]
b97eeaa66e91bbcc3b5e616cb480c7af
The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
1,500
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
standard output
PASSED
2e0eac9b6bd39809ed85286c288b1c58
train_003.jsonl
1508151900
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class Main { public static void main(String[] args) throws IOException { final BufferedReader inputReader = new BufferedReader(new InputStreamReader(System.in)); final int n = Integer.parseInt(inputReader.readLine()); String line[] = inputReader.readLine().split(" "); final int p[] = new int[n]; final StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(1).append(' '); int maxIndex = n - 1; boolean[] hits = new boolean[n]; for (int i = 0; i < n - 1; i++) { p[i] = Integer.parseInt(line[i]) - 1; hits[p[i]] = true; if (p[i] == maxIndex) { while (hits[maxIndex]) { maxIndex--; } } int movement = maxIndex + 2 - (n - i - 1); stringBuilder.append(movement).append(' '); } stringBuilder.append(1).append(' '); System.out.println(stringBuilder); } }
Java
["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"]
1 second
["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"]
NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Java 8
standard input
[ "two pointers", "dsu", "implementation", "sortings", "trees" ]
b97eeaa66e91bbcc3b5e616cb480c7af
The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
1,500
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
standard output
PASSED
080f3c80c8851c3e6397a5718cbc9c4e
train_003.jsonl
1508151900
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; /** * @author Don Li */ public class SortingCoins { int N = (int) 3e5 + 10; int n; int[] t = new int[N]; void solve() { n = in.nextInt(); out.print(1); int idx = n - 1; int[] p = new int[n]; for (int i = 0; i < n; i++) { int x = in.nextInt() - 1; p[x] = 1; add(x, 1); while (idx >= 0 && p[idx] == 1) idx--; int ans = sum(0, idx) + 1; out.printf(" %d", ans); } } void add(int i, int v) { for (int x = i; x < t.length; x = x | x + 1) { t[x] += v; } } int sum(int l, int r) { if (l > r) return 0; return sum(r) - sum(l - 1); } int sum(int i) { int res = 0; for (int x = i; x >= 0; x = (x & x + 1) - 1) { res += t[x]; } return res; } public static void main(String[] args) { in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); new SortingCoins().solve(); out.close(); } static FastScanner in; static PrintWriter out; static class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"]
1 second
["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"]
NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Java 8
standard input
[ "two pointers", "dsu", "implementation", "sortings", "trees" ]
b97eeaa66e91bbcc3b5e616cb480c7af
The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
1,500
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
standard output
PASSED
1f99ecf22cf0ddbba8b9997e9ec5679a
train_003.jsonl
1508151900
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; /** * @author Don Li */ public class SortingCoins2 { void solve() { int n = in.nextInt(); int rightmost = n - 1; int[] p = new int[n]; for (int i = 0; i < n; i++) { if (i == 0) out.print(1); int x = in.nextInt() - 1; p[x] = 1; while (rightmost >= 0 && p[rightmost] == 1) rightmost--; int cnt = (i + 1) - (n - rightmost - 1); int ans = cnt + 1; out.printf(" %d", ans); } } public static void main(String[] args) { in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); new SortingCoins2().solve(); out.close(); } static FastScanner in; static PrintWriter out; static class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"]
1 second
["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"]
NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Java 8
standard input
[ "two pointers", "dsu", "implementation", "sortings", "trees" ]
b97eeaa66e91bbcc3b5e616cb480c7af
The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
1,500
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
standard output
PASSED
9d8eecccc170ef20aec9356b61faeac6
train_003.jsonl
1508151900
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Sanket Makani */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader sc, PrintWriter w) { int n = sc.nextInt(); int max = (int) 3e5 + 1; int arr[] = new int[max]; w.print("1 "); int ans = 0; int taken = 0; int curr = n; for (int i = 0; i < n; i++) { int ip = sc.nextInt(); arr[ip]++; while (curr > 0 && arr[curr] != 0) { curr--; taken++; } w.print((i + 1 - taken + 1) + " "); } } } 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 nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"]
1 second
["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"]
NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Java 8
standard input
[ "two pointers", "dsu", "implementation", "sortings", "trees" ]
b97eeaa66e91bbcc3b5e616cb480c7af
The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
1,500
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
standard output
PASSED
1b806e6aa1f5c19692a1dd0e7db7362e
train_003.jsonl
1508151900
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.TreeSet; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); boolean[] coin = new boolean[n + 1]; int last = n; out.print(1); TreeSet<Integer> left = new TreeSet<>(); for (int i = 0; i < n; i++) { int c = in.nextInt(); coin[c] = true; if (c == last) { last--; while (coin[last]) { left.remove(last); last--; } out.print(" " + (left.size() + 1)); } else { left.add(c); out.print(" " + (left.size() + 1)); } } } } static class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream a) { br = new BufferedReader(new InputStreamReader(a)); } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } catch (NullPointerException e) { return null; } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"]
1 second
["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"]
NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Java 8
standard input
[ "two pointers", "dsu", "implementation", "sortings", "trees" ]
b97eeaa66e91bbcc3b5e616cb480c7af
The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
1,500
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
standard output
PASSED
6dba14ac815d4f82ef7eb0083d34e5f7
train_003.jsonl
1508151900
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
512 megabytes
import java.io.*; import java.util.*; import static java.util.stream.Collectors.toList; public class Solution { static MyScanner sc; private static PrintWriter out; static long M = 1000000007; public static void main(String[] s) throws Exception { StringBuilder stringBuilder = new StringBuilder(); // stringBuilder.append("\n" + // "3\n" + // "2:3,2\n" + // "1:1-1:3\n" + // "2:1,2"); // stringBuilder.append(" 10000 10000 "); // for (int i = 0; i < 10000; i++) { // stringBuilder.append(" " + 100_000_000_000L); // } //// if (stringBuilder.length() == 0) { sc = new MyScanner(System.in); } else { sc = new MyScanner(new BufferedReader(new StringReader(stringBuilder.toString()))); } out = new PrintWriter(new OutputStreamWriter(System.out)); initData(); solve(); out.flush(); } private static void initData() { } private static void solve() throws IOException { int n = sc.nextInt(); int[] r = sc.na(n); int t = 0; boolean[] used = new boolean[n]; int turn = 0; out.print(turn + 1 - t + " "); for (int mm : r) { used[mm - 1] = true; turn++; while ((t < n) && used[n - t - 1]) { t++; } out.print(turn + 1 - t + " "); } } private static void solveT() throws IOException { int t = sc.nextInt(); while (t-- > 0) { solve(); } } private static long gcd(long l, long l1) { if (l > l1) return gcd(l1, l); if (l == 0) return l1; return gcd(l1 % l, l); } private static long pow(long a, long b, long m) { if (b == 0) return 1; if (b == 1) return a; long pp = pow(a, b / 2, m); pp *= pp; pp %= m; return (pp * (b % 2 == 0 ? 1 : a)) % m; } static class MyScanner { BufferedReader br; StringTokenizer st; MyScanner(BufferedReader br) { this.br = br; } public MyScanner(InputStream in) { this(new BufferedReader(new InputStreamReader(in))); } void findToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } } String next() { findToken(); return st.nextToken(); } Integer[] nab(int n) { Integer[] k = new Integer[n]; for (int i = 0; i < n; i++) { k[i] = sc.fi(); } return k; } int[] na(int n) { int[] k = new int[n]; for (int i = 0; i < n; i++) { k[i] = sc.fi(); } return k; } long[] nl(int n) { long[] k = new long[n]; for (int i = 0; i < n; i++) { k[i] = sc.nextLong(); } return k; } int nextInt() { return Integer.parseInt(next()); } int fi() { String t = next(); int cur = 0; boolean n = t.charAt(0) == '-'; for (int a = n ? 1 : 0; a < t.length(); a++) { cur = cur * 10 + t.charAt(a) - '0'; } return n ? -cur : cur; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } private static final class STree { private final boolean maxt; int rs; int[] val1; int[] from1; int[] to1; int[] metric; public STree(int c, boolean maxt) { rs = c; this.maxt = maxt; int size = Integer.highestOneBit(c); if (size != c) { size <<= 1; } int rs = size << 1; val1 = new int[rs]; from1 = new int[rs]; metric = new int[rs]; to1 = new int[rs]; Arrays.fill(from1, Integer.MAX_VALUE); if (!maxt) Arrays.fill(metric, Integer.MAX_VALUE); for (int r = rs - 1; r > 1; r--) { if (r >= size) { from1[r] = r - size; to1[r] = r - size; } from1[r / 2] = Math.min(from1[r / 2], from1[r]); to1[r / 2] = Math.max(to1[r / 2], to1[r]); } } public STree(int c) { this(c, true); } public int max(int from, int to) { return max(1, from, to); } private int max(int cur, int from, int to) { if (cur >= val1.length) return 0; if (from <= from1[cur] && to1[cur] <= to) { return metric[cur]; } if (from1[cur] > to || from > to1[cur]) { return 0; } cur <<= 1; return Math.max(max(cur, from, to), max(cur + 1, from, to)); } public void put(int x, int val) { x += val1.length >> 1; val1[x] = val; metric[x] = val; addToParent(x); } private void addToParent(int cur) { while (cur > 1) { cur >>= 1; if (maxt) { metric[cur] = Math.max(metric[cur << 1], metric[1 + (cur << 1)]); } else { metric[cur] = Math.min(metric[cur << 1], metric[1 + (cur << 1)]); } } } public long x(int i) { return val1[i + val1.length >> 1]; } } }
Java
["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"]
1 second
["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"]
NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Java 8
standard input
[ "two pointers", "dsu", "implementation", "sortings", "trees" ]
b97eeaa66e91bbcc3b5e616cb480c7af
The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
1,500
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
standard output
PASSED
e1d5a4bc7febeb34ceb19c761f92893f
train_003.jsonl
1508151900
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class D { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); Integer n = Integer.parseInt(br.readLine()); String[] as = br.readLine().split(" "); int[] ai = new int[n]; for(int i = 0; i < n; i++) { ai[i] = Integer.parseInt(as[i]); } String space = " "; StringBuilder sb = new StringBuilder(); sb.append(1).append(space); int index = n - 1; int num = 0; boolean[] contains = new boolean[n]; for(int i = 0; i < n; i++) { contains[ai[i] - 1] = true; num++; while(index >= 0 && contains[index]) index--; sb.append(1 + num - (n - 1 - index)); if(num != n) sb.append(space); } System.out.println(sb.toString()); } }
Java
["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"]
1 second
["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"]
NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Java 8
standard input
[ "two pointers", "dsu", "implementation", "sortings", "trees" ]
b97eeaa66e91bbcc3b5e616cb480c7af
The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
1,500
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
standard output
PASSED
84e0b7ef0fb3fcaa4e3aab82bbed797d
train_003.jsonl
1508151900
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; /** * Created by dtnha on 10/17/2017. */ public class SortingCoins { static class Reader { static BufferedReader reader; static StringTokenizer tokenizer; /** call this method to initialize reader for InputStream */ public static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input) ); tokenizer = new StringTokenizer(""); } /** get next word */ public static String next() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } public static int nextInt() throws IOException { return Integer.parseInt( next() ); } public static double nextDouble() throws IOException { return Double.parseDouble( next() ); } } public static void main(String[] args) throws IOException { Reader.init(System.in); int n = Reader.nextInt(); boolean[] p = new boolean[n + 1]; int tmp = n; int c2 = 0; StringBuffer output = new StringBuffer(); output.append(1+" "); for (int i = 1; i <= n; i++) { int ai = Reader.nextInt(); p[ai] = true; int c1 = i; while (tmp >= 1) { if (p[tmp]) { c2++; } else { break; } tmp--; } output.append((c1 - c2) + 1 + " "); } System.out.print(output.toString()); } }
Java
["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"]
1 second
["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"]
NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Java 8
standard input
[ "two pointers", "dsu", "implementation", "sortings", "trees" ]
b97eeaa66e91bbcc3b5e616cb480c7af
The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
1,500
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
standard output
PASSED
7f5a54b4489cdbbcade43ac8f8fd2b22
train_003.jsonl
1508151900
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; /** * Created by dtnha on 10/17/2017. */ public class SortingCoins { static class Reader { static BufferedReader reader; static StringTokenizer tokenizer; /** call this method to initialize reader for InputStream */ public static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input) ); tokenizer = new StringTokenizer(""); } /** get next word */ public static String next() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } public static int nextInt() throws IOException { return Integer.parseInt( next() ); } public static double nextDouble() throws IOException { return Double.parseDouble( next() ); } } public static void main(String[] args) throws IOException { Reader.init(System.in); int n = Reader.nextInt(); boolean[] p = new boolean[n + 1]; System.out.print(1 + " "); int tmp = n; int c2 = 0; for (int i = 1; i <= n; i++) { int ai = Reader.nextInt(); p[ai] = true; int c1 = i; while (tmp >= 1) { if (p[tmp]) { c2++; } else { break; } tmp--; } System.out.print((c1 - c2) + 1 + " "); } } }
Java
["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"]
1 second
["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"]
NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Java 8
standard input
[ "two pointers", "dsu", "implementation", "sortings", "trees" ]
b97eeaa66e91bbcc3b5e616cb480c7af
The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
1,500
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
standard output
PASSED
df6e2a1750a98fdd10010cbd81c209c9
train_003.jsonl
1508151900
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.TreeSet; public class AD { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(in.readLine()); String[] tokens = in.readLine().split(" "); System.out.print("1 "); boolean[] flipped = new boolean[n]; int ignoreX = flipped.length - 1; for (int i = 0; i < tokens.length - 1; i++) { int coinPosition = Integer.parseInt(tokens[i]); flipped[coinPosition - 1] = true; while (ignoreX >= 0 && flipped[ignoreX]) { ignoreX--; } System.out.print((1 + (i + 1) - (tokens.length - 1 - ignoreX)) + " "); } System.out.println(1); in.close(); } }
Java
["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"]
1 second
["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"]
NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Java 8
standard input
[ "two pointers", "dsu", "implementation", "sortings", "trees" ]
b97eeaa66e91bbcc3b5e616cb480c7af
The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
1,500
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
standard output
PASSED
4dce3429234fb68fad79bb8f8d696729
train_003.jsonl
1508151900
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
512 megabytes
import java.io.*; import java.util.*; public class CF876_D2_D { public static void main(String[] args)throws Throwable { MyScanner sc=new MyScanner(); PrintWriter pw=new PrintWriter(System.out); int n=sc.nextInt(); int [] a=new int [n]; for(int i=0;i<n;i++) a[i]=sc.nextInt()-1; boolean [] vis=new boolean [n]; DSU d=new DSU(n); pw.print("1 "); int cnt=0; for(int i : a){ vis[i]=true; cnt++; if((i<n-1 && vis[i+1])) d.union(i, i+1); if((i>0 && vis[i-1])) d.union(i, i-1); if(!vis[n-1]) pw.print(cnt+1+" "); else{ int s=d.findSet(n-1); pw.print(cnt-d.setSize[s]+1+" "); } } pw.flush(); pw.close(); } static class DSU { int n,cntSets; int [] rank,parent,setSize; public DSU(int n) { cntSets=n; this.n=n; rank=new int [n]; parent=new int [n]; setSize=new int [n]; for(int i=0;i<n;i++){ setSize[i]=1; parent[i]=i; } } public int findSet(int i){ return parent[i]==i? i : (parent[i]=findSet(parent[i])); } public boolean union(int u,int v){ int x=findSet(u); int y=findSet(v); if(x==y) return false; if(rank[x]<rank[y]){ setSize[y]+=setSize[x]; parent[x]=y; }else{ setSize[x]+=setSize[y]; if(rank[x]==rank[y]) rank[x]++; parent[y]=x; } cntSets--; return true; } } 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
["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"]
1 second
["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"]
NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Java 8
standard input
[ "two pointers", "dsu", "implementation", "sortings", "trees" ]
b97eeaa66e91bbcc3b5e616cb480c7af
The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
1,500
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
standard output
PASSED
05b17f002adf04ed0187a20962b20548
train_003.jsonl
1508151900
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
512 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { InputStream inputStream = System.in; // InputStream inputStream = new FileInputStream("sum.in"); OutputStream outputStream = System.out; // OutputStream outputStream = new FileOutputStream("sum.out"); InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Answer solver = new Answer(); solver.solve(in, out); out.close(); } } class Answer {// private final int INF = (int) (1e9 + 7); private final int MOD = (int) (1e9 + 7); private final int MOD1 = (int) (1e6 + 3); private final long INF_LONG = (long) (1e18 + 1); private final double EPS = 1e-9; private long gcd(long a, long b) { return (b == 0) ? a : gcd(b, a % b); } private long[] tree; private void buildTree(int n) { tree = new long[4 * (n + 1)]; } private void set(int index, int n) { set(1, 1, n, index); } private void set(int v, int l, int r, int index) { if (l > index || r < index) { return; } if (l == r) { tree[v] = 1; return; } int m = (l + r) >> 1; if (m < index) { set(v * 2 + 1, m + 1, r, index); } else { set(v * 2, l, m, index); } tree[v] = tree[v * 2] + tree[v * 2 + 1]; } private long get(int l, int r, int n) { return get(1, 1, n, l, r); } private long get(int v, int tl, int tr, int l, int r) { if (tl > r || tr < l) { return 0; } if (l <= tl && tr <= r) { return tree[v]; } int m = (tl + tr) >> 1; long leftSum = get(v * 2, tl, m, l, Math.min(m, r)); long rightSum = get(v * 2 + 1, m + 1, tr, Math.max(m + 1, l), r); return leftSum + rightSum; } public void solve(InputReader in, PrintWriter out) throws IOException { int n = in.nextInt(); buildTree(n); int[] a = new int[n + 1]; int lastZeroPosition = n; out.print(1 + " "); for (int i = 0; i < n; i++) { int p = in.nextInt(); a[p] = 1; try { set(p, n); } catch (ArrayIndexOutOfBoundsException e) { out.println(); out.println("error: " + p); return; } while (lastZeroPosition > 0 && a[lastZeroPosition] == 1) { lastZeroPosition--; } long x = 1 + get(1, lastZeroPosition, n); out.print(x + " "); } out.println(); } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public int[] nextArrayInt(int count) { int[] a = new int[count]; for (int i = 0; i < count; i++) { a[i] = nextInt(); } return a; } public long[] nextArrayLong(int count) { long[] a = new long[count]; for (int i = 0; i < count; i++) { a[i] = nextLong(); } return a; } }
Java
["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"]
1 second
["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"]
NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Java 8
standard input
[ "two pointers", "dsu", "implementation", "sortings", "trees" ]
b97eeaa66e91bbcc3b5e616cb480c7af
The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
1,500
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
standard output
PASSED
25b94fc45c56dcaf01f791839cbbc55e
train_003.jsonl
1508151900
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
512 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { InputStream inputStream = System.in; // InputStream inputStream = new FileInputStream("sum.in"); OutputStream outputStream = System.out; // OutputStream outputStream = new FileOutputStream("sum.out"); InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Answer solver = new Answer(); solver.solve(in, out); out.close(); } } class Answer { private final int INF = (int) (1e9 + 7); private final int MOD = (int) (1e9 + 7); private final int MOD1 = (int) (1e6 + 3); private final long INF_LONG = (long) (1e18 + 1); private final double EPS = 1e-9; private long gcd(long a, long b) { return (b == 0) ? a : gcd(b, a % b); } private long[] tree; private void buildTree(int n) { tree = new long[4 * (n + 1)]; } private void set(int index, int n) { set(1, 1, n, index); } private void set(int v, int l, int r, int index) { if (l > index || r < index) { return; } if (l == r) { tree[v] = 1; return; } int m = (l + r) >> 1; if (m < index) { set(v * 2 + 1, m + 1, r, index); } else { set(v * 2, l, m, index); } tree[v] = tree[v * 2] + tree[v * 2 + 1]; } private long get(int l, int r, int n) { return get(1, 1, n, l, r); } private long get(int v, int tl, int tr, int l, int r) { if (tl > r || tr < l) { return 0; } if (l <= tl && tr <= r) { return tree[v]; } int m = (tl + tr) >> 1; long leftSum = get(v * 2, tl, m, l, Math.min(m, r)); long rightSum = get(v * 2 + 1, m + 1, tr, Math.max(m + 1, l), r); return leftSum + rightSum; } public void solve(InputReader in, PrintWriter out) throws IOException { int n = in.nextInt(); buildTree(n); int[] a = new int[n + 1]; int lastZeroPosition = n; out.print(1 + " "); for (int i = 0; i < n; i++) { int p = in.nextInt(); a[p] = 1; try { set(p, n); } catch (ArrayIndexOutOfBoundsException e) { out.println(); out.println("error: " + p); return; } while (lastZeroPosition > 0 && a[lastZeroPosition] == 1) { lastZeroPosition--; } long x = 1 + get(1, lastZeroPosition, n); out.print(x + " "); } out.println(); } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public int[] nextArrayInt(int count) { int[] a = new int[count]; for (int i = 0; i < count; i++) { a[i] = nextInt(); } return a; } public long[] nextArrayLong(int count) { long[] a = new long[count]; for (int i = 0; i < count; i++) { a[i] = nextLong(); } return a; } }
Java
["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"]
1 second
["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"]
NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Java 8
standard input
[ "two pointers", "dsu", "implementation", "sortings", "trees" ]
b97eeaa66e91bbcc3b5e616cb480c7af
The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
1,500
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
standard output
PASSED
b893650f269c89015871271ef7599af7
train_003.jsonl
1508151900
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
512 megabytes
import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.util.InputMismatchException; public class Main { public static void main(String[] args) throws IOException { FastScanner input = new FastScanner(System.in); int N = input.nextInt(); boolean[] activated = new boolean[N]; BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); Node[] nodes = new Node[N]; for (int i = 0; i < N; i++) nodes[i] = new Node(); out.append("1 "); for (int i = 1; i <= N; i++) { int x = input.nextInt() - 1; activated[x] = true; if (x > 0 && activated[x - 1]) union(nodes[x], nodes[x - 1]); if (x < N - 1 && activated[x + 1]) union(nodes[x], nodes[x + 1]); out.append(1 + i - (activated[N - 1] ? root(nodes[N - 1]).count : 0) + (i == N ? "\n" : " ")); } out.close(); } static class Node { Node parent; int count; Node() { parent = this; count = 1; } } static boolean connected(Node a, Node b) { return root(a) == root(b); } static void union(Node a, Node b) { a = root(a); b = root(b); if (a == b) return; if (a.count > b.count) { b.parent = a; a.count += b.count; } else { a.parent = b; b.count += a.count; } } static Node root(Node a) { while (a.parent != a) { a.parent = a.parent.parent; a = a.parent; } return a; } // Matt Fontaine's Fast IO 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; } 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; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } 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(); } 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(); } } }
Java
["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"]
1 second
["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"]
NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Java 8
standard input
[ "two pointers", "dsu", "implementation", "sortings", "trees" ]
b97eeaa66e91bbcc3b5e616cb480c7af
The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
1,500
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
standard output
PASSED
79117ba61fb07ab3f3a768676095778e
train_003.jsonl
1508151900
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
512 megabytes
import java.util.*; import java.text.*; import java.io.*; import java.math.*; public class code5 { InputStream is; PrintWriter out; static long mod=pow(10,9)+7; static int dx[]={0,0,1,-1},dy[]={1,-1,0,0}; void solve() throws Exception { int n=ni(); int a[]=na(n); TreeSet<Integer> ts=new TreeSet<Integer>(); for(int i=1;i<=n;i++) ts.add(i); int online=0; for(int i=0;i<=n;i++) { int minus=0; if(ts.size()!=0) minus=ts.last(); out.print((online+1-(n-minus))+" "); online++; if(i!=n) ts.remove(a[i]); } } long ans[]; long value[]; ArrayList<Integer> al[]; void take(int n,int m) { al=new ArrayList[n]; for(int i=0;i<n;i++) al[i]=new ArrayList<Integer>(); for(int i=0;i<m;i++) { int x=ni()-1; int y=ni()-1; al[x].add(y); al[y].add(x); } } int check(long n) { int count=0; while(n!=0) { if(n%10!=0) break; n/=10; count++; } return count; } public static int count(int x) { int num=0; while(x!=0) { x=x&(x-1); num++; } return num; } static long d, x, y; void extendedEuclid(long A, long B) { if(B == 0) { d = A; x = 1; y = 0; } else { extendedEuclid(B, A%B); long temp = x; x = y; y = temp - (A/B)*y; } } long modInverse(long A,long M) //A and M are coprime { extendedEuclid(A,M); return (x%M+M)%M; //x may be negative } public static void mergeSort(int[] arr, int l ,int r){ if((r-l)>=1){ int mid = (l+r)/2; mergeSort(arr,l,mid); mergeSort(arr,mid+1,r); merge(arr,l,r,mid); } } public static void merge(int arr[], int l, int r, int mid){ int n1 = (mid-l+1), n2 = (r-mid); int left[] = new int[n1]; int right[] = new int[n2]; for(int i =0 ;i<n1;i++) left[i] = arr[l+i]; for(int i =0 ;i<n2;i++) right[i] = arr[mid+1+i]; int i =0, j =0, k = l; while(i<n1 && j<n2){ if(left[i]>right[j]){ arr[k++] = right[j++]; } else{ arr[k++] = left[i++]; } } while(i<n1) arr[k++] = left[i++]; while(j<n2) arr[k++] = right[j++]; } public static void mergeSort(long[] arr, int l ,int r){ if((r-l)>=1){ int mid = (l+r)/2; mergeSort(arr,l,mid); mergeSort(arr,mid+1,r); merge(arr,l,r,mid); } } public static void merge(long arr[], int l, int r, int mid){ int n1 = (mid-l+1), n2 = (r-mid); long left[] = new long[n1]; long right[] = new long[n2]; for(int i =0 ;i<n1;i++) left[i] = arr[l+i]; for(int i =0 ;i<n2;i++) right[i] = arr[mid+1+i]; int i =0, j =0, k = l; while(i<n1 && j<n2){ if(left[i]>right[j]){ arr[k++] = right[j++]; } else{ arr[k++] = left[i++]; } } while(i<n1) arr[k++] = left[i++]; while(j<n2) arr[k++] = right[j++]; } static class Pair implements Comparable<Pair>{ int x,y,k; int i,dir; Pair (int xx,int yy){ this.x=xx; this.y=yy; this.k=k; } public int compareTo(Pair o) { if(this.y!=o.y) return this.y-o.y; return this.k-o.k; } public String toString(){ return x+" "+y+" "+k+" "+i;} public boolean equals(Object o) { if (o instanceof Pair) { Pair p = (Pair)o; return p.x == x && p.y == y; } return false; } public int hashCode() { return new Long(x).hashCode()*31 + new Long(y).hashCode() ; } } public static boolean isPal(String s){ for(int i=0, j=s.length()-1;i<=j;i++,j--){ if(s.charAt(i)!=s.charAt(j)) return false; } return true; } public static String rev(String s){ StringBuilder sb=new StringBuilder(s); sb.reverse(); return sb.toString(); } public static long gcd(long x,long y){ if(y==0) return x; else return gcd(y,x%y); } public static int gcd(int x,int y){ if(y==0) return x; return gcd(y,x%y); } public static long gcdExtended(long a,long b,long[] x){ if(a==0){ x[0]=0; x[1]=1; return b; } long[] y=new long[2]; long gcd=gcdExtended(b%a, a, y); x[0]=y[1]-(b/a)*y[0]; x[1]=y[0]; return gcd; } public static int abs(int a,int b){ return (int)Math.abs(a-b); } public static long abs(long a,long b){ return (long)Math.abs(a-b); } public static int max(int a,int b){ if(a>b) return a; else return b; } public static int min(int a,int b){ if(a>b) return b; else return a; } public static long max(long a,long b){ if(a>b) return a; else return b; } public static long min(long a,long b){ if(a>b) return b; else return a; } public static long pow(long n,long p,long m){ long result = 1; if(p==0) return 1; if (p==1) return n; while(p!=0) { if(p%2==1) result *= n; if(result>=m) result%=m; p >>=1; n*=n; if(n>=m) n%=m; } return result; } public static long pow(long n,long p){ long result = 1; if(p==0) return 1; if (p==1) return n; while(p!=0) { if(p%2==1) result *= n; p >>=1; n*=n; } return result; } public static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } void run() throws Exception { is = System.in; out = new PrintWriter(System.out); solve(); out.flush(); } public static void main(String[] args) throws Exception { new Thread(null, new Runnable() { public void run() { try { new code5().run(); } catch (Exception e) { e.printStackTrace(); } } }, "1", 1 << 26).start(); //new code5().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 long[] nl(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nl(); 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
["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"]
1 second
["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"]
NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Java 8
standard input
[ "two pointers", "dsu", "implementation", "sortings", "trees" ]
b97eeaa66e91bbcc3b5e616cb480c7af
The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
1,500
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
standard output
PASSED
0308ed8e1c44e9e0cb7a681e57809de0
train_003.jsonl
1508151900
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
512 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; public class Main { public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()), maxJ = 0; String[] input = br.readLine().split(" "); int[] result = new int[n]; for(int j = 0; j < n; j++) result[j] = (maxJ = Math.max(maxJ, Integer.parseInt(input[n - j - 1]))) - j; StringBuilder sb = new StringBuilder(); for(int i = n - 1; i >= 0; i--) sb.append(result[i] + (i != 0 ? " " : " 1")); System.out.println(sb); } }
Java
["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"]
1 second
["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"]
NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Java 8
standard input
[ "two pointers", "dsu", "implementation", "sortings", "trees" ]
b97eeaa66e91bbcc3b5e616cb480c7af
The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
1,500
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
standard output
PASSED
db0bd53798ceac74e71b81079051521d
train_003.jsonl
1508151900
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
512 megabytes
import java.io.*; import java.util.*; public class Main { public static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader() { reader = new BufferedReader(new InputStreamReader(System.in), 32765); tokenizer = null; } public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(System.in), 32765); 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 char nextChar() { return next().charAt(0); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public int[] nextIntArr(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = this.nextInt(); } return arr; } public Integer[] nextIntegerArr(int n) { Integer[] arr = new Integer[n]; for (int i = 0; i < n; i++) { arr[i] = new Integer(this.nextInt()); } return arr; } public int[][] next2DIntArr(int n, int m) { int[][] arr = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { arr[i][j] = this.nextInt(); } } return arr; } public int[] nextSortedIntArr(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = this.nextInt(); } Arrays.sort(arr); return arr; } public long[] nextLongArr(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = this.nextLong(); } return arr; } public long[] nextSortedLongArr(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = this.nextInt(); } Arrays.sort(arr); return arr; } public char[] nextCharArr(int n) { char[] arr = new char[n]; for (int i = 0; i < n; i++) { arr[i] = this.nextChar(); } return arr; } } public static InputReader scn = new InputReader(); public static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { // InputStream inputStream = System.in; // Useful when taking input other than // console eg file handling // check ctor of inputReader // To print in file use this:- out = new PrintWriter("destination of file") // including extension"); int n = scn.nextInt(), last = n; int[] bit = new int[n + 1]; out.print(1 + " "); while(n-- > 0) { int p = scn.nextInt(); update(bit, 1, p); while(query(bit, last) - query(bit, last - 1) != 0) { last--; } out.print(query(bit, last) + 1 + " "); } out.close(); } public static void update(int[] bit, int val, int ind) { while (ind < bit.length) { bit[ind] += val; int x = ind & (-ind); ind += x; } } public static int query(int[] bit, int ind) { int rv = 0; while (ind > 0) { rv += bit[ind]; ind -= ind & (-ind); } return rv; } }
Java
["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"]
1 second
["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"]
NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Java 8
standard input
[ "two pointers", "dsu", "implementation", "sortings", "trees" ]
b97eeaa66e91bbcc3b5e616cb480c7af
The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
1,500
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
standard output
PASSED
2297c3bf85b20a06e4af2bdc5bc46f96
train_003.jsonl
1508151900
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
512 megabytes
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.InputMismatchException; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.logging.Level; import java.util.logging.Logger; /* * 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 ssaxena36 :D Solution is at the Top * */ public class DSU4 { public boolean isPrime(long n) { return BigInteger.valueOf(n).isProbablePrime(5); } void solve() { int n = inpi(); int arr[] = new int[n + 1], change, finalAns[] = new int[n + 1]; out.print(1 + " "); change = n; for (int i = 0; i < n; i++) { arr[i] = inpi() - 1; } for (int i = n - 1; i >= 0; i--) { finalAns[i] = i + 1 - change; change = Math.min(change, n - arr[i] - 1); } for (int i = 0; i < n; i++) { out.print((finalAns[i] + 1) + " "); }; } public boolean[] SieveOfEratosthenes(int n) { boolean prime[] = new boolean[n + 1]; Arrays.fill(prime, true); for (int p = 2; p * p <= n; p++) { if (prime[p] == true) { for (int i = p * 2; i <= n; i += p) { prime[i] = false; } } } for (int i = 2; i < n; i++) { if (prime[i]) { //do some stuff } } return prime; } InputStream obj; PrintWriter out; String check = ""; public static void main(String[] args) throws IOException { new Thread(null, new Runnable() { public void run() { try { new DSU4().main1(); } catch (IOException ex) { Logger.getLogger(DSU4.class.getName()).log(Level.SEVERE, null, ex); } } }, "child-thread", 1 << 26).start(); } void main1() throws IOException { out = new PrintWriter(System.out); obj = check.isEmpty() ? System.in : new ByteArrayInputStream(check.getBytes()); // obj=check.isEmpty() ? new FileInputStream("/home/ssaxena36/Desktop/CDGO1704_6.in") : new ByteArrayInputStream(check.getBytes()); solve(); out.flush(); out.close(); } 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++]; } boolean isSpaceChar(int c) { return (!(c >= 33 && c <= 126)); } int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)); return b; } String inps() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } int inpi() { 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 inpl() { 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(); } } float inpf() { return Float.parseFloat(inps()); } double inpd() { return Double.parseDouble(inps()); } char inpc() { return (char) skip(); } int[] inpia(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = inpi(); } return a; } long[] inpla(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = inpl(); } return a; } String[] inpsa(int n) { String a[] = new String[n]; for (int i = 0; i < n; i++) { a[i] = inps(); } return a; } double[][] inpdm(int n, int m) { double a[][] = new double[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[i][j] = inpd(); } } return a; } int[][] inpim(int n, int m) { int a[][] = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[i][j] = inpi(); } } return a; } }
Java
["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"]
1 second
["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"]
NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Java 8
standard input
[ "two pointers", "dsu", "implementation", "sortings", "trees" ]
b97eeaa66e91bbcc3b5e616cb480c7af
The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
1,500
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
standard output
PASSED
f4e4977230dc7c70dee082f0f7568e09
train_003.jsonl
1508151900
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class TaskD { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()), max = 0; String[] input = br.readLine().split(" "); int[] ans = new int[n]; for(int j = 0; j < n; j++) ans[j] = (max = Math.max(max, Integer.parseInt(input[n-j-1]))) - j; StringBuilder res = new StringBuilder(); for(int i = n - 1; i >= 0; i--) res.append(ans[i]).append(i != 0 ? " " : " 1"); System.out.println(res.toString()); } }
Java
["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"]
1 second
["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"]
NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Java 8
standard input
[ "two pointers", "dsu", "implementation", "sortings", "trees" ]
b97eeaa66e91bbcc3b5e616cb480c7af
The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
1,500
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
standard output
PASSED
cafe6b0908c5801c7977bf22e79d5eca
train_003.jsonl
1508151900
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
512 megabytes
import java.io.*; import java.util.*; import java.util.Map.Entry; import java.lang.Math; import java.math.BigInteger; public class Problem { int INF = -1000 * 1000 * 1000 - 100; int counter; int[] arr; int[] t; void solve() throws IOException { int n = rI(); out.print(1 + " "); int curLast = n; arr = new int[n + 1]; t = new int[n+1]; for(int i=0;i<n;++i){ int q = rI(); if(q==curLast){ curLast--; while(arr[curLast]==1) curLast--; }else{ arr[q] = 1; inc(q, 1); } if(curLast>0){ out.print(get(curLast)+1+" "); } } out.print(1); } long get(int r) { long sum = 0; for (int i = r; i >= 1; i = (i & (i + 1)) - 1) { sum += t[i]; } return sum; } void init() { for (int i = 1; i < arr.length; ++i) { inc(i, arr[i]); } } void inc(int i, int delta) { for (; i < arr.length; i = i | (i + 1)) { t[i] += delta; } } public static void main(String[] args) throws IOException { new Problem().run(); } boolean isLower(char a) { return ((int) a) >= 97 ? true : false; } BufferedReader in; PrintWriter out; StringTokenizer tok; Random rnd = new Random(); static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; Problem() throws FileNotFoundException { if (ONLINE_JUDGE) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } tok = new StringTokenizer(""); } long checkBit(long mask, int bit) { return (mask >> bit) & 1; } // ====================================================== // ====================================================== void run() throws IOException { solve(); out.close(); } char[] reverseCharArray(char[] arr) { char[] ans = new char[arr.length]; for (int i = 0; i < arr.length; ++i) { ans[i] = arr[arr.length - i - 1]; } return ans; } int sqrt(double m) { int l = 0; int r = 1000000000 + 9; int i = 1000; while (r - l > 1) { int mid = (r + l) / 2; if (mid * mid > m) { r = mid; } else { l = mid; } } return l; } int countPow(int m, int n) { int ans = 0; while (m % n == 0 && m > 0) { ans++; m /= n; } return ans; } long binPow(long a, long b) { if (b == 0) { return 1; } if (b % 2 == 1) { return a * binPow(a, b - 1); } else { long c = binPow(a, b / 2); return c * c; } } long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } long pow(long x, long k) { long ans = 1; for (int i = 0; i < k; ++i) { ans *= x; } return ans; } // //////////////////////////////////////////////////////////////////// String delimiter = " "; String readLine() throws IOException { return in.readLine(); } String rS() throws IOException { while (!tok.hasMoreTokens()) { String nextLine = readLine(); if (null == nextLine) return null; tok = new StringTokenizer(nextLine); } return tok.nextToken(delimiter); } int rI() throws IOException { return Integer.parseInt(rS()); } long rL() throws IOException { return Long.parseLong(rS()); } double rD() throws IOException { return Double.parseDouble(rS()); } int[] rA(int b) { int a[] = new int[b]; for (int i = 0; i < b; i++) { try { a[i] = rI(); } catch (IOException e) { e.printStackTrace(); } } return a; } int[] readSortedIntArray(int size) throws IOException { Integer[] array = new Integer[size]; for (int index = 0; index < size; ++index) { array[index] = rI(); } Arrays.sort(array); int[] sortedArray = new int[size]; for (int index = 0; index < size; ++index) { sortedArray[index] = array[index]; } return sortedArray; } int[] sortedIntArray(int size, int[] array) throws IOException { for (int index = 0; index < size; ++index) { array[index] = rI(); } Arrays.sort(array); int[] sortedArray = new int[size]; for (int index = 0; index < size; ++index) { sortedArray[index] = array[index]; } return sortedArray; } }
Java
["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"]
1 second
["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"]
NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Java 8
standard input
[ "two pointers", "dsu", "implementation", "sortings", "trees" ]
b97eeaa66e91bbcc3b5e616cb480c7af
The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
1,500
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
standard output
PASSED
1dacb5389ac36aa9b39c73a4853ee2bb
train_003.jsonl
1508151900
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
512 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) { FastScanner sc=new FastScanner(); PrintWriter pw=new PrintWriter(System.out); while(sc.hasNext()){ int n=sc.nextInt(); Integer[]shu=new Integer[n]; for(int i=0;i<n;i++)shu[i]=sc.nextInt(); int[]p=new int[300050]; pw.print(1+" "); int max=n; int d=0; for(int i=0;i<n;i++){ p[shu[i]]=1; while(p[max]==1&&max>=0){ max--; d++; } pw.print((i-d+2)+" "); } pw.flush(); } } } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { try { br = new BufferedReader(new InputStreamReader(System.in),32768); st = new StringTokenizer(""); } catch (Exception e) { e.printStackTrace(); } } public boolean hasNext() { while (!st.hasMoreTokens()) { String line = nextLine(); if (line == null) { return false; } st = new StringTokenizer(line); } return true; } public String next() { while(!st.hasMoreTokens()){ st=new StringTokenizer(nextLine()); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { String line = ""; try { line = br.readLine(); } catch (Exception e) { e.printStackTrace(); } return line; } }
Java
["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"]
1 second
["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"]
NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Java 8
standard input
[ "two pointers", "dsu", "implementation", "sortings", "trees" ]
b97eeaa66e91bbcc3b5e616cb480c7af
The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
1,500
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
standard output
PASSED
dfd021ddc400cfb7ff2ccd2a52beb85d
train_003.jsonl
1508151900
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
512 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Stream; public class D_441 { public static final long[] POWER2 = generatePOWER2(); public static final IteratorBuffer<Long> ITERATOR_BUFFER_PRIME = new IteratorBuffer<>(streamPrime(1000000).iterator()); private static BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); private static StringTokenizer stringTokenizer = null; private static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); static class Array<Type> implements Iterable<Type> { private final Object[] array; public Array(int size) { this.array = new Object[size]; } public Array(int size, Type element) { this(size); Arrays.fill(this.array, element); } public Array(Array<Type> array, Type element) { this(array.size() + 1); for (int index = 0; index < array.size(); index++) { set(index, array.get(index)); } set(size() - 1, element); } public Array(List<Type> list) { this(list.size()); int index = 0; for (Type element : list) { set(index, element); index += 1; } } public Type get(int index) { return (Type) this.array[index]; } @Override public Iterator<Type> iterator() { return new Iterator<Type>() { int index = 0; @Override public boolean hasNext() { return this.index < size(); } @Override public Type next() { Type result = Array.this.get(index); index += 1; return result; } }; } public Array set(int index, Type value) { this.array[index] = value; return this; } public int size() { return this.array.length; } public List<Type> toList() { List<Type> result = new ArrayList<>(); for (Type element : this) { result.add(element); } return result; } @Override public String toString() { return "[" + D_441.toString(this, ", ") + "]"; } } static class BIT { private static int lastBit(int index) { return index & -index; } private final long[] tree; public BIT(int size) { this.tree = new long[size]; } public void add(int index, long delta) { index += 1; while (index <= this.tree.length) { tree[index - 1] += delta; index += lastBit(index); } } private long prefix(int end) { long result = 0; while (end > 0) { result += this.tree[end - 1]; end -= lastBit(end); } return result; } public int size() { return this.tree.length; } public long sum(int start, int end) { return prefix(end) - prefix(start); } } static abstract class Edge<TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge>> { public final TypeVertex vertex0; public final TypeVertex vertex1; public final boolean bidirectional; public Edge(TypeVertex vertex0, TypeVertex vertex1, boolean bidirectional) { this.vertex0 = vertex0; this.vertex1 = vertex1; this.bidirectional = bidirectional; this.vertex0.edges.add(getThis()); if (this.bidirectional) { this.vertex1.edges.add(getThis()); } } public abstract TypeEdge getThis(); public TypeVertex other(Vertex<TypeVertex, TypeEdge> vertex) { TypeVertex result; if (vertex0 == vertex) { result = vertex1; } else { result = vertex0; } return result; } public void remove() { this.vertex0.edges.remove(getThis()); if (this.bidirectional) { this.vertex1.edges.remove(getThis()); } } @Override public String toString() { return this.vertex0 + "->" + this.vertex1; } } public static class EdgeDefault<TypeVertex extends Vertex<TypeVertex, EdgeDefault<TypeVertex>>> extends Edge<TypeVertex, EdgeDefault<TypeVertex>> { public EdgeDefault(TypeVertex vertex0, TypeVertex vertex1, boolean bidirectional) { super(vertex0, vertex1, bidirectional); } @Override public EdgeDefault<TypeVertex> getThis() { return this; } } public static class EdgeDefaultDefault extends Edge<VertexDefaultDefault, EdgeDefaultDefault> { public EdgeDefaultDefault(VertexDefaultDefault vertex0, VertexDefaultDefault vertex1, boolean bidirectional) { super(vertex0, vertex1, bidirectional); } @Override public EdgeDefaultDefault getThis() { return this; } } public static class FIFO<Type> { public SingleLinkedList<Type> start; public SingleLinkedList<Type> end; public FIFO() { this.start = null; this.end = null; } public boolean isEmpty() { return this.start == null; } public Type peek() { return this.start.element; } public Type pop() { Type result = this.start.element; this.start = this.start.next; return result; } public void push(Type element) { SingleLinkedList<Type> list = new SingleLinkedList<>(element, null); if (this.start == null) { this.start = list; this.end = list; } else { this.end.next = list; this.end = list; } } } static class Fraction implements Comparable<Fraction> { public static final Fraction ZERO = new Fraction(0, 1); public static Fraction fraction(long whole) { return fraction(whole, 1); } public static Fraction fraction(long numerator, long denominator) { Fraction result; if (denominator == 0) { throw new ArithmeticException(); } if (numerator == 0) { result = Fraction.ZERO; } else { int sign; if (numerator < 0 ^ denominator < 0) { sign = -1; numerator = Math.abs(numerator); denominator = Math.abs(denominator); } else { sign = 1; } long gcd = gcd(numerator, denominator); result = new Fraction(sign * numerator / gcd, denominator / gcd); } return result; } public final long numerator; public final long denominator; private Fraction(long numerator, long denominator) { this.numerator = numerator; this.denominator = denominator; } public Fraction add(Fraction fraction) { return fraction(this.numerator * fraction.denominator + fraction.numerator * this.denominator, this.denominator * fraction.denominator); } @Override public int compareTo(Fraction that) { return Long.compare(this.numerator * that.denominator, that.numerator * this.denominator); } public Fraction divide(Fraction fraction) { return multiply(fraction.inverse()); } public boolean equals(Fraction that) { return this.compareTo(that) == 0; } public boolean equals(Object that) { return this.compareTo((Fraction) that) == 0; } public Fraction getRemainder() { return fraction(this.numerator - getWholePart() * denominator, denominator); } public long getWholePart() { return this.numerator / this.denominator; } public Fraction inverse() { return fraction(this.denominator, this.numerator); } public Fraction multiply(Fraction fraction) { return fraction(this.numerator * fraction.numerator, this.denominator * fraction.denominator); } public Fraction neg() { return fraction(-this.numerator, this.denominator); } public Fraction sub(Fraction fraction) { return add(fraction.neg()); } @Override public String toString() { String result; if (getRemainder().equals(Fraction.ZERO)) { result = "" + this.numerator; } else { result = this.numerator + "/" + this.denominator; } return result; } } static class IteratorBuffer<Type> { private Iterator<Type> iterator; private List<Type> list; public IteratorBuffer(Iterator<Type> iterator) { this.iterator = iterator; this.list = new ArrayList<Type>(); } public Iterator<Type> iterator() { return new Iterator<Type>() { int index = 0; @Override public boolean hasNext() { return this.index < list.size() || IteratorBuffer.this.iterator.hasNext(); } @Override public Type next() { if (list.size() <= this.index) { list.add(iterator.next()); } Type result = list.get(index); index += 1; return result; } }; } } public static class MapCount<Type> extends SortedMapAVL<Type, Long> { private int count; public MapCount(Comparator<? super Type> comparator) { super(comparator); this.count = 0; } public long add(Type key, Long delta) { long result; if (delta > 0) { Long value = get(key); if (value == null) { value = delta; } else { value += delta; } put(key, value); result = delta; } else { result = 0; } this.count += result; return result; } public int count() { return this.count; } public List<Type> flatten() { List<Type> result = new ArrayList<>(); for (Entry<Type, Long> entry : entrySet()) { for (long index = 0; index < entry.getValue(); index++) { result.add(entry.getKey()); } } return result; } @Override public SortedMapAVL<Type, Long> headMap(Type keyEnd) { throw new UnsupportedOperationException(); } @Override public void putAll(Map<? extends Type, ? extends Long> map) { throw new UnsupportedOperationException(); } public long remove(Type key, Long delta) { long result; if (delta > 0) { Long value = get(key) - delta; if (value <= 0) { result = delta + value; remove(key); } else { result = delta; put(key, value); } } else { result = 0; } this.count -= result; return result; } @Override public Long remove(Object key) { Long result = super.remove(key); this.count -= result; return result; } @Override public SortedMapAVL<Type, Long> subMap(Type keyStart, Type keyEnd) { throw new UnsupportedOperationException(); } @Override public SortedMapAVL<Type, Long> tailMap(Type keyStart) { throw new UnsupportedOperationException(); } } public static class MapSet<TypeKey, TypeValue> extends SortedMapAVL<TypeKey, SortedSetAVL<TypeValue>> implements Iterable<TypeValue> { private Comparator<? super TypeValue> comparatorValue; public MapSet(Comparator<? super TypeKey> comparatorKey, Comparator<? super TypeValue> comparatorValue) { super(comparatorKey); this.comparatorValue = comparatorValue; } public MapSet(Comparator<? super TypeKey> comparatorKey, SortedSetAVL<Entry<TypeKey, SortedSetAVL<TypeValue>>> entrySet, Comparator<? super TypeValue> comparatorValue) { super(comparatorKey, entrySet); this.comparatorValue = comparatorValue; } public boolean add(TypeKey key, TypeValue value) { SortedSetAVL<TypeValue> set = computeIfAbsent(key, k -> new SortedSetAVL<>(comparatorValue)); return set.add(value); } public TypeValue firstValue() { TypeValue result; Entry<TypeKey, SortedSetAVL<TypeValue>> firstEntry = firstEntry(); if (firstEntry == null) { result = null; } else { result = firstEntry.getValue().first(); } return result; } @Override public MapSet<TypeKey, TypeValue> headMap(TypeKey keyEnd) { return new MapSet<>(this.comparator, this.entrySet.headSet(new AbstractMap.SimpleEntry<>(keyEnd, null)), this.comparatorValue); } public Iterator<TypeValue> iterator() { return new Iterator<TypeValue>() { Iterator<SortedSetAVL<TypeValue>> iteratorValues = values().iterator(); Iterator<TypeValue> iteratorValue = null; @Override public boolean hasNext() { return iteratorValues.hasNext() || (iteratorValue != null && iteratorValue.hasNext()); } @Override public TypeValue next() { if (iteratorValue == null || !iteratorValue.hasNext()) { iteratorValue = iteratorValues.next().iterator(); } return iteratorValue.next(); } }; } public TypeValue lastValue() { TypeValue result; Entry<TypeKey, SortedSetAVL<TypeValue>> lastEntry = lastEntry(); if (lastEntry == null) { result = null; } else { result = lastEntry.getValue().last(); } return result; } public boolean removeSet(TypeKey key, TypeValue value) { boolean result; SortedSetAVL<TypeValue> set = get(key); if (set == null) { result = false; } else { result = set.remove(value); if (set.size() == 0) { remove(key); } } return result; } @Override public MapSet<TypeKey, TypeValue> tailMap(TypeKey keyStart) { return new MapSet<>(this.comparator, this.entrySet.tailSet(new AbstractMap.SimpleEntry<>(keyStart, null)), this.comparatorValue); } } public static class Matrix { public final int rows; public final int columns; public final Fraction[][] cells; public Matrix(int rows, int columns) { this.rows = rows; this.columns = columns; this.cells = new Fraction[rows][columns]; for (int row = 0; row < rows; row++) { for (int column = 0; column < columns; column++) { set(row, column, Fraction.ZERO); } } } public void add(int rowSource, int rowTarget, Fraction fraction) { for (int column = 0; column < columns; column++) { this.cells[rowTarget][column] = this.cells[rowTarget][column].add(this.cells[rowSource][column].multiply(fraction)); } } private int columnPivot(int row) { int result = this.columns; for (int column = this.columns - 1; 0 <= column; column--) { if (this.cells[row][column].compareTo(Fraction.ZERO) != 0) { result = column; } } return result; } public void reduce() { for (int rowMinimum = 0; rowMinimum < this.rows; rowMinimum++) { int rowPivot = rowPivot(rowMinimum); if (rowPivot != -1) { int columnPivot = columnPivot(rowPivot); Fraction current = this.cells[rowMinimum][columnPivot]; Fraction pivot = this.cells[rowPivot][columnPivot]; Fraction fraction = pivot.inverse().sub(current.divide(pivot)); add(rowPivot, rowMinimum, fraction); for (int row = rowMinimum + 1; row < this.rows; row++) { if (columnPivot(row) == columnPivot) { add(rowMinimum, row, this.cells[row][columnPivot(row)].neg()); } } } } } private int rowPivot(int rowMinimum) { int result = -1; int pivotColumnMinimum = this.columns; for (int row = rowMinimum; row < this.rows; row++) { int pivotColumn = columnPivot(row); if (pivotColumn < pivotColumnMinimum) { result = row; pivotColumnMinimum = pivotColumn; } } return result; } public void set(int row, int column, Fraction value) { this.cells[row][column] = value; } public String toString() { String result = ""; for (int row = 0; row < rows; row++) { for (int column = 0; column < columns; column++) { result += this.cells[row][column] + "\t"; } result += "\n"; } return result; } } public static class Node<Type> { public static <Type> Node<Type> balance(Node<Type> result) { while (result != null && 1 < Math.abs(height(result.left) - height(result.right))) { if (height(result.left) < height(result.right)) { Node<Type> right = result.right; if (height(right.right) < height(right.left)) { result = new Node<>(result.value, result.left, right.rotateRight()); } result = result.rotateLeft(); } else { Node<Type> left = result.left; if (height(left.left) < height(left.right)) { result = new Node<>(result.value, left.rotateLeft(), result.right); } result = result.rotateRight(); } } return result; } public static <Type> Node<Type> clone(Node<Type> result) { if (result != null) { result = new Node<>(result.value, clone(result.left), clone(result.right)); } return result; } public static <Type> Node<Type> delete(Node<Type> node, Type value, Comparator<? super Type> comparator) { Node<Type> result; if (node == null) { result = null; } else { int compare = comparator.compare(value, node.value); if (compare == 0) { if (node.left == null) { result = node.right; } else { if (node.right == null) { result = node.left; } else { Node<Type> first = first(node.right); result = new Node<>(first.value, node.left, delete(node.right, first.value, comparator)); } } } else { if (compare < 0) { result = new Node<>(node.value, delete(node.left, value, comparator), node.right); } else { result = new Node<>(node.value, node.left, delete(node.right, value, comparator)); } } result = balance(result); } return result; } public static <Type> Node<Type> first(Node<Type> result) { while (result.left != null) { result = result.left; } return result; } public static <Type> Node<Type> get(Node<Type> node, Type value, Comparator<? super Type> comparator) { Node<Type> result; if (node == null) { result = null; } else { int compare = comparator.compare(value, node.value); if (compare == 0) { result = node; } else { if (compare < 0) { result = get(node.left, value, comparator); } else { result = get(node.right, value, comparator); } } } return result; } public static <Type> Node<Type> head(Node<Type> node, Type value, Comparator<? super Type> comparator) { Node<Type> result; if (node == null) { result = null; } else { int compare = comparator.compare(value, node.value); if (compare == 0) { result = node.left; } else { if (compare < 0) { result = head(node.left, value, comparator); } else { result = new Node<>(node.value, node.left, head(node.right, value, comparator)); } } result = balance(result); } return result; } public static int height(Node node) { return node == null ? 0 : node.height; } public static <Type> Node<Type> insert(Node<Type> node, Type value, Comparator<? super Type> comparator) { Node<Type> result; if (node == null) { result = new Node<>(value, null, null); } else { int compare = comparator.compare(value, node.value); if (compare == 0) { result = new Node<>(value, node.left, node.right); ; } else { if (compare < 0) { result = new Node<>(node.value, insert(node.left, value, comparator), node.right); } else { result = new Node<>(node.value, node.left, insert(node.right, value, comparator)); } } result = balance(result); } return result; } public static <Type> Node<Type> last(Node<Type> result) { while (result.right != null) { result = result.right; } return result; } public static int size(Node node) { return node == null ? 0 : node.size; } public static <Type> Node<Type> tail(Node<Type> node, Type value, Comparator<? super Type> comparator) { Node<Type> result; if (node == null) { result = null; } else { int compare = comparator.compare(value, node.value); if (compare == 0) { result = new Node<>(node.value, null, node.right); } else { if (compare < 0) { result = new Node<>(node.value, tail(node.left, value, comparator), node.right); } else { result = tail(node.right, value, comparator); } } result = balance(result); } return result; } public static <Type> void traverseOrderIn(Node<Type> node, Consumer<Type> consumer) { if (node != null) { traverseOrderIn(node.left, consumer); consumer.accept(node.value); traverseOrderIn(node.right, consumer); } } public final Type value; public final Node<Type> left; public final Node<Type> right; public final int size; private final int height; public Node(Type value, Node<Type> left, Node<Type> right) { this.value = value; this.left = left; this.right = right; this.size = 1 + size(left) + size(right); this.height = 1 + Math.max(height(left), height(right)); } public Node<Type> rotateLeft() { Node<Type> left = new Node<>(this.value, this.left, this.right.left); return new Node<>(this.right.value, left, this.right.right); } public Node<Type> rotateRight() { Node<Type> right = new Node<>(this.value, this.left.right, this.right); return new Node<>(this.left.value, this.left.left, right); } } public static class SingleLinkedList<Type> { public final Type element; public SingleLinkedList<Type> next; public SingleLinkedList(Type element, SingleLinkedList<Type> next) { this.element = element; this.next = next; } public void toCollection(Collection<Type> collection) { if (this.next != null) { this.next.toCollection(collection); } collection.add(this.element); } } public static class SmallSetIntegers { public static final int SIZE = 20; public static final int[] SET = generateSet(); public static final int[] COUNT = generateCount(); public static final int[] INTEGER = generateInteger(); private static int count(int set) { int result = 0; for (int integer = 0; integer < SIZE; integer++) { if (0 < (set & set(integer))) { result += 1; } } return result; } private static final int[] generateCount() { int[] result = new int[1 << SIZE]; for (int set = 0; set < result.length; set++) { result[set] = count(set); } return result; } private static final int[] generateInteger() { int[] result = new int[1 << SIZE]; Arrays.fill(result, -1); for (int integer = 0; integer < SIZE; integer++) { result[SET[integer]] = integer; } return result; } private static final int[] generateSet() { int[] result = new int[SIZE]; for (int integer = 0; integer < result.length; integer++) { result[integer] = set(integer); } return result; } private static int set(int integer) { return 1 << integer; } } public static class SortedMapAVL<TypeKey, TypeValue> implements SortedMap<TypeKey, TypeValue> { public final Comparator<? super TypeKey> comparator; public final SortedSetAVL<Entry<TypeKey, TypeValue>> entrySet; public SortedMapAVL(Comparator<? super TypeKey> comparator) { this(comparator, new SortedSetAVL<>((entry0, entry1) -> comparator.compare(entry0.getKey(), entry1.getKey()))); } private SortedMapAVL(Comparator<? super TypeKey> comparator, SortedSetAVL<Entry<TypeKey, TypeValue>> entrySet) { this.comparator = comparator; this.entrySet = entrySet; } @Override public void clear() { this.entrySet.clear(); } @Override public Comparator<? super TypeKey> comparator() { return this.comparator; } @Override public boolean containsKey(Object key) { return this.entrySet().contains(new AbstractMap.SimpleEntry<>((TypeKey) key, null)); } @Override public boolean containsValue(Object value) { throw new UnsupportedOperationException(); } @Override public SortedSetAVL<Entry<TypeKey, TypeValue>> entrySet() { return this.entrySet; } public Entry<TypeKey, TypeValue> firstEntry() { return this.entrySet.first(); } @Override public TypeKey firstKey() { return firstEntry().getKey(); } @Override public TypeValue get(Object key) { Entry<TypeKey, TypeValue> entry = new AbstractMap.SimpleEntry<>((TypeKey) key, null); entry = this.entrySet.get(entry); return entry == null ? null : entry.getValue(); } @Override public SortedMapAVL<TypeKey, TypeValue> headMap(TypeKey keyEnd) { return new SortedMapAVL<>(this.comparator, this.entrySet.headSet(new AbstractMap.SimpleEntry<>(keyEnd, null))); } @Override public boolean isEmpty() { return this.entrySet.isEmpty(); } @Override public Set<TypeKey> keySet() { return new SortedSet<TypeKey>() { @Override public boolean add(TypeKey typeKey) { throw new UnsupportedOperationException(); } @Override public boolean addAll(Collection<? extends TypeKey> collection) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public Comparator<? super TypeKey> comparator() { throw new UnsupportedOperationException(); } @Override public boolean contains(Object o) { throw new UnsupportedOperationException(); } @Override public boolean containsAll(Collection<?> collection) { throw new UnsupportedOperationException(); } @Override public TypeKey first() { throw new UnsupportedOperationException(); } @Override public SortedSet<TypeKey> headSet(TypeKey typeKey) { throw new UnsupportedOperationException(); } @Override public boolean isEmpty() { return size() == 0; } @Override public Iterator<TypeKey> iterator() { final Iterator<Entry<TypeKey, TypeValue>> iterator = SortedMapAVL.this.entrySet.iterator(); return new Iterator<TypeKey>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public TypeKey next() { return iterator.next().getKey(); } }; } @Override public TypeKey last() { throw new UnsupportedOperationException(); } @Override public boolean remove(Object o) { throw new UnsupportedOperationException(); } @Override public boolean removeAll(Collection<?> collection) { throw new UnsupportedOperationException(); } @Override public boolean retainAll(Collection<?> collection) { throw new UnsupportedOperationException(); } @Override public int size() { return SortedMapAVL.this.entrySet.size(); } @Override public SortedSet<TypeKey> subSet(TypeKey typeKey, TypeKey e1) { throw new UnsupportedOperationException(); } @Override public SortedSet<TypeKey> tailSet(TypeKey typeKey) { throw new UnsupportedOperationException(); } @Override public Object[] toArray() { throw new UnsupportedOperationException(); } @Override public <T> T[] toArray(T[] ts) { throw new UnsupportedOperationException(); } }; } public Entry<TypeKey, TypeValue> lastEntry() { return this.entrySet.last(); } @Override public TypeKey lastKey() { return lastEntry().getKey(); } @Override public TypeValue put(TypeKey key, TypeValue value) { TypeValue result = get(key); Entry<TypeKey, TypeValue> entry = new AbstractMap.SimpleEntry<>(key, value); this.entrySet().add(entry); return result; } @Override public void putAll(Map<? extends TypeKey, ? extends TypeValue> map) { map.entrySet() .forEach(entry -> put(entry.getKey(), entry.getValue())); } @Override public TypeValue remove(Object key) { TypeValue result = get(key); Entry<TypeKey, TypeValue> entry = new AbstractMap.SimpleEntry<>((TypeKey) key, null); this.entrySet.remove(entry); return result; } @Override public int size() { return this.entrySet().size(); } @Override public SortedMapAVL<TypeKey, TypeValue> subMap(TypeKey keyStart, TypeKey keyEnd) { return new SortedMapAVL<>(this.comparator, this.entrySet.subSet(new AbstractMap.SimpleEntry<>(keyStart, null), new AbstractMap.SimpleEntry<>(keyEnd, null))); } @Override public SortedMapAVL<TypeKey, TypeValue> tailMap(TypeKey keyStart) { return new SortedMapAVL<>(this.comparator, this.entrySet.tailSet(new AbstractMap.SimpleEntry<>(keyStart, null))); } @Override public String toString() { return this.entrySet().toString(); } @Override public Collection<TypeValue> values() { return new Collection<TypeValue>() { @Override public boolean add(TypeValue typeValue) { throw new UnsupportedOperationException(); } @Override public boolean addAll(Collection<? extends TypeValue> collection) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public boolean contains(Object value) { throw new UnsupportedOperationException(); } @Override public boolean containsAll(Collection<?> collection) { throw new UnsupportedOperationException(); } @Override public boolean isEmpty() { return SortedMapAVL.this.entrySet.isEmpty(); } @Override public Iterator<TypeValue> iterator() { return new Iterator<TypeValue>() { Iterator<Entry<TypeKey, TypeValue>> iterator = SortedMapAVL.this.entrySet.iterator(); @Override public boolean hasNext() { return this.iterator.hasNext(); } @Override public TypeValue next() { return this.iterator.next().getValue(); } }; } @Override public boolean remove(Object o) { throw new UnsupportedOperationException(); } @Override public boolean removeAll(Collection<?> collection) { throw new UnsupportedOperationException(); } @Override public boolean retainAll(Collection<?> collection) { throw new UnsupportedOperationException(); } @Override public int size() { return SortedMapAVL.this.entrySet.size(); } @Override public Object[] toArray() { throw new UnsupportedOperationException(); } @Override public <T> T[] toArray(T[] ts) { throw new UnsupportedOperationException(); } }; } } public static class SortedSetAVL<Type> implements SortedSet<Type> { public Comparator<? super Type> comparator; public Node<Type> root; private SortedSetAVL(Comparator<? super Type> comparator, Node<Type> root) { this.comparator = comparator; this.root = root; } public SortedSetAVL(Comparator<? super Type> comparator) { this(comparator, null); } public SortedSetAVL(Collection<? extends Type> collection, Comparator<? super Type> comparator) { this(comparator, null); this.addAll(collection); } public SortedSetAVL(SortedSetAVL<Type> sortedSetAVL) { this(sortedSetAVL.comparator, Node.clone(sortedSetAVL.root)); } @Override public boolean add(Type value) { int sizeBefore = size(); this.root = Node.insert(this.root, value, this.comparator); return sizeBefore != size(); } @Override public boolean addAll(Collection<? extends Type> collection) { return collection.stream() .map(this::add) .reduce(true, (x, y) -> x | y); } @Override public void clear() { this.root = null; } @Override public Comparator<? super Type> comparator() { return this.comparator; } @Override public boolean contains(Object value) { return Node.get(this.root, (Type) value, this.comparator) != null; } @Override public boolean containsAll(Collection<?> collection) { return collection.stream() .allMatch(this::contains); } @Override public Type first() { return Node.first(this.root).value; } public Type get(Type value) { Node<Type> node = Node.get(this.root, value, this.comparator); return node == null ? null : node.value; } @Override public SortedSetAVL<Type> headSet(Type valueEnd) { return new SortedSetAVL<>(this.comparator, Node.head(this.root, valueEnd, this.comparator)); } @Override public boolean isEmpty() { return this.root == null; } @Override public Iterator<Type> iterator() { Stack<Node<Type>> path = new Stack<>(); return new Iterator<Type>() { { push(SortedSetAVL.this.root); } @Override public boolean hasNext() { return !path.isEmpty(); } @Override public Type next() { if (path.isEmpty()) { throw new NoSuchElementException(); } else { Node<Type> node = path.peek(); Type result = node.value; if (node.right != null) { push(node.right); } else { do { node = path.pop(); } while (!path.isEmpty() && path.peek().right == node); } return result; } } public void push(Node<Type> node) { while (node != null) { path.push(node); node = node.left; } } }; } @Override public Type last() { return Node.last(this.root).value; } @Override public boolean remove(Object value) { int sizeBefore = size(); this.root = Node.delete(this.root, (Type) value, this.comparator); return sizeBefore != size(); } @Override public boolean removeAll(Collection<?> collection) { return collection.stream() .map(this::remove) .reduce(true, (x, y) -> x | y); } @Override public boolean retainAll(Collection<?> collection) { SortedSetAVL<Type> set = new SortedSetAVL<>(this.comparator); collection.stream() .map(element -> (Type) element) .filter(this::contains) .forEach(set::add); boolean result = size() != set.size(); this.root = set.root; return result; } @Override public int size() { return this.root == null ? 0 : this.root.size; } @Override public SortedSetAVL<Type> subSet(Type valueStart, Type valueEnd) { return tailSet(valueStart).headSet(valueEnd); } @Override public SortedSetAVL<Type> tailSet(Type valueStart) { return new SortedSetAVL<>(this.comparator, Node.tail(this.root, valueStart, this.comparator)); } @Override public Object[] toArray() { return toArray(new Object[0]); } @Override public <T> T[] toArray(T[] ts) { List<Object> list = new ArrayList<>(); Node.traverseOrderIn(this.root, list::add); return list.toArray(ts); } @Override public String toString() { return "{" + D_441.toString(this, ", ") + "}"; } } public static class Tree2D { public static final int SIZE = 1 << 30; public static final Tree2D[] TREES_NULL = new Tree2D[] { null, null, null, null }; public static boolean contains(int x, int y, int left, int bottom, int size) { return left <= x && x < left + size && bottom <= y && y < bottom + size; } public static int count(Tree2D[] trees) { int result = 0; for (int index = 0; index < 4; index++) { if (trees[index] != null) { result += trees[index].count; } } return result; } public static int count ( int rectangleLeft, int rectangleBottom, int rectangleRight, int rectangleTop, Tree2D tree, int left, int bottom, int size ) { int result; if (tree == null) { result = 0; } else { int right = left + size; int top = bottom + size; int intersectionLeft = Math.max(rectangleLeft, left); int intersectionBottom = Math.max(rectangleBottom, bottom); int intersectionRight = Math.min(rectangleRight, right); int intersectionTop = Math.min(rectangleTop, top); if (intersectionRight <= intersectionLeft || intersectionTop <= intersectionBottom) { result = 0; } else { if (intersectionLeft == left && intersectionBottom == bottom && intersectionRight == right && intersectionTop == top) { result = tree.count; } else { size = size >> 1; result = 0; for (int index = 0; index < 4; index++) { result += count ( rectangleLeft, rectangleBottom, rectangleRight, rectangleTop, tree.trees[index], quadrantLeft(left, size, index), quadrantBottom(bottom, size, index), size ); } } } } return result; } public static int quadrantBottom(int bottom, int size, int index) { return bottom + (index >> 1) * size; } public static int quadrantLeft(int left, int size, int index) { return left + (index & 1) * size; } public final Tree2D[] trees; public final int count; private Tree2D(Tree2D[] trees, int count) { this.trees = trees; this.count = count; } public Tree2D(Tree2D[] trees) { this(trees, count(trees)); } public Tree2D() { this(TREES_NULL); } public int count(int rectangleLeft, int rectangleBottom, int rectangleRight, int rectangleTop) { return count ( rectangleLeft, rectangleBottom, rectangleRight, rectangleTop, this, 0, 0, SIZE ); } public Tree2D setPoint ( int x, int y, Tree2D tree, int left, int bottom, int size ) { Tree2D result; if (contains(x, y, left, bottom, size)) { if (size == 1) { result = new Tree2D(TREES_NULL, 1); } else { size = size >> 1; Tree2D[] trees = new Tree2D[4]; for (int index = 0; index < 4; index++) { trees[index] = setPoint ( x, y, tree == null ? null : tree.trees[index], quadrantLeft(left, size, index), quadrantBottom(bottom, size, index), size ); } result = new Tree2D(trees); } } else { result = tree; } return result; } public Tree2D setPoint(int x, int y) { return setPoint ( x, y, this, 0, 0, SIZE ); } } public static class Tuple2<Type0, Type1> { public final Type0 v0; public final Type1 v1; public Tuple2(Type0 v0, Type1 v1) { this.v0 = v0; this.v1 = v1; } @Override public String toString() { return "(" + this.v0 + ", " + this.v1 + ")"; } } public static class Tuple2Comparable<Type0 extends Comparable<? super Type0>, Type1 extends Comparable<? super Type1>> extends Tuple2<Type0, Type1> implements Comparable<Tuple2Comparable<Type0, Type1>> { public Tuple2Comparable(Type0 v0, Type1 v1) { super(v0, v1); } @Override public int compareTo(Tuple2Comparable<Type0, Type1> that) { int result = this.v0.compareTo(that.v0); if (result == 0) { result = this.v1.compareTo(that.v1); } return result; } } public static class Tuple3<Type0, Type1, Type2> { public final Type0 v0; public final Type1 v1; public final Type2 v2; public Tuple3(Type0 v0, Type1 v1, Type2 v2) { this.v0 = v0; this.v1 = v1; this.v2 = v2; } @Override public String toString() { return "(" + this.v0 + ", " + this.v1 + ", " + this.v2 + ")"; } } public static class Vertex < TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge> > implements Comparable<Vertex<? super TypeVertex, ? super TypeEdge>> { public static < TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge>, TypeResult > TypeResult breadthFirstSearch ( TypeVertex vertex, TypeEdge edge, BiFunctionResult<TypeVertex, TypeEdge, TypeResult> function, Array<Boolean> visited, FIFO<TypeVertex> verticesNext, FIFO<TypeEdge> edgesNext, TypeResult result ) { if (!visited.get(vertex.index)) { visited.set(vertex.index, true); result = function.apply(vertex, edge, result); for (TypeEdge edgeNext : vertex.edges) { TypeVertex vertexNext = edgeNext.other(vertex); if (!visited.get(vertexNext.index)) { verticesNext.push(vertexNext); edgesNext.push(edgeNext); } } } return result; } public static < TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge>, TypeResult > TypeResult breadthFirstSearch ( Array<TypeVertex> vertices, int indexVertexStart, BiFunctionResult<TypeVertex, TypeEdge, TypeResult> function, TypeResult result ) { Array<Boolean> visited = new Array<>(vertices.size(), false); FIFO<TypeVertex> verticesNext = new FIFO<>(); verticesNext.push(vertices.get(indexVertexStart)); FIFO<TypeEdge> edgesNext = new FIFO<>(); edgesNext.push(null); while (!verticesNext.isEmpty()) { result = breadthFirstSearch(verticesNext.pop(), edgesNext.pop(), function, visited, verticesNext, edgesNext, result); } return result; } public static < TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge> > boolean cycle ( TypeVertex start, SortedSet<TypeVertex> result ) { boolean cycle = false; Stack<TypeVertex> stackVertex = new Stack<>(); Stack<TypeEdge> stackEdge = new Stack<>(); stackVertex.push(start); stackEdge.push(null); while (!stackVertex.isEmpty()) { TypeVertex vertex = stackVertex.pop(); TypeEdge edge = stackEdge.pop(); if (!result.contains(vertex)) { result.add(vertex); for (TypeEdge otherEdge : vertex.edges) { if (otherEdge != edge) { TypeVertex otherVertex = otherEdge.other(vertex); if (result.contains(otherVertex)) { cycle = true; } else { stackVertex.push(otherVertex); stackEdge.push(otherEdge); } } } } } return cycle; } public static < TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge> > SortedSet<TypeVertex> depthFirstSearch ( TypeVertex start, BiConsumer<TypeVertex, TypeEdge> functionVisitPre, BiConsumer<TypeVertex, TypeEdge> functionVisitPost ) { SortedSet<TypeVertex> result = new SortedSetAVL<>(Comparator.naturalOrder()); Stack<TypeVertex> stackVertex = new Stack<>(); Stack<TypeEdge> stackEdge = new Stack<>(); stackVertex.push(start); stackEdge.push(null); while (!stackVertex.isEmpty()) { TypeVertex vertex = stackVertex.pop(); TypeEdge edge = stackEdge.pop(); if (result.contains(vertex)) { functionVisitPost.accept(vertex, edge); } else { result.add(vertex); stackVertex.push(vertex); stackEdge.push(edge); functionVisitPre.accept(vertex, edge); for (TypeEdge otherEdge : vertex.edges) { TypeVertex otherVertex = otherEdge.other(vertex); if (!result.contains(otherVertex)) { stackVertex.push(otherVertex); stackEdge.push(otherEdge); } } } } return result; } public static < TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge> > SortedSet<TypeVertex> depthFirstSearch ( TypeVertex start, Consumer<TypeVertex> functionVisitPreVertex, Consumer<TypeVertex> functionVisitPostVertex ) { BiConsumer<TypeVertex, TypeEdge> functionVisitPreVertexEdge = (vertex, edge) -> { functionVisitPreVertex.accept(vertex); }; BiConsumer<TypeVertex, TypeEdge> functionVisitPostVertexEdge = (vertex, edge) -> { functionVisitPostVertex.accept(vertex); }; return depthFirstSearch(start, functionVisitPreVertexEdge, functionVisitPostVertexEdge); } public final int index; public final List<TypeEdge> edges; public Vertex(int index) { this.index = index; this.edges = new ArrayList<>(); } @Override public int compareTo(Vertex<? super TypeVertex, ? super TypeEdge> that) { return Integer.compare(this.index, that.index); } @Override public String toString() { return "" + this.index; } } public static class VertexDefault<TypeEdge extends Edge<VertexDefault<TypeEdge>, TypeEdge>> extends Vertex<VertexDefault<TypeEdge>, TypeEdge> { public VertexDefault(int index) { super(index); } } public static class VertexDefaultDefault extends Vertex<VertexDefaultDefault, EdgeDefaultDefault> { public static Array<VertexDefaultDefault> vertices(int n) { Array<VertexDefaultDefault> result = new Array<>(n); for (int index = 0; index < n; index++) { result.set(index, new VertexDefaultDefault(index)); } return result; } public VertexDefaultDefault(int index) { super(index); } } public static class Wrapper<Type> { public Type value; public Wrapper(Type value) { this.value = value; } public Type get() { return this.value; } public void set(Type value) { this.value = value; } @Override public String toString() { return this.value.toString(); } } public static void add(int delta, int[] result) { for (int index = 0; index < result.length; index++) { result[index] += delta; } } public static void add(int delta, int[]... result) { for (int index = 0; index < result.length; index++) { add(delta, result[index]); } } public static int binarySearchMaximum(Function<Integer, Boolean> filter, int start, int end) { return -binarySearchMinimum(x -> filter.apply(-x), -end, -start); } public static int binarySearchMinimum(Function<Integer, Boolean> filter, int start, int end) { int result; if (start == end) { result = end; } else { int middle = start + (end - start) / 2; if (filter.apply(middle)) { result = binarySearchMinimum(filter, start, middle); } else { result = binarySearchMinimum(filter, middle + 1, end); } } return result; } public static void close() { out.close(); } public static List<List<Integer>> combinations(int n, int k) { List<List<Integer>> result = new ArrayList<>(); if (k == 0) { } else { if (k == 1) { List<Integer> combination = new ArrayList<>(); combination.add(n); result.add(combination); } else { for (int index = 0; index <= n; index++) { for (List<Integer> combination : combinations(n - index, k - 1)) { combination.add(index); result.add(combination); } } } } return result; } public static <Type> int compare(Iterator<Type> iterator0, Iterator<Type> iterator1, Comparator<Type> comparator) { int result = 0; while (result == 0 && iterator0.hasNext() && iterator1.hasNext()) { result = comparator.compare(iterator0.next(), iterator1.next()); } if (result == 0) { if (iterator1.hasNext()) { result = -1; } else { if (iterator0.hasNext()) { result = 1; } } } return result; } public static <Type> int compare(Iterable<Type> iterable0, Iterable<Type> iterable1, Comparator<Type> comparator) { return compare(iterable0.iterator(), iterable1.iterator(), comparator); } public static long divideCeil(long x, long y) { return (x + y - 1) / y; } public static Set<Long> divisors(long n) { SortedSetAVL<Long> result = new SortedSetAVL<>(Comparator.naturalOrder()); result.add(1L); for (Long factor : factors(n)) { SortedSetAVL<Long> divisors = new SortedSetAVL<>(result); for (Long divisor : result) { divisors.add(divisor * factor); } result = divisors; } return result; } public static LinkedList<Long> factors(long n) { LinkedList<Long> result = new LinkedList<>(); Iterator<Long> primes = ITERATOR_BUFFER_PRIME.iterator(); Long prime; while (n > 1 && (prime = primes.next()) * prime <= n) { while (n % prime == 0) { result.add(prime); n /= prime; } } if (n > 1) { result.add(n); } return result; } public static long faculty(int n) { long result = 1; for (int index = 2; index <= n; index++) { result *= index; } return result; } public static long gcd(long a, long b) { while (a != 0 && b != 0) { if (a > b) { a %= b; } else { b %= a; } } return a + b; } public static long[] generatePOWER2() { long[] result = new long[63]; for (int x = 0; x < result.length; x++) { result[x] = 1L << x; } return result; } public static boolean isPrime(long x) { boolean result = x > 1; Iterator<Long> iterator = ITERATOR_BUFFER_PRIME.iterator(); Long prime; while ((prime = iterator.next()) * prime <= x) { result &= x % prime > 0; } return result; } public static long knapsack(List<Tuple3<Long, Integer, Integer>> itemsValueWeightCount, int weightMaximum) { long[] valuesMaximum = new long[weightMaximum + 1]; for (Tuple3<Long, Integer, Integer> itemValueWeightCount : itemsValueWeightCount) { long itemValue = itemValueWeightCount.v0; int itemWeight = itemValueWeightCount.v1; int itemCount = itemValueWeightCount.v2; for (int weight = weightMaximum; 0 <= weight; weight--) { for (int index = 1; index <= itemCount && 0 <= weight - index * itemWeight; index++) { valuesMaximum[weight] = Math.max(valuesMaximum[weight], valuesMaximum[weight - index * itemWeight] + index * itemValue); } } } long result = 0; for (long valueMaximum : valuesMaximum) { result = Math.max(result, valueMaximum); } return result; } public static boolean knapsackPossible(List<Tuple2<Integer, Integer>> itemsWeightCount, int weightMaximum) { boolean[] weightPossible = new boolean[weightMaximum + 1]; weightPossible[0] = true; int weightLargest = 0; for (Tuple2<Integer, Integer> itemWeightCount : itemsWeightCount) { int itemWeight = itemWeightCount.v0; int itemCount = itemWeightCount.v1; for (int weightStart = 0; weightStart < itemWeight; weightStart++) { int count = 0; for (int weight = weightStart; weight <= weightMaximum && (0 < count || weight <= weightLargest); weight += itemWeight) { if (weightPossible[weight]) { count = itemCount; } else { if (0 < count) { weightPossible[weight] = true; weightLargest = weight; count -= 1; } } } } } return weightPossible[weightMaximum]; } public static long lcm(int a, int b) { return a * b / gcd(a, b); } public static void main(String[] args) { try { solve(); } catch (IOException exception) { exception.printStackTrace(); } close(); } public static double nextDouble() throws IOException { return Double.parseDouble(nextString()); } public static int nextInt() throws IOException { return Integer.parseInt(nextString()); } public static void nextInts(int n, int[]... result) throws IOException { for (int index = 0; index < n; index++) { for (int value = 0; value < result.length; value++) { result[value][index] = nextInt(); } } } public static int[] nextInts(int n) throws IOException { int[] result = new int[n]; nextInts(n, result); return result; } public static String nextLine() throws IOException { return bufferedReader.readLine(); } public static long nextLong() throws IOException { return Long.parseLong(nextString()); } public static void nextLongs(int n, long[]... result) throws IOException { for (int index = 0; index < n; index++) { for (int value = 0; value < result.length; value++) { result[value][index] = nextLong(); } } } public static long[] nextLongs(int n) throws IOException { long[] result = new long[n]; nextLongs(n, result); return result; } public static String nextString() throws IOException { while ((stringTokenizer == null) || (!stringTokenizer.hasMoreTokens())) { stringTokenizer = new StringTokenizer(bufferedReader.readLine()); } return stringTokenizer.nextToken(); } public static String[] nextStrings(int n) throws IOException { String[] result = new String[n]; { for (int index = 0; index < n; index++) { result[index] = nextString(); } } return result; } public static <T> List<T> permutation(long p, List<T> x) { List<T> copy = new ArrayList<>(); for (int index = 0; index < x.size(); index++) { copy.add(x.get(index)); } List<T> result = new ArrayList<>(); for (int indexTo = 0; indexTo < x.size(); indexTo++) { int indexFrom = (int) p % copy.size(); p = p / copy.size(); result.add(copy.remove(indexFrom)); } return result; } public static <Type> List<List<Type>> permutations(List<Type> list) { List<List<Type>> result = new ArrayList<>(); result.add(new ArrayList<>()); for (Type element : list) { List<List<Type>> permutations = result; result = new ArrayList<>(); for (List<Type> permutation : permutations) { for (int index = 0; index <= permutation.size(); index++) { List<Type> permutationNew = new ArrayList<>(permutation); permutationNew.add(index, element); result.add(permutationNew); } } } return result; } public static Stream<BigInteger> streamFibonacci() { return Stream.generate(new Supplier<BigInteger>() { private BigInteger n0 = BigInteger.ZERO; private BigInteger n1 = BigInteger.ONE; @Override public BigInteger get() { BigInteger result = n0; n0 = n1; n1 = result.add(n0); return result; } }); } public static Stream<Long> streamPrime(int sieveSize) { return Stream.generate(new Supplier<Long>() { private boolean[] isPrime = new boolean[sieveSize]; private long sieveOffset = 2; private List<Long> primes = new ArrayList<>(); private int index = 0; public void filter(long prime, boolean[] result) { if (prime * prime < this.sieveOffset + sieveSize) { long remainingStart = this.sieveOffset % prime; long start = remainingStart == 0 ? 0 : prime - remainingStart; for (long index = start; index < sieveSize; index += prime) { result[(int) index] = false; } } } public void generatePrimes() { Arrays.fill(this.isPrime, true); this.primes.forEach(prime -> filter(prime, isPrime)); for (int index = 0; index < sieveSize; index++) { if (isPrime[index]) { this.primes.add(this.sieveOffset + index); filter(this.sieveOffset + index, isPrime); } } this.sieveOffset += sieveSize; } @Override public Long get() { while (this.primes.size() <= this.index) { generatePrimes(); } Long result = this.primes.get(this.index); this.index += 1; return result; } }); } public static <Type> String toString(Iterator<Type> iterator, String separator) { StringBuilder stringBuilder = new StringBuilder(); if (iterator.hasNext()) { stringBuilder.append(iterator.next()); } while (iterator.hasNext()) { stringBuilder.append(separator); stringBuilder.append(iterator.next()); } return stringBuilder.toString(); } public static <Type> String toString(Iterator<Type> iterator) { return toString(iterator, " "); } public static <Type> String toString(Iterable<Type> iterable, String separator) { return toString(iterable.iterator(), separator); } public static <Type> String toString(Iterable<Type> iterable) { return toString(iterable, " "); } public static long totient(long n) { Set<Long> factors = new SortedSetAVL<>(factors(n), Comparator.naturalOrder()); long result = n; for (long p : factors) { result -= result / p; } return result; } interface BiFunctionResult<Type0, Type1, TypeResult> { TypeResult apply(Type0 x0, Type1 x1, TypeResult x2); } public static List<Integer> solve(int[] ps) { int n = ps.length; List<Integer> result = new ArrayList<>(); result.add(1); boolean[] inCirculation = new boolean[n]; int firstX = n - 1; // int countO = 0; int lastO = n - 1; int countX = 0; for (int p : ps) { if (!inCirculation[p]) { inCirculation[p] = true; countX += 1; while (!inCirculation[firstX]) { firstX -= 1; // countO += 1; } while (0 <= lastO && inCirculation[lastO]) { lastO -= 1; countX -= 1; } } // result.add(Math.min(countO, countX) + 1); result.add(countX + 1); } return result; } public static void solve() throws IOException { int n = nextInt(); int[] ps = nextInts(n); add(-1, ps); out.println(toString(solve(ps))); } }
Java
["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"]
1 second
["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"]
NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Java 8
standard input
[ "two pointers", "dsu", "implementation", "sortings", "trees" ]
b97eeaa66e91bbcc3b5e616cb480c7af
The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
1,500
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
standard output
PASSED
fa25a3cc273951e0aaaccf9c3bde02ab
train_003.jsonl
1508151900
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
512 megabytes
import java.io.*; import java.util.*; public class Solution { public final static int MOD = 1000000007; public static int count = 0; public static int dx[] = {0,0,1,-1,1,1,-1,-1}; public static int dy[] = {1,-1,0,0,1,-1,1,-1}; public static int max = 0; public static boolean flag; public static LinkedList<Integer> adj[]; @SuppressWarnings({ "unchecked", "resource" }) public static void main(String[] args) throws IOException { InputReader scan = new InputReader(System.in); OutputStream outputStream = System.out; PrintWriter pw = new PrintWriter(outputStream); StringBuilder sb = new StringBuilder(); int n = scan.nextInt(); boolean arr[] = new boolean[n+1]; Arrays.fill(arr, false); int max = n; sb.append("1 "); for(int i=1;i<n;i++) { int temp = scan.nextInt(); //System.out.println(max); if(temp==max) { max--; while(arr[max]) max--; } int ans = (i-(n-max))+1; sb.append(ans+" "); arr[temp] = true; } sb.append("1\n"); pw.println(sb); pw.close(); } public static int[][] graph(int from[],int to[],int m,int n) { from = new int[m]; to = new int[n]; from[0] = 1; System.out.println(from[0]); int[][] g = new int[n+1][]; /*int count[] = new int[n+1]; Arrays.fill(count, 0); for(int i=0;i<m;i++) { count[from[i]]++; count[to[i]]++; } for(int i=0;i<n+1;i++) g[i] = new int[count[i]]; Arrays.fill(count, 0); for(int i=0;i<m;i++) { g[from[i]][count[from[i]]++] = to[i]; g[to[i]][count[to[i]]++] = from[i]; }*/ return g; } public static int binarySearch(ArrayList<Integer> arr,int key) { int l = 0, r = arr.size()-1; while(l<=r) { int mid = (l+r)/2; if(arr.get(mid)==key) { r = mid; break; } if(arr.get(mid)>key) r = mid-1; else l = mid+1; } return r; } public static void inOrder(int i,int arr[],int n,ArrayList<Integer> ans) { if(i<n) { inOrder(2*i+1,arr,n,ans); ans.add(arr[i]); inOrder(2*i+2,arr,n,ans); } } public static int find(int x,int parent[]) { if(parent[x]!=x) parent[x] = find(parent[x],parent); return parent[x]; } public static void union(int parent[],int x,int y) { int xParent = find(x,parent); int yParent = find(y,parent); parent[xParent] = yParent; } public static int dfs(int x,int parent,int[][] g) { int count = 1; for(int i=0;i<g[x].length;i++) { int temp = g[x][i]; if(temp!=parent){ int t = dfs(temp,x,g); count+=t; if(t%2==0) max++; } } return count; } public static void buildTree(int arr[],int tree[],int node,int start,int end) { if(start==end) { tree[node] = arr[start]; return; } int mid = (start+end)/2; buildTree(arr,tree,2*node,start,mid); buildTree(arr,tree,2*node+1,mid+1,end); tree[node] = tree[2*node]+tree[2*node+1]; } public static void update(int arr[],int tree[],int node,int inx,int val,int start,int end) { if(start==end) { tree[node] = val; arr[inx] = val; return; } int mid = (start+end)/2; if(inx<=mid) update(arr,tree,2*node,inx,val,start,mid); else update(arr,tree,2*node+1,inx,val,mid+1,end); tree[node] = tree[2*node]+tree[2*node+1]; } public static int query(int tree[],int node,int l,int r,int start,int end) { if(r<start || l>end) return 0; if(l<=start && end<=r) return tree[node]; int mid = (start+end)/2; int ans1 = query(tree,2*node,l,r,start,mid); int ans2 = query(tree,2*node+1,l,r,mid+1,end); return ans1+ans2; } public static void merge(int arr[],int start,int mid,int end) { int l = start, r = mid+1; int temp[] = new int[end-start+1]; int k = 0; for(int i=start;i<=end;i++) { if(l>mid) temp[k++] = arr[r++]; else if(r>end) temp[k++] = arr[l++]; else if(arr[l]<=arr[r]) temp[k++] = arr[l++]; else{ temp[k++] = arr[r++]; count+=(mid-l+1); } } for(int i=0;i<k;i++) arr[start++] = temp[i]; } public static void mergeSort(int arr[],int l,int r) { if(l<r){ int mid = (l+r)/2; mergeSort(arr,l,mid); mergeSort(arr,mid+1,r); merge(arr,l,mid,r); } } public static void sieve(int spf[],int n) { for(int i=1;i<=n;i++) spf[i] = i; for(int i=2;i*i<=n;i++) { if(spf[i]==i) { for(int j=i;j<=n;j+=i) if(spf[j]==j) spf[j] = i; } } } public static void factors(int n,int spf[],ArrayList<Integer> factors) { int pre = 0; while(n!=1) { int temp = spf[n]; if(temp!=pre) { factors.add(temp); pre = temp; } n/=temp; } } public static boolean isPrime(int n) { if(n==0 || n==1) return false; int limit = (int)Math.sqrt(n); for(int i=2;i<=limit;i++) { if(n%i==0) return false; } return true; } public static long pow(long a,long b,int m) { long result = 1; while(b>0) { if(b%2==1) result = ((result%m)*(a%m))%m; a = ((a%m)*(a%m))%m; b/=2; } return result; } public static long mulinv(long a,long m) { long arr[] = new long[2]; long gcd = gcdExtended(a,m,arr); if(gcd==1) return (arr[0]%m+m)%m; else return Integer.MAX_VALUE; } public static long gcdExtended(long a,long b,long arr[]) { if (a == 0) { arr[0] = 0; arr[1] = 1; return b; } long gcd = gcdExtended(b%a, a, arr); long temp = arr[0]; arr[0] = arr[1] - (b/a) * arr[0]; arr[1] = temp; return gcd; } public static long kadane(int items[]) { int n = items.length; long max = (long)items[0]; long curr_max = (long)items[0]; for(int i=1;i<n;i++) { curr_max = Math.max((long)curr_max+items[i], items[i]); max = Math.max(max, curr_max); } return max; } public static int gcd(int a,int b) { if(b==0) return a; return gcd(b,a%b); } public static int LCS(String s1,String s2) //Longest common subsequence { int n = s1.length(); int m = s2.length(); int lcs[][] = new int[n+1][m+1]; for(int i=0;i<=n;i++) { for(int j=0;j<=m;j++) { if(i==0 || j==0) lcs[i][j] = 0; else if(s1.charAt(i-1)==s2.charAt(j-1)) lcs[i][j] = lcs[i-1][j-1] + 1; else lcs[i][j] = Math.max(lcs[i][j-1], lcs[i-1][j]); } } return lcs[n][m]; } 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; } } } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream inputstream) { reader = new BufferedReader(new InputStreamReader(inputstream)); tokenizer = null; } public String nextLine(){ String fullLine=null; while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { fullLine=reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return fullLine; } return fullLine; } 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 long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"]
1 second
["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"]
NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Java 8
standard input
[ "two pointers", "dsu", "implementation", "sortings", "trees" ]
b97eeaa66e91bbcc3b5e616cb480c7af
The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
1,500
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
standard output
PASSED
85ce3029a0a3c7b1700ecd6e1591c152
train_003.jsonl
1508151900
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
512 megabytes
import java.util.Scanner; public class CodeForces_875B { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(), j=n-1; boolean[] vCoins = new boolean[n]; StringBuilder sCoins = new StringBuilder("1"); for (int i=0; i<n; i++) { vCoins[scan.nextInt()-1] = true; while ((j>=0) && (vCoins[j])) j--; sCoins.append(" " + (i-n+j+3)); } System.out.println(sCoins); scan.close(); } }
Java
["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"]
1 second
["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"]
NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Java 8
standard input
[ "two pointers", "dsu", "implementation", "sortings", "trees" ]
b97eeaa66e91bbcc3b5e616cb480c7af
The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
1,500
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
standard output