prob_desc_description
stringlengths
63
3.8k
prob_desc_output_spec
stringlengths
17
1.47k
lang_cluster
stringclasses
2 values
src_uid
stringlengths
32
32
code_uid
stringlengths
32
32
lang
stringclasses
7 values
prob_desc_output_to
stringclasses
3 values
prob_desc_memory_limit
stringclasses
19 values
file_name
stringclasses
111 values
tags
listlengths
0
11
prob_desc_created_at
stringlengths
10
10
prob_desc_sample_inputs
stringlengths
2
802
prob_desc_notes
stringlengths
4
3k
exec_outcome
stringclasses
1 value
difficulty
int64
-1
3.5k
prob_desc_input_from
stringclasses
3 values
prob_desc_time_limit
stringclasses
27 values
prob_desc_input_spec
stringlengths
28
2.42k
prob_desc_sample_outputs
stringlengths
2
796
source_code
stringlengths
42
65.5k
hidden_unit_tests
stringclasses
1 value
For an array $$$b$$$ of $$$n$$$ integers, the extreme value of this array is the minimum number of times (possibly, zero) the following operation has to be performed to make $$$b$$$ non-decreasing: Select an index $$$i$$$ such that $$$1 \le i \le |b|$$$, where $$$|b|$$$ is the current length of $$$b$$$. Replace $$$b_i$$$ with two elements $$$x$$$ and $$$y$$$ such that $$$x$$$ and $$$y$$$ both are positive integers and $$$x + y = b_i$$$. This way, the array $$$b$$$ changes and the next operation is performed on this modified array. For example, if $$$b = [2, 4, 3]$$$ and index $$$2$$$ gets selected, then the possible arrays after this operation are $$$[2, \underline{1}, \underline{3}, 3]$$$, $$$[2, \underline{2}, \underline{2}, 3]$$$, or $$$[2, \underline{3}, \underline{1}, 3]$$$. And consequently, for this array, this single operation is enough to make it non-decreasing: $$$[2, 4, 3] \rightarrow [2, \underline{2}, \underline{2}, 3]$$$.It's easy to see that every array of positive integers can be made non-decreasing this way.YouKn0wWho has an array $$$a$$$ of $$$n$$$ integers. Help him find the sum of extreme values of all nonempty subarrays of $$$a$$$ modulo $$$998\,244\,353$$$. If a subarray appears in $$$a$$$ multiple times, its extreme value should be counted the number of times it appears.An array $$$d$$$ is a subarray of an array $$$c$$$ if $$$d$$$ can be obtained from $$$c$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
For each test case, print a single integer  — the sum of extreme values of all subarrays of $$$a$$$ modulo $$$998\,244\,353$$$.
Java
f760f108c66f695e1e51dc6470d29ce7
fc8fd4e9a408022498efc7db7d6acfd4
Java 8
standard output
256 megabytes
train_110.jsonl
[ "dp", "greedy", "math", "number theory" ]
1635604500
["4\n3\n5 4 3\n4\n3 2 1 4\n1\n69\n8\n7264 40515 28226 92776 35285 21709 75124 48163"]
NoteLet $$$f(l, r)$$$ denote the extreme value of $$$[a_l, a_{l+1}, \ldots, a_r]$$$.In the first test case, $$$f(1, 3) = 3$$$, because YouKn0wWho can perform the following operations on the subarray $$$[5, 4, 3]$$$ (the newly inserted elements are underlined):$$$[5, 4, 3] \rightarrow [\underline{3}, \underline{2}, 4, 3] \rightarrow [3, 2, \underline{2}, \underline{2}, 3] \rightarrow [\underline{1}, \underline{2}, 2, 2, 2, 3]$$$; $$$f(1, 2) = 1$$$, because $$$[5, 4] \rightarrow [\underline{2}, \underline{3}, 4]$$$; $$$f(2, 3) = 1$$$, because $$$[4, 3] \rightarrow [\underline{1}, \underline{3}, 3]$$$; $$$f(1, 1) = f(2, 2) = f(3, 3) = 0$$$, because they are already non-decreasing. So the total sum of extreme values of all subarrays of $$$a = 3 + 1 + 1 + 0 + 0 + 0 = 5$$$.
PASSED
2,300
standard input
4 seconds
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10\,000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^5$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
["5\n9\n0\n117"]
/* I am dead inside Do you like NCT, sKz, BTS? 5 4 3 2 1 Moonwalk Imma knock it down like domino Is this what you want? Is this what you want? Let's ttalkbocky about that :() */ import static java.lang.Math.*; import java.util.*; import java.io.*; public class x1603C { static final long MOD = 998244353L; static final int MAX = 100000; public static void main(String omkar[]) throws Exception { FastScanner infile = new FastScanner(); int T = infile.nextInt(); StringBuilder sb = new StringBuilder(); long[] dp = new long[MAX+1]; long[] next = new long[MAX+1]; for(int q=1; q <= T; q++) { int N = infile.nextInt(); int[] arr = infile.nextInts(N); dp[arr[N-1]] = 1L; ArrayDeque<Integer> keys = new ArrayDeque<Integer>(); keys.add(arr[N-1]); long res = 0L; for(int t=N-2; t >= 0; t--) { ArrayDeque<Integer> nextKeys = new ArrayDeque<Integer>(); int curr = -1; for(int prev: keys) { int sections = (arr[t]+prev-1)/prev; int val = arr[t]/sections; if(curr != val) { nextKeys.add(val); next[val] = 0L; curr = val; } next[val] += dp[prev]; if(next[val] >= MOD) next[val] -= MOD; long temp = (dp[prev]*(sections-1))%MOD; temp = (temp*(t+1))%MOD; res += temp; if(res >= MOD) res -= MOD; } if(curr == arr[t]) { next[curr]++; if(next[curr] >= MOD) next[curr] -= MOD; } else { next[arr[t]] = 1L; nextKeys.add(arr[t]); } for(int x: nextKeys) dp[x] = next[x]; keys = nextKeys; } sb.append(res+"\n"); } System.out.print(sb); } } /* 23 8 -> 7 8 8 8 24 8 -> 8 8 8 8 25 8 -> 6 6 6 7 8 2 3 5 4 3 2 4 3 */ class FastScanner { //I don't understand how this works lmao private int BS = 1 << 16; private char NC = (char) 0; private byte[] buf = new byte[BS]; private int bId = 0, size = 0; private char c = NC; private double cnt = 1; private BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } private char getChar() { while (bId == size) { try { size = in.read(buf); } catch (Exception e) { return NC; } if (size == -1) return NC; bId = 0; } return (char) buf[bId++]; } public int nextInt() { return (int) nextLong(); } public int[] nextInts(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) nextLong(); } return res; } public long[] nextLongs(int N) { long[] res = new long[N]; for (int i = 0; i < N; i++) { res[i] = nextLong(); } return res; } public long nextLong() { cnt = 1; boolean neg = false; if (c == NC) c = getChar(); for (; (c < '0' || c > '9'); c = getChar()) { if (c == '-') neg = true; } long res = 0; for (; c >= '0' && c <= '9'; c = getChar()) { res = (res << 3) + (res << 1) + c - '0'; cnt *= 10; } return neg ? -res : res; } public double nextDouble() { double cur = nextLong(); return c != '.' ? cur : cur + nextLong() / cnt; } public double[] nextDoubles(int N) { double[] res = new double[N]; for (int i = 0; i < N; i++) { res[i] = nextDouble(); } return res; } public String next() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c > 32) { res.append(c); c = getChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c != '\n') { res.append(c); c = getChar(); } return res.toString(); } public boolean hasNext() { if (c > 32) return true; while (true) { c = getChar(); if (c == NC) return false; else if (c > 32) return true; } } }
For an array $$$b$$$ of $$$n$$$ integers, the extreme value of this array is the minimum number of times (possibly, zero) the following operation has to be performed to make $$$b$$$ non-decreasing: Select an index $$$i$$$ such that $$$1 \le i \le |b|$$$, where $$$|b|$$$ is the current length of $$$b$$$. Replace $$$b_i$$$ with two elements $$$x$$$ and $$$y$$$ such that $$$x$$$ and $$$y$$$ both are positive integers and $$$x + y = b_i$$$. This way, the array $$$b$$$ changes and the next operation is performed on this modified array. For example, if $$$b = [2, 4, 3]$$$ and index $$$2$$$ gets selected, then the possible arrays after this operation are $$$[2, \underline{1}, \underline{3}, 3]$$$, $$$[2, \underline{2}, \underline{2}, 3]$$$, or $$$[2, \underline{3}, \underline{1}, 3]$$$. And consequently, for this array, this single operation is enough to make it non-decreasing: $$$[2, 4, 3] \rightarrow [2, \underline{2}, \underline{2}, 3]$$$.It's easy to see that every array of positive integers can be made non-decreasing this way.YouKn0wWho has an array $$$a$$$ of $$$n$$$ integers. Help him find the sum of extreme values of all nonempty subarrays of $$$a$$$ modulo $$$998\,244\,353$$$. If a subarray appears in $$$a$$$ multiple times, its extreme value should be counted the number of times it appears.An array $$$d$$$ is a subarray of an array $$$c$$$ if $$$d$$$ can be obtained from $$$c$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
For each test case, print a single integer  — the sum of extreme values of all subarrays of $$$a$$$ modulo $$$998\,244\,353$$$.
Java
f760f108c66f695e1e51dc6470d29ce7
96997eebe21c0d81d9d7c8705f970334
Java 8
standard output
256 megabytes
train_110.jsonl
[ "dp", "greedy", "math", "number theory" ]
1635604500
["4\n3\n5 4 3\n4\n3 2 1 4\n1\n69\n8\n7264 40515 28226 92776 35285 21709 75124 48163"]
NoteLet $$$f(l, r)$$$ denote the extreme value of $$$[a_l, a_{l+1}, \ldots, a_r]$$$.In the first test case, $$$f(1, 3) = 3$$$, because YouKn0wWho can perform the following operations on the subarray $$$[5, 4, 3]$$$ (the newly inserted elements are underlined):$$$[5, 4, 3] \rightarrow [\underline{3}, \underline{2}, 4, 3] \rightarrow [3, 2, \underline{2}, \underline{2}, 3] \rightarrow [\underline{1}, \underline{2}, 2, 2, 2, 3]$$$; $$$f(1, 2) = 1$$$, because $$$[5, 4] \rightarrow [\underline{2}, \underline{3}, 4]$$$; $$$f(2, 3) = 1$$$, because $$$[4, 3] \rightarrow [\underline{1}, \underline{3}, 3]$$$; $$$f(1, 1) = f(2, 2) = f(3, 3) = 0$$$, because they are already non-decreasing. So the total sum of extreme values of all subarrays of $$$a = 3 + 1 + 1 + 0 + 0 + 0 = 5$$$.
PASSED
2,300
standard input
4 seconds
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10\,000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^5$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
["5\n9\n0\n117"]
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.Locale; import java.util.StringTokenizer; public class Solution2 implements Runnable { public static final long MOD = 998244353; private PrintStream out; private BufferedReader in; private StringTokenizer st; public void solve() throws IOException { long time0 = System.currentTimeMillis(); int t = nextInt(); for (int test = 1; test <= t; test++) { int n = nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } int answer = solve(n, a); out.println(answer); } System.err.println("time: " + (System.currentTimeMillis() - time0)); } private int solve(int n, int[] a) { int[] h0 = new int[n]; int[] h1 = new int[n]; int[] w = new int[n]; long sum = 0; long ans = 0; for (int i = 0; i < n; i++) { h0[i] = a[i]; h1[i] = a[i]; w[i] = 0; for (int j = i - 1; j >= 0; j--) { if (h1[j] <= h0[j + 1]) { break; } sum = (((sum - 1L * w[j] * (j + 1)) % MOD) + MOD) % MOD; int r = (a[j] + h0[j + 1] - 1) / h0[j + 1]; h0[j] = a[j] / r; h1[j] = (a[j] + r - 1) / r; w[j] = r - 1; sum = (sum + 1L * w[j] * (j + 1)) % MOD; } ans = (ans + sum) % MOD; } return (int) ans; } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public String next() throws IOException { while (!st.hasMoreTokens()) { String line = in.readLine(); if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } @Override public void run() { try { solve(); out.close(); } catch (Throwable e) { throw new RuntimeException(e); } } public Solution2(String name) throws IOException { Locale.setDefault(Locale.US); if (name == null) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintStream(new BufferedOutputStream(System.out)); } else { in = new BufferedReader(new InputStreamReader(new FileInputStream(name + ".in"))); out = new PrintStream(new BufferedOutputStream(new FileOutputStream(name + ".out"))); } st = new StringTokenizer(""); } public static void main(String[] args) throws IOException { new Thread(new Solution2(null)).start(); } }
For an array $$$b$$$ of $$$n$$$ integers, the extreme value of this array is the minimum number of times (possibly, zero) the following operation has to be performed to make $$$b$$$ non-decreasing: Select an index $$$i$$$ such that $$$1 \le i \le |b|$$$, where $$$|b|$$$ is the current length of $$$b$$$. Replace $$$b_i$$$ with two elements $$$x$$$ and $$$y$$$ such that $$$x$$$ and $$$y$$$ both are positive integers and $$$x + y = b_i$$$. This way, the array $$$b$$$ changes and the next operation is performed on this modified array. For example, if $$$b = [2, 4, 3]$$$ and index $$$2$$$ gets selected, then the possible arrays after this operation are $$$[2, \underline{1}, \underline{3}, 3]$$$, $$$[2, \underline{2}, \underline{2}, 3]$$$, or $$$[2, \underline{3}, \underline{1}, 3]$$$. And consequently, for this array, this single operation is enough to make it non-decreasing: $$$[2, 4, 3] \rightarrow [2, \underline{2}, \underline{2}, 3]$$$.It's easy to see that every array of positive integers can be made non-decreasing this way.YouKn0wWho has an array $$$a$$$ of $$$n$$$ integers. Help him find the sum of extreme values of all nonempty subarrays of $$$a$$$ modulo $$$998\,244\,353$$$. If a subarray appears in $$$a$$$ multiple times, its extreme value should be counted the number of times it appears.An array $$$d$$$ is a subarray of an array $$$c$$$ if $$$d$$$ can be obtained from $$$c$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
For each test case, print a single integer  — the sum of extreme values of all subarrays of $$$a$$$ modulo $$$998\,244\,353$$$.
Java
f760f108c66f695e1e51dc6470d29ce7
cc5868d32c3bff7889016d1636516bd6
Java 8
standard output
256 megabytes
train_110.jsonl
[ "dp", "greedy", "math", "number theory" ]
1635604500
["4\n3\n5 4 3\n4\n3 2 1 4\n1\n69\n8\n7264 40515 28226 92776 35285 21709 75124 48163"]
NoteLet $$$f(l, r)$$$ denote the extreme value of $$$[a_l, a_{l+1}, \ldots, a_r]$$$.In the first test case, $$$f(1, 3) = 3$$$, because YouKn0wWho can perform the following operations on the subarray $$$[5, 4, 3]$$$ (the newly inserted elements are underlined):$$$[5, 4, 3] \rightarrow [\underline{3}, \underline{2}, 4, 3] \rightarrow [3, 2, \underline{2}, \underline{2}, 3] \rightarrow [\underline{1}, \underline{2}, 2, 2, 2, 3]$$$; $$$f(1, 2) = 1$$$, because $$$[5, 4] \rightarrow [\underline{2}, \underline{3}, 4]$$$; $$$f(2, 3) = 1$$$, because $$$[4, 3] \rightarrow [\underline{1}, \underline{3}, 3]$$$; $$$f(1, 1) = f(2, 2) = f(3, 3) = 0$$$, because they are already non-decreasing. So the total sum of extreme values of all subarrays of $$$a = 3 + 1 + 1 + 0 + 0 + 0 = 5$$$.
PASSED
2,300
standard input
4 seconds
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10\,000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^5$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
["5\n9\n0\n117"]
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.Locale; import java.util.StringTokenizer; public class Solution implements Runnable { public static final long MOD = 998244353; private PrintStream out; private BufferedReader in; private StringTokenizer st; public void solve() throws IOException { long time0 = System.currentTimeMillis(); int t = nextInt(); for (int test = 1; test <= t; test++) { int n = nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } int answer = solve(n, a); out.println(answer); } System.err.println("time: " + (System.currentTimeMillis() - time0)); } private int solve(int n, int[] a) { int[] h0 = new int[n]; int[] h1 = new int[n]; int[] w = new int[n]; long sum = 0; long ans = 0; for (int i = 0; i < n; i++) { h0[i] = a[i]; h1[i] = a[i]; w[i] = 0; for (int j = i - 1; j >= 0; j--) { if (h1[j] <= h0[j + 1]) { break; } sum = (((sum - 1L * w[j] * (j + 1)) % MOD) + MOD) % MOD; int l = w[j] + 1; int r = (a[j] + h0[j + 1] - 1) / h0[j + 1]; while (l + 1 < r) { int m = (l + r) / 2; int hh1 = (a[j] + m - 1) / m; if (hh1 <= h0[j + 1]) { r = m; } else { l = m; } } h0[j] = a[j] / r; h1[j] = (a[j] + r - 1) / r; w[j] = r - 1; sum = (sum + 1L * w[j] * (j + 1)) % MOD; } ans = (ans + sum) % MOD; } return (int) ans; } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public String next() throws IOException { while (!st.hasMoreTokens()) { String line = in.readLine(); if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } @Override public void run() { try { solve(); out.close(); } catch (Throwable e) { throw new RuntimeException(e); } } public Solution(String name) throws IOException { Locale.setDefault(Locale.US); if (name == null) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintStream(new BufferedOutputStream(System.out)); } else { in = new BufferedReader(new InputStreamReader(new FileInputStream(name + ".in"))); out = new PrintStream(new BufferedOutputStream(new FileOutputStream(name + ".out"))); } st = new StringTokenizer(""); } public static void main(String[] args) throws IOException { new Thread(new Solution(null)).start(); } }
For an array $$$b$$$ of $$$n$$$ integers, the extreme value of this array is the minimum number of times (possibly, zero) the following operation has to be performed to make $$$b$$$ non-decreasing: Select an index $$$i$$$ such that $$$1 \le i \le |b|$$$, where $$$|b|$$$ is the current length of $$$b$$$. Replace $$$b_i$$$ with two elements $$$x$$$ and $$$y$$$ such that $$$x$$$ and $$$y$$$ both are positive integers and $$$x + y = b_i$$$. This way, the array $$$b$$$ changes and the next operation is performed on this modified array. For example, if $$$b = [2, 4, 3]$$$ and index $$$2$$$ gets selected, then the possible arrays after this operation are $$$[2, \underline{1}, \underline{3}, 3]$$$, $$$[2, \underline{2}, \underline{2}, 3]$$$, or $$$[2, \underline{3}, \underline{1}, 3]$$$. And consequently, for this array, this single operation is enough to make it non-decreasing: $$$[2, 4, 3] \rightarrow [2, \underline{2}, \underline{2}, 3]$$$.It's easy to see that every array of positive integers can be made non-decreasing this way.YouKn0wWho has an array $$$a$$$ of $$$n$$$ integers. Help him find the sum of extreme values of all nonempty subarrays of $$$a$$$ modulo $$$998\,244\,353$$$. If a subarray appears in $$$a$$$ multiple times, its extreme value should be counted the number of times it appears.An array $$$d$$$ is a subarray of an array $$$c$$$ if $$$d$$$ can be obtained from $$$c$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
For each test case, print a single integer  — the sum of extreme values of all subarrays of $$$a$$$ modulo $$$998\,244\,353$$$.
Java
f760f108c66f695e1e51dc6470d29ce7
bb8ea2dad5c6df70f083973ed8074bc2
Java 8
standard output
256 megabytes
train_110.jsonl
[ "dp", "greedy", "math", "number theory" ]
1635604500
["4\n3\n5 4 3\n4\n3 2 1 4\n1\n69\n8\n7264 40515 28226 92776 35285 21709 75124 48163"]
NoteLet $$$f(l, r)$$$ denote the extreme value of $$$[a_l, a_{l+1}, \ldots, a_r]$$$.In the first test case, $$$f(1, 3) = 3$$$, because YouKn0wWho can perform the following operations on the subarray $$$[5, 4, 3]$$$ (the newly inserted elements are underlined):$$$[5, 4, 3] \rightarrow [\underline{3}, \underline{2}, 4, 3] \rightarrow [3, 2, \underline{2}, \underline{2}, 3] \rightarrow [\underline{1}, \underline{2}, 2, 2, 2, 3]$$$; $$$f(1, 2) = 1$$$, because $$$[5, 4] \rightarrow [\underline{2}, \underline{3}, 4]$$$; $$$f(2, 3) = 1$$$, because $$$[4, 3] \rightarrow [\underline{1}, \underline{3}, 3]$$$; $$$f(1, 1) = f(2, 2) = f(3, 3) = 0$$$, because they are already non-decreasing. So the total sum of extreme values of all subarrays of $$$a = 3 + 1 + 1 + 0 + 0 + 0 = 5$$$.
PASSED
2,300
standard input
4 seconds
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10\,000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^5$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
["5\n9\n0\n117"]
import java.util.*; import java.lang.*; // StringBuilder uses java.lang public class mC { public static void main(String[] args) { Scanner sc = new Scanner(System.in); StringBuilder st = new StringBuilder(); int t = sc.nextInt(); long MOD = 998244353; for (int test = 0; test < t; test++) { int n = sc.nextInt(); long[] inputList = new long[n]; long[] numDiv = new long[n]; // number of divisions to make, not num of resulting numbers long indexProdSum = 0; long ans = 0; for (int i = 0; i < n; i++) { inputList[i] = sc.nextInt(); boolean cont = true; for (int j = i-1; (j>=0 && cont); j--) { long maxAt = inputList[j+1] / (numDiv[j+1]+1); long minForcedDivs = (inputList[j]-1) / maxAt; // ceiling minus one if (minForcedDivs > numDiv[j]) { indexProdSum += (minForcedDivs - numDiv[j]) * (j+1); indexProdSum %= MOD; numDiv[j] = minForcedDivs; } else { cont = false; } } ans += indexProdSum; ans %= MOD; } st.append(ans+"\n"); } System.out.print(st.toString()); } public static int firstLargerAb(int val,ArrayList<Integer> ok,int left,int right) { if (Math.abs(ok.get(right))<=val) { return -1; } if (left==right) { return left; } else if (left+1==right) { if (val<Math.abs(ok.get(left))) { return left; } else { return right; } } else { int mid = (left+right)/2; if (Math.abs(ok.get(mid))>val) { return firstLargerAb(val,ok,left,mid); } else { return firstLargerAb(val,ok,mid+1,right); } } } public static int findNthInArray(int[] arr,int val,int start,int o) { if (o==0) { return start-1; } else if (arr[start] == val) { return findNthInArray(arr,val,start+1,o-1); } else { return findNthInArray(arr,val,start+1,o); } } public static ArrayList<Integer> dfs(int at,ArrayList<Integer> went,ArrayList<ArrayList<Integer>> connect) { for (int i=0;i<connect.get(at).size();i++) { if (!(went.contains(connect.get(at).get(i)))) { went.add(connect.get(at).get(i)); went=dfs(connect.get(at).get(i),went,connect); } } return went; } public static int[] bfs (int at, int[] went, ArrayList<ArrayList<Integer>> queue, int numNodes, ArrayList<ArrayList<Integer>> connect) { if (went[at]==0) { went[at]=queue.get(numNodes).get(1); for (int i=0;i<connect.get(at).size();i++) { if (went[connect.get(at).get(i)]==0) { ArrayList<Integer> temp = new ArrayList<>(); temp.add(connect.get(at).get(i)); temp.add(queue.get(numNodes).get(1)+1); queue.add(temp); } } } if (queue.size()==numNodes+1) { return went; } else { return bfs(queue.get(numNodes+1).get(0),went, queue, numNodes+1, connect); } } public static long fastPow(long base,long exp,long mod) { if (exp==0) { return 1; } else { if (exp % 2 == 1) { long z = fastPow(base,(exp-1)/2,mod); return ((((z*base) % mod) * z) % mod); } else { long z = fastPow(base,exp/2,mod); return ((z*z) % mod); } } } public static int fastPow(int base,long exp) { if (exp==0) { return 1; } else { if (exp % 2 == 1) { int z = fastPow(base,(exp-1)/2); return ((((z*base)) * z)); } else { int z = fastPow(base,exp/2); return ((z*z)); } } } public static int firstLarger(int val,ArrayList<Integer> ok,int left,int right) { if (ok.get(right)<=val) { return -1; } if (left==right) { return left; } else if (left+1==right) { if (val<ok.get(left)) { return left; } else { return right; } } else { int mid = (left+right)/2; if (ok.get(mid)>val) { return firstLarger(val,ok,left,mid); } else { return firstLarger(val,ok,mid+1,right); } } } public static int binSearchArr(long val,ArrayList<Integer> ok,long[] arr,int left,int right) { if (arr[ok.get(right)]<=val) { return -1; } if (left==right) { return left; } else if (left+1==right) { if (val<arr[ok.get(left)]) { return left; } else { return right; } } else { int mid = (left+right)/2; if (arr[ok.get(mid)]>val) { return binSearchArr(val,ok,arr,left,mid); } else { return binSearchArr(val,ok,arr,mid+1,right); } } } public static long gcd(long a, long b) { if (b>a) { return gcd(b,a); } if (b==0) { return a; } if (a%b==0) { return b; } else { return gcd(b,a%b); } } }
For an array $$$b$$$ of $$$n$$$ integers, the extreme value of this array is the minimum number of times (possibly, zero) the following operation has to be performed to make $$$b$$$ non-decreasing: Select an index $$$i$$$ such that $$$1 \le i \le |b|$$$, where $$$|b|$$$ is the current length of $$$b$$$. Replace $$$b_i$$$ with two elements $$$x$$$ and $$$y$$$ such that $$$x$$$ and $$$y$$$ both are positive integers and $$$x + y = b_i$$$. This way, the array $$$b$$$ changes and the next operation is performed on this modified array. For example, if $$$b = [2, 4, 3]$$$ and index $$$2$$$ gets selected, then the possible arrays after this operation are $$$[2, \underline{1}, \underline{3}, 3]$$$, $$$[2, \underline{2}, \underline{2}, 3]$$$, or $$$[2, \underline{3}, \underline{1}, 3]$$$. And consequently, for this array, this single operation is enough to make it non-decreasing: $$$[2, 4, 3] \rightarrow [2, \underline{2}, \underline{2}, 3]$$$.It's easy to see that every array of positive integers can be made non-decreasing this way.YouKn0wWho has an array $$$a$$$ of $$$n$$$ integers. Help him find the sum of extreme values of all nonempty subarrays of $$$a$$$ modulo $$$998\,244\,353$$$. If a subarray appears in $$$a$$$ multiple times, its extreme value should be counted the number of times it appears.An array $$$d$$$ is a subarray of an array $$$c$$$ if $$$d$$$ can be obtained from $$$c$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
For each test case, print a single integer  — the sum of extreme values of all subarrays of $$$a$$$ modulo $$$998\,244\,353$$$.
Java
f760f108c66f695e1e51dc6470d29ce7
b551f4d142944d349118fe09171cabce
Java 11
standard output
256 megabytes
train_110.jsonl
[ "dp", "greedy", "math", "number theory" ]
1635604500
["4\n3\n5 4 3\n4\n3 2 1 4\n1\n69\n8\n7264 40515 28226 92776 35285 21709 75124 48163"]
NoteLet $$$f(l, r)$$$ denote the extreme value of $$$[a_l, a_{l+1}, \ldots, a_r]$$$.In the first test case, $$$f(1, 3) = 3$$$, because YouKn0wWho can perform the following operations on the subarray $$$[5, 4, 3]$$$ (the newly inserted elements are underlined):$$$[5, 4, 3] \rightarrow [\underline{3}, \underline{2}, 4, 3] \rightarrow [3, 2, \underline{2}, \underline{2}, 3] \rightarrow [\underline{1}, \underline{2}, 2, 2, 2, 3]$$$; $$$f(1, 2) = 1$$$, because $$$[5, 4] \rightarrow [\underline{2}, \underline{3}, 4]$$$; $$$f(2, 3) = 1$$$, because $$$[4, 3] \rightarrow [\underline{1}, \underline{3}, 3]$$$; $$$f(1, 1) = f(2, 2) = f(3, 3) = 0$$$, because they are already non-decreasing. So the total sum of extreme values of all subarrays of $$$a = 3 + 1 + 1 + 0 + 0 + 0 = 5$$$.
PASSED
2,300
standard input
4 seconds
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10\,000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^5$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
["5\n9\n0\n117"]
import java.util.*; import java.io.*; public class _1604_E { static final long MOD = 998244353; public static void main(String[] args) throws IOException { Reader in = new Reader(); PrintWriter out = new PrintWriter(System.out); int t = in.nextInt(); while(t-- > 0) { int n = in.nextInt(); int[] a = new int[n]; for(int i = 0; i < n; i++) { a[i] = in.nextInt(); } int[][] dp = new int[2][100005]; ArrayList<Integer>[] keys = new ArrayList[2]; keys[0] = new ArrayList<Integer>(); keys[1] = new ArrayList<Integer>(); dp[0][a[n - 1]] = 1; keys[0].add(a[n - 1]); long res = 0; int cur = 0; for(int i = n - 1; i > 0; i--) { dp[1 - cur][a[i - 1]] += 1; keys[1 - cur].add(a[i - 1]); int prev = a[i - 1]; for(int key : keys[cur]) { int ceil = a[i - 1] / key; if(a[i - 1] % key != 0) ceil++; int min = a[i - 1] / ceil; dp[1 - cur][min] += dp[cur][key]; res = modadd(res, modmult(modmult(dp[cur][key], ceil - 1), i)); if(min != prev) { keys[1 - cur].add(min); prev = min; } dp[cur][key] = 0; } keys[cur].clear(); cur = 1 - cur; } out.println(res); } in.close(); out.close(); } static long modadd(long a, long b) { return (a + b + MOD) % MOD; } static long modmult(long a, long b) { return a * b % MOD; } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') { if (cnt != 0) { break; } else { continue; } } 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(); } } }
For an array $$$b$$$ of $$$n$$$ integers, the extreme value of this array is the minimum number of times (possibly, zero) the following operation has to be performed to make $$$b$$$ non-decreasing: Select an index $$$i$$$ such that $$$1 \le i \le |b|$$$, where $$$|b|$$$ is the current length of $$$b$$$. Replace $$$b_i$$$ with two elements $$$x$$$ and $$$y$$$ such that $$$x$$$ and $$$y$$$ both are positive integers and $$$x + y = b_i$$$. This way, the array $$$b$$$ changes and the next operation is performed on this modified array. For example, if $$$b = [2, 4, 3]$$$ and index $$$2$$$ gets selected, then the possible arrays after this operation are $$$[2, \underline{1}, \underline{3}, 3]$$$, $$$[2, \underline{2}, \underline{2}, 3]$$$, or $$$[2, \underline{3}, \underline{1}, 3]$$$. And consequently, for this array, this single operation is enough to make it non-decreasing: $$$[2, 4, 3] \rightarrow [2, \underline{2}, \underline{2}, 3]$$$.It's easy to see that every array of positive integers can be made non-decreasing this way.YouKn0wWho has an array $$$a$$$ of $$$n$$$ integers. Help him find the sum of extreme values of all nonempty subarrays of $$$a$$$ modulo $$$998\,244\,353$$$. If a subarray appears in $$$a$$$ multiple times, its extreme value should be counted the number of times it appears.An array $$$d$$$ is a subarray of an array $$$c$$$ if $$$d$$$ can be obtained from $$$c$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
For each test case, print a single integer  — the sum of extreme values of all subarrays of $$$a$$$ modulo $$$998\,244\,353$$$.
Java
f760f108c66f695e1e51dc6470d29ce7
6c49059084d6c1d4b898f727b94acadd
Java 11
standard output
256 megabytes
train_110.jsonl
[ "dp", "greedy", "math", "number theory" ]
1635604500
["4\n3\n5 4 3\n4\n3 2 1 4\n1\n69\n8\n7264 40515 28226 92776 35285 21709 75124 48163"]
NoteLet $$$f(l, r)$$$ denote the extreme value of $$$[a_l, a_{l+1}, \ldots, a_r]$$$.In the first test case, $$$f(1, 3) = 3$$$, because YouKn0wWho can perform the following operations on the subarray $$$[5, 4, 3]$$$ (the newly inserted elements are underlined):$$$[5, 4, 3] \rightarrow [\underline{3}, \underline{2}, 4, 3] \rightarrow [3, 2, \underline{2}, \underline{2}, 3] \rightarrow [\underline{1}, \underline{2}, 2, 2, 2, 3]$$$; $$$f(1, 2) = 1$$$, because $$$[5, 4] \rightarrow [\underline{2}, \underline{3}, 4]$$$; $$$f(2, 3) = 1$$$, because $$$[4, 3] \rightarrow [\underline{1}, \underline{3}, 3]$$$; $$$f(1, 1) = f(2, 2) = f(3, 3) = 0$$$, because they are already non-decreasing. So the total sum of extreme values of all subarrays of $$$a = 3 + 1 + 1 + 0 + 0 + 0 = 5$$$.
PASSED
2,300
standard input
4 seconds
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10\,000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^5$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
["5\n9\n0\n117"]
import java.util.*; import java.io.*; public class _1604_E { static final long MOD = 998244353; public static void main(String[] args) throws IOException { Reader in = new Reader(); PrintWriter out = new PrintWriter(System.out); int t = in.nextInt(); while(t-- > 0) { int n = in.nextInt(); int[] a = new int[n]; for(int i = 0; i < n; i++) { a[i] = in.nextInt(); } int[][] dp = new int[2][100005]; ArrayList<Integer>[] keys = new ArrayList[2]; keys[0] = new ArrayList<Integer>(); keys[1] = new ArrayList<Integer>(); dp[0][a[n - 1]] = 1; keys[0].add(a[n - 1]); long res = 0; int cur = 0; for(int i = n - 1; i > 0; i--) { int prev = -1; for(int key : keys[cur]) { int ceil = a[i - 1] / key; if(a[i - 1] % key != 0) ceil++; int min = a[i - 1] / ceil; dp[1 - cur][min] += dp[cur][key]; res = modadd(res, modmult(modmult(dp[cur][key], ceil - 1), i)); if(min != prev) { keys[1 - cur].add(min); prev = min; } dp[cur][key] = 0; } dp[1 - cur][a[i - 1]] += 1; keys[1 - cur].add(a[i - 1]); keys[cur].clear(); cur = 1 - cur; } out.println(res); } in.close(); out.close(); } static long modadd(long a, long b) { return (a + b + MOD) % MOD; } static long modmult(long a, long b) { return a * b % MOD; } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') { if (cnt != 0) { break; } else { continue; } } 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(); } } }
For an array $$$b$$$ of $$$n$$$ integers, the extreme value of this array is the minimum number of times (possibly, zero) the following operation has to be performed to make $$$b$$$ non-decreasing: Select an index $$$i$$$ such that $$$1 \le i \le |b|$$$, where $$$|b|$$$ is the current length of $$$b$$$. Replace $$$b_i$$$ with two elements $$$x$$$ and $$$y$$$ such that $$$x$$$ and $$$y$$$ both are positive integers and $$$x + y = b_i$$$. This way, the array $$$b$$$ changes and the next operation is performed on this modified array. For example, if $$$b = [2, 4, 3]$$$ and index $$$2$$$ gets selected, then the possible arrays after this operation are $$$[2, \underline{1}, \underline{3}, 3]$$$, $$$[2, \underline{2}, \underline{2}, 3]$$$, or $$$[2, \underline{3}, \underline{1}, 3]$$$. And consequently, for this array, this single operation is enough to make it non-decreasing: $$$[2, 4, 3] \rightarrow [2, \underline{2}, \underline{2}, 3]$$$.It's easy to see that every array of positive integers can be made non-decreasing this way.YouKn0wWho has an array $$$a$$$ of $$$n$$$ integers. Help him find the sum of extreme values of all nonempty subarrays of $$$a$$$ modulo $$$998\,244\,353$$$. If a subarray appears in $$$a$$$ multiple times, its extreme value should be counted the number of times it appears.An array $$$d$$$ is a subarray of an array $$$c$$$ if $$$d$$$ can be obtained from $$$c$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
For each test case, print a single integer  — the sum of extreme values of all subarrays of $$$a$$$ modulo $$$998\,244\,353$$$.
Java
f760f108c66f695e1e51dc6470d29ce7
3cf08b4eb1ae0e355dcf885437d5a9d3
Java 11
standard output
256 megabytes
train_110.jsonl
[ "dp", "greedy", "math", "number theory" ]
1635604500
["4\n3\n5 4 3\n4\n3 2 1 4\n1\n69\n8\n7264 40515 28226 92776 35285 21709 75124 48163"]
NoteLet $$$f(l, r)$$$ denote the extreme value of $$$[a_l, a_{l+1}, \ldots, a_r]$$$.In the first test case, $$$f(1, 3) = 3$$$, because YouKn0wWho can perform the following operations on the subarray $$$[5, 4, 3]$$$ (the newly inserted elements are underlined):$$$[5, 4, 3] \rightarrow [\underline{3}, \underline{2}, 4, 3] \rightarrow [3, 2, \underline{2}, \underline{2}, 3] \rightarrow [\underline{1}, \underline{2}, 2, 2, 2, 3]$$$; $$$f(1, 2) = 1$$$, because $$$[5, 4] \rightarrow [\underline{2}, \underline{3}, 4]$$$; $$$f(2, 3) = 1$$$, because $$$[4, 3] \rightarrow [\underline{1}, \underline{3}, 3]$$$; $$$f(1, 1) = f(2, 2) = f(3, 3) = 0$$$, because they are already non-decreasing. So the total sum of extreme values of all subarrays of $$$a = 3 + 1 + 1 + 0 + 0 + 0 = 5$$$.
PASSED
2,300
standard input
4 seconds
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10\,000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^5$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
["5\n9\n0\n117"]
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { static int MOD = 998244353; // After writing solution, quick scan for: // array out of bounds // special cases e.g. n=1? // npe, particularly in maps // // Big numbers arithmetic bugs: // int overflow // sorting, or taking max, after MOD void solve() throws IOException { int T = ri(); // We need to initialize these only once... int AMAX = 100000; long[] rightCounts = new long[AMAX+1]; long[] currCounts = new long[AMAX+1]; for (int Ti = 0; Ti < T; Ti++) { int n = ri(); int[] a = ril(n); // dp[i][x] is the number of subarrays starting at i, where after the procedure, the // first element becomes x. // // Let split := number of splits needed to turn a[i] into x. // Then the answer is the sum of contributions over all (i, x) pairs of dp[i][x] * split. // How to compute dp[i][x]? // It's pretty difficult to compute dp[i][x] using dp[i][x+e] for e in [0..?] since // it's hard to tell what that ? should be. // It's easier to "compute the other way". That is, let's loop over dp[i+1][x]. Now, // with fixed x as the value to the right, we can add that contribution to // dp[i][y] where y = floor(a[i] / ceil(a[i] / x)). (see below). Set<Integer> rightNonzero = new HashSet<>(); Set<Integer> currNonzero = new HashSet<>(); rightCounts[a[n-1]]++; rightNonzero.add(a[n-1]); long ans = 0; for (int i = n-2; i >= 0; i--) { // Add all the contributions of i+1 to i. for (int x : rightNonzero) { // x is the value to the right long count = rightCounts[x]; // number of subarrays [i+1..] with the value x. int y = a[i] / ((a[i] + x - 1) / x); // y is the value i become int splits = (a[i] + x - 1) / x; // splits is the new number of elems when i become x. currCounts[y] += count; currNonzero.add(y); ans += (i+1) * count * (splits - 1); // Clear in preparation for swap rightCounts[x] = 0; } currCounts[a[i]]++; currNonzero.add(a[i]); // Swap around the memory we're re-using. long[] temp = rightCounts; // This is empty rightCounts = currCounts; currCounts = temp; Set<Integer> temp2 = rightNonzero; rightNonzero = currNonzero; currNonzero = temp2; currNonzero.clear(); ans %= MOD; } // Clear out rightCounts in preparation for next test case for (int x : rightNonzero) rightCounts[x] = 0; pw.println(ans); } } // IMPORTANT // DID YOU CHECK THE COMMON MISTAKES ABOVE? // Finds the extreme value for subarray a[i..j]. int solve(int[] a, int l, int r) { if (l >= r) return 0; int ans = 0; int upper = a[r]; for (int i = r-1; i >= l; i--) { if (a[i] <= upper) { upper = a[i]; continue; } // Want a[i] / k <= upper (k sections) // So we want k >= a[i] / upper int k = (a[i] + upper - 1) / upper; ans += k-1; upper = a[i] / k; } return ans; } // Template code below BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); public static void main(String[] args) throws IOException { Main m = new Main(); m.solve(); m.close(); } void close() throws IOException { pw.flush(); pw.close(); br.close(); } int ri() throws IOException { return Integer.parseInt(br.readLine().trim()); } long rl() throws IOException { return Long.parseLong(br.readLine().trim()); } int[] ril(int n) throws IOException { int[] nums = new int[n]; int c = 0; for (int i = 0; i < n; i++) { int sign = 1; c = br.read(); int x = 0; if (c == '-') { sign = -1; c = br.read(); } while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = br.read(); } nums[i] = x * sign; } while (c != '\n' && c != -1) c = br.read(); return nums; } long[] rll(int n) throws IOException { long[] nums = new long[n]; int c = 0; for (int i = 0; i < n; i++) { int sign = 1; c = br.read(); long x = 0; if (c == '-') { sign = -1; c = br.read(); } while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = br.read(); } nums[i] = x * sign; } while (c != '\n' && c != -1) c = br.read(); return nums; } int[] rkil() throws IOException { int sign = 1; int c = br.read(); int x = 0; if (c == '-') { sign = -1; c = br.read(); } while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = br.read(); } return ril(x); } long[] rkll() throws IOException { int sign = 1; int c = br.read(); int x = 0; if (c == '-') { sign = -1; c = br.read(); } while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = br.read(); } return rll(x); } char[] rs() throws IOException { return br.readLine().toCharArray(); } void sort(int[] A) { Random r = new Random(); for (int i = A.length-1; i > 0; i--) { int j = r.nextInt(i+1); int temp = A[i]; A[i] = A[j]; A[j] = temp; } Arrays.sort(A); } void printDouble(double d) { pw.printf("%.16f", d); } }
For an array $$$b$$$ of $$$n$$$ integers, the extreme value of this array is the minimum number of times (possibly, zero) the following operation has to be performed to make $$$b$$$ non-decreasing: Select an index $$$i$$$ such that $$$1 \le i \le |b|$$$, where $$$|b|$$$ is the current length of $$$b$$$. Replace $$$b_i$$$ with two elements $$$x$$$ and $$$y$$$ such that $$$x$$$ and $$$y$$$ both are positive integers and $$$x + y = b_i$$$. This way, the array $$$b$$$ changes and the next operation is performed on this modified array. For example, if $$$b = [2, 4, 3]$$$ and index $$$2$$$ gets selected, then the possible arrays after this operation are $$$[2, \underline{1}, \underline{3}, 3]$$$, $$$[2, \underline{2}, \underline{2}, 3]$$$, or $$$[2, \underline{3}, \underline{1}, 3]$$$. And consequently, for this array, this single operation is enough to make it non-decreasing: $$$[2, 4, 3] \rightarrow [2, \underline{2}, \underline{2}, 3]$$$.It's easy to see that every array of positive integers can be made non-decreasing this way.YouKn0wWho has an array $$$a$$$ of $$$n$$$ integers. Help him find the sum of extreme values of all nonempty subarrays of $$$a$$$ modulo $$$998\,244\,353$$$. If a subarray appears in $$$a$$$ multiple times, its extreme value should be counted the number of times it appears.An array $$$d$$$ is a subarray of an array $$$c$$$ if $$$d$$$ can be obtained from $$$c$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
For each test case, print a single integer  — the sum of extreme values of all subarrays of $$$a$$$ modulo $$$998\,244\,353$$$.
Java
f760f108c66f695e1e51dc6470d29ce7
aaafa80b40639f180ce3323d3b24df0d
Java 11
standard output
256 megabytes
train_110.jsonl
[ "dp", "greedy", "math", "number theory" ]
1635604500
["4\n3\n5 4 3\n4\n3 2 1 4\n1\n69\n8\n7264 40515 28226 92776 35285 21709 75124 48163"]
NoteLet $$$f(l, r)$$$ denote the extreme value of $$$[a_l, a_{l+1}, \ldots, a_r]$$$.In the first test case, $$$f(1, 3) = 3$$$, because YouKn0wWho can perform the following operations on the subarray $$$[5, 4, 3]$$$ (the newly inserted elements are underlined):$$$[5, 4, 3] \rightarrow [\underline{3}, \underline{2}, 4, 3] \rightarrow [3, 2, \underline{2}, \underline{2}, 3] \rightarrow [\underline{1}, \underline{2}, 2, 2, 2, 3]$$$; $$$f(1, 2) = 1$$$, because $$$[5, 4] \rightarrow [\underline{2}, \underline{3}, 4]$$$; $$$f(2, 3) = 1$$$, because $$$[4, 3] \rightarrow [\underline{1}, \underline{3}, 3]$$$; $$$f(1, 1) = f(2, 2) = f(3, 3) = 0$$$, because they are already non-decreasing. So the total sum of extreme values of all subarrays of $$$a = 3 + 1 + 1 + 0 + 0 + 0 = 5$$$.
PASSED
2,300
standard input
4 seconds
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10\,000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^5$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
["5\n9\n0\n117"]
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashMap; import java.util.StringTokenizer; public class A1603 { private static final int P = 998244353; private static final int M = 100000; private static final int SQ = 800; private static final int SQ2 = 400; private static int[][] g = new int[2][SQ + 1]; private static int getB1(int a, int b) { return a / ceil(a, b); } private static int getMoves(int a, int b) { return ceil(a, b) - 1; } private static int ceil(int a, int b) { return (a + b - 1) / b; } private static int getIndex(int num, int last) { if (last * 1l * last >= num) { return num / last; } return SQ2 + last; } private static int count(int[] a, int n) { Arrays.fill(g[0], 0); Arrays.fill(g[1], 0); int ans = 0; int active = 0; for (int i = 1; i < n; i++) { // compute g[] Arrays.fill(g[active], 0); for (int j = 1; j <= SQ2; j++) { int last = a[i] / j; if (last == 0) { g[active][j] = 0; continue; } long res = (getMoves(a[i - 1], last) * 1l * i) % P; res = (res + g[active ^ 1][getIndex(a[i - 1], getB1(a[i - 1], last))]) % P; g[active][j] = (int) res; } for (int j = SQ2 + 1; j <= SQ; j++) { // last = (j - sq2), if [a[i] / [a[i] / (j - sq2)]] == j - sq2. int div = a[i] / (j - SQ2); if (div <= 0 || a[i] / div != j - SQ2) { g[active][j] = 0; continue; } int last = j - SQ2; long res = (getMoves(a[i - 1], last) * 1l * i) % P; res = (res + g[active ^ 1][getIndex(a[i - 1], getB1(a[i - 1], last))]) % P; g[active][j] = (int) res; } ans = (ans + g[active][1]) % P; active ^= 1; } return ans; } public static void main(String[] args) throws IOException { BufferedReader rd = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); int numTests = Integer.parseInt(rd.readLine()); for (int t = 0; t < numTests; t++) { int n = Integer.parseInt(rd.readLine()); StringTokenizer st = new StringTokenizer(rd.readLine()); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = Integer.parseInt(st.nextToken()); } pw.println(count(a, n)); } pw.flush(); pw.close(); rd.close(); } }
For an array $$$b$$$ of $$$n$$$ integers, the extreme value of this array is the minimum number of times (possibly, zero) the following operation has to be performed to make $$$b$$$ non-decreasing: Select an index $$$i$$$ such that $$$1 \le i \le |b|$$$, where $$$|b|$$$ is the current length of $$$b$$$. Replace $$$b_i$$$ with two elements $$$x$$$ and $$$y$$$ such that $$$x$$$ and $$$y$$$ both are positive integers and $$$x + y = b_i$$$. This way, the array $$$b$$$ changes and the next operation is performed on this modified array. For example, if $$$b = [2, 4, 3]$$$ and index $$$2$$$ gets selected, then the possible arrays after this operation are $$$[2, \underline{1}, \underline{3}, 3]$$$, $$$[2, \underline{2}, \underline{2}, 3]$$$, or $$$[2, \underline{3}, \underline{1}, 3]$$$. And consequently, for this array, this single operation is enough to make it non-decreasing: $$$[2, 4, 3] \rightarrow [2, \underline{2}, \underline{2}, 3]$$$.It's easy to see that every array of positive integers can be made non-decreasing this way.YouKn0wWho has an array $$$a$$$ of $$$n$$$ integers. Help him find the sum of extreme values of all nonempty subarrays of $$$a$$$ modulo $$$998\,244\,353$$$. If a subarray appears in $$$a$$$ multiple times, its extreme value should be counted the number of times it appears.An array $$$d$$$ is a subarray of an array $$$c$$$ if $$$d$$$ can be obtained from $$$c$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
For each test case, print a single integer  — the sum of extreme values of all subarrays of $$$a$$$ modulo $$$998\,244\,353$$$.
Java
f760f108c66f695e1e51dc6470d29ce7
129d326248a90064d051a0a1e90ec874
Java 11
standard output
256 megabytes
train_110.jsonl
[ "dp", "greedy", "math", "number theory" ]
1635604500
["4\n3\n5 4 3\n4\n3 2 1 4\n1\n69\n8\n7264 40515 28226 92776 35285 21709 75124 48163"]
NoteLet $$$f(l, r)$$$ denote the extreme value of $$$[a_l, a_{l+1}, \ldots, a_r]$$$.In the first test case, $$$f(1, 3) = 3$$$, because YouKn0wWho can perform the following operations on the subarray $$$[5, 4, 3]$$$ (the newly inserted elements are underlined):$$$[5, 4, 3] \rightarrow [\underline{3}, \underline{2}, 4, 3] \rightarrow [3, 2, \underline{2}, \underline{2}, 3] \rightarrow [\underline{1}, \underline{2}, 2, 2, 2, 3]$$$; $$$f(1, 2) = 1$$$, because $$$[5, 4] \rightarrow [\underline{2}, \underline{3}, 4]$$$; $$$f(2, 3) = 1$$$, because $$$[4, 3] \rightarrow [\underline{1}, \underline{3}, 3]$$$; $$$f(1, 1) = f(2, 2) = f(3, 3) = 0$$$, because they are already non-decreasing. So the total sum of extreme values of all subarrays of $$$a = 3 + 1 + 1 + 0 + 0 + 0 = 5$$$.
PASSED
2,300
standard input
4 seconds
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10\,000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^5$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
["5\n9\n0\n117"]
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.StringTokenizer; public class A1603 { private static final int P = 998244353; private static final int M = 100000; private static final int SQ = 800; private static final int SQ2 = 400; private static int[] answer = new int[M + 1]; private static HashMap<Integer, Integer>[] g = new HashMap[M + 1]; private static int countAnswer(int n, int[] a) { if (answer[n] < 0) { if (n == 0) { answer[0] = 0; } else { answer[n] = (countAnswer(n - 1, a) + countG(n, a[n], a)) % P; } } return answer[n]; } private static int countG(int n, int last, int[] a) { if (!g[n].containsKey(last)) { if (n == 0) { g[n].put(last, 0); } else { long ans = (getMoves(a[n - 1], last) * 1l * n) % P; ans = (ans + countG(n - 1, getB1(a[n - 1], last), a)) % P; g[n].put(last, (int) (ans % P)); } } return g[n].get(last); } private static int getB1(int a, int b) { return a / ceil(a, b); } private static int getMoves(int a, int b) { return ceil(a, b) - 1; } private static int ceil(int a, int b) { return (a + b - 1) / b; } private static int getIndex(int num, int last) { if (last * 1l * last >= num) { return num / last; } return SQ2 + last; } private static int count(int[] a, int n) { // answer = new int[n]; // g = new HashMap[n]; // for (int i = 0; i < n; i++) { // answer[i] = -1; // g[i] = new HashMap<>(); // } // return countAnswer(n - 1, a); int ans = 0; int[][] g = new int[2][SQ + 1]; int active = 0; for (int i = 1; i < n; i++) { // compute g[] for (int j = 1; j <= SQ; j++) { g[active][j] = 0; } for (int j = 1; j <= SQ2; j++) { int last = a[i] / j; if (last == 0) { g[active][j] = 0; continue; } long res = (getMoves(a[i - 1], last) * 1l * i) % P; res = (res + g[active ^ 1][getIndex(a[i - 1], getB1(a[i - 1], last))]) % P; g[active][j] = (int) res; } for (int j = SQ2 + 1; j <= SQ; j++) { // last = (j - sq2), if [a[i] / [a[i] / (j - sq2)]] == j - sq2. int div = a[i] / (j - SQ2); if (div <= 0 || a[i] / div != j - SQ2) { g[active][j] = 0; continue; } int last = j - SQ2; long res = (getMoves(a[i - 1], last) * 1l * i) % P; res = (res + g[active ^ 1][getIndex(a[i - 1], getB1(a[i - 1], last))]) % P; g[active][j] = (int) res; } ans = (ans + g[active][1]) % P; active ^= 1; } return ans; } public static void main(String[] args) throws IOException { BufferedReader rd = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); int numTests = Integer.parseInt(rd.readLine()); for (int t = 0; t < numTests; t++) { int n = Integer.parseInt(rd.readLine()); StringTokenizer st = new StringTokenizer(rd.readLine()); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = Integer.parseInt(st.nextToken()); } pw.println(count(a, n)); } pw.flush(); pw.close(); rd.close(); } }
For an array $$$b$$$ of $$$n$$$ integers, the extreme value of this array is the minimum number of times (possibly, zero) the following operation has to be performed to make $$$b$$$ non-decreasing: Select an index $$$i$$$ such that $$$1 \le i \le |b|$$$, where $$$|b|$$$ is the current length of $$$b$$$. Replace $$$b_i$$$ with two elements $$$x$$$ and $$$y$$$ such that $$$x$$$ and $$$y$$$ both are positive integers and $$$x + y = b_i$$$. This way, the array $$$b$$$ changes and the next operation is performed on this modified array. For example, if $$$b = [2, 4, 3]$$$ and index $$$2$$$ gets selected, then the possible arrays after this operation are $$$[2, \underline{1}, \underline{3}, 3]$$$, $$$[2, \underline{2}, \underline{2}, 3]$$$, or $$$[2, \underline{3}, \underline{1}, 3]$$$. And consequently, for this array, this single operation is enough to make it non-decreasing: $$$[2, 4, 3] \rightarrow [2, \underline{2}, \underline{2}, 3]$$$.It's easy to see that every array of positive integers can be made non-decreasing this way.YouKn0wWho has an array $$$a$$$ of $$$n$$$ integers. Help him find the sum of extreme values of all nonempty subarrays of $$$a$$$ modulo $$$998\,244\,353$$$. If a subarray appears in $$$a$$$ multiple times, its extreme value should be counted the number of times it appears.An array $$$d$$$ is a subarray of an array $$$c$$$ if $$$d$$$ can be obtained from $$$c$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
For each test case, print a single integer  — the sum of extreme values of all subarrays of $$$a$$$ modulo $$$998\,244\,353$$$.
Java
f760f108c66f695e1e51dc6470d29ce7
8503b883c5458421fae574d9b1acfe8c
Java 11
standard output
256 megabytes
train_110.jsonl
[ "dp", "greedy", "math", "number theory" ]
1635604500
["4\n3\n5 4 3\n4\n3 2 1 4\n1\n69\n8\n7264 40515 28226 92776 35285 21709 75124 48163"]
NoteLet $$$f(l, r)$$$ denote the extreme value of $$$[a_l, a_{l+1}, \ldots, a_r]$$$.In the first test case, $$$f(1, 3) = 3$$$, because YouKn0wWho can perform the following operations on the subarray $$$[5, 4, 3]$$$ (the newly inserted elements are underlined):$$$[5, 4, 3] \rightarrow [\underline{3}, \underline{2}, 4, 3] \rightarrow [3, 2, \underline{2}, \underline{2}, 3] \rightarrow [\underline{1}, \underline{2}, 2, 2, 2, 3]$$$; $$$f(1, 2) = 1$$$, because $$$[5, 4] \rightarrow [\underline{2}, \underline{3}, 4]$$$; $$$f(2, 3) = 1$$$, because $$$[4, 3] \rightarrow [\underline{1}, \underline{3}, 3]$$$; $$$f(1, 1) = f(2, 2) = f(3, 3) = 0$$$, because they are already non-decreasing. So the total sum of extreme values of all subarrays of $$$a = 3 + 1 + 1 + 0 + 0 + 0 = 5$$$.
PASSED
2,300
standard input
4 seconds
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10\,000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^5$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
["5\n9\n0\n117"]
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.util.Arrays; import java.io.IOException; import java.lang.reflect.Field; import java.nio.charset.StandardCharsets; import java.io.UncheckedIOException; import java.io.Closeable; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 29); thread.start(); thread.join(); } static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastInput in = new FastInput(inputStream); FastOutput out = new FastOutput(outputStream); CExtremeExtension solver = new CExtremeExtension(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } } static class CExtremeExtension { int mod = 998244353; int L = (int) 1e5; IntegerArrayList prevList = new IntegerArrayList(L); IntegerArrayList nextList = new IntegerArrayList(L); long[] prevWay = new long[L]; long[] nextWay = new long[L]; long[] prevCost = new long[L]; long[] nextCost = new long[L]; Debug debug = new Debug(false); public void process(int x, IntegerArrayList list) { list.clear(); for (int i = 1, r; i <= x; i = r + 1) { int v = x / i; r = x / v; assert r >= i; list.add(v); } list.reverse(); } public void solve(int testNumber, FastInput in, FastOutput out) { int n = in.ri(); int[] a = in.ri(n); prevList.clear(); // prevListMap.clear(); long sumOfCost = 0; for (int i = n - 1; i >= 0; i--) { process(a[i], nextList); debug.debug("i", i); debug.debug("nextList", nextList); int m = nextList.size(); for (int j = 0; j < m; j++) { nextWay[j] = 0; nextCost[j] = 0; } int[] prevListData = prevList.getData(); int prevSize = prevList.size(); int[] nextListData = nextList.getData(); int iter = 0; for (int j = 0; j < prevSize; j++) { int back = prevListData[j]; int block = (a[i] + back - 1) / back; int f = a[i] / block; while (nextListData[iter] < f) { iter++; } int findex = iter; nextWay[findex] += prevWay[j]; nextCost[findex] += prevCost[j] + prevWay[j] * (block - 1); } //add new end int findex = nextList.size() - 1; nextWay[findex]++; for (int j = 0; j < m; j++) { nextCost[j] %= mod; nextWay[j] %= mod; sumOfCost += nextCost[j]; } debug.run(() -> { debug.debug("nextWay", Arrays.copyOf(nextWay, m)); debug.debug("nextCost", Arrays.copyOf(nextCost, m)); }); { IntegerArrayList tmp = prevList; prevList = nextList; nextList = tmp; } // { // IntegerHashMap tmp = prevListMap; // prevListMap = nextListMap; // nextListMap = tmp; // } { long[] tmp = prevCost; prevCost = nextCost; nextCost = tmp; } { long[] tmp = prevWay; prevWay = nextWay; nextWay = tmp; } } sumOfCost = DigitUtils.mod(sumOfCost, mod); out.println(sumOfCost); } } static class SequenceUtils { public static void swap(int[] data, int i, int j) { int tmp = data[i]; data[i] = data[j]; data[j] = tmp; } public static void reverse(int[] data, int l, int r) { while (l < r) { swap(data, l, r); l++; r--; } } public static boolean equal(int[] a, int al, int ar, int[] b, int bl, int br) { if ((ar - al) != (br - bl)) { return false; } for (int i = al, j = bl; i <= ar; i++, j++) { if (a[i] != b[j]) { return false; } } return true; } } static class IntegerArrayList implements Cloneable { private int size; private int cap; private int[] data; private static final int[] EMPTY = new int[0]; public int[] getData() { return data; } public IntegerArrayList(int cap) { this.cap = cap; if (cap == 0) { data = EMPTY; } else { data = new int[cap]; } } public IntegerArrayList(int[] data) { this(0); addAll(data); } public IntegerArrayList(IntegerArrayList list) { this.size = list.size; this.cap = list.cap; this.data = Arrays.copyOf(list.data, size); } public IntegerArrayList() { this(0); } public void reverse(int l, int r) { SequenceUtils.reverse(data, l, r); } public void reverse() { reverse(0, size - 1); } public void ensureSpace(int req) { if (req > cap) { while (cap < req) { cap = Math.max(cap + 10, 2 * cap); } data = Arrays.copyOf(data, cap); } } public void add(int x) { ensureSpace(size + 1); data[size++] = x; } public void addAll(int[] x) { addAll(x, 0, x.length); } public void addAll(int[] x, int offset, int len) { ensureSpace(size + len); System.arraycopy(x, offset, data, size, len); size += len; } public void addAll(IntegerArrayList list) { addAll(list.data, 0, list.size); } public int size() { return size; } public int[] toArray() { return Arrays.copyOf(data, size); } public void clear() { size = 0; } public String toString() { return Arrays.toString(toArray()); } public boolean equals(Object obj) { if (!(obj instanceof IntegerArrayList)) { return false; } IntegerArrayList other = (IntegerArrayList) obj; return SequenceUtils.equal(data, 0, size - 1, other.data, 0, other.size - 1); } public int hashCode() { int h = 1; for (int i = 0; i < size; i++) { h = h * 31 + Integer.hashCode(data[i]); } return h; } public IntegerArrayList clone() { IntegerArrayList ans = new IntegerArrayList(); ans.addAll(this); return ans; } } static class DigitUtils { private DigitUtils() { } public static int mod(long x, int mod) { if (x < -mod || x >= mod) { x %= mod; } if (x < 0) { x += mod; } return (int) x; } } static class FastOutput implements AutoCloseable, Closeable, Appendable { private static final int THRESHOLD = 32 << 10; private OutputStream writer; private StringBuilder cache = new StringBuilder(THRESHOLD * 2); private static Field stringBuilderValueField; private char[] charBuf = new char[THRESHOLD * 2]; private byte[] byteBuf = new byte[THRESHOLD * 2]; static { try { stringBuilderValueField = StringBuilder.class.getSuperclass().getDeclaredField("value"); stringBuilderValueField.setAccessible(true); } catch (Exception e) { stringBuilderValueField = null; } stringBuilderValueField = null; } public FastOutput append(CharSequence csq) { cache.append(csq); return this; } public FastOutput append(CharSequence csq, int start, int end) { cache.append(csq, start, end); return this; } private void afterWrite() { if (cache.length() < THRESHOLD) { return; } flush(); } public FastOutput(OutputStream writer) { this.writer = writer; } public FastOutput append(char c) { cache.append(c); afterWrite(); return this; } public FastOutput append(long c) { cache.append(c); afterWrite(); return this; } public FastOutput println(long c) { return append(c).println(); } public FastOutput println() { return append('\n'); } public FastOutput flush() { try { if (stringBuilderValueField != null) { try { byte[] value = (byte[]) stringBuilderValueField.get(cache); writer.write(value, 0, cache.length()); } catch (Exception e) { stringBuilderValueField = null; } } if (stringBuilderValueField == null) { int n = cache.length(); if (n > byteBuf.length) { //slow writer.write(cache.toString().getBytes(StandardCharsets.UTF_8)); // writer.append(cache); } else { cache.getChars(0, n, charBuf, 0); for (int i = 0; i < n; i++) { byteBuf[i] = (byte) charBuf[i]; } writer.write(byteBuf, 0, n); } } writer.flush(); cache.setLength(0); } catch (IOException e) { throw new UncheckedIOException(e); } return this; } public void close() { flush(); try { writer.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } public String toString() { return cache.toString(); } } static class Debug { private boolean offline; private PrintStream out = System.err; static int[] empty = new int[0]; public Debug(boolean enable) { offline = enable && System.getSecurityManager() == null; } public void run(Runnable task) { if (offline) { task.run(); } } public Debug debug(String name, int x) { if (offline) { debug(name, "" + x); } return this; } public Debug debug(String name, String x) { if (offline) { out.printf("%s=%s", name, x); out.println(); } return this; } public Debug debug(String name, Object x) { return debug(name, x, empty); } public Debug debug(String name, Object x, int... indexes) { if (offline) { if (x == null || !x.getClass().isArray()) { out.append(name); for (int i : indexes) { out.printf("[%d]", i); } out.append("=").append("" + x); out.println(); } else { indexes = Arrays.copyOf(indexes, indexes.length + 1); if (x instanceof byte[]) { byte[] arr = (byte[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof short[]) { short[] arr = (short[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof boolean[]) { boolean[] arr = (boolean[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof char[]) { char[] arr = (char[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof int[]) { int[] arr = (int[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof float[]) { float[] arr = (float[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof double[]) { double[] arr = (double[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof long[]) { long[] arr = (long[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else { Object[] arr = (Object[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } } } return this; } } static class FastInput { private final InputStream is; private StringBuilder defaultStringBuf = new StringBuilder(1 << 13); private byte[] buf = new byte[1 << 13]; private int bufLen; private int bufOffset; private int next; public FastInput(InputStream is) { this.is = is; } public void populate(int[] data) { for (int i = 0; i < data.length; i++) { data[i] = readInt(); } } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { bufLen = -1; } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public String next() { return readString(); } public int ri() { return readInt(); } public int[] ri(int n) { int[] ans = new int[n]; populate(ans); return ans; } public int readInt() { boolean rev = false; skipBlank(); if (next == '+' || next == '-') { rev = next == '-'; next = read(); } int val = 0; while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } return rev ? val : -val; } public String readString(StringBuilder builder) { skipBlank(); while (next > 32) { builder.append((char) next); next = read(); } return builder.toString(); } public String readString() { defaultStringBuf.setLength(0); return readString(defaultStringBuf); } } }
For two positive integers $$$l$$$ and $$$r$$$ ($$$l \le r$$$) let $$$c(l, r)$$$ denote the number of integer pairs $$$(i, j)$$$ such that $$$l \le i \le j \le r$$$ and $$$\operatorname{gcd}(i, j) \ge l$$$. Here, $$$\operatorname{gcd}(i, j)$$$ is the greatest common divisor (GCD) of integers $$$i$$$ and $$$j$$$.YouKn0wWho has two integers $$$n$$$ and $$$k$$$ where $$$1 \le k \le n$$$. Let $$$f(n, k)$$$ denote the minimum of $$$\sum\limits_{i=1}^{k}{c(x_i+1,x_{i+1})}$$$ over all integer sequences $$$0=x_1 \lt x_2 \lt \ldots \lt x_{k} \lt x_{k+1}=n$$$.Help YouKn0wWho find $$$f(n, k)$$$.
For each test case, print a single integer — $$$f(n, k)$$$.
Java
2e7d4deeeb700d7ad008875779d6f969
87d3b5e6eca4cc9dd5ea2833c2f35558
Java 11
standard output
1024 megabytes
train_110.jsonl
[ "divide and conquer", "dp", "number theory" ]
1635604500
["4\n6 2\n4 4\n3 1\n10 3"]
NoteIn the first test case, YouKn0wWho can select the sequence $$$[0, 2, 6]$$$. So $$$f(6, 2) = c(1, 2) + c(3, 6) = 3 + 5 = 8$$$ which is the minimum possible.
PASSED
3,000
standard input
3 seconds
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 3 \cdot 10^5$$$) — the number of test cases. The first and only line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 10^5$$$).
["8\n4\n6\n11"]
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import java.io.IOException; import java.lang.reflect.Field; import java.nio.charset.StandardCharsets; import java.io.UncheckedIOException; import java.io.Closeable; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) throws Exception { new TaskAdapter().run(); } static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastInput in = new FastInput(inputStream); FastOutput out = new FastOutput(outputStream); DArtisticPartition solver = new DArtisticPartition(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } } static class DArtisticPartition { int K = 20; int N = (int) 1e5; long[][] dp = new long[K][N + 1]; int[][] pts = new int[N + 1][]; long[][] suffix = new long[N + 1][]; int[][] start = new int[N + 1][]; Cost cost; long inf = (long) 1e18; long[] p; public void preprocess() { IntegerArrayList ptBuf = new IntegerArrayList(N + 1); IntegerArrayList startBuf = new IntegerArrayList(N + 1); for (int i = 1; i <= N; i++) { ptBuf.clear(); startBuf.clear(); for (int j = 1, r; j <= i; j = r + 1) { int v = i / j; r = i / v; ptBuf.add(v); startBuf.add(j); } pts[i] = ptBuf.toArray(); start[i] = startBuf.toArray(); int m = pts[i].length; suffix[i] = new long[m]; long last = i + 1; long lastSum = 0; for (int j = m - 1; j >= 0; j--) { suffix[i][j] = lastSum + (last - start[i][j]) * p[pts[i][j]]; last = start[i][j]; lastSum = suffix[i][j]; } } } public void dac(int level, int l, int r, int L, int R) { if (l > r) { return; } int m = (l + r) >>> 1; int start = Math.min(m, R); cost.reset(start + 1, m); int bestChoice = -1; long bestCost = inf; for (int i = start; i >= L; i--) { cost.move(i + 1); long cand = cost.cost + dp[level - 1][i]; if (cand < bestCost) { bestCost = cand; bestChoice = i; } } dp[level][m] = bestCost; dac(level, l, m - 1, L, bestChoice); dac(level, m + 1, r, bestChoice, R); } public DArtisticPartition() { MultiplicativeFunctionSieve sieve = new MultiplicativeFunctionSieve(N); int[] euler = sieve.getEuler(); p = new long[N + 1]; p[0] = euler[0]; for (int i = 1; i <= N; i++) { p[i] = p[i - 1] + euler[i]; } preprocess(); cost = new Cost(); SequenceUtils.deepFill(dp, inf); dp[0][0] = 0; for (int i = 1; i < K; i++) { dac(i, 1, N, 0, N); } } public void solve(int testNumber, FastInput in, FastOutput out) { int n = in.ri(); int k = in.ri(); if (k >= K) { out.println(n); return; } long ans = dp[k][n]; out.println(ans); } class Cost { int r; int l; long cost; public void reset(int L, int R) { r = R; l = L; if (l > r) { cost = 0; return; } int high = BinarySearch.upperBound(start[r], 0, start[r].length - 1, l); assert high > 0; cost = 0; int last = r + 1; if (high < suffix[r].length) { cost += suffix[r][high]; last = start[r][high]; } cost += (last - l) * p[pts[r][high - 1]]; } public void move(int L) { while (l < L) { cost -= p[r / l]; l++; } while (l > L) { l--; cost += p[r / l]; } } } } static class SequenceUtils { public static void deepFill(Object array, long val) { if (array == null) { return; } if (!array.getClass().isArray()) { throw new IllegalArgumentException(); } if (array instanceof long[]) { long[] longArray = (long[]) array; Arrays.fill(longArray, val); } else { Object[] objArray = (Object[]) array; for (Object obj : objArray) { deepFill(obj, val); } } } public static boolean equal(int[] a, int al, int ar, int[] b, int bl, int br) { if ((ar - al) != (br - bl)) { return false; } for (int i = al, j = bl; i <= ar; i++, j++) { if (a[i] != b[j]) { return false; } } return true; } } static class BinarySearch { private BinarySearch() { } public static int lowerBound(int[] arr, int l, int r, int target) { while (l < r) { int mid = DigitUtils.floorAverage(l, r); if (arr[mid] >= target) { r = mid; } else { l = mid + 1; } } if (arr[l] < target) { l++; } return l; } public static int upperBound(int[] arr, int l, int r, int target) { return lowerBound(arr, l, r, target + 1); } } static class DigitUtils { private DigitUtils() { } public static int floorAverage(int x, int y) { return (x & y) + ((x ^ y) >> 1); } } static class FastOutput implements AutoCloseable, Closeable, Appendable { private static final int THRESHOLD = 32 << 10; private OutputStream writer; private StringBuilder cache = new StringBuilder(THRESHOLD * 2); private static Field stringBuilderValueField; private char[] charBuf = new char[THRESHOLD * 2]; private byte[] byteBuf = new byte[THRESHOLD * 2]; static { try { stringBuilderValueField = StringBuilder.class.getSuperclass().getDeclaredField("value"); stringBuilderValueField.setAccessible(true); } catch (Exception e) { stringBuilderValueField = null; } stringBuilderValueField = null; } public FastOutput append(CharSequence csq) { cache.append(csq); return this; } public FastOutput append(CharSequence csq, int start, int end) { cache.append(csq, start, end); return this; } private void afterWrite() { if (cache.length() < THRESHOLD) { return; } flush(); } public FastOutput(OutputStream writer) { this.writer = writer; } public FastOutput append(char c) { cache.append(c); afterWrite(); return this; } public FastOutput append(int c) { cache.append(c); afterWrite(); return this; } public FastOutput append(long c) { cache.append(c); afterWrite(); return this; } public FastOutput println(int c) { return append(c).println(); } public FastOutput println(long c) { return append(c).println(); } public FastOutput println() { return append('\n'); } public FastOutput flush() { try { if (stringBuilderValueField != null) { try { byte[] value = (byte[]) stringBuilderValueField.get(cache); writer.write(value, 0, cache.length()); } catch (Exception e) { stringBuilderValueField = null; } } if (stringBuilderValueField == null) { int n = cache.length(); if (n > byteBuf.length) { //slow writer.write(cache.toString().getBytes(StandardCharsets.UTF_8)); // writer.append(cache); } else { cache.getChars(0, n, charBuf, 0); for (int i = 0; i < n; i++) { byteBuf[i] = (byte) charBuf[i]; } writer.write(byteBuf, 0, n); } } writer.flush(); cache.setLength(0); } catch (IOException e) { throw new UncheckedIOException(e); } return this; } public void close() { flush(); try { writer.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } public String toString() { return cache.toString(); } } static class MultiplicativeFunctionSieve { public int[] primes; public boolean[] isComp; public int primeLength; public int[] smallestPrimeFactor; public int[] expOfSmallestPrimeFactor; int limit; public int[] getEuler() { int[] euler = new int[limit + 1]; euler[1] = 1; for (int i = 2; i <= limit; i++) { if (!isComp[i]) { euler[i] = i - 1; } else { if (expOfSmallestPrimeFactor[i] == i) { euler[i] = i - i / smallestPrimeFactor[i]; } else { euler[i] = euler[expOfSmallestPrimeFactor[i]] * euler[i / expOfSmallestPrimeFactor[i]]; } } } return euler; } public MultiplicativeFunctionSieve(int limit) { this.limit = limit; isComp = new boolean[limit + 1]; primes = new int[limit + 1]; expOfSmallestPrimeFactor = new int[limit + 1]; smallestPrimeFactor = new int[limit + 1]; primeLength = 0; for (int i = 2; i <= limit; i++) { if (!isComp[i]) { primes[primeLength++] = i; expOfSmallestPrimeFactor[i] = smallestPrimeFactor[i] = i; } for (int j = 0, until = limit / i; j < primeLength && primes[j] <= until; j++) { int pi = primes[j] * i; smallestPrimeFactor[pi] = primes[j]; expOfSmallestPrimeFactor[pi] = smallestPrimeFactor[i] == primes[j] ? (expOfSmallestPrimeFactor[i] * expOfSmallestPrimeFactor[primes[j]]) : expOfSmallestPrimeFactor[primes[j]]; isComp[pi] = true; if (i % primes[j] == 0) { break; } } } } } static class FastInput { private final InputStream is; private StringBuilder defaultStringBuf = new StringBuilder(1 << 13); private byte[] buf = new byte[1 << 13]; private int bufLen; private int bufOffset; private int next; public FastInput(InputStream is) { this.is = is; } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { bufLen = -1; } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public String next() { return readString(); } public int ri() { return readInt(); } public int readInt() { boolean rev = false; skipBlank(); if (next == '+' || next == '-') { rev = next == '-'; next = read(); } int val = 0; while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } return rev ? val : -val; } public String readString(StringBuilder builder) { skipBlank(); while (next > 32) { builder.append((char) next); next = read(); } return builder.toString(); } public String readString() { defaultStringBuf.setLength(0); return readString(defaultStringBuf); } } static class IntegerArrayList implements Cloneable { private int size; private int cap; private int[] data; private static final int[] EMPTY = new int[0]; public IntegerArrayList(int cap) { this.cap = cap; if (cap == 0) { data = EMPTY; } else { data = new int[cap]; } } public IntegerArrayList(int[] data) { this(0); addAll(data); } public IntegerArrayList(IntegerArrayList list) { this.size = list.size; this.cap = list.cap; this.data = Arrays.copyOf(list.data, size); } public IntegerArrayList() { this(0); } public void ensureSpace(int req) { if (req > cap) { while (cap < req) { cap = Math.max(cap + 10, 2 * cap); } data = Arrays.copyOf(data, cap); } } public void add(int x) { ensureSpace(size + 1); data[size++] = x; } public void addAll(int[] x) { addAll(x, 0, x.length); } public void addAll(int[] x, int offset, int len) { ensureSpace(size + len); System.arraycopy(x, offset, data, size, len); size += len; } public void addAll(IntegerArrayList list) { addAll(list.data, 0, list.size); } public int[] toArray() { return Arrays.copyOf(data, size); } public void clear() { size = 0; } public String toString() { return Arrays.toString(toArray()); } public boolean equals(Object obj) { if (!(obj instanceof IntegerArrayList)) { return false; } IntegerArrayList other = (IntegerArrayList) obj; return SequenceUtils.equal(data, 0, size - 1, other.data, 0, other.size - 1); } public int hashCode() { int h = 1; for (int i = 0; i < size; i++) { h = h * 31 + Integer.hashCode(data[i]); } return h; } public IntegerArrayList clone() { IntegerArrayList ans = new IntegerArrayList(); ans.addAll(this); return ans; } } }