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 | 2b8dc8be92c51beafd70f8e025c3dd8a | train_109.jsonl | 1659623700 | A permutation of length $$$n$$$ is a sequence of integers from $$$1$$$ to $$$n$$$ such that each integer appears in it exactly once.Let the fixedness of a permutation $$$p$$$ be the number of fixed points in it — the number of positions $$$j$$$ such that $$$p_j = j$$$, where $$$p_j$$$ is the $$$j$$$-th element of the permutation $$$p$$$.You are asked to build a sequence of permutations $$$a_1, a_2, \dots$$$, starting from the identity permutation (permutation $$$a_1 = [1, 2, \dots, n]$$$). Let's call it a permutation chain. Thus, $$$a_i$$$ is the $$$i$$$-th permutation of length $$$n$$$.For every $$$i$$$ from $$$2$$$ onwards, the permutation $$$a_i$$$ should be obtained from the permutation $$$a_{i-1}$$$ by swapping any two elements in it (not necessarily neighboring). The fixedness of the permutation $$$a_i$$$ should be strictly lower than the fixedness of the permutation $$$a_{i-1}$$$.Consider some chains for $$$n = 3$$$: $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$ — that is a valid chain of length $$$2$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. $$$a_1 = [2, 1, 3]$$$, $$$a_2 = [3, 1, 2]$$$ — that is not a valid chain. The first permutation should always be $$$[1, 2, 3]$$$ for $$$n = 3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$, $$$a_3 = [1, 2, 3]$$$ — that is not a valid chain. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped but the fixedness increase from $$$1$$$ to $$$3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [3, 2, 1]$$$, $$$a_3 = [3, 1, 2]$$$ — that is a valid chain of length $$$3$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$1$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$1$$$ to $$$0$$$. Find the longest permutation chain. If there are multiple longest answers, print any of them. | 256 megabytes | import java.io.*;
import java.util.*;
import javax.lang.model.util.ElementScanner14;
public class pavan
{
static BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
public static void main(String[] args) throws IOException
{
Scanner sc = new Scanner(System.in);
long t = sc.nextLong();
while(t > 0)
{
int n = sc.nextInt();
output.write(n + "\n");
int[] a = new int[n];
for(int i=0;i<n;i++)
{
a[i] = i+1;
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
output.write(a[j] + " ");
}
output.write("\n");
if(i == n-1)
{
break;
}
int temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
}
t--;
}
output.flush();
}
}
| Java | ["2\n\n2\n\n3"] | 2 seconds | ["2\n1 2\n2 1\n3\n1 2 3\n3 2 1\n3 1 2"] | null | Java 17 | standard input | [
"constructive algorithms",
"math"
] | 02bdd12987af6e666d4283f075f73725 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 99$$$) — the number of testcases. The only line of each testcase contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the required length of permutations in the chain. | 800 | For each testcase, first, print the length of a permutation chain $$$k$$$. Then print $$$k$$$ permutations $$$a_1, a_2, \dots, a_k$$$. $$$a_1$$$ should be an identity permutation of length $$$n$$$ ($$$[1, 2, \dots, n]$$$). For each $$$i$$$ from $$$2$$$ to $$$k$$$, $$$a_i$$$ should be obtained by swapping two elements in $$$a_{i-1}$$$. It should also have a strictly lower fixedness than $$$a_{i-1}$$$. | standard output | |
PASSED | 93b44dfa9a21683cdaabffe40c728659 | train_109.jsonl | 1659623700 | A permutation of length $$$n$$$ is a sequence of integers from $$$1$$$ to $$$n$$$ such that each integer appears in it exactly once.Let the fixedness of a permutation $$$p$$$ be the number of fixed points in it — the number of positions $$$j$$$ such that $$$p_j = j$$$, where $$$p_j$$$ is the $$$j$$$-th element of the permutation $$$p$$$.You are asked to build a sequence of permutations $$$a_1, a_2, \dots$$$, starting from the identity permutation (permutation $$$a_1 = [1, 2, \dots, n]$$$). Let's call it a permutation chain. Thus, $$$a_i$$$ is the $$$i$$$-th permutation of length $$$n$$$.For every $$$i$$$ from $$$2$$$ onwards, the permutation $$$a_i$$$ should be obtained from the permutation $$$a_{i-1}$$$ by swapping any two elements in it (not necessarily neighboring). The fixedness of the permutation $$$a_i$$$ should be strictly lower than the fixedness of the permutation $$$a_{i-1}$$$.Consider some chains for $$$n = 3$$$: $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$ — that is a valid chain of length $$$2$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. $$$a_1 = [2, 1, 3]$$$, $$$a_2 = [3, 1, 2]$$$ — that is not a valid chain. The first permutation should always be $$$[1, 2, 3]$$$ for $$$n = 3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$, $$$a_3 = [1, 2, 3]$$$ — that is not a valid chain. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped but the fixedness increase from $$$1$$$ to $$$3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [3, 2, 1]$$$, $$$a_3 = [3, 1, 2]$$$ — that is a valid chain of length $$$3$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$1$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$1$$$ to $$$0$$$. Find the longest permutation chain. If there are multiple longest answers, print any of them. | 256 megabytes | import java.util.Scanner;
import static java.lang.System.out;
public class Problem7 {
static Scanner scanner = new Scanner(System.in);
static void solve() {
int n = scanner.nextInt();
out.println(n);
for (int i = 1; i<=n; i++) {
StringBuilder builder = new StringBuilder(i+" ");
for (int j = 1; j<=n; j++) {
if (j==i) continue;
builder.append(j).append(" ");
}
out.println(builder);
}
}
public static void main(String[] args) {
int T = scanner.nextInt();
while (T-- > 0) solve();
scanner.close();
}
}
| Java | ["2\n\n2\n\n3"] | 2 seconds | ["2\n1 2\n2 1\n3\n1 2 3\n3 2 1\n3 1 2"] | null | Java 17 | standard input | [
"constructive algorithms",
"math"
] | 02bdd12987af6e666d4283f075f73725 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 99$$$) — the number of testcases. The only line of each testcase contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the required length of permutations in the chain. | 800 | For each testcase, first, print the length of a permutation chain $$$k$$$. Then print $$$k$$$ permutations $$$a_1, a_2, \dots, a_k$$$. $$$a_1$$$ should be an identity permutation of length $$$n$$$ ($$$[1, 2, \dots, n]$$$). For each $$$i$$$ from $$$2$$$ to $$$k$$$, $$$a_i$$$ should be obtained by swapping two elements in $$$a_{i-1}$$$. It should also have a strictly lower fixedness than $$$a_{i-1}$$$. | standard output | |
PASSED | fb395d8e6a0567f80771e7cf04f1f8ab | train_109.jsonl | 1659623700 | A permutation of length $$$n$$$ is a sequence of integers from $$$1$$$ to $$$n$$$ such that each integer appears in it exactly once.Let the fixedness of a permutation $$$p$$$ be the number of fixed points in it — the number of positions $$$j$$$ such that $$$p_j = j$$$, where $$$p_j$$$ is the $$$j$$$-th element of the permutation $$$p$$$.You are asked to build a sequence of permutations $$$a_1, a_2, \dots$$$, starting from the identity permutation (permutation $$$a_1 = [1, 2, \dots, n]$$$). Let's call it a permutation chain. Thus, $$$a_i$$$ is the $$$i$$$-th permutation of length $$$n$$$.For every $$$i$$$ from $$$2$$$ onwards, the permutation $$$a_i$$$ should be obtained from the permutation $$$a_{i-1}$$$ by swapping any two elements in it (not necessarily neighboring). The fixedness of the permutation $$$a_i$$$ should be strictly lower than the fixedness of the permutation $$$a_{i-1}$$$.Consider some chains for $$$n = 3$$$: $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$ — that is a valid chain of length $$$2$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. $$$a_1 = [2, 1, 3]$$$, $$$a_2 = [3, 1, 2]$$$ — that is not a valid chain. The first permutation should always be $$$[1, 2, 3]$$$ for $$$n = 3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$, $$$a_3 = [1, 2, 3]$$$ — that is not a valid chain. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped but the fixedness increase from $$$1$$$ to $$$3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [3, 2, 1]$$$, $$$a_3 = [3, 1, 2]$$$ — that is a valid chain of length $$$3$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$1$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$1$$$ to $$$0$$$. Find the longest permutation chain. If there are multiple longest answers, print any of them. | 256 megabytes | import java.util.Scanner;
public class SolutionB {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int t = input.nextInt();
while (t > 0) {
t--;
solve(input.nextInt());
}
input.close();
}
private static void solve(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = i;
System.out.println(n);
printArray(a);
while(next(a)) printArray(a);
}
private static boolean next(int[] a) {
int trueIndex = -1;
int falseIndex = -1;
for (int i = 0; i < a.length; i++) {
if (a[i] == i) {
if (trueIndex == -1) trueIndex = i;
}
else {
if (falseIndex == -1) falseIndex = i;
}
}
if (trueIndex == -1) return false;
if (falseIndex == -1) falseIndex = a.length-1;
swap(a, trueIndex, falseIndex);
return true;
}
private static void swap(int[] a, int i1, int i2) {
int tmp = a[i1]; a[i1] = a[i2]; a[i2] = tmp;
}
private static void printArray(int[] a) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < a.length; i++)
sb.append(a[i]+1).append(' ');
sb.deleteCharAt(sb.length()-1);
System.out.println(sb.toString());
}
}
| Java | ["2\n\n2\n\n3"] | 2 seconds | ["2\n1 2\n2 1\n3\n1 2 3\n3 2 1\n3 1 2"] | null | Java 17 | standard input | [
"constructive algorithms",
"math"
] | 02bdd12987af6e666d4283f075f73725 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 99$$$) — the number of testcases. The only line of each testcase contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the required length of permutations in the chain. | 800 | For each testcase, first, print the length of a permutation chain $$$k$$$. Then print $$$k$$$ permutations $$$a_1, a_2, \dots, a_k$$$. $$$a_1$$$ should be an identity permutation of length $$$n$$$ ($$$[1, 2, \dots, n]$$$). For each $$$i$$$ from $$$2$$$ to $$$k$$$, $$$a_i$$$ should be obtained by swapping two elements in $$$a_{i-1}$$$. It should also have a strictly lower fixedness than $$$a_{i-1}$$$. | standard output | |
PASSED | 9dff6391224eaf8055aeab3d8a706b51 | train_109.jsonl | 1659623700 | A permutation of length $$$n$$$ is a sequence of integers from $$$1$$$ to $$$n$$$ such that each integer appears in it exactly once.Let the fixedness of a permutation $$$p$$$ be the number of fixed points in it — the number of positions $$$j$$$ such that $$$p_j = j$$$, where $$$p_j$$$ is the $$$j$$$-th element of the permutation $$$p$$$.You are asked to build a sequence of permutations $$$a_1, a_2, \dots$$$, starting from the identity permutation (permutation $$$a_1 = [1, 2, \dots, n]$$$). Let's call it a permutation chain. Thus, $$$a_i$$$ is the $$$i$$$-th permutation of length $$$n$$$.For every $$$i$$$ from $$$2$$$ onwards, the permutation $$$a_i$$$ should be obtained from the permutation $$$a_{i-1}$$$ by swapping any two elements in it (not necessarily neighboring). The fixedness of the permutation $$$a_i$$$ should be strictly lower than the fixedness of the permutation $$$a_{i-1}$$$.Consider some chains for $$$n = 3$$$: $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$ — that is a valid chain of length $$$2$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. $$$a_1 = [2, 1, 3]$$$, $$$a_2 = [3, 1, 2]$$$ — that is not a valid chain. The first permutation should always be $$$[1, 2, 3]$$$ for $$$n = 3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$, $$$a_3 = [1, 2, 3]$$$ — that is not a valid chain. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped but the fixedness increase from $$$1$$$ to $$$3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [3, 2, 1]$$$, $$$a_3 = [3, 1, 2]$$$ — that is a valid chain of length $$$3$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$1$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$1$$$ to $$$0$$$. Find the longest permutation chain. If there are multiple longest answers, print any of them. | 256 megabytes | import java.io.*;
import java.lang.*;
import java.lang.Exception;
import java.math.BigInteger;
import java.util.*;
public class Main {
private static final BufferedWriter sout = new BufferedWriter(new OutputStreamWriter(System.out));
private static final double PI = 3.141592653;
public static int lowerBoundIndex(int[] arr, int key) {
// Arrays.sort(arr);
int idx = Arrays.binarySearch(arr, key);
if (idx >= 0) {
return idx;
} else if ((idx + 1) * -1 < arr.length && (idx + 1) * -1 >= 0) return (idx + 1) * -1;
return -1;
}
public static int lowerBoundElement(int[] arr, int key) {
// Arrays.sort(arr);
int idx = Arrays.binarySearch(arr, key);
if (idx >= 0) {
return arr[idx];
} else if ((idx + 1) * -1 < arr.length && (idx + 1) * -1 >= 0) return arr[(idx + 1) * -1];
return -1;
}
public static int upperBoundElement(int[] arr, int key) {
int idx = Arrays.binarySearch(arr, key);
if ((idx + 1) < arr.length && idx >= 0) {
return arr[idx + 1];
} else if ((idx + 1) * -1 < arr.length && (idx + 1) * -1 >= 0) return arr[(idx + 1) * -1];
return -1;
}
public static int upperBoundIndex(int[] arr, int key) {
int idx = Arrays.binarySearch(arr, key);
if ((idx + 1) < arr.length && idx >= 0) {
return idx + 1;
} else if ((idx + 1) * -1 < arr.length && (idx + 1) * -1 >= 0) return (idx + 1) * -1;
return -1;
}
public static boolean prime(int n) {
if (n == 1)
return false;
if (n == 2)
return true;
if (n % 2 == 0)
return false;
for (int i = 3; i * i <= n; i += 2)
if (n % i == 0)
return false;
return true;
}
//-------------------------------------------------------------------------------------------------------------------//
public static void main(String[] argus) throws IOException {
Flash flash = new Flash(System.in);
int t= flash.nextInt();
for(int i=0;i<t;i++){
int n= flash.nextInt();
int[] arr= new int[n];
for(int j=0;j<n;j++){
arr[j]=j+1;
}
sout.write(n+"\n");
for(int j=0;j<n;j++){
sout.write(arr[j]+" ");
}
sout.write("\n");
for(int j=n-1;j>0;j--){
int temp=arr[j];
arr[j]=arr[0];
arr[0]=temp;
for(int k=0;k<n;k++){
sout.write(arr[k]+" ");
}
sout.write("\n");
}
}
// 1 2 3 4
// 4 2 3 1
// 2 4 3 1
// 2 4 1 3
sout.flush();
}
//------------------------------------------------------------------------------------------------------------------//
}
/* *****to iterate through a map*****
for(Map.Entry<String, Integer> entry:map.entrySet()){}
*/
class Pair{
List<Integer> pos;
List<Integer> value;
public Pair(List<Integer> pos, List<Integer> value) {
this.pos=pos;
this.value=value;
}
public List<Integer> getLeft() {
return this.pos;
}
public List<Integer> getRight() {
return this.value;
}
public void setLeft(List<Integer> pos) {
this.pos=pos;
}
public void setRight(List<Integer> value) {
this.value=value;
}
public static void toString(List<Pair> pairs) {
for (int i = 0; i < pairs.size(); i++) {
System.out.print(pairs.get(i).getLeft() + " " + pairs.get(i).getRight());
System.out.println();
}
}
}
//7 7 6 4 2 2
//don't get panic, it's just speed code :)
class Flash {
StringTokenizer st;
BufferedReader br;
public Flash(File file) throws FileNotFoundException {
br = new BufferedReader(new FileReader(file));
}
public Flash(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public int[] intArr(int n) throws IOException {
int[] in = new int[n];
for (int i = 0; i < in.length; i++) in[i] = nextInt();
return in;
}
public long[] longArr(int n) throws IOException {
long[] in = new long[n];
for (int i = 0; i < in.length; i++) in[i] = nextLong();
return in;
}
public int[] intSortedArr(int n) throws IOException {
int[] in = new int[n];
for (int i = 0; i < in.length; i++) in[i] = nextInt();
shuffle(in);
Arrays.sort(in);
return in;
}
public long[] longSortedArr(int n) throws IOException {
long[] in = new long[n];
for (int i = 0; i < in.length; i++) in[i] = nextLong();
shuffle(in);
Arrays.sort(in);
return in;
}
static void shuffle(int[] in) {
for (int i = 0; i < in.length; i++) {
int idx = (int) (Math.random() * in.length);
int tmp = in[i];
in[i] = in[idx];
in[idx] = tmp;
}
}
static void shuffle(long[] in) {
for (int i = 0; i < in.length; i++) {
int idx = (int) (Math.random() * in.length);
long tmp = in[i];
in[i] = in[idx];
in[idx] = tmp;
}
}
} | Java | ["2\n\n2\n\n3"] | 2 seconds | ["2\n1 2\n2 1\n3\n1 2 3\n3 2 1\n3 1 2"] | null | Java 17 | standard input | [
"constructive algorithms",
"math"
] | 02bdd12987af6e666d4283f075f73725 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 99$$$) — the number of testcases. The only line of each testcase contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the required length of permutations in the chain. | 800 | For each testcase, first, print the length of a permutation chain $$$k$$$. Then print $$$k$$$ permutations $$$a_1, a_2, \dots, a_k$$$. $$$a_1$$$ should be an identity permutation of length $$$n$$$ ($$$[1, 2, \dots, n]$$$). For each $$$i$$$ from $$$2$$$ to $$$k$$$, $$$a_i$$$ should be obtained by swapping two elements in $$$a_{i-1}$$$. It should also have a strictly lower fixedness than $$$a_{i-1}$$$. | standard output | |
PASSED | 52f5283cec1bed64270cbe4fea6e7301 | train_109.jsonl | 1659623700 | A permutation of length $$$n$$$ is a sequence of integers from $$$1$$$ to $$$n$$$ such that each integer appears in it exactly once.Let the fixedness of a permutation $$$p$$$ be the number of fixed points in it — the number of positions $$$j$$$ such that $$$p_j = j$$$, where $$$p_j$$$ is the $$$j$$$-th element of the permutation $$$p$$$.You are asked to build a sequence of permutations $$$a_1, a_2, \dots$$$, starting from the identity permutation (permutation $$$a_1 = [1, 2, \dots, n]$$$). Let's call it a permutation chain. Thus, $$$a_i$$$ is the $$$i$$$-th permutation of length $$$n$$$.For every $$$i$$$ from $$$2$$$ onwards, the permutation $$$a_i$$$ should be obtained from the permutation $$$a_{i-1}$$$ by swapping any two elements in it (not necessarily neighboring). The fixedness of the permutation $$$a_i$$$ should be strictly lower than the fixedness of the permutation $$$a_{i-1}$$$.Consider some chains for $$$n = 3$$$: $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$ — that is a valid chain of length $$$2$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. $$$a_1 = [2, 1, 3]$$$, $$$a_2 = [3, 1, 2]$$$ — that is not a valid chain. The first permutation should always be $$$[1, 2, 3]$$$ for $$$n = 3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$, $$$a_3 = [1, 2, 3]$$$ — that is not a valid chain. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped but the fixedness increase from $$$1$$$ to $$$3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [3, 2, 1]$$$, $$$a_3 = [3, 1, 2]$$$ — that is a valid chain of length $$$3$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$1$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$1$$$ to $$$0$$$. Find the longest permutation chain. If there are multiple longest answers, print any of them. | 256 megabytes | import java.io.*;
import java.util.*;
public class AB {
public static void main(String args[]) throws IOException {
FastReader sc = new FastReader();
PrintWriter out = new PrintWriter(System.out);
int tc, i, j;
String s;
char p;
tc = sc.nextInt();
while (tc-- > 0) {
int n = sc.nextInt();
int arr[]=new int[n];
for (i = 0; i <n; i++)
arr[i]=i+1;
out.println(n);
for(int it:arr)
out.print(it+" ");
out.println();
for (i = 0; i < n-1; i++) {
int temp=arr[n-i-2];
arr[n-i-2]=arr[n-i-1];
arr[n-i-1]=temp;
for (j = 0; j < n; j++)
out.print(arr[j]+" ");
out.println();
}
}
out.close();
}
/*--------------------------------------------------------
----------------------------------------------------------*/
//Pair Class
public static class Pair implements Comparable<Pair> {
int x, y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Pair o) {
return this.x - o.x;
}
}
/*
FASTREADER
*/
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;
}
/*DEFINED BY ME*/
//READING ARRAY
int[] readArray(int n) {
int arr[] = new int[n];
for (int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
//COLLECTIONS SORT
void sort(int arr[]) {
ArrayList<Integer> l = new ArrayList<>();
for (int i : arr)
l.add(i);
Collections.sort(l);
for (int i = 0; i < arr.length; i++)
arr[i] = l.get(i);
}
//EUCLID'S GCD
int gcd(int a, int b) {
if (b != 0)
return gcd(b, a % b);
else
return a;
}
void swap(int arr[], int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
} | Java | ["2\n\n2\n\n3"] | 2 seconds | ["2\n1 2\n2 1\n3\n1 2 3\n3 2 1\n3 1 2"] | null | Java 17 | standard input | [
"constructive algorithms",
"math"
] | 02bdd12987af6e666d4283f075f73725 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 99$$$) — the number of testcases. The only line of each testcase contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the required length of permutations in the chain. | 800 | For each testcase, first, print the length of a permutation chain $$$k$$$. Then print $$$k$$$ permutations $$$a_1, a_2, \dots, a_k$$$. $$$a_1$$$ should be an identity permutation of length $$$n$$$ ($$$[1, 2, \dots, n]$$$). For each $$$i$$$ from $$$2$$$ to $$$k$$$, $$$a_i$$$ should be obtained by swapping two elements in $$$a_{i-1}$$$. It should also have a strictly lower fixedness than $$$a_{i-1}$$$. | standard output | |
PASSED | 3fe32e4ec9a5ae37b05cdca19132bef2 | train_109.jsonl | 1659623700 | A permutation of length $$$n$$$ is a sequence of integers from $$$1$$$ to $$$n$$$ such that each integer appears in it exactly once.Let the fixedness of a permutation $$$p$$$ be the number of fixed points in it — the number of positions $$$j$$$ such that $$$p_j = j$$$, where $$$p_j$$$ is the $$$j$$$-th element of the permutation $$$p$$$.You are asked to build a sequence of permutations $$$a_1, a_2, \dots$$$, starting from the identity permutation (permutation $$$a_1 = [1, 2, \dots, n]$$$). Let's call it a permutation chain. Thus, $$$a_i$$$ is the $$$i$$$-th permutation of length $$$n$$$.For every $$$i$$$ from $$$2$$$ onwards, the permutation $$$a_i$$$ should be obtained from the permutation $$$a_{i-1}$$$ by swapping any two elements in it (not necessarily neighboring). The fixedness of the permutation $$$a_i$$$ should be strictly lower than the fixedness of the permutation $$$a_{i-1}$$$.Consider some chains for $$$n = 3$$$: $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$ — that is a valid chain of length $$$2$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. $$$a_1 = [2, 1, 3]$$$, $$$a_2 = [3, 1, 2]$$$ — that is not a valid chain. The first permutation should always be $$$[1, 2, 3]$$$ for $$$n = 3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$, $$$a_3 = [1, 2, 3]$$$ — that is not a valid chain. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped but the fixedness increase from $$$1$$$ to $$$3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [3, 2, 1]$$$, $$$a_3 = [3, 1, 2]$$$ — that is a valid chain of length $$$3$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$1$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$1$$$ to $$$0$$$. Find the longest permutation chain. If there are multiple longest answers, print any of them. | 256 megabytes | import jdk.swing.interop.SwingInterOpUtils;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
public class Codechef {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
int t = sc.nextInt();
while(t-->0) {
int n = sc.nextInt();
StringBuilder sb = new StringBuilder();
int[] arr = new int[n+1];
for(int i=1;i<=n;i++){
arr[i]=i;
sb.append(i+" ");
}
System.out.println(n);
System.out.println(sb);
// System.out.println(Arrays.toString(arr));
swap(1,n,arr);
sb = new StringBuilder();
for(int j=1;j<=n;j++){
sb.append(arr[j]+" ");
}
System.out.println(sb);
if(n==2)
continue;
for(int i=2;i<n;i++){
swap(i,i-1,arr);
sb = new StringBuilder();
for(int j=1;j<=n;j++){
sb.append(arr[j]+" ");
}
System.out.println(sb);
}
}
}static void swap(int i ,int j , int[] arr){
int tmp = arr[i];
arr[i]=arr[j];
arr[j]=tmp;
}
}
| Java | ["2\n\n2\n\n3"] | 2 seconds | ["2\n1 2\n2 1\n3\n1 2 3\n3 2 1\n3 1 2"] | null | Java 17 | standard input | [
"constructive algorithms",
"math"
] | 02bdd12987af6e666d4283f075f73725 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 99$$$) — the number of testcases. The only line of each testcase contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the required length of permutations in the chain. | 800 | For each testcase, first, print the length of a permutation chain $$$k$$$. Then print $$$k$$$ permutations $$$a_1, a_2, \dots, a_k$$$. $$$a_1$$$ should be an identity permutation of length $$$n$$$ ($$$[1, 2, \dots, n]$$$). For each $$$i$$$ from $$$2$$$ to $$$k$$$, $$$a_i$$$ should be obtained by swapping two elements in $$$a_{i-1}$$$. It should also have a strictly lower fixedness than $$$a_{i-1}$$$. | standard output | |
PASSED | 866b3fbc76c1c8742f89e0c16c1d04e3 | train_109.jsonl | 1659623700 | A permutation of length $$$n$$$ is a sequence of integers from $$$1$$$ to $$$n$$$ such that each integer appears in it exactly once.Let the fixedness of a permutation $$$p$$$ be the number of fixed points in it — the number of positions $$$j$$$ such that $$$p_j = j$$$, where $$$p_j$$$ is the $$$j$$$-th element of the permutation $$$p$$$.You are asked to build a sequence of permutations $$$a_1, a_2, \dots$$$, starting from the identity permutation (permutation $$$a_1 = [1, 2, \dots, n]$$$). Let's call it a permutation chain. Thus, $$$a_i$$$ is the $$$i$$$-th permutation of length $$$n$$$.For every $$$i$$$ from $$$2$$$ onwards, the permutation $$$a_i$$$ should be obtained from the permutation $$$a_{i-1}$$$ by swapping any two elements in it (not necessarily neighboring). The fixedness of the permutation $$$a_i$$$ should be strictly lower than the fixedness of the permutation $$$a_{i-1}$$$.Consider some chains for $$$n = 3$$$: $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$ — that is a valid chain of length $$$2$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. $$$a_1 = [2, 1, 3]$$$, $$$a_2 = [3, 1, 2]$$$ — that is not a valid chain. The first permutation should always be $$$[1, 2, 3]$$$ for $$$n = 3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$, $$$a_3 = [1, 2, 3]$$$ — that is not a valid chain. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped but the fixedness increase from $$$1$$$ to $$$3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [3, 2, 1]$$$, $$$a_3 = [3, 1, 2]$$$ — that is a valid chain of length $$$3$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$1$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$1$$$ to $$$0$$$. Find the longest permutation chain. If there are multiple longest answers, print any of them. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main implements Runnable {
public void solve() throws IOException {
var T = readInt();
while (T-- > 0)
solveTestCase();
}
private void solveTestCase() throws IOException {
int n = readInt();
out.println(n);
int[] a = new int[n];
for(int i = 0; i < n; i++) a[i] = i + 1;
printIt(a);
for(int i = 0; i < n-1; i ++){
int t = a[i];
a[i] = a[i+1];
a[i+1] = t;
printIt(a);
}
}
private void printIt(int[] a){
StringBuilder sb = new StringBuilder();
for(int i = 0; i < a.length; i++){
if(i > 0) sb.append(" ");
sb.append(a[i]);
}
out.println(sb.toString());
}
//-----------------------------------------------------------
public static void main(String[] args) {
new Main().run();
}
public void debug(Object... arr) {
System.out.println(Arrays.deepToString(arr));
}
public void print1Int(int[] a) {
for (int i = 0; i < a.length; i++)
System.out.print(a[i] + " ");
System.out.println();
}
public void print2Int(int[][] a) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
tok = null;
solve();
in.close();
out.close();
} catch (IOException e) {
System.exit(0);
}
}
public String readToken() throws IOException {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
public int readInt() throws IOException {
return Integer.parseInt(readToken());
}
public long readLong() throws IOException {
return Long.parseLong(readToken());
}
public double readDouble() throws IOException {
return Double.parseDouble(readToken());
}
PrintWriter out;
BufferedReader in;
StringTokenizer tok;
} | Java | ["2\n\n2\n\n3"] | 2 seconds | ["2\n1 2\n2 1\n3\n1 2 3\n3 2 1\n3 1 2"] | null | Java 17 | standard input | [
"constructive algorithms",
"math"
] | 02bdd12987af6e666d4283f075f73725 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 99$$$) — the number of testcases. The only line of each testcase contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the required length of permutations in the chain. | 800 | For each testcase, first, print the length of a permutation chain $$$k$$$. Then print $$$k$$$ permutations $$$a_1, a_2, \dots, a_k$$$. $$$a_1$$$ should be an identity permutation of length $$$n$$$ ($$$[1, 2, \dots, n]$$$). For each $$$i$$$ from $$$2$$$ to $$$k$$$, $$$a_i$$$ should be obtained by swapping two elements in $$$a_{i-1}$$$. It should also have a strictly lower fixedness than $$$a_{i-1}$$$. | standard output | |
PASSED | ef713b21fd7e6acdaaee8804e4cd5d4c | train_109.jsonl | 1659623700 | A permutation of length $$$n$$$ is a sequence of integers from $$$1$$$ to $$$n$$$ such that each integer appears in it exactly once.Let the fixedness of a permutation $$$p$$$ be the number of fixed points in it — the number of positions $$$j$$$ such that $$$p_j = j$$$, where $$$p_j$$$ is the $$$j$$$-th element of the permutation $$$p$$$.You are asked to build a sequence of permutations $$$a_1, a_2, \dots$$$, starting from the identity permutation (permutation $$$a_1 = [1, 2, \dots, n]$$$). Let's call it a permutation chain. Thus, $$$a_i$$$ is the $$$i$$$-th permutation of length $$$n$$$.For every $$$i$$$ from $$$2$$$ onwards, the permutation $$$a_i$$$ should be obtained from the permutation $$$a_{i-1}$$$ by swapping any two elements in it (not necessarily neighboring). The fixedness of the permutation $$$a_i$$$ should be strictly lower than the fixedness of the permutation $$$a_{i-1}$$$.Consider some chains for $$$n = 3$$$: $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$ — that is a valid chain of length $$$2$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. $$$a_1 = [2, 1, 3]$$$, $$$a_2 = [3, 1, 2]$$$ — that is not a valid chain. The first permutation should always be $$$[1, 2, 3]$$$ for $$$n = 3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$, $$$a_3 = [1, 2, 3]$$$ — that is not a valid chain. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped but the fixedness increase from $$$1$$$ to $$$3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [3, 2, 1]$$$, $$$a_3 = [3, 1, 2]$$$ — that is a valid chain of length $$$3$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$1$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$1$$$ to $$$0$$$. Find the longest permutation chain. If there are multiple longest answers, print any of them. | 256 megabytes | import java.util.*;
import java.io.*;
public class B {
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() throws IOException{
return Integer.parseInt(next());
}
long nextLong(){
return Long.parseLong(next());
}
double nextDouble(){
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
if(st.hasMoreTokens()){
str = st.nextToken("\n");
}
else{
str = br.readLine();
}
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] nextArray(int n){
int[] a = new int[n];
for(int i = 0; i < n; i++){
a[i] = Integer.parseInt(next());
}
return a;
}
}
public static void main(String[] args) throws IOException
{
// System.setIn(new FileInputStream(new File("/Users/pluo/Desktop/CF/input.txt")));
// System.setOut(new PrintStream(new File("/Users/pluo/Desktop/CF/output.txt")));
FastReader sc = new FastReader();
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
int tt = sc.nextInt();
for(int a0 = 0; a0 < tt; a0++){
int n = sc.nextInt();
out.write(n + "\n");
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++){
if(j < i){
out.write(j+1 + " ");
}
else if(j > i){
out.write(j + " ");
}
else{
out.write(1 + " ");
}
}
out.write("\n");
}
}
out.flush();
}
}
| Java | ["2\n\n2\n\n3"] | 2 seconds | ["2\n1 2\n2 1\n3\n1 2 3\n3 2 1\n3 1 2"] | null | Java 17 | standard input | [
"constructive algorithms",
"math"
] | 02bdd12987af6e666d4283f075f73725 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 99$$$) — the number of testcases. The only line of each testcase contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the required length of permutations in the chain. | 800 | For each testcase, first, print the length of a permutation chain $$$k$$$. Then print $$$k$$$ permutations $$$a_1, a_2, \dots, a_k$$$. $$$a_1$$$ should be an identity permutation of length $$$n$$$ ($$$[1, 2, \dots, n]$$$). For each $$$i$$$ from $$$2$$$ to $$$k$$$, $$$a_i$$$ should be obtained by swapping two elements in $$$a_{i-1}$$$. It should also have a strictly lower fixedness than $$$a_{i-1}$$$. | standard output | |
PASSED | 31bc7309395f8a97ceaa402740519020 | train_109.jsonl | 1659623700 | A permutation of length $$$n$$$ is a sequence of integers from $$$1$$$ to $$$n$$$ such that each integer appears in it exactly once.Let the fixedness of a permutation $$$p$$$ be the number of fixed points in it — the number of positions $$$j$$$ such that $$$p_j = j$$$, where $$$p_j$$$ is the $$$j$$$-th element of the permutation $$$p$$$.You are asked to build a sequence of permutations $$$a_1, a_2, \dots$$$, starting from the identity permutation (permutation $$$a_1 = [1, 2, \dots, n]$$$). Let's call it a permutation chain. Thus, $$$a_i$$$ is the $$$i$$$-th permutation of length $$$n$$$.For every $$$i$$$ from $$$2$$$ onwards, the permutation $$$a_i$$$ should be obtained from the permutation $$$a_{i-1}$$$ by swapping any two elements in it (not necessarily neighboring). The fixedness of the permutation $$$a_i$$$ should be strictly lower than the fixedness of the permutation $$$a_{i-1}$$$.Consider some chains for $$$n = 3$$$: $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$ — that is a valid chain of length $$$2$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. $$$a_1 = [2, 1, 3]$$$, $$$a_2 = [3, 1, 2]$$$ — that is not a valid chain. The first permutation should always be $$$[1, 2, 3]$$$ for $$$n = 3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$, $$$a_3 = [1, 2, 3]$$$ — that is not a valid chain. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped but the fixedness increase from $$$1$$$ to $$$3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [3, 2, 1]$$$, $$$a_3 = [3, 1, 2]$$$ — that is a valid chain of length $$$3$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$1$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$1$$$ to $$$0$$$. Find the longest permutation chain. If there are multiple longest answers, print any of them. | 256 megabytes | import java.io.*;
import java.util.*;
public class B {
Input in;
PrintWriter out;
public B() {
in = new Input(System.in);
out = new PrintWriter(System.out);
}
public static void main(String[] args) {
B solution = new B();
for (int t = solution.in.nextInt(); t > 0; t--) {
solution.solve();
}
solution.out.close();
}
void solve() {
int n = in.nextInt();
int[] p = new int[n];
for (int i=0; i<n; i++) p[i] = i+1;
out.println(n);
print(p);
p[n-1] = n-1;
p[n-2] = n;
print(p);
for (int i=n-3; i>=0; i--) {
int temp = p[i];
p[i] = p[n-1];
p[n-1] = temp;
print(p);
}
}
void print(int[] a) {
for (int i=0; i<a.length; i++) {
out.print(a[i]);
out.print(' ');
}
out.println();
}
static class Input {
BufferedReader br;
StringTokenizer st;
public Input(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
st = new StringTokenizer("");
}
String nextString() {
while (!st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(nextString());
}
long nextLong() {
return Long.parseLong(nextString());
}
int[] nextIntArray(int size) {
int[] ans = new int[size];
for (int i = 0; i < size; i++) {
ans[i] = nextInt();
}
return ans;
}
}
} | Java | ["2\n\n2\n\n3"] | 2 seconds | ["2\n1 2\n2 1\n3\n1 2 3\n3 2 1\n3 1 2"] | null | Java 17 | standard input | [
"constructive algorithms",
"math"
] | 02bdd12987af6e666d4283f075f73725 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 99$$$) — the number of testcases. The only line of each testcase contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the required length of permutations in the chain. | 800 | For each testcase, first, print the length of a permutation chain $$$k$$$. Then print $$$k$$$ permutations $$$a_1, a_2, \dots, a_k$$$. $$$a_1$$$ should be an identity permutation of length $$$n$$$ ($$$[1, 2, \dots, n]$$$). For each $$$i$$$ from $$$2$$$ to $$$k$$$, $$$a_i$$$ should be obtained by swapping two elements in $$$a_{i-1}$$$. It should also have a strictly lower fixedness than $$$a_{i-1}$$$. | standard output | |
PASSED | 1d338575a397fcd3f9c8240a09cdf142 | train_109.jsonl | 1659623700 | A permutation of length $$$n$$$ is a sequence of integers from $$$1$$$ to $$$n$$$ such that each integer appears in it exactly once.Let the fixedness of a permutation $$$p$$$ be the number of fixed points in it — the number of positions $$$j$$$ such that $$$p_j = j$$$, where $$$p_j$$$ is the $$$j$$$-th element of the permutation $$$p$$$.You are asked to build a sequence of permutations $$$a_1, a_2, \dots$$$, starting from the identity permutation (permutation $$$a_1 = [1, 2, \dots, n]$$$). Let's call it a permutation chain. Thus, $$$a_i$$$ is the $$$i$$$-th permutation of length $$$n$$$.For every $$$i$$$ from $$$2$$$ onwards, the permutation $$$a_i$$$ should be obtained from the permutation $$$a_{i-1}$$$ by swapping any two elements in it (not necessarily neighboring). The fixedness of the permutation $$$a_i$$$ should be strictly lower than the fixedness of the permutation $$$a_{i-1}$$$.Consider some chains for $$$n = 3$$$: $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$ — that is a valid chain of length $$$2$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. $$$a_1 = [2, 1, 3]$$$, $$$a_2 = [3, 1, 2]$$$ — that is not a valid chain. The first permutation should always be $$$[1, 2, 3]$$$ for $$$n = 3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$, $$$a_3 = [1, 2, 3]$$$ — that is not a valid chain. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped but the fixedness increase from $$$1$$$ to $$$3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [3, 2, 1]$$$, $$$a_3 = [3, 1, 2]$$$ — that is a valid chain of length $$$3$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$1$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$1$$$ to $$$0$$$. Find the longest permutation chain. If there are multiple longest answers, print any of them. | 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
*/
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);
BPermutationChain solver = new BPermutationChain();
solver.solve(1, in, out);
out.close();
}
static class BPermutationChain {
public void solve(int testNumber, InputReader in, OutputWriter out) {
var tc = in.nextInt();
for (int i = 0; i < tc; i++) {
solution(i, in, out);
}
}
void solution(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
// we want to increment by 1 at each step
// swap 1 with 2, then swap 2 with 3.. etc
// maximum we can do is n steps
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = i + 1;
}
out.println(n);
out.println(arr);
for (int i = 0; i < n - 1; i++) {
int temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
out.println(arr);
}
}
}
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);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(int[] array) {
for (int i = 0; i < array.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(array[i]);
}
}
public void println(int[] array) {
print(array);
writer.println();
}
public void close() {
writer.close();
}
public void println(int i) {
writer.println(i);
}
}
}
| Java | ["2\n\n2\n\n3"] | 2 seconds | ["2\n1 2\n2 1\n3\n1 2 3\n3 2 1\n3 1 2"] | null | Java 17 | standard input | [
"constructive algorithms",
"math"
] | 02bdd12987af6e666d4283f075f73725 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 99$$$) — the number of testcases. The only line of each testcase contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the required length of permutations in the chain. | 800 | For each testcase, first, print the length of a permutation chain $$$k$$$. Then print $$$k$$$ permutations $$$a_1, a_2, \dots, a_k$$$. $$$a_1$$$ should be an identity permutation of length $$$n$$$ ($$$[1, 2, \dots, n]$$$). For each $$$i$$$ from $$$2$$$ to $$$k$$$, $$$a_i$$$ should be obtained by swapping two elements in $$$a_{i-1}$$$. It should also have a strictly lower fixedness than $$$a_{i-1}$$$. | standard output | |
PASSED | dc9aacfa21749779103a1de09f91dabe | train_109.jsonl | 1659623700 | A permutation of length $$$n$$$ is a sequence of integers from $$$1$$$ to $$$n$$$ such that each integer appears in it exactly once.Let the fixedness of a permutation $$$p$$$ be the number of fixed points in it — the number of positions $$$j$$$ such that $$$p_j = j$$$, where $$$p_j$$$ is the $$$j$$$-th element of the permutation $$$p$$$.You are asked to build a sequence of permutations $$$a_1, a_2, \dots$$$, starting from the identity permutation (permutation $$$a_1 = [1, 2, \dots, n]$$$). Let's call it a permutation chain. Thus, $$$a_i$$$ is the $$$i$$$-th permutation of length $$$n$$$.For every $$$i$$$ from $$$2$$$ onwards, the permutation $$$a_i$$$ should be obtained from the permutation $$$a_{i-1}$$$ by swapping any two elements in it (not necessarily neighboring). The fixedness of the permutation $$$a_i$$$ should be strictly lower than the fixedness of the permutation $$$a_{i-1}$$$.Consider some chains for $$$n = 3$$$: $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$ — that is a valid chain of length $$$2$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. $$$a_1 = [2, 1, 3]$$$, $$$a_2 = [3, 1, 2]$$$ — that is not a valid chain. The first permutation should always be $$$[1, 2, 3]$$$ for $$$n = 3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$, $$$a_3 = [1, 2, 3]$$$ — that is not a valid chain. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped but the fixedness increase from $$$1$$$ to $$$3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [3, 2, 1]$$$, $$$a_3 = [3, 1, 2]$$$ — that is a valid chain of length $$$3$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$1$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$1$$$ to $$$0$$$. Find the longest permutation chain. If there are multiple longest answers, print any of them. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class Codechef {
private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
private static PrintWriter pw = new PrintWriter(System.out);
private static Scanner sc = new Scanner(System.in);
static void printPerm(int[] arr) {
for (int x = 0; x < arr.length; x++)
pw.print(arr[x] + " ");
pw.println();
}
static void getRes() throws Exception {
int n = Integer.parseInt(br.readLine());
int[] arr = new int[n];
for (int x = 0; x < n; x++) arr[x] = x + 1;
pw.println(n);
for (int x = 0; x < n - 1; x++) {
printPerm(arr);
arr[x] += arr[n - 1];
arr[n - 1] = arr[x] - arr[n - 1];
arr[x] = arr[x] - arr[n - 1];
}
printArray(arr);
}
public static void main(String[] args) throws Exception {
int tests = Integer.parseInt(br.readLine());
while (tests-- > 0) {
getRes();
}
pw.flush();
pw.close();
}
static int[] inputIntArray(int n) throws Exception {
int[] arr = new int[n];
String[] inp = br.readLine().split(" ");
for (int x = 0; x < n; x++)
arr[x] = Integer.parseInt(inp[x]);
return arr;
}
static long[] inputLongArray(int n) throws Exception {
long[] arr = new long[n];
String[] inp = br.readLine().split(" ");
for (int x = 0; x < n; x++)
arr[x] = Integer.parseInt(inp[x]);
return arr;
}
static void printArray(int[] arr) {
for (int x = 0; x < arr.length; x++)
pw.print(arr[x] + " ");
pw.println();
}
} | Java | ["2\n\n2\n\n3"] | 2 seconds | ["2\n1 2\n2 1\n3\n1 2 3\n3 2 1\n3 1 2"] | null | Java 17 | standard input | [
"constructive algorithms",
"math"
] | 02bdd12987af6e666d4283f075f73725 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 99$$$) — the number of testcases. The only line of each testcase contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the required length of permutations in the chain. | 800 | For each testcase, first, print the length of a permutation chain $$$k$$$. Then print $$$k$$$ permutations $$$a_1, a_2, \dots, a_k$$$. $$$a_1$$$ should be an identity permutation of length $$$n$$$ ($$$[1, 2, \dots, n]$$$). For each $$$i$$$ from $$$2$$$ to $$$k$$$, $$$a_i$$$ should be obtained by swapping two elements in $$$a_{i-1}$$$. It should also have a strictly lower fixedness than $$$a_{i-1}$$$. | standard output | |
PASSED | 494fceffe66bea00bce21a96e8181de6 | train_109.jsonl | 1659623700 | A permutation of length $$$n$$$ is a sequence of integers from $$$1$$$ to $$$n$$$ such that each integer appears in it exactly once.Let the fixedness of a permutation $$$p$$$ be the number of fixed points in it — the number of positions $$$j$$$ such that $$$p_j = j$$$, where $$$p_j$$$ is the $$$j$$$-th element of the permutation $$$p$$$.You are asked to build a sequence of permutations $$$a_1, a_2, \dots$$$, starting from the identity permutation (permutation $$$a_1 = [1, 2, \dots, n]$$$). Let's call it a permutation chain. Thus, $$$a_i$$$ is the $$$i$$$-th permutation of length $$$n$$$.For every $$$i$$$ from $$$2$$$ onwards, the permutation $$$a_i$$$ should be obtained from the permutation $$$a_{i-1}$$$ by swapping any two elements in it (not necessarily neighboring). The fixedness of the permutation $$$a_i$$$ should be strictly lower than the fixedness of the permutation $$$a_{i-1}$$$.Consider some chains for $$$n = 3$$$: $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$ — that is a valid chain of length $$$2$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. $$$a_1 = [2, 1, 3]$$$, $$$a_2 = [3, 1, 2]$$$ — that is not a valid chain. The first permutation should always be $$$[1, 2, 3]$$$ for $$$n = 3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$, $$$a_3 = [1, 2, 3]$$$ — that is not a valid chain. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped but the fixedness increase from $$$1$$$ to $$$3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [3, 2, 1]$$$, $$$a_3 = [3, 1, 2]$$$ — that is a valid chain of length $$$3$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$1$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$1$$$ to $$$0$$$. Find the longest permutation chain. If there are multiple longest answers, print any of them. | 256 megabytes | //package com.tdorosz._1716;
import java.util.Scanner;
public class PermutationChain {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int testCases = scanner.nextInt();
for (int i = 0; i < testCases; i++) {
executeTestCase(scanner);
}
}
private static void executeTestCase(Scanner scanner) {
int numberOfIntegers = scanner.nextInt();
System.out.println(numberOfIntegers);
String[] array = new String[numberOfIntegers];
for (int i = 0; i < numberOfIntegers; i++) {
array[i] = Integer.toString(i + 1);
}
for (int i = 0; i < numberOfIntegers; i++) {
swap(array, 0, i);
String permutation = String.join(" ", array);
System.out.println(permutation);
}
}
private static void swap(String[] array, int a, int b) {
String tmp = array[a];
array[a] = array[b];
array[b] = tmp;
}
}
| Java | ["2\n\n2\n\n3"] | 2 seconds | ["2\n1 2\n2 1\n3\n1 2 3\n3 2 1\n3 1 2"] | null | Java 17 | standard input | [
"constructive algorithms",
"math"
] | 02bdd12987af6e666d4283f075f73725 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 99$$$) — the number of testcases. The only line of each testcase contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the required length of permutations in the chain. | 800 | For each testcase, first, print the length of a permutation chain $$$k$$$. Then print $$$k$$$ permutations $$$a_1, a_2, \dots, a_k$$$. $$$a_1$$$ should be an identity permutation of length $$$n$$$ ($$$[1, 2, \dots, n]$$$). For each $$$i$$$ from $$$2$$$ to $$$k$$$, $$$a_i$$$ should be obtained by swapping two elements in $$$a_{i-1}$$$. It should also have a strictly lower fixedness than $$$a_{i-1}$$$. | standard output | |
PASSED | afd9928ef7b50eaf29876fa7bbac1451 | train_109.jsonl | 1659623700 | A permutation of length $$$n$$$ is a sequence of integers from $$$1$$$ to $$$n$$$ such that each integer appears in it exactly once.Let the fixedness of a permutation $$$p$$$ be the number of fixed points in it — the number of positions $$$j$$$ such that $$$p_j = j$$$, where $$$p_j$$$ is the $$$j$$$-th element of the permutation $$$p$$$.You are asked to build a sequence of permutations $$$a_1, a_2, \dots$$$, starting from the identity permutation (permutation $$$a_1 = [1, 2, \dots, n]$$$). Let's call it a permutation chain. Thus, $$$a_i$$$ is the $$$i$$$-th permutation of length $$$n$$$.For every $$$i$$$ from $$$2$$$ onwards, the permutation $$$a_i$$$ should be obtained from the permutation $$$a_{i-1}$$$ by swapping any two elements in it (not necessarily neighboring). The fixedness of the permutation $$$a_i$$$ should be strictly lower than the fixedness of the permutation $$$a_{i-1}$$$.Consider some chains for $$$n = 3$$$: $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$ — that is a valid chain of length $$$2$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. $$$a_1 = [2, 1, 3]$$$, $$$a_2 = [3, 1, 2]$$$ — that is not a valid chain. The first permutation should always be $$$[1, 2, 3]$$$ for $$$n = 3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$, $$$a_3 = [1, 2, 3]$$$ — that is not a valid chain. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped but the fixedness increase from $$$1$$$ to $$$3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [3, 2, 1]$$$, $$$a_3 = [3, 1, 2]$$$ — that is a valid chain of length $$$3$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$1$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$1$$$ to $$$0$$$. Find the longest permutation chain. If there are multiple longest answers, print any of them. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class TaskB {
public static void main(String[] args) {
FastScanner in = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
TaskB s = new TaskB();
s.solve(in, out);
out.flush();
}
void solveOne(FastScanner in, PrintWriter out) {
int n = in.nextInt();
int[] a = new int[n];
out.println(n);
for (int i = 0; i < n; i++) {
a[i] = i + 1;
out.printf("%d ", a[i]);
}
out.println("");
for (int i = 1; i < n; i++) {
// swap a[i] and a[0]
int t = a[i];
a[i] = a[0];
a[0] = t;
for (int x : a) {
out.printf("%d ", x);
}
out.println("");
}
}
void solve(FastScanner in, PrintWriter out) {
int t = 1;
t = in.nextInt();
for (int tc = 1; tc <= t; tc++) {
// out.printf("Case #%d: ", tc);
solveOne(in, out);
}
}
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
float nextFloat() { return Float.parseFloat(next()); }
double nextDouble() { return Double.parseDouble(next()); }
}
} | Java | ["2\n\n2\n\n3"] | 2 seconds | ["2\n1 2\n2 1\n3\n1 2 3\n3 2 1\n3 1 2"] | null | Java 17 | standard input | [
"constructive algorithms",
"math"
] | 02bdd12987af6e666d4283f075f73725 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 99$$$) — the number of testcases. The only line of each testcase contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the required length of permutations in the chain. | 800 | For each testcase, first, print the length of a permutation chain $$$k$$$. Then print $$$k$$$ permutations $$$a_1, a_2, \dots, a_k$$$. $$$a_1$$$ should be an identity permutation of length $$$n$$$ ($$$[1, 2, \dots, n]$$$). For each $$$i$$$ from $$$2$$$ to $$$k$$$, $$$a_i$$$ should be obtained by swapping two elements in $$$a_{i-1}$$$. It should also have a strictly lower fixedness than $$$a_{i-1}$$$. | standard output | |
PASSED | 765ed9340f0dfb910d235a25d0f9f449 | train_109.jsonl | 1659623700 | A permutation of length $$$n$$$ is a sequence of integers from $$$1$$$ to $$$n$$$ such that each integer appears in it exactly once.Let the fixedness of a permutation $$$p$$$ be the number of fixed points in it — the number of positions $$$j$$$ such that $$$p_j = j$$$, where $$$p_j$$$ is the $$$j$$$-th element of the permutation $$$p$$$.You are asked to build a sequence of permutations $$$a_1, a_2, \dots$$$, starting from the identity permutation (permutation $$$a_1 = [1, 2, \dots, n]$$$). Let's call it a permutation chain. Thus, $$$a_i$$$ is the $$$i$$$-th permutation of length $$$n$$$.For every $$$i$$$ from $$$2$$$ onwards, the permutation $$$a_i$$$ should be obtained from the permutation $$$a_{i-1}$$$ by swapping any two elements in it (not necessarily neighboring). The fixedness of the permutation $$$a_i$$$ should be strictly lower than the fixedness of the permutation $$$a_{i-1}$$$.Consider some chains for $$$n = 3$$$: $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$ — that is a valid chain of length $$$2$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. $$$a_1 = [2, 1, 3]$$$, $$$a_2 = [3, 1, 2]$$$ — that is not a valid chain. The first permutation should always be $$$[1, 2, 3]$$$ for $$$n = 3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$, $$$a_3 = [1, 2, 3]$$$ — that is not a valid chain. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped but the fixedness increase from $$$1$$$ to $$$3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [3, 2, 1]$$$, $$$a_3 = [3, 1, 2]$$$ — that is a valid chain of length $$$3$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$1$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$1$$$ to $$$0$$$. Find the longest permutation chain. If there are multiple longest answers, print any of them. | 256 megabytes | import java.io.*;
import java.util.*;
public class permchain {
public static void main(String args[]) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
int t = Integer.parseInt(br.readLine());
for (int i = 0; i < t; i++) {
int n = Integer.parseInt(br.readLine());
pw.println(n);
int[] arr = new int[n];
int add = 1;
for (int j = 0; j < n; j++) {
arr[j] = add;
add++;
}
for (int j = 0; j < n; j++) {
for (int l = 0; l < n; l++) {
pw.print(arr[l] + " ");
}
pw.println();
if (j + 1 < n) {
int temp = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = temp;
}
}
}
pw.close();
br.close();
}
}
| Java | ["2\n\n2\n\n3"] | 2 seconds | ["2\n1 2\n2 1\n3\n1 2 3\n3 2 1\n3 1 2"] | null | Java 17 | standard input | [
"constructive algorithms",
"math"
] | 02bdd12987af6e666d4283f075f73725 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 99$$$) — the number of testcases. The only line of each testcase contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the required length of permutations in the chain. | 800 | For each testcase, first, print the length of a permutation chain $$$k$$$. Then print $$$k$$$ permutations $$$a_1, a_2, \dots, a_k$$$. $$$a_1$$$ should be an identity permutation of length $$$n$$$ ($$$[1, 2, \dots, n]$$$). For each $$$i$$$ from $$$2$$$ to $$$k$$$, $$$a_i$$$ should be obtained by swapping two elements in $$$a_{i-1}$$$. It should also have a strictly lower fixedness than $$$a_{i-1}$$$. | standard output | |
PASSED | 6f844840c5a78095f5e93a1c835382e2 | train_109.jsonl | 1659623700 | A permutation of length $$$n$$$ is a sequence of integers from $$$1$$$ to $$$n$$$ such that each integer appears in it exactly once.Let the fixedness of a permutation $$$p$$$ be the number of fixed points in it — the number of positions $$$j$$$ such that $$$p_j = j$$$, where $$$p_j$$$ is the $$$j$$$-th element of the permutation $$$p$$$.You are asked to build a sequence of permutations $$$a_1, a_2, \dots$$$, starting from the identity permutation (permutation $$$a_1 = [1, 2, \dots, n]$$$). Let's call it a permutation chain. Thus, $$$a_i$$$ is the $$$i$$$-th permutation of length $$$n$$$.For every $$$i$$$ from $$$2$$$ onwards, the permutation $$$a_i$$$ should be obtained from the permutation $$$a_{i-1}$$$ by swapping any two elements in it (not necessarily neighboring). The fixedness of the permutation $$$a_i$$$ should be strictly lower than the fixedness of the permutation $$$a_{i-1}$$$.Consider some chains for $$$n = 3$$$: $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$ — that is a valid chain of length $$$2$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. $$$a_1 = [2, 1, 3]$$$, $$$a_2 = [3, 1, 2]$$$ — that is not a valid chain. The first permutation should always be $$$[1, 2, 3]$$$ for $$$n = 3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$, $$$a_3 = [1, 2, 3]$$$ — that is not a valid chain. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped but the fixedness increase from $$$1$$$ to $$$3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [3, 2, 1]$$$, $$$a_3 = [3, 1, 2]$$$ — that is a valid chain of length $$$3$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$1$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$1$$$ to $$$0$$$. Find the longest permutation chain. If there are multiple longest answers, print any of them. | 256 megabytes |
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException{
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int t = sc.nextInt();
while(t --> 0)
{
int n = sc.nextInt();
int[] current = new int[n];
pw.println(n);
for(int i = 0 ; i < n ; i++)
current[i] = i+1;
for(int k = 0 ; k < n - 1 ; k++)
{
for(int i = 0 ; i < current.length ; i++)
pw.print(current[i] + " ");
pw.println();
current[k] += k+1;
current[k+1] = 1;
}
for(int i = 0 ; i < current.length ; i++)
pw.print(current[i] + " ");
pw.println();
}
pw.flush();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(String s) throws FileNotFoundException {
br = new BufferedReader(new FileReader(s));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
| Java | ["2\n\n2\n\n3"] | 2 seconds | ["2\n1 2\n2 1\n3\n1 2 3\n3 2 1\n3 1 2"] | null | Java 17 | standard input | [
"constructive algorithms",
"math"
] | 02bdd12987af6e666d4283f075f73725 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 99$$$) — the number of testcases. The only line of each testcase contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the required length of permutations in the chain. | 800 | For each testcase, first, print the length of a permutation chain $$$k$$$. Then print $$$k$$$ permutations $$$a_1, a_2, \dots, a_k$$$. $$$a_1$$$ should be an identity permutation of length $$$n$$$ ($$$[1, 2, \dots, n]$$$). For each $$$i$$$ from $$$2$$$ to $$$k$$$, $$$a_i$$$ should be obtained by swapping two elements in $$$a_{i-1}$$$. It should also have a strictly lower fixedness than $$$a_{i-1}$$$. | standard output | |
PASSED | 724b4971d2da2f91d0ca1977c93bdb52 | train_109.jsonl | 1659623700 | A permutation of length $$$n$$$ is a sequence of integers from $$$1$$$ to $$$n$$$ such that each integer appears in it exactly once.Let the fixedness of a permutation $$$p$$$ be the number of fixed points in it — the number of positions $$$j$$$ such that $$$p_j = j$$$, where $$$p_j$$$ is the $$$j$$$-th element of the permutation $$$p$$$.You are asked to build a sequence of permutations $$$a_1, a_2, \dots$$$, starting from the identity permutation (permutation $$$a_1 = [1, 2, \dots, n]$$$). Let's call it a permutation chain. Thus, $$$a_i$$$ is the $$$i$$$-th permutation of length $$$n$$$.For every $$$i$$$ from $$$2$$$ onwards, the permutation $$$a_i$$$ should be obtained from the permutation $$$a_{i-1}$$$ by swapping any two elements in it (not necessarily neighboring). The fixedness of the permutation $$$a_i$$$ should be strictly lower than the fixedness of the permutation $$$a_{i-1}$$$.Consider some chains for $$$n = 3$$$: $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$ — that is a valid chain of length $$$2$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. $$$a_1 = [2, 1, 3]$$$, $$$a_2 = [3, 1, 2]$$$ — that is not a valid chain. The first permutation should always be $$$[1, 2, 3]$$$ for $$$n = 3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$, $$$a_3 = [1, 2, 3]$$$ — that is not a valid chain. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped but the fixedness increase from $$$1$$$ to $$$3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [3, 2, 1]$$$, $$$a_3 = [3, 1, 2]$$$ — that is a valid chain of length $$$3$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$1$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$1$$$ to $$$0$$$. Find the longest permutation chain. If there are multiple longest answers, print any of them. | 256 megabytes | import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for (int tc = 0; tc < t; ++tc) {
int n = sc.nextInt();
System.out.println(solve(n));
}
sc.close();
}
static String solve(int n) {
List<String> permutations = new ArrayList<>();
int[] a = IntStream.rangeClosed(1, n).toArray();
for (int i = 0; i < n; ++i) {
permutations.add(Arrays.stream(a).mapToObj(String::valueOf).collect(Collectors.joining(" ")));
if (i != n - 1) {
int temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
}
}
return String.format("%d\n%s", permutations.size(), String.join("\n", permutations));
}
} | Java | ["2\n\n2\n\n3"] | 2 seconds | ["2\n1 2\n2 1\n3\n1 2 3\n3 2 1\n3 1 2"] | null | Java 17 | standard input | [
"constructive algorithms",
"math"
] | 02bdd12987af6e666d4283f075f73725 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 99$$$) — the number of testcases. The only line of each testcase contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the required length of permutations in the chain. | 800 | For each testcase, first, print the length of a permutation chain $$$k$$$. Then print $$$k$$$ permutations $$$a_1, a_2, \dots, a_k$$$. $$$a_1$$$ should be an identity permutation of length $$$n$$$ ($$$[1, 2, \dots, n]$$$). For each $$$i$$$ from $$$2$$$ to $$$k$$$, $$$a_i$$$ should be obtained by swapping two elements in $$$a_{i-1}$$$. It should also have a strictly lower fixedness than $$$a_{i-1}$$$. | standard output | |
PASSED | 4111572391af703401728ba9c4881f87 | train_109.jsonl | 1659623700 | A permutation of length $$$n$$$ is a sequence of integers from $$$1$$$ to $$$n$$$ such that each integer appears in it exactly once.Let the fixedness of a permutation $$$p$$$ be the number of fixed points in it — the number of positions $$$j$$$ such that $$$p_j = j$$$, where $$$p_j$$$ is the $$$j$$$-th element of the permutation $$$p$$$.You are asked to build a sequence of permutations $$$a_1, a_2, \dots$$$, starting from the identity permutation (permutation $$$a_1 = [1, 2, \dots, n]$$$). Let's call it a permutation chain. Thus, $$$a_i$$$ is the $$$i$$$-th permutation of length $$$n$$$.For every $$$i$$$ from $$$2$$$ onwards, the permutation $$$a_i$$$ should be obtained from the permutation $$$a_{i-1}$$$ by swapping any two elements in it (not necessarily neighboring). The fixedness of the permutation $$$a_i$$$ should be strictly lower than the fixedness of the permutation $$$a_{i-1}$$$.Consider some chains for $$$n = 3$$$: $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$ — that is a valid chain of length $$$2$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. $$$a_1 = [2, 1, 3]$$$, $$$a_2 = [3, 1, 2]$$$ — that is not a valid chain. The first permutation should always be $$$[1, 2, 3]$$$ for $$$n = 3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$, $$$a_3 = [1, 2, 3]$$$ — that is not a valid chain. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped but the fixedness increase from $$$1$$$ to $$$3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [3, 2, 1]$$$, $$$a_3 = [3, 1, 2]$$$ — that is a valid chain of length $$$3$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$1$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$1$$$ to $$$0$$$. Find the longest permutation chain. If there are multiple longest answers, print any of them. | 256 megabytes | /*--------
Author : Ryan Ranaut
__Hope is a big word, never lose it__
----------*/
import java.io.*;
import java.util.*;
public class Codechef1 {
static PrintWriter out = new PrintWriter(System.out);
static final int mod = 1_000_000_007;
static final long max = (int) (1e18);
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());
}
int[] readIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
long[] readLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
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;
}
}
/*--------------------------------------------------------------*/
//Try seeing general case
//If WA...try using long
//Try for smallest input
public static void main(String[] args)
{
FastReader s = new FastReader();
int t = s.nextInt();
while(t-->0)
{
int n = s.nextInt();
find(n);
}
out.close();
}
public static void find(int n)
{
out.println(n);
int[] res = new int[n];
for(int i=0;i<n;i++)
res[i] = i+1;
print(res);
for(int i=0;i<n-1;i++)
{
int temp = res[i+1];
res[i+1] = res[i];
res[i] = temp;
print(res);
}
}
public static void print(int[] res)
{
for(int x: res)
out.print(x+" ");
out.println();
}
/*----------------End of the road-------------------*/
static class DSU {
int[] parent;
int[] ranks;
int[] groupSize;
int size;
public DSU(int n) {
size = n;
parent = new int[n];//0 based
ranks = new int[n];
groupSize = new int[n];//Size of each component
for (int i = 0; i < n; i++) {
parent[i] = i;
ranks[i] = 1; groupSize[i] = 1;
}
}
public int find(int x)//Path Compression
{
if (parent[x] == x)
return x;
else
return parent[x] = find(parent[x]);
}
public void union(int x, int y)//Union by rank
{
int x_rep = find(x);
int y_rep = find(y);
if (x_rep == y_rep)
return;
if (ranks[x_rep] < ranks[y_rep])
{
parent[x_rep] = y_rep;
groupSize[y_rep] += groupSize[x_rep];
}
else if (ranks[x_rep] > ranks[y_rep])
{
parent[y_rep] = x_rep;
groupSize[x_rep] += groupSize[y_rep];
}
else {
parent[y_rep] = x_rep;
ranks[x_rep]++;
groupSize[x_rep] += groupSize[y_rep];
}
size--;//Total connected components
}
}
public static int gcd(int x,int y)
{
return y==0?x:gcd(y,x%y);
}
public static long gcd(long x,long y)
{
return y==0L?x:gcd(y,x%y);
}
public static int lcm(int a, int b) {
return (a * b) / gcd(a, b);
}
public static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
public static long pow(long a,long b)
{
if(b==0L)
return 1L;
long tmp=1;
while(b>1L)
{
if((b&1L)==1)
tmp*=a;
a*=a;
b>>=1;
}
return (tmp*a);
}
public static long modPow(long a,long b,long mod)
{
if(b==0L)
return 1L;
long tmp=1;
while(b>1L)
{
if((b&1L)==1L)
tmp*=a;
a*=a;
a%=mod;
tmp%=mod;
b>>=1;
}
return (tmp*a)%mod;
}
static long mul(long a, long b) {
return a*b%mod;
}
static long fact(int n) {
long ans=1;
for (int i=2; i<=n; i++) ans=mul(ans, i);
return ans;
}
static long fastPow(long base, long exp) {
if (exp==0) return 1;
long half=fastPow(base, exp/2);
if (exp%2==0) return mul(half, half);
return mul(half, mul(half, base));
}
static void debug(int ...a)
{
for(int x: a)
out.print(x+" ");
out.println();
}
static void debug(long ...a)
{
for(long x: a)
out.print(x+" ");
out.println();
}
static void debugMatrix(int[][] a)
{
for(int[] x:a)
out.println(Arrays.toString(x));
}
static void debugMatrix(long[][] a)
{
for(long[] x:a)
out.println(Arrays.toString(x));
}
static void reverseArray(int[] a) {
int n = a.length;
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = a[n - i - 1];
for (int i = 0; i < n; i++)
a[i] = arr[i];
}
static void reverseArray(long[] a) {
int n = a.length;
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = a[n - i - 1];
for (int i = 0; i < n; i++)
a[i] = arr[i];
}
static void sort(int[] a)
{
ArrayList<Integer> ls = new ArrayList<>();
for(int x: a) ls.add(x);
Collections.sort(ls);
for(int i=0;i<a.length;i++)
a[i] = ls.get(i);
}
static void sort(long[] a)
{
ArrayList<Long> ls = new ArrayList<>();
for(long x: a) ls.add(x);
Collections.sort(ls);
for(int i=0;i<a.length;i++)
a[i] = ls.get(i);
}
static class Pair{
int x, y;
Pair(int x, int y)
{
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair pair = (Pair) o;
return x == pair.x && y == pair.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
}
}
| Java | ["2\n\n2\n\n3"] | 2 seconds | ["2\n1 2\n2 1\n3\n1 2 3\n3 2 1\n3 1 2"] | null | Java 17 | standard input | [
"constructive algorithms",
"math"
] | 02bdd12987af6e666d4283f075f73725 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 99$$$) — the number of testcases. The only line of each testcase contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the required length of permutations in the chain. | 800 | For each testcase, first, print the length of a permutation chain $$$k$$$. Then print $$$k$$$ permutations $$$a_1, a_2, \dots, a_k$$$. $$$a_1$$$ should be an identity permutation of length $$$n$$$ ($$$[1, 2, \dots, n]$$$). For each $$$i$$$ from $$$2$$$ to $$$k$$$, $$$a_i$$$ should be obtained by swapping two elements in $$$a_{i-1}$$$. It should also have a strictly lower fixedness than $$$a_{i-1}$$$. | standard output | |
PASSED | be0da04e3dc0e60daceddfc88c3b6cf5 | train_109.jsonl | 1659623700 | A permutation of length $$$n$$$ is a sequence of integers from $$$1$$$ to $$$n$$$ such that each integer appears in it exactly once.Let the fixedness of a permutation $$$p$$$ be the number of fixed points in it — the number of positions $$$j$$$ such that $$$p_j = j$$$, where $$$p_j$$$ is the $$$j$$$-th element of the permutation $$$p$$$.You are asked to build a sequence of permutations $$$a_1, a_2, \dots$$$, starting from the identity permutation (permutation $$$a_1 = [1, 2, \dots, n]$$$). Let's call it a permutation chain. Thus, $$$a_i$$$ is the $$$i$$$-th permutation of length $$$n$$$.For every $$$i$$$ from $$$2$$$ onwards, the permutation $$$a_i$$$ should be obtained from the permutation $$$a_{i-1}$$$ by swapping any two elements in it (not necessarily neighboring). The fixedness of the permutation $$$a_i$$$ should be strictly lower than the fixedness of the permutation $$$a_{i-1}$$$.Consider some chains for $$$n = 3$$$: $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$ — that is a valid chain of length $$$2$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. $$$a_1 = [2, 1, 3]$$$, $$$a_2 = [3, 1, 2]$$$ — that is not a valid chain. The first permutation should always be $$$[1, 2, 3]$$$ for $$$n = 3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$, $$$a_3 = [1, 2, 3]$$$ — that is not a valid chain. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped but the fixedness increase from $$$1$$$ to $$$3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [3, 2, 1]$$$, $$$a_3 = [3, 1, 2]$$$ — that is a valid chain of length $$$3$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$1$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$1$$$ to $$$0$$$. Find the longest permutation chain. If there are multiple longest answers, print any of them. | 256 megabytes | import java.util.*;
import java.io.*;
import java.lang.*;
public class practice {
static FastInput scn;
static PrintWriter out;
final static int MOD = (int) (1e9 + 7);
final static int MAX = Integer.MAX_VALUE;
final static int MIN = Integer.MIN_VALUE;
// MAIN
public static void main(String[] args) throws IOException {
scn = new FastInput();
out = new PrintWriter(System.out);
int t = 1;
t = scn.nextInt();
while (t-- > 0) {
solve();
}
out.flush();
}
private static void solve() throws IOException {
int n = scn.nextInt();
int[] a = new int[n];
int j = 0;
for(int i=0;i<n;i++){
a[i] = 1+i;
}
out.println(n);
while(n-->0){
printIntArray(a);
if(n>0){
swap(j+1,j,a);
}
j++;
}
}
private static void swap(int i,int j,int[] a){
int t = a[i];
a[i] = a[j];
a[j] = t;
}
// CLASSES
static class Pair implements Comparable<Pair> {
int first, second;
Pair(int first, int second) {
this.first = first;
this.second = second;
}
Pair(Pair o) {
this.first = o.first;
this.second = o.second;
}
public int compareTo(Pair o) {
return this.first - o.first;
}
}
// CHECK IF STRING IS NUMBER
private static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch (NumberFormatException e) {
return false;
} catch (NullPointerException e) {
return false;
}
return true;
}
private static boolean isLong(String s) {
try {
Long.parseLong(s);
} catch (NumberFormatException e) {
return false;
} catch (NullPointerException e) {
return false;
}
return true;
}
// FASTER SORT
private static void fastSort(int[] arr) {
int n = arr.length;
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++)
list.add(arr[i]);
Collections.sort(list);
for (int i = 0; i < n; i++)
arr[i] = list.get(i);
}
private static void fastSortReverse(int[] arr) {
int n = arr.length;
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++)
list.add(arr[i]);
Collections.sort(list, Collections.reverseOrder());
for (int i = 0; i < n; i++)
arr[i] = list.get(i);
}
private static void fastSort(long[] arr) {
int n = arr.length;
List<Long> list = new ArrayList<>();
for (int i = 0; i < n; i++)
list.add(arr[i]);
Collections.sort(list);
for (int i = 0; i < n; i++)
arr[i] = list.get(i);
}
private static void fastSortReverse(long[] arr) {
int n = arr.length;
List<Long> list = new ArrayList<>();
for (int i = 0; i < n; i++)
list.add(arr[i]);
Collections.sort(list, Collections.reverseOrder());
for (int i = 0; i < n; i++)
arr[i] = list.get(i);
}
// QUICK MATHS
private static int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
private static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
private static int lcm(int a, int b) {
return (a / gcd(a, b)) * b;
}
private static long lcm(long a, long b) {
return (a / gcd(a, b)) * b;
}
private static long power(long a, long b) {
if (b == 0)
return 1L;
long ans = power(a, b / 2);
ans *= ans;
if ((b & 1) == 1)
ans *= a;
return ans;
}
private static int mod_power(int a, int b) {
if (b == 0)
return 1;
int temp = mod_power(a, b / 2);
temp %= MOD;
temp = (int) ((1L * temp * temp) % MOD);
if ((b & 1) == 1)
temp = (int) ((1L * temp * a) % MOD);
return temp;
}
private static int multiply(int a, int b) {
return (int) ((((1L * a) % MOD) * ((1L * b) % MOD)) % MOD);
}
private static boolean isPrime(int n) {
for (int i = 2; i * i <= n; i++)
if (n % i == 0)
return false;
return true;
}
private static boolean isPrime(long n) {
for (long i = 2; i * i <= n; i++)
if (n % i == 0)
return false;
return true;
}
// STRING FUNCTIONS
private static boolean isPalindrome(String str) {
int i = 0, j = str.length() - 1;
while (i < j)
if (str.charAt(i++) != str.charAt(j--))
return false;
return true;
}
private static String reverseString(String str) {
StringBuilder sb = new StringBuilder(str);
return sb.reverse().toString();
}
private static String sortString(String str) {
int[] arr = new int[256];
for (char ch : str.toCharArray())
arr[ch]++;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 256; i++)
while (arr[i]-- > 0)
sb.append((char) i);
return sb.toString();
}
// LONGEST INCREASING AND NON-DECREASING SUBSEQUENCE
private static int LIS(int arr[]) {
int n = arr.length;
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
int idx = find1(list, arr[i]);
if (idx < list.size()) {
list.set(idx, arr[i]);
} else {
list.add(arr[i]);
}
}
return list.size();
}
private static int find1(List<Integer> list, int val) {
int ret = list.size(), i = 0, j = list.size() - 1;
while (i <= j) {
int mid = (i + j) / 2;
if (list.get(mid) >= val) {
ret = mid;
j = mid - 1;
} else {
i = mid + 1;
}
}
return ret;
}
private static int LNDS(int[] arr) {
int n = arr.length;
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
int idx = find2(list, arr[i]);
if (idx < list.size()) {
list.set(idx, arr[i]);
} else {
list.add(arr[i]);
}
}
return list.size();
}
private static int find2(List<Integer> list, int val) {
int ret = list.size(), i = 0, j = list.size() - 1;
while (i <= j) {
int mid = (i + j) / 2;
if (list.get(mid) <= val) {
i = mid + 1;
} else {
ret = mid;
j = mid - 1;
}
}
return ret;
}
// DISJOINT SET UNION
private static int find(int x, int[] parent) {
if (parent[x] == x) {
return x;
}
parent[x] = find(parent[x], parent);
return parent[x];
}
private static boolean union(int x, int y, int[] parent, int[] rank) {
int lx = find(x, parent), ly = find(y, parent);
if (lx == ly) {
return true;
} else if (rank[lx] > rank[ly]) {
parent[ly] = lx;
} else if (rank[lx] < rank[ly]) {
parent[lx] = ly;
} else {
parent[lx] = ly;
rank[ly]++;
}
return false;
}
// TRIE
static class Trie {
class Node {
Node[] children;
boolean isEnd;
Node() {
children = new Node[26];
}
}
Node root;
Trie() {
root = new Node();
}
public void insert(String word) {
Node curr = root;
for (char ch : word.toCharArray()) {
if (curr.children[ch - 'a'] == null) {
curr.children[ch - 'a'] = new Node();
}
curr = curr.children[ch - 'a'];
}
curr.isEnd = true;
}
public boolean find(String word) {
Node curr = root;
for (char ch : word.toCharArray()) {
if (curr.children[ch - 'a'] == null) {
return false;
}
curr = curr.children[ch - 'a'];
}
return curr.isEnd;
}
}
// INPUT
static class FastInput {
BufferedReader br;
StringTokenizer st;
FastInput() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(nextLine());
return st.nextToken();
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
char nextCharacter() throws IOException {
return next().charAt(0);
}
String nextLine() throws IOException {
return br.readLine().trim();
}
int[] nextIntArray(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
int[][] next2DIntArray(int n, int m) throws IOException {
int[][] arr = new int[n][m];
for (int i = 0; i < n; i++)
arr[i] = nextIntArray(m);
return arr;
}
long[] nextLongArray(int n) throws IOException {
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = nextLong();
return arr;
}
long[][] next2DLongArray(int n, int m) throws IOException {
long[][] arr = new long[n][m];
for (int i = 0; i < n; i++)
arr[i] = nextLongArray(m);
return arr;
}
List<Integer> nextIntList(int n) throws IOException {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++)
list.add(nextInt());
return list;
}
List<Long> nextLongList(int n) throws IOException {
List<Long> list = new ArrayList<>();
for (int i = 0; i < n; i++)
list.add(nextLong());
return list;
}
char[] nextCharArray(int n) throws IOException {
return next().toCharArray();
}
char[][] next2DCharArray(int n, int m) throws IOException {
char[][] mat = new char[n][m];
for (int i = 0; i < n; i++)
mat[i] = nextCharArray(m);
return mat;
}
}
// OUTPUT
private static void printIntList(List<Integer> list) {
for (int i = 0; i < list.size(); i++)
out.print(list.get(i) + " ");
out.println(" ");
}
private static void printLongList(List<Long> list) {
for (int i = 0; i < list.size(); i++)
out.print(list.get(i) + " ");
out.println(" ");
}
private static void printIntArray(int[] arr) {
for (int i = 0; i < arr.length; i++)
out.print(arr[i] + " ");
out.println(" ");
}
private static void print2DIntArray(int[][] arr) {
for (int i = 0; i < arr.length; i++)
printIntArray(arr[i]);
}
private static void printLongArray(long[] arr) {
for (int i = 0; i < arr.length; i++)
out.print(arr[i] + " ");
out.println(" ");
}
private static void print2DLongArray(long[][] arr) {
for (int i = 0; i < arr.length; i++)
printLongArray(arr[i]);
}
} | Java | ["2\n\n2\n\n3"] | 2 seconds | ["2\n1 2\n2 1\n3\n1 2 3\n3 2 1\n3 1 2"] | null | Java 17 | standard input | [
"constructive algorithms",
"math"
] | 02bdd12987af6e666d4283f075f73725 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 99$$$) — the number of testcases. The only line of each testcase contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the required length of permutations in the chain. | 800 | For each testcase, first, print the length of a permutation chain $$$k$$$. Then print $$$k$$$ permutations $$$a_1, a_2, \dots, a_k$$$. $$$a_1$$$ should be an identity permutation of length $$$n$$$ ($$$[1, 2, \dots, n]$$$). For each $$$i$$$ from $$$2$$$ to $$$k$$$, $$$a_i$$$ should be obtained by swapping two elements in $$$a_{i-1}$$$. It should also have a strictly lower fixedness than $$$a_{i-1}$$$. | standard output | |
PASSED | 48622d35db322aeaa925f8c2cf2c125d | train_109.jsonl | 1659623700 | A permutation of length $$$n$$$ is a sequence of integers from $$$1$$$ to $$$n$$$ such that each integer appears in it exactly once.Let the fixedness of a permutation $$$p$$$ be the number of fixed points in it — the number of positions $$$j$$$ such that $$$p_j = j$$$, where $$$p_j$$$ is the $$$j$$$-th element of the permutation $$$p$$$.You are asked to build a sequence of permutations $$$a_1, a_2, \dots$$$, starting from the identity permutation (permutation $$$a_1 = [1, 2, \dots, n]$$$). Let's call it a permutation chain. Thus, $$$a_i$$$ is the $$$i$$$-th permutation of length $$$n$$$.For every $$$i$$$ from $$$2$$$ onwards, the permutation $$$a_i$$$ should be obtained from the permutation $$$a_{i-1}$$$ by swapping any two elements in it (not necessarily neighboring). The fixedness of the permutation $$$a_i$$$ should be strictly lower than the fixedness of the permutation $$$a_{i-1}$$$.Consider some chains for $$$n = 3$$$: $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$ — that is a valid chain of length $$$2$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. $$$a_1 = [2, 1, 3]$$$, $$$a_2 = [3, 1, 2]$$$ — that is not a valid chain. The first permutation should always be $$$[1, 2, 3]$$$ for $$$n = 3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$, $$$a_3 = [1, 2, 3]$$$ — that is not a valid chain. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped but the fixedness increase from $$$1$$$ to $$$3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [3, 2, 1]$$$, $$$a_3 = [3, 1, 2]$$$ — that is a valid chain of length $$$3$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$1$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$1$$$ to $$$0$$$. Find the longest permutation chain. If there are multiple longest answers, print any of them. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static java.lang.System.*;
import static java.lang.System.out;
import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.util.Arrays.sort;
import static java.util.Collections.sort;
public class Solution {
private final static FastScanner scanner = new FastScanner();
private final static int mod = (int) 1e9+7;
private final static int max_value = Integer.MAX_VALUE;
private final static int min_value = Integer.MIN_VALUE;
private final static String endl = "\n";
private static void solve() {
int n = ii();
println(n);
for (int i = 1; i<=n; i++) {
StringBuilder builder = new StringBuilder(i+" ");
for (int j = 1; j<=n; j++) {
if (j != i) {
builder.append(j).append(" ");
}
}
println(builder);
}
}
public static void main(String[] args) {
int t = ii();
while (t-->0) {
solve();
}
}
private static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
private static void swap(int[] a, int[] b, int i) {
int temp = a[i];
a[i] = b[i];
b[i] = temp;
}
private static int[] reverse(int[] a) {
int[] b = new int[a.length];
int k = 0;
for (int i = a.length-1; i>=0; i--) {
b[k++] = a[i];
}
return b;
}
private static int[] readArrayInt(int n) {
return scanner.readArray(n);
}
private static String[] readArrayString(int n) {
return IntStream.range(0, n).mapToObj(i -> s()).toArray(String[]::new);
}
private static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
private static int ii() {
return scanner.nextInt();
}
private static long l() {
return scanner.nextLong();
}
private static double d() {
return scanner.nextDouble();
}
private static String s() {
return scanner.next();
}
private static int toInt(String s) {
return Integer.parseInt(s);
}
private static ArrayList<Integer> list() {
return new ArrayList<>();
}
private static HashSet<Integer> set() {
return new HashSet<>();
}
private static HashMap<Integer, Integer> map() {
return new HashMap<>();
}
private static int toInt(char c) {
return Integer.parseInt(c+"");
}
private static<K> void println(K a) {
print(a+endl);
}
private static<K> void print(K a) {
out.print(a);
}
private static void yes() {
println("YES");
}
private static void no() {
println("NO");
}
private static int max_a(int[] a) {
int max = a[0];
for (int j : a) {
if (j > max) {
max = j;
}
}
return max;
}
private static int min_a(int[] a) {
int min = a[0];
for (int j : a) {
if (j < min) {
min = j;
}
}
return min;
}
private static long sum(int[] a) {
return stream(a).asLongStream().sum();
}
private static void println() {
out.println();
}
private static void printArray(int[] a) {
stream(a).mapToObj(i -> i + " ").forEachOrdered(Solution::print);
println();
}
private static<K> void printArray(K[] a) {
stream(a).map(k -> k + " ").forEachOrdered(Solution::print);
println();
}
private static int reverseInteger(int k) {
String a = k+"", res = "";
for (int i = a.length()-1; i>=0; i--) {
res+=a.charAt(i);
}
return toInt(res);
}
private static long phi(long n) {
long result = n;
for (long i=2; i*i<=n; i++)
if (n % i == 0) {
while (n % i == 0)
n /= i;
result -= result / i;
}
if (n > 1)
result -= result / n;
return result;
}
private static int pow(int a, int n) {
if (n == 0)
return 1;
if (n % 2 == 1)
return pow(a, n-1) * a;
else {
int b = pow (a, n/2);
return b * b;
}
}
private static boolean isPrimeLong(long n) {
BigInteger a = BigInteger.valueOf(n);
return a.isProbablePrime(10);
}
private static boolean isPrime(int n) {
return IntStream.iterate(2, i -> i * i <= n, i -> i + 1).noneMatch(i -> n % i == 0);
}
private static List<Integer> primes(int N) {
int[] lp = new int[N+1];
List<Integer> pr = new ArrayList<>();
for (int i=2; i<=N; ++i) {
if (lp[i] == 0) {
lp[i] = i;
pr.add(i);
}
for (int j = 0; j<pr.size() && pr.get(j)<=lp[i] && i*pr.get(j)<=N; ++j)
lp[i * pr.get(j)] = pr.get(j);
}
return pr;
}
private static Set<Integer> toSet(int[] a) {
return stream(a).boxed().collect(Collectors.toSet());
}
private static int linearSearch(int[] a, int key) {
return IntStream.range(0, a.length).filter(i -> a[i] == key).findFirst().orElse(-1);
}
private static<K> int linearSearch(K[] a, K key) {
return IntStream.range(0, a.length).filter(i -> a[i].equals(key)).findFirst().orElse(-1);
}
static int upper_bound(int[] arr, int key) {
int index = binarySearch(arr, key);
int n = arr.length;
if (index < 0) {
int upperBound = abs(index) - 1;
if (upperBound < n)
return upperBound;
else return -1;
}
else {
while (index < n) {
if (arr[index] == key)
index++;
else {
return index;
}
}
return -1;
}
}
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
public static void psort(int[] arr, int n) {
int min = min_a(arr);
int max = max_a(arr);
int range = max-min+1, i, j, index = 0;
int[] count = new int[range];
for(i = 0; i<n; i++)
count[arr[i] - min]++;
for(j = 0; j<range; j++)
while(count[j]-->0)
arr[index++]=j+min;
}
private static void csort(int[] a, int n) {
int max = max_a(a);
int min = min_a(a);
int range = max - min + 1;
int[] count = new int[range];
int[] output = new int[n];
for (int i = 0; i < n; i++) {
count[a[i] - min]++;
}
for (int i = 1; i < range; i++) {
count[i] += count[i - 1];
}
for (int i = n - 1; i >= 0; i--) {
output[count[a[i] - min] - 1] = a[i];
count[a[i] - min]--;
}
arraycopy(output, 0, a, 0, n);
}
private static void csort(char[] arr) {
int n = arr.length;
char[] output = new char[n];
int[] count = new int[256];
for (int i = 0; i < 256; ++i)
count[i] = 0;
for (char c : arr) ++count[c];
for (int i = 1; i <= 255; ++i)
count[i] += count[i - 1];
for (int i = n - 1; i >= 0; i--) {
output[count[arr[i]] - 1] = arr[i];
--count[arr[i]];
}
arraycopy(output, 0, arr, 0, n);
}
static class Pair implements Comparable<Pair> {
String key;
Integer count = 0;
public Pair(String key, Integer count) {
this.key = key;
this.count = count;
}
@Override
public int compareTo(Pair pair) {
return count.compareTo(pair.count);
}
}
} | Java | ["2\n\n2\n\n3"] | 2 seconds | ["2\n1 2\n2 1\n3\n1 2 3\n3 2 1\n3 1 2"] | null | Java 17 | standard input | [
"constructive algorithms",
"math"
] | 02bdd12987af6e666d4283f075f73725 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 99$$$) — the number of testcases. The only line of each testcase contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the required length of permutations in the chain. | 800 | For each testcase, first, print the length of a permutation chain $$$k$$$. Then print $$$k$$$ permutations $$$a_1, a_2, \dots, a_k$$$. $$$a_1$$$ should be an identity permutation of length $$$n$$$ ($$$[1, 2, \dots, n]$$$). For each $$$i$$$ from $$$2$$$ to $$$k$$$, $$$a_i$$$ should be obtained by swapping two elements in $$$a_{i-1}$$$. It should also have a strictly lower fixedness than $$$a_{i-1}$$$. | standard output | |
PASSED | bc56b0d2af22d2c2fc7c22b39872af9c | train_109.jsonl | 1659623700 | A permutation of length $$$n$$$ is a sequence of integers from $$$1$$$ to $$$n$$$ such that each integer appears in it exactly once.Let the fixedness of a permutation $$$p$$$ be the number of fixed points in it — the number of positions $$$j$$$ such that $$$p_j = j$$$, where $$$p_j$$$ is the $$$j$$$-th element of the permutation $$$p$$$.You are asked to build a sequence of permutations $$$a_1, a_2, \dots$$$, starting from the identity permutation (permutation $$$a_1 = [1, 2, \dots, n]$$$). Let's call it a permutation chain. Thus, $$$a_i$$$ is the $$$i$$$-th permutation of length $$$n$$$.For every $$$i$$$ from $$$2$$$ onwards, the permutation $$$a_i$$$ should be obtained from the permutation $$$a_{i-1}$$$ by swapping any two elements in it (not necessarily neighboring). The fixedness of the permutation $$$a_i$$$ should be strictly lower than the fixedness of the permutation $$$a_{i-1}$$$.Consider some chains for $$$n = 3$$$: $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$ — that is a valid chain of length $$$2$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. $$$a_1 = [2, 1, 3]$$$, $$$a_2 = [3, 1, 2]$$$ — that is not a valid chain. The first permutation should always be $$$[1, 2, 3]$$$ for $$$n = 3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$, $$$a_3 = [1, 2, 3]$$$ — that is not a valid chain. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped but the fixedness increase from $$$1$$$ to $$$3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [3, 2, 1]$$$, $$$a_3 = [3, 1, 2]$$$ — that is a valid chain of length $$$3$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$1$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$1$$$ to $$$0$$$. Find the longest permutation chain. If there are multiple longest answers, print any of them. | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.lang.System.*;
public class PermutationChain implements Runnable {
private final void solution() throws IOException {
// InputReader input = new InputReader(new FileReader(System.getenv("INPUT")));
// PrintWriter output = new PrintWriter(new BufferedOutputStream(new FileOutputStream(System.getenv("OUTPUT"))));
InputReader input = new InputReader(in);
PrintWriter output = new PrintWriter(new BufferedOutputStream(out));
byte test = input.nextByte();
while (test-- > 0) {
short n = input.nextShort();
int[] arr = new int[n];
for (int i = 1; i <= n; i++) {
arr[i - 1] = i;
}
short possiblePerm = n;
output.println(possiblePerm);
int j = 1;
while (possiblePerm-- > 0) {
printArr(output, arr);
if (possiblePerm > 0) {
j %= n - 1;
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
j++;
}
}
output.close();
input.close();
}
@Override
public void run() {
try {
solution();
} catch (IOException ignore) {}
}
public static void main(String... args) throws IOException {
new Thread(null, new PermutationChain(), "Main", 1 << 26).start();
}
private final void printArr(PrintWriter output, int...arr) {
output.println(Arrays.toString(arr).replaceAll("\\[|]|, ", " ").trim());
}
private final void printArr(PrintWriter output, double...arr) {
output.println(Arrays.toString(arr).replaceAll("\\[|]|, ", " ").trim());
}
private final void printArr(PrintWriter output, long...arr) {
output.println(Arrays.toString(arr).replaceAll("\\[|]|, ", " ").trim());
}
private final void printArr(PrintWriter output, String...arr) {
output.println(Arrays.toString(arr).replaceAll("\\[|]|, ", " ").trim());
}
private final boolean isPowerofTwo(long n){
if (n <= 0) return false;
int bit = (int) (Math.log(n) / Math.log(2));
long expec = 1 << bit;
return n % expec == 0;
}
}
class InputReader {
private StringTokenizer st;
private BufferedReader br;
public InputReader(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public InputReader(FileReader s) throws FileNotFoundException {
br = new BufferedReader(s);
}
public final String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public final String nextLine() throws IOException {
return br.readLine();
}
public final byte nextByte() throws IOException {
return Byte.parseByte(next());
}
public final short nextShort() throws IOException {
return Short.parseShort(next());
}
public final int nextInt() throws IOException {
return Integer.parseInt(next());
}
public final long nextLong() throws IOException {
return Long.parseLong(next());
}
public final double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public final char nextChar() throws IOException {
return next().charAt(0);
}
public final boolean nextBoolean() throws IOException {
return Boolean.parseBoolean(next());
// return Boolean.getBoolean(next());
// return Boolean.valueOf(next());
}
public int[] readIntArray(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
public int[] readIntArray() throws IOException {
return java.util.Arrays.stream(nextLine().split("\\s+")).
mapToInt(Integer::parseInt).toArray();
}
public long[] readLongArray(int n) throws IOException {
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = nextLong();
return arr;
}
public long[] readLongArray() throws IOException {
return java.util.Arrays.stream(nextLine().split("\\s+")).
mapToLong(Long::parseLong).toArray();
}
public double[] readDoubleArray(int n) throws IOException {
double[] arr = new double[n];
for (int i = 0; i < n; i++)
arr[i] = nextDouble();
return arr;
}
public double[] readDoubleArray() throws IOException {
return java.util.Arrays.stream(nextLine().split("\\s+")).
mapToDouble(Double::parseDouble).toArray();
}
public String[] readStringArray(int n) throws IOException {
String[] arr = new String[n];
for (int i = 0; i < n; i++)
arr[i] = next();
return arr;
}
public String[] readStringArray() throws IOException {
return nextLine().split("\\s+");
}
public boolean ready() throws IOException {
return br.ready();
}
public void close() throws IOException {
br.close();
}
} | Java | ["2\n\n2\n\n3"] | 2 seconds | ["2\n1 2\n2 1\n3\n1 2 3\n3 2 1\n3 1 2"] | null | Java 17 | standard input | [
"constructive algorithms",
"math"
] | 02bdd12987af6e666d4283f075f73725 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 99$$$) — the number of testcases. The only line of each testcase contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the required length of permutations in the chain. | 800 | For each testcase, first, print the length of a permutation chain $$$k$$$. Then print $$$k$$$ permutations $$$a_1, a_2, \dots, a_k$$$. $$$a_1$$$ should be an identity permutation of length $$$n$$$ ($$$[1, 2, \dots, n]$$$). For each $$$i$$$ from $$$2$$$ to $$$k$$$, $$$a_i$$$ should be obtained by swapping two elements in $$$a_{i-1}$$$. It should also have a strictly lower fixedness than $$$a_{i-1}$$$. | standard output | |
PASSED | ff8c0b884dddfb0a6e5a24f88fb34514 | train_109.jsonl | 1659623700 | A permutation of length $$$n$$$ is a sequence of integers from $$$1$$$ to $$$n$$$ such that each integer appears in it exactly once.Let the fixedness of a permutation $$$p$$$ be the number of fixed points in it — the number of positions $$$j$$$ such that $$$p_j = j$$$, where $$$p_j$$$ is the $$$j$$$-th element of the permutation $$$p$$$.You are asked to build a sequence of permutations $$$a_1, a_2, \dots$$$, starting from the identity permutation (permutation $$$a_1 = [1, 2, \dots, n]$$$). Let's call it a permutation chain. Thus, $$$a_i$$$ is the $$$i$$$-th permutation of length $$$n$$$.For every $$$i$$$ from $$$2$$$ onwards, the permutation $$$a_i$$$ should be obtained from the permutation $$$a_{i-1}$$$ by swapping any two elements in it (not necessarily neighboring). The fixedness of the permutation $$$a_i$$$ should be strictly lower than the fixedness of the permutation $$$a_{i-1}$$$.Consider some chains for $$$n = 3$$$: $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$ — that is a valid chain of length $$$2$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. $$$a_1 = [2, 1, 3]$$$, $$$a_2 = [3, 1, 2]$$$ — that is not a valid chain. The first permutation should always be $$$[1, 2, 3]$$$ for $$$n = 3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$, $$$a_3 = [1, 2, 3]$$$ — that is not a valid chain. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped but the fixedness increase from $$$1$$$ to $$$3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [3, 2, 1]$$$, $$$a_3 = [3, 1, 2]$$$ — that is a valid chain of length $$$3$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$1$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$1$$$ to $$$0$$$. Find the longest permutation chain. If there are multiple longest answers, print any of them. | 256 megabytes | import java.io.*;
import java.util.*;
public class MainClass{
static class Reader{
private final BufferedReader reader;
private StringTokenizer tokenizer;
Reader(InputStream input)
{
this.reader = new BufferedReader(new InputStreamReader(input));
this.tokenizer = new StringTokenizer("");
}
public String next() throws IOException {
while(!tokenizer.hasMoreTokens())
{
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
public int nextInt() throws IOException
{
return Integer.parseInt(next());
}
public double nextDouble() throws IOException
{
return Double.parseDouble(next());
}
public long nextLong() throws IOException
{
return Long.parseLong(next());
}
public int[] nextIntArr(int n) throws IOException {
int[] arr = new int[n];
for(int i=0;i<n;i++)arr[i]=nextInt();
return arr;
}
public long[] nextLongArr(int n)throws IOException {
long[] arr = new long[n];
for(int i=0;i<n;i++)arr[i]=nextLong();
return arr;
}
public char[] nextCharArr(int n) throws IOException {
char[] arr = new char[n];
for(int i=0;i<n;i++)arr[i] = next().charAt(0);
return arr;
}
}
public static void main(String[] args) throws IOException {
Reader scan = new Reader(System.in);
// int t = 1;
int t = scan.nextInt();
StringBuffer sb = new StringBuffer();
BufferedOutputStream b = new BufferedOutputStream(System.out);
while(t-->0)
{
int n = scan.nextInt();
sb.append(solve(n));
}
b.write((sb.toString()).getBytes());
b.flush();
}
static String solve(int n)
{
StringBuffer sb = new StringBuffer();
sb.append(n).append("\n");
int[] arr = new int[n];
for(int i=0;i<n;i++)arr[i] = i+1;
for(int i=0;i<n;i++)
{
for(int j : arr)sb.append(j).append(" ");
sb.append("\n");
if(i < n-1)
{
int d = arr[n-1-i]^arr[n-2-i];
arr[n-1-i] = d^arr[n-1-i];
arr[n-2-i] = d^arr[n-2-i];
}
}
return sb.toString();
}
static int HCF(int a, int b)
{
if(a == 0)return b;
return HCF(b%a, a);
}
}
class Pair {
String s;
int idx;
Pair(String string, int idx)
{
this.s = string;
this.idx = idx;
}
public int length(){
return this.s.length();
}
}
class comp2 implements Comparator<Pair>
{
@Override
public int compare(Pair a, Pair b)
{
return b.s.length() - a.s.length();
}
}
| Java | ["2\n\n2\n\n3"] | 2 seconds | ["2\n1 2\n2 1\n3\n1 2 3\n3 2 1\n3 1 2"] | null | Java 17 | standard input | [
"constructive algorithms",
"math"
] | 02bdd12987af6e666d4283f075f73725 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 99$$$) — the number of testcases. The only line of each testcase contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the required length of permutations in the chain. | 800 | For each testcase, first, print the length of a permutation chain $$$k$$$. Then print $$$k$$$ permutations $$$a_1, a_2, \dots, a_k$$$. $$$a_1$$$ should be an identity permutation of length $$$n$$$ ($$$[1, 2, \dots, n]$$$). For each $$$i$$$ from $$$2$$$ to $$$k$$$, $$$a_i$$$ should be obtained by swapping two elements in $$$a_{i-1}$$$. It should also have a strictly lower fixedness than $$$a_{i-1}$$$. | standard output | |
PASSED | 09228674762a202dffae8cd2d6115807 | train_109.jsonl | 1659623700 | A permutation of length $$$n$$$ is a sequence of integers from $$$1$$$ to $$$n$$$ such that each integer appears in it exactly once.Let the fixedness of a permutation $$$p$$$ be the number of fixed points in it — the number of positions $$$j$$$ such that $$$p_j = j$$$, where $$$p_j$$$ is the $$$j$$$-th element of the permutation $$$p$$$.You are asked to build a sequence of permutations $$$a_1, a_2, \dots$$$, starting from the identity permutation (permutation $$$a_1 = [1, 2, \dots, n]$$$). Let's call it a permutation chain. Thus, $$$a_i$$$ is the $$$i$$$-th permutation of length $$$n$$$.For every $$$i$$$ from $$$2$$$ onwards, the permutation $$$a_i$$$ should be obtained from the permutation $$$a_{i-1}$$$ by swapping any two elements in it (not necessarily neighboring). The fixedness of the permutation $$$a_i$$$ should be strictly lower than the fixedness of the permutation $$$a_{i-1}$$$.Consider some chains for $$$n = 3$$$: $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$ — that is a valid chain of length $$$2$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. $$$a_1 = [2, 1, 3]$$$, $$$a_2 = [3, 1, 2]$$$ — that is not a valid chain. The first permutation should always be $$$[1, 2, 3]$$$ for $$$n = 3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$, $$$a_3 = [1, 2, 3]$$$ — that is not a valid chain. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped but the fixedness increase from $$$1$$$ to $$$3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [3, 2, 1]$$$, $$$a_3 = [3, 1, 2]$$$ — that is a valid chain of length $$$3$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$1$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$1$$$ to $$$0$$$. Find the longest permutation chain. If there are multiple longest answers, print any of them. | 256 megabytes | import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.util.Scanner;
import java.io.IOException;
import java.util.Arrays;
import java.util.ArrayList;
public class codeforces_2022_08_04_B {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
for (int numCases = scanner.nextInt(); numCases > 0; --numCases) {
int n = scanner.nextInt();
writer.write(n + "\n");
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = 1 + i;
writer.write(arr[i] + " ");
}
writer.write("\n");
for (int i = 0; i < n - 1; i++) {
int temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
for (int j : arr) {
writer.write((j) + " ");
}
writer.write("\n");
}
}
writer.flush();
scanner.close();
}
} | Java | ["2\n\n2\n\n3"] | 2 seconds | ["2\n1 2\n2 1\n3\n1 2 3\n3 2 1\n3 1 2"] | null | Java 17 | standard input | [
"constructive algorithms",
"math"
] | 02bdd12987af6e666d4283f075f73725 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 99$$$) — the number of testcases. The only line of each testcase contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the required length of permutations in the chain. | 800 | For each testcase, first, print the length of a permutation chain $$$k$$$. Then print $$$k$$$ permutations $$$a_1, a_2, \dots, a_k$$$. $$$a_1$$$ should be an identity permutation of length $$$n$$$ ($$$[1, 2, \dots, n]$$$). For each $$$i$$$ from $$$2$$$ to $$$k$$$, $$$a_i$$$ should be obtained by swapping two elements in $$$a_{i-1}$$$. It should also have a strictly lower fixedness than $$$a_{i-1}$$$. | standard output | |
PASSED | 6e233ebb83cb96e6dbc732221c762569 | train_109.jsonl | 1659623700 | A permutation of length $$$n$$$ is a sequence of integers from $$$1$$$ to $$$n$$$ such that each integer appears in it exactly once.Let the fixedness of a permutation $$$p$$$ be the number of fixed points in it — the number of positions $$$j$$$ such that $$$p_j = j$$$, where $$$p_j$$$ is the $$$j$$$-th element of the permutation $$$p$$$.You are asked to build a sequence of permutations $$$a_1, a_2, \dots$$$, starting from the identity permutation (permutation $$$a_1 = [1, 2, \dots, n]$$$). Let's call it a permutation chain. Thus, $$$a_i$$$ is the $$$i$$$-th permutation of length $$$n$$$.For every $$$i$$$ from $$$2$$$ onwards, the permutation $$$a_i$$$ should be obtained from the permutation $$$a_{i-1}$$$ by swapping any two elements in it (not necessarily neighboring). The fixedness of the permutation $$$a_i$$$ should be strictly lower than the fixedness of the permutation $$$a_{i-1}$$$.Consider some chains for $$$n = 3$$$: $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$ — that is a valid chain of length $$$2$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. $$$a_1 = [2, 1, 3]$$$, $$$a_2 = [3, 1, 2]$$$ — that is not a valid chain. The first permutation should always be $$$[1, 2, 3]$$$ for $$$n = 3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$, $$$a_3 = [1, 2, 3]$$$ — that is not a valid chain. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped but the fixedness increase from $$$1$$$ to $$$3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [3, 2, 1]$$$, $$$a_3 = [3, 1, 2]$$$ — that is a valid chain of length $$$3$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$1$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$1$$$ to $$$0$$$. Find the longest permutation chain. If there are multiple longest answers, print any of them. | 256 megabytes | import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import java.util.*;
import java.io.*;
import java.math.*;
/**
*
* @Har_Har_Mahadev
*/
public class B {
public static void process() throws IOException {
int n = sc.nextInt();
System.out.println(n);
for(int i = 1; i<=n; i++) {
StringBuilder ans = new StringBuilder();
int cc = 2;
for(int j = 1; j<=n; j++) {
if(j == i)ans.append(1+" ");
else ans.append(cc+++" ");
}
System.out.println(ans);
}
}
//=============================================================================
//--------------------------The End---------------------------------
//=============================================================================
private static long INF = 2000000000000000000L, M = 1000000007, MM = 998244353;
private static int N = 0;
private static void google(int tt) {
System.out.print("Case #" + (tt) + ": ");
}
static FastScanner sc;
static FastWriter out;
public static void main(String[] args) throws IOException {
boolean oj = true;
if (oj) {
sc = new FastScanner();
out = new FastWriter(System.out);
} else {
sc = new FastScanner("input.txt");
out = new FastWriter("output.txt");
}
long s = System.currentTimeMillis();
int t = 1;
t = sc.nextInt();
int TTT = 1;
while (t-- > 0) {
// google(TTT++);
process();
}
out.flush();
// tr(System.currentTimeMillis()-s+"ms");
}
private static boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private static void tr(Object... o) {
if (!oj)
System.err.println(Arrays.deepToString(o));
}
static class Pair implements Comparable<Pair> {
int x, y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Pair o) {
return Integer.compare(this.x, o.x);
}
/*
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Pair)) return false;
Pair key = (Pair) o;
return x == key.x && y == key.y;
}
@Override
public int hashCode() {
int result = x;
result = 31 * result + y;
return result;
}
*/
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
static int ceil(int x, int y) {
return (x % y == 0 ? x / y : (x / y + 1));
}
static long ceil(long x, long y) {
return (x % y == 0 ? x / y : (x / y + 1));
}
static long sqrt(long z) {
long sqz = (long) Math.sqrt(z);
while (sqz * 1L * sqz < z) {
sqz++;
}
while (sqz * 1L * sqz > z) {
sqz--;
}
return sqz;
}
static int log2(int N) {
int result = (int) (Math.log(N) / Math.log(2));
return result;
}
public static long gcd(long a, long b) {
if (a > b)
a = (a + b) - (b = a);
if (a == 0L)
return b;
return gcd(b % a, a);
}
public static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
public static int lower_bound(int[] arr, int x) {
int low = 0, high = arr.length - 1, mid = -1;
int ans = -1;
while (low <= high) {
mid = (low + high) / 2;
if (arr[mid] > x) {
high = mid - 1;
} else {
ans = mid;
low = mid + 1;
}
}
return ans;
}
public static int upper_bound(int[] arr, int x) {
int low = 0, high = arr.length - 1, mid = -1;
int ans = arr.length;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] >= x) {
ans = mid;
high = mid - 1;
} else {
low = mid + 1;
}
}
return ans;
}
static void ruffleSort(int[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
Arrays.sort(a);
}
static void ruffleSort(long[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
long temp = a[i];
a[i] = a[r];
a[r] = temp;
}
Arrays.sort(a);
}
static void reverseArray(int[] a) {
int n = a.length;
int arr[] = new int[n];
for (int i = 0; i < n; i++)
arr[i] = a[n - i - 1];
for (int i = 0; i < n; i++)
a[i] = arr[i];
}
static void reverseArray(long[] a) {
int n = a.length;
long arr[] = new long[n];
for (int i = 0; i < n; i++)
arr[i] = a[n - i - 1];
for (int i = 0; i < n; i++)
a[i] = arr[i];
}
//custom multiset (replace with HashMap if needed)
public static void push(TreeMap<Integer, Integer> map, int k, int v) {
//map[k] += v;
if (!map.containsKey(k))
map.put(k, v);
else
map.put(k, map.get(k) + v);
}
public static void pull(TreeMap<Integer, Integer> map, int k, int v) {
//assumes map[k] >= v
//map[k] -= v
int lol = map.get(k);
if (lol == v)
map.remove(k);
else
map.put(k, lol - v);
}
// compress Big value to Time Limit
public static int[] compress(int[] arr) {
ArrayList<Integer> ls = new ArrayList<Integer>();
for (int x : arr)
ls.add(x);
Collections.sort(ls);
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int boof = 1; //min value
for (int x : ls)
if (!map.containsKey(x))
map.put(x, boof++);
int[] brr = new int[arr.length];
for (int i = 0; i < arr.length; i++)
brr[i] = map.get(arr[i]);
return brr;
}
// Fast Writer
public static class FastWriter {
private static final int BUF_SIZE = 1 << 13;
private final byte[] buf = new byte[BUF_SIZE];
private final OutputStream out;
private int ptr = 0;
private FastWriter() {
out = null;
}
public FastWriter(OutputStream os) {
this.out = os;
}
public FastWriter(String path) {
try {
this.out = new FileOutputStream(path);
} catch (FileNotFoundException e) {
throw new RuntimeException("FastWriter");
}
}
public FastWriter write(byte b) {
buf[ptr++] = b;
if (ptr == BUF_SIZE)
innerflush();
return this;
}
public FastWriter write(char c) {
return write((byte) c);
}
public FastWriter write(char[] s) {
for (char c : s) {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE)
innerflush();
}
return this;
}
public FastWriter write(String s) {
s.chars().forEach(c -> {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE)
innerflush();
});
return this;
}
private static int countDigits(int l) {
if (l >= 1000000000)
return 10;
if (l >= 100000000)
return 9;
if (l >= 10000000)
return 8;
if (l >= 1000000)
return 7;
if (l >= 100000)
return 6;
if (l >= 10000)
return 5;
if (l >= 1000)
return 4;
if (l >= 100)
return 3;
if (l >= 10)
return 2;
return 1;
}
public FastWriter write(int x) {
if (x == Integer.MIN_VALUE) {
return write((long) x);
}
if (ptr + 12 >= BUF_SIZE)
innerflush();
if (x < 0) {
write((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
private static int countDigits(long l) {
if (l >= 1000000000000000000L)
return 19;
if (l >= 100000000000000000L)
return 18;
if (l >= 10000000000000000L)
return 17;
if (l >= 1000000000000000L)
return 16;
if (l >= 100000000000000L)
return 15;
if (l >= 10000000000000L)
return 14;
if (l >= 1000000000000L)
return 13;
if (l >= 100000000000L)
return 12;
if (l >= 10000000000L)
return 11;
if (l >= 1000000000L)
return 10;
if (l >= 100000000L)
return 9;
if (l >= 10000000L)
return 8;
if (l >= 1000000L)
return 7;
if (l >= 100000L)
return 6;
if (l >= 10000L)
return 5;
if (l >= 1000L)
return 4;
if (l >= 100L)
return 3;
if (l >= 10L)
return 2;
return 1;
}
public FastWriter write(long x) {
if (x == Long.MIN_VALUE) {
return write("" + x);
}
if (ptr + 21 >= BUF_SIZE)
innerflush();
if (x < 0) {
write((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
public FastWriter write(double x, int precision) {
if (x < 0) {
write('-');
x = -x;
}
x += Math.pow(10, -precision) / 2;
// if(x < 0){ x = 0; }
write((long) x).write(".");
x -= (long) x;
for (int i = 0; i < precision; i++) {
x *= 10;
write((char) ('0' + (int) x));
x -= (int) x;
}
return this;
}
public FastWriter writeln(char c) {
return write(c).writeln();
}
public FastWriter writeln(int x) {
return write(x).writeln();
}
public FastWriter writeln(long x) {
return write(x).writeln();
}
public FastWriter writeln(double x, int precision) {
return write(x, precision).writeln();
}
public FastWriter write(int... xs) {
boolean first = true;
for (int x : xs) {
if (!first)
write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter write(long... xs) {
boolean first = true;
for (long x : xs) {
if (!first)
write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter writeln() {
return write((byte) '\n');
}
public FastWriter writeln(int... xs) {
return write(xs).writeln();
}
public FastWriter writeln(long... xs) {
return write(xs).writeln();
}
public FastWriter writeln(char[] line) {
return write(line).writeln();
}
public FastWriter writeln(char[]... map) {
for (char[] line : map)
write(line).writeln();
return this;
}
public FastWriter writeln(String s) {
return write(s).writeln();
}
private void innerflush() {
try {
out.write(buf, 0, ptr);
ptr = 0;
} catch (IOException e) {
throw new RuntimeException("innerflush");
}
}
public void flush() {
innerflush();
try {
out.flush();
} catch (IOException e) {
throw new RuntimeException("flush");
}
}
public FastWriter print(byte b) {
return write(b);
}
public FastWriter print(char c) {
return write(c);
}
public FastWriter print(char[] s) {
return write(s);
}
public FastWriter print(String s) {
return write(s);
}
public FastWriter print(int x) {
return write(x);
}
public FastWriter print(long x) {
return write(x);
}
public FastWriter print(double x, int precision) {
return write(x, precision);
}
public FastWriter println(char c) {
return writeln(c);
}
public FastWriter println(int x) {
return writeln(x);
}
public FastWriter println(long x) {
return writeln(x);
}
public FastWriter println(double x, int precision) {
return writeln(x, precision);
}
public FastWriter print(int... xs) {
return write(xs);
}
public FastWriter print(long... xs) {
return write(xs);
}
public FastWriter println(int... xs) {
return writeln(xs);
}
public FastWriter println(long... xs) {
return writeln(xs);
}
public FastWriter println(char[] line) {
return writeln(line);
}
public FastWriter println(char[]... map) {
return writeln(map);
}
public FastWriter println(String s) {
return writeln(s);
}
public FastWriter println() {
return writeln();
}
}
// Fast Inputs
static 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[] readArray(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] readArrayLong(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public int[][] readArrayMatrix(int N, int M, int Index) {
if (Index == 0) {
int[][] res = new int[N][M];
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++)
res[i][j] = (int) nextLong();
}
return res;
}
int[][] res = new int[N][M];
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= M; j++)
res[i][j] = (int) nextLong();
}
return res;
}
public long[][] readArrayMatrixLong(int N, int M, int Index) {
if (Index == 0) {
long[][] res = new long[N][M];
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++)
res[i][j] = nextLong();
}
return res;
}
long[][] res = new long[N][M];
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= M; j++)
res[i][j] = 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[] readArrayDouble(int N) {
double[] res = new double[N];
for (int i = 0; i < N; i++) {
res[i] = nextDouble();
}
return res;
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32)
c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32)
c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
public boolean hasNext() {
if (c > 32)
return true;
while (true) {
c = getChar();
if (c == NC)
return false;
else if (c > 32)
return true;
}
}
}
}
| Java | ["2\n\n2\n\n3"] | 2 seconds | ["2\n1 2\n2 1\n3\n1 2 3\n3 2 1\n3 1 2"] | null | Java 17 | standard input | [
"constructive algorithms",
"math"
] | 02bdd12987af6e666d4283f075f73725 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 99$$$) — the number of testcases. The only line of each testcase contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the required length of permutations in the chain. | 800 | For each testcase, first, print the length of a permutation chain $$$k$$$. Then print $$$k$$$ permutations $$$a_1, a_2, \dots, a_k$$$. $$$a_1$$$ should be an identity permutation of length $$$n$$$ ($$$[1, 2, \dots, n]$$$). For each $$$i$$$ from $$$2$$$ to $$$k$$$, $$$a_i$$$ should be obtained by swapping two elements in $$$a_{i-1}$$$. It should also have a strictly lower fixedness than $$$a_{i-1}$$$. | standard output | |
PASSED | 633c3d0fb810ddaa8759852c5ff0fbc0 | train_109.jsonl | 1659623700 | A permutation of length $$$n$$$ is a sequence of integers from $$$1$$$ to $$$n$$$ such that each integer appears in it exactly once.Let the fixedness of a permutation $$$p$$$ be the number of fixed points in it — the number of positions $$$j$$$ such that $$$p_j = j$$$, where $$$p_j$$$ is the $$$j$$$-th element of the permutation $$$p$$$.You are asked to build a sequence of permutations $$$a_1, a_2, \dots$$$, starting from the identity permutation (permutation $$$a_1 = [1, 2, \dots, n]$$$). Let's call it a permutation chain. Thus, $$$a_i$$$ is the $$$i$$$-th permutation of length $$$n$$$.For every $$$i$$$ from $$$2$$$ onwards, the permutation $$$a_i$$$ should be obtained from the permutation $$$a_{i-1}$$$ by swapping any two elements in it (not necessarily neighboring). The fixedness of the permutation $$$a_i$$$ should be strictly lower than the fixedness of the permutation $$$a_{i-1}$$$.Consider some chains for $$$n = 3$$$: $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$ — that is a valid chain of length $$$2$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. $$$a_1 = [2, 1, 3]$$$, $$$a_2 = [3, 1, 2]$$$ — that is not a valid chain. The first permutation should always be $$$[1, 2, 3]$$$ for $$$n = 3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$, $$$a_3 = [1, 2, 3]$$$ — that is not a valid chain. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped but the fixedness increase from $$$1$$$ to $$$3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [3, 2, 1]$$$, $$$a_3 = [3, 1, 2]$$$ — that is a valid chain of length $$$3$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$1$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$1$$$ to $$$0$$$. Find the longest permutation chain. If there are multiple longest answers, print any of them. | 256 megabytes | // O(NN)
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.HashSet;
import java.util.NoSuchElementException;
public class Main implements Runnable {
public static void main(String[] args) {
new Thread(null, new Main(), "", Runtime.getRuntime().maxMemory()).start();
}
HashSet<String> set=new HashSet<>();
void dfs(boolean[] vis, int n, ArrayDeque<Integer> dq) {
boolean found = false;
for (int mod=1;mod<vis.length;++mod) {
if (!vis[mod]) {
found = true;
vis[mod]=true;
int nn = n%mod;
dq.addLast(nn);
dfs(vis, nn, dq);
dq.pollLast();
vis[mod]=false;
}
}
if (!found) {
String str = "";
for (int i=0;i<dq.size();++i) {
str = str + String.valueOf(dq.peekFirst());
dq.addLast(dq.pollFirst());
}
set.add(str);
}
}
void check() {
int n = 10;
boolean[] vis = new boolean[n+1];
ArrayDeque<Integer> dq=new ArrayDeque<>();
dfs(vis, n, dq);
System.out.println(set.size());
}
public void run() {
FastScanner sc = new FastScanner();
PrintWriter pw = new PrintWriter(System.out);
int T=sc.nextInt();
while (T-->0) {
int n = sc.nextInt();
pw.println(n);
for (int t = 0; t < n; ++t) {
int[] a = new int[n];
for (int i = 0; i < t; ++i) {
a[i] = 2 + i;
}
a[t] = 1;
for (int i = t + 1; i < n; ++i) {
a[i] = i + 1;
}
for (int i=0;i<n;++i) {
pw.print(a[i] + (i == n - 1 ? "\n" : " "));
}
}
}
pw.close();
}
void tr(Object... objects) {
System.err.println(Arrays.deepToString(objects));
}
}
class FastScanner {
private final InputStream in = System.in;
private final byte[] buffer = new byte[1024];
private int ptr = 0;
private int buflen = 0;
private boolean hasNextByte() {
if (ptr < buflen) {
return true;
} else {
ptr = 0;
try {
buflen = in.read(buffer);
} catch (IOException e) {
e.printStackTrace();
}
if (buflen <= 0) {
return false;
}
}
return true;
}
private int readByte() {
if (hasNextByte())
return buffer[ptr++];
else
return -1;
}
private static boolean isPrintableChar(int c) {
return 33 <= c && c <= 126;
}
private void skipUnprintable() {
while (hasNextByte() && !isPrintableChar(buffer[ptr]))
ptr++;
}
public boolean hasNext() {
skipUnprintable();
return hasNextByte();
}
public String next() {
if (!hasNext())
throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = readByte();
while (isPrintableChar(b)) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public long nextLong() {
if (!hasNext())
throw new NoSuchElementException();
long n = 0;
boolean minus = false;
int b = readByte();
if (b == '-') {
minus = true;
b = readByte();
}
if (b < '0' || '9' < b) {
throw new NumberFormatException();
}
while (true) {
if ('0' <= b && b <= '9') {
n *= 10;
n += b - '0';
} else if (b == -1 || !isPrintableChar(b)) {
return minus ? -n : n;
} else {
throw new NumberFormatException();
}
b = readByte();
}
}
public int nextInt() {
return (int) nextLong();
}
} | Java | ["2\n\n2\n\n3"] | 2 seconds | ["2\n1 2\n2 1\n3\n1 2 3\n3 2 1\n3 1 2"] | null | Java 17 | standard input | [
"constructive algorithms",
"math"
] | 02bdd12987af6e666d4283f075f73725 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 99$$$) — the number of testcases. The only line of each testcase contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the required length of permutations in the chain. | 800 | For each testcase, first, print the length of a permutation chain $$$k$$$. Then print $$$k$$$ permutations $$$a_1, a_2, \dots, a_k$$$. $$$a_1$$$ should be an identity permutation of length $$$n$$$ ($$$[1, 2, \dots, n]$$$). For each $$$i$$$ from $$$2$$$ to $$$k$$$, $$$a_i$$$ should be obtained by swapping two elements in $$$a_{i-1}$$$. It should also have a strictly lower fixedness than $$$a_{i-1}$$$. | standard output | |
PASSED | c604f68281a3c657224dd5e85d28483a | train_109.jsonl | 1659623700 | A permutation of length $$$n$$$ is a sequence of integers from $$$1$$$ to $$$n$$$ such that each integer appears in it exactly once.Let the fixedness of a permutation $$$p$$$ be the number of fixed points in it — the number of positions $$$j$$$ such that $$$p_j = j$$$, where $$$p_j$$$ is the $$$j$$$-th element of the permutation $$$p$$$.You are asked to build a sequence of permutations $$$a_1, a_2, \dots$$$, starting from the identity permutation (permutation $$$a_1 = [1, 2, \dots, n]$$$). Let's call it a permutation chain. Thus, $$$a_i$$$ is the $$$i$$$-th permutation of length $$$n$$$.For every $$$i$$$ from $$$2$$$ onwards, the permutation $$$a_i$$$ should be obtained from the permutation $$$a_{i-1}$$$ by swapping any two elements in it (not necessarily neighboring). The fixedness of the permutation $$$a_i$$$ should be strictly lower than the fixedness of the permutation $$$a_{i-1}$$$.Consider some chains for $$$n = 3$$$: $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$ — that is a valid chain of length $$$2$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. $$$a_1 = [2, 1, 3]$$$, $$$a_2 = [3, 1, 2]$$$ — that is not a valid chain. The first permutation should always be $$$[1, 2, 3]$$$ for $$$n = 3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$, $$$a_3 = [1, 2, 3]$$$ — that is not a valid chain. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped but the fixedness increase from $$$1$$$ to $$$3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [3, 2, 1]$$$, $$$a_3 = [3, 1, 2]$$$ — that is a valid chain of length $$$3$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$1$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$1$$$ to $$$0$$$. Find the longest permutation chain. If there are multiple longest answers, print any of them. | 256 megabytes | import java.util.*;
import java.util.function.*;
import java.io.*;
// you can compare with output.txt and expected out
public class RoundEdu133B {
MyPrintWriter out;
MyScanner in;
// final static long FIXED_RANDOM;
// static {
// FIXED_RANDOM = System.currentTimeMillis();
// }
final static String IMPOSSIBLE = "IMPOSSIBLE";
final static String POSSIBLE = "POSSIBLE";
final static String YES = "YES";
final static String NO = "NO";
private void initIO(boolean isFileIO) {
if (System.getProperty("ONLINE_JUDGE") == null && isFileIO) {
try{
in = new MyScanner(new FileInputStream("input.txt"));
out = new MyPrintWriter(new FileOutputStream("output.txt"));
}
catch(FileNotFoundException e){
e.printStackTrace();
}
}
else{
in = new MyScanner(System.in);
out = new MyPrintWriter(new BufferedOutputStream(System.out));
}
}
public static void main(String[] args){
// Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
RoundEdu133B sol = new RoundEdu133B();
sol.run();
}
private void run() {
boolean isDebug = false;
boolean isFileIO = true;
boolean hasMultipleTests = true;
initIO(isFileIO);
int t = hasMultipleTests? in.nextInt() : 1;
for (int i = 1; i <= t; ++i) {
if(isDebug){
out.printf("Test %d\n", i);
}
getInput();
solve();
printOutput();
}
in.close();
out.close();
}
// use suitable one between matrix(2, n) or matrix(n, 2) for graph edges, pairs, ...
int n;
void getInput() {
n = in.nextInt();
}
void printOutput() {
out.printlnAns(ans.length);
for(int[] a: ans)
out.printlnAns(a, 1);
}
int[][] ans;
void solve(){
ans = new int[n][n];
int[] a = new int[n];
for(int i=0; i<n; i++)
a[i] = i;
ans[0] = a;
for(int i=1; i<n; i++) {
a = Arrays.copyOf(ans[i-1], n);
int temp = a[n-1];
a[n-1] = a[i-1];
a[i-1] = temp;
ans[i] = a;
}
}
static class Pair implements Comparable<Pair>{
final static long FIXED_RANDOM = System.currentTimeMillis();
int first, second;
public Pair(int first, int second) {
this.first = first;
this.second = second;
}
@Override
public int hashCode() {
// http://xorshift.di.unimi.it/splitmix64.c
long x = first;
x <<= 32;
x += second;
x += FIXED_RANDOM;
x += 0x9e3779b97f4a7c15l;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9l;
x = (x ^ (x >> 27)) * 0x94d049bb133111ebl;
return (int)(x ^ (x >> 31));
}
@Override
public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
Pair other = (Pair) obj;
return first == other.first && second == other.second;
}
@Override
public String toString() {
return "[" + first + "," + second + "]";
}
@Override
public int compareTo(Pair o) {
int cmp = Integer.compare(first, o.first);
return cmp != 0? cmp: Integer.compare(second, o.second);
}
}
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
// 32768?
public MyScanner(InputStream is, int bufferSize) {
br = new BufferedReader(new InputStreamReader(is), bufferSize);
}
public MyScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
// br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));
}
public void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[][] nextMatrix(int n, int m) {
return nextMatrix(n, m, 0);
}
int[][] nextMatrix(int n, int m, int offset) {
int[][] mat = new int[n][m];
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
mat[i][j] = nextInt()+offset;
}
}
return mat;
}
int[] nextIntArray(int len) {
return nextIntArray(len, 0);
}
int[] nextIntArray(int len, int offset){
int[] a = new int[len];
for(int j=0; j<len; j++)
a[j] = nextInt()+offset;
return a;
}
long[] nextLongArray(int len) {
return nextLongArray(len, 0);
}
long[] nextLongArray(int len, int offset){
long[] a = new long[len];
for(int j=0; j<len; j++)
a[j] = nextLong()+offset;
return a;
}
String[] nextStringArray(int len) {
String[] s = new String[len];
for(int i=0; i<len; i++)
s[i] = next();
return s;
}
}
public static class MyPrintWriter extends PrintWriter{
public MyPrintWriter(OutputStream os) {
super(os);
}
public void printlnAns(long ans) {
println(ans);
}
public void printlnAns(int ans) {
println(ans);
}
public void printlnAns(boolean ans) {
if(ans)
println(YES);
else
println(NO);
}
public void printAns(long[] arr){
if(arr != null && arr.length > 0){
print(arr[0]);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]);
}
}
}
public void printlnAns(long[] arr){
printAns(arr);
println();
}
public void printAns(int[] arr){
if(arr != null && arr.length > 0){
print(arr[0]);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]);
}
}
}
public void printlnAns(int[] arr){
printAns(arr);
println();
}
public <T> void printAns(ArrayList<T> arr){
if(arr != null && arr.size() > 0){
print(arr.get(0));
for(int i=1; i<arr.size(); i++){
print(" ");
print(arr.get(i));
}
}
}
public <T> void printlnAns(ArrayList<T> arr){
printAns(arr);
println();
}
public void printAns(int[] arr, int add){
if(arr != null && arr.length > 0){
print(arr[0]+add);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]+add);
}
}
}
public void printlnAns(int[] arr, int add){
printAns(arr, add);
println();
}
public void printAns(ArrayList<Integer> arr, int add) {
if(arr != null && arr.size() > 0){
print(arr.get(0)+add);
for(int i=1; i<arr.size(); i++){
print(" ");
print(arr.get(i)+add);
}
}
}
public void printlnAns(ArrayList<Integer> arr, int add){
printAns(arr, add);
println();
}
public void printlnAnsSplit(long[] arr, int split){
if(arr != null){
for(int i=0; i<arr.length; i+=split){
print(arr[i]);
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr[j]);
}
println();
}
}
}
public void printlnAnsSplit(int[] arr, int split){
if(arr != null){
for(int i=0; i<arr.length; i+=split){
print(arr[i]);
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr[j]);
}
println();
}
}
}
public <T> void printlnAnsSplit(ArrayList<T> arr, int split){
if(arr != null && !arr.isEmpty()){
for(int i=0; i<arr.size(); i+=split){
print(arr.get(i));
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr.get(j));
}
println();
}
}
}
}
static private void permutateAndSort(long[] a) {
int n = a.length;
Random R = new Random(System.currentTimeMillis());
for(int i=0; i<n; i++) {
int t = R.nextInt(n-i);
long temp = a[n-1-i];
a[n-1-i] = a[t];
a[t] = temp;
}
Arrays.sort(a);
}
static private void permutateAndSort(int[] a) {
int n = a.length;
Random R = new Random(System.currentTimeMillis());
for(int i=0; i<n; i++) {
int t = R.nextInt(n-i);
int temp = a[n-1-i];
a[n-1-i] = a[t];
a[t] = temp;
}
Arrays.sort(a);
}
static private int[][] constructChildren(int n, int[] parent, int parentRoot){
int[][] childrens = new int[n][];
int[] numChildren = new int[n];
for(int i=0; i<parent.length; i++) {
if(parent[i] != parentRoot)
numChildren[parent[i]]++;
}
for(int i=0; i<n; i++) {
childrens[i] = new int[numChildren[i]];
}
int[] idx = new int[n];
for(int i=0; i<parent.length; i++) {
if(parent[i] != parentRoot)
childrens[parent[i]][idx[parent[i]]++] = i;
}
return childrens;
}
static private int[][][] constructDirectedNeighborhood(int n, int[][] e){
int[] inDegree = new int[n];
int[] outDegree = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
outDegree[u]++;
inDegree[v]++;
}
int[][] inNeighbors = new int[n][];
int[][] outNeighbors = new int[n][];
for(int i=0; i<n; i++) {
inNeighbors[i] = new int[inDegree[i]];
outNeighbors[i] = new int[outDegree[i]];
}
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
outNeighbors[u][--outDegree[u]] = v;
inNeighbors[v][--inDegree[v]] = u;
}
return new int[][][] {inNeighbors, outNeighbors};
}
static private int[][] constructNeighborhood(int n, int[][] e) {
int[] degree = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
degree[u]++;
degree[v]++;
}
int[][] neighbors = new int[n][];
for(int i=0; i<n; i++)
neighbors[i] = new int[degree[i]];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
neighbors[u][--degree[u]] = v;
neighbors[v][--degree[v]] = u;
}
return neighbors;
}
static private void drawGraph(int[][] e) {
makeDotUndirected(e);
try {
final Process process = new ProcessBuilder("dot", "-Tpng", "graph.dot")
.redirectOutput(new File("graph.png"))
.start();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
static private void makeDotUndirected(int[][] e) {
MyPrintWriter out2 = null;
try {
out2 = new MyPrintWriter(new FileOutputStream("graph.dot"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
out2.println("strict graph {");
for(int i=0; i<e.length; i++){
out2.println(e[i][0] + "--" + e[i][1] + ";");
}
out2.println("}");
out2.close();
}
static private void makeDotDirected(int[][] e) {
MyPrintWriter out2 = null;
try {
out2 = new MyPrintWriter(new FileOutputStream("graph.dot"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
out2.println("strict digraph {");
for(int i=0; i<e.length; i++){
out2.println(e[i][0] + "->" + e[i][1] + ";");
}
out2.println("}");
out2.close();
}
}
| Java | ["2\n\n2\n\n3"] | 2 seconds | ["2\n1 2\n2 1\n3\n1 2 3\n3 2 1\n3 1 2"] | null | Java 17 | standard input | [
"constructive algorithms",
"math"
] | 02bdd12987af6e666d4283f075f73725 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 99$$$) — the number of testcases. The only line of each testcase contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the required length of permutations in the chain. | 800 | For each testcase, first, print the length of a permutation chain $$$k$$$. Then print $$$k$$$ permutations $$$a_1, a_2, \dots, a_k$$$. $$$a_1$$$ should be an identity permutation of length $$$n$$$ ($$$[1, 2, \dots, n]$$$). For each $$$i$$$ from $$$2$$$ to $$$k$$$, $$$a_i$$$ should be obtained by swapping two elements in $$$a_{i-1}$$$. It should also have a strictly lower fixedness than $$$a_{i-1}$$$. | standard output | |
PASSED | 33885f7465a817b282f8f3a0f452c284 | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | import java.util.*;
import java.io.*;
public class ybg{
static int [][] ss;
static int [][] s;
public static void main(String[]args) {
PrintWriter d = new PrintWriter(new OutputStreamWriter(System.out));
FastScanner c = new FastScanner();
int a = c.nextInt();
for(int aa = 0; aa < a; aa++){
int n = c.nextInt();
int [][] z = new int [2][n];
int [][] s = new int [2][n];
int [][] sc = new int [2][n];
int [][] ss = new int [2][n];
int [][] ssc = new int [2][n];
for(int q = 0; q < n; q++){
z[0][q] = c.nextInt();
sc[0][q] = z[0][q] - q + 1;
ssc[0][q] = z[0][q] - 2*n + q + 1;
if(q == 0) sc[0][q] = 0;
}
for(int q = 0; q < n; q++){
z[1][q] = c.nextInt();
sc[1][q] = z[1][q] - n*2 + q + 2;
ssc[1][q] = z[1][q] - q;
}
for(int q = n - 1; q >= 0; q--){
sc[0][q] = Math.max(sc[0][q] , sc[1][q]);
if(q != 0) sc[0][q - 1] = Math.max(sc[0][q] , sc[0][q - 1]);
ssc[0][q] = Math.max(ssc[0][q] , ssc[1][q]);
if(q != 0) ssc[0][q - 1] = Math.max(ssc[0][q] , ssc[0][q - 1]);
}
/*int st = 0;
for(int q = 1; q < n; q++){
st = Math.max(st + 1, z[0][q] + 1);
s[0][q] = st;
}
for(int q = n - 1; q >= 0; q--){
st = Math.max(st + 1, z[1][q] + 1);
s[1][q] = st;
}
// int t = 0;
/*for(int q = 0; q < n; q++){
t = Math.max(t + 1, z[0][q] + 1);
s[0][q] = st - t + 1;
}
for(int q = n - 1; q >= 1; q--){
t = Math.max(t + 1, z[1][q] + 1);
s[1][q] = st - t + 1;
}*/
/*st = 0;
for(int q = 0; q < n; q++){
st = Math.max(st + 1, z[1][q] + 1);
ss[1][q] = st;
}
for(int q = n - 1; q >= 1; q--){
st = Math.max(st + 1, z[0][q] + 1);
ss[0][q] = st;
}*/
/* t = 0;
for(int q = 0; q < n; q++){
t = Math.max(t + 1, z[1][q] + 1);
ss[1][q] = st - t + 1;
}
for(int q = n - 1; q >= 1; q--){
t = Math.max(t + 1, z[0][q] + 1);
ss[0][q] = st - t + 1;
}*/
/*int o = 1;
for(int q = n - 2; q >= 0; q--){
sy[q] = s[1][q]-s[0][q] - (2*o + 1);
ssy[q] = ss[0][q]-ss[1][q] - (2*o + 1);
o++;
}*/
int ans = Integer.MAX_VALUE;
int w = 0;
int tt = 0;
for(int q = 0; q <n; q++){
if(w == 0){
w = 1;
if(q != n - 1)ans = Math.min(tt+Math.max(0,sc[0][q] - tt + q) + 2*(n-q-1)+1, ans);
tt = Math.max(tt + 1, z[1][q] + 1);
if(q < n - 1) tt = Math.max(tt + 1, z[1][q + 1] + 1);
}
else{
w = 0;
if(q != n - 1)ans = Math.min(tt+Math.max(0,ssc[0][q] - tt + q + 1) + 2*(n-q-1)+1, ans);
tt = Math.max(tt + 1, z[0][q] + 1);
if(q < n - 1) tt = Math.max(tt + 1, z[0][q + 1] + 1);
}
}
ans = Math.min(ans , tt);
/*if(aa == 183){
for(int q = 0; q < n; q++){
d.print(z[0][q]+""+z[1][q]);
}
d.println();
}*/
d.println(ans);
}
d.close();
}
/*1
3
0 0 1
4 3 2 */
static class p implements Comparable<p>{
int j,k,l;
p(int j, int k){
this.j = j;
this.k =k;
}
public int compareTo(p o) {
return Integer.compare(j, o.j);
}
}
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;
}
}
}
/*
import java.util.*;
import java.io.*;
public class ybg{
static int [][] ss;
static int [][] s;
public static void main(String[]args) {
PrintWriter d = new PrintWriter(new OutputStreamWriter(System.out));
FastScanner c = new FastScanner();
int a = c.nextInt();
for(int aa = 0; aa < a; aa++){
int n = c.nextInt();
int [][] z = new int [2][n];
int [][] s = new int [2][n];
int [][] ss = new int [2][n];
int [] sy = new int [2][n];
for(int q = 0; q < n; q++) z[0][q] = c.nextInt();
for(int q = 0; q < n; q++) z[1][q] = c.nextInt();
int st = 0;
for(int q = 1; q < n; q++){
st = Math.max(st + 1, z[0][q] + 1);
}
for(int q = n - 1; q >= 0; q--){
st = Math.max(st + 1, z[1][q] + 1);
}
int t = 0;
for(int q = 0; q < n; q++){
t = Math.max(t + 1, z[0][q] + 1);
s[0][q] = st - t + 1;
}
for(int q = n - 1; q >= 1; q--){
t = Math.max(t + 1, z[1][q] + 1);
s[1][q] = st - t + 1;
}
st = 0;
for(int q = 0; q < n; q++){
st = Math.max(st + 1, z[1][q] + 1);
}
for(int q = n - 1; q >= 1; q--){
st = Math.max(st + 1, z[0][q] + 1);
}
t = 0;
for(int q = 0; q < n; q++){
t = Math.max(t + 1, z[1][q] + 1);
ss[1][q] = st - t + 1;
}
for(int q = n - 1; q >= 1; q--){
t = Math.max(t + 1, z[0][q] + 1);
ss[0][q] = st - t + 1;
}
int [] sy = new int [n];
int [] ssy = new int [n];
int o = n%2 == 0 ? 0 : 1;
for(int q = n - 2; q >= 0; q++){
if(q != 0) ssy[q] =
sy[q]
o++;
}
int ans = st;
int w = 0;
int tt = 0;
for(int q = 0; q < n; q++){
if(w == 0){
w = 1;
if(tt > sy[q]) ans = Math.min(tt - s[1][q] + s[0][q] - sy[q] , ans);
else ans = Math.min(tt - s[1][q] + s[0][q] , ans);
tt = Math.max(tt + 1, z[1][q] + 1);
if(q < n - 1) tt = Math.max(tt + 1, z[1][q + 1] + 1);
}
else{
w = 0;
ans = Math.min(tt - ss[0][q - 1] + ss[1][q] , ans);
tt = Math.max(tt + 1, z[0][q] + 1);
if(q < n - 1) tt = Math.max(tt + 1, z[0][q + 1] + 1);
}
}
ans = Math.min(ans , tt);
/*if(aa == 3581){
for(int q = 0; q < n; q++){
d.print(z[0][q]+""+z[1][q]);
}
d.println();
}
d.println(ans);
}
d.close();
}
/*1
3
0 0 1
4 3 2
static class p implements Comparable<p>{
int j,k,l;
p(int j, int k){
this.j = j;
this.k =k;
}
public int compareTo(p o) {
return Integer.compare(j, o.j);
}
}
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;
}
}
}*/ | Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 8 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | dad97780e4d95f08c01c64fc48cb9d43 | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | import java.io.*;
import java.util.*;
/*
1
2
0 1
0 1
1
3
0 0 1
4 3 2
*/
public class C{
static FastReader sc=null;
static int dx[]= {1,0,-1,0},dy[]= {0,1,0,1};
public static void main(String[] args) {
sc=new FastReader();
int t=sc.nextInt();
for(int tt=0;tt<t;tt++) {
int m=sc.nextInt();
int a[][]=new int[2][m];
for(int i=0;i<2;i++) {
a[i]=sc.readArray(m);
for(int j=0;j<m;j++)if(a[i][j]==0)a[i][j]--;
//print(a[i]);
}
int moves[][]=new int[2][m];
int x=0,y=0,c=0;
for(int i=0;i<2*m;i++) {
int d=i%4;
moves[x][y]=c++;
x+=dx[d];
y+=dy[d];
}
long l=-1,r=(long)2e9+5;
while(l+1<r) {
long mid=(l+r)/2;
if(pos(a,mid,moves))r=mid;
else l=mid;
}
//System.out.println(r);
System.out.println(r+2*m-1);
}
}
static boolean pos(int a[][],long wait, int moves[][]) {
//System.out.println("Wait time: "+wait);
int m=a[0].length;
boolean visited[][]=new boolean[2][m];
int x=0,y=0,c=0;
visited[x][y]=true;
int xa=1,ya=m;
while(y<m) {
int xi=x+dx[c],yi=y+dy[c];
if(yi==m)return true;
int mi=moves[xi][yi];
if(a[xi][yi]<wait+mi) {
visited[xi][yi]=true;
//System.out.println("Possible :"+xi+" "+yi);
x=xi;
y=yi;
c++;
if(c>=4)c-=4;
continue;
}
//we move one position back
xa=x;
ya=y;
if(c==1 || c==3) {
visited[xa][ya]=false;
xa=1-xa;
}
//System.out.println("Broke here "+xi+" "+yi+" value is "+a[xi][yi]+" "+mi+" going from "+xa+" "+ya);
break;
}
long cur=wait+moves[xa][ya];
while(ya<m) {
//System.out.println(xa+" "+ya+" "+cur+" "+a[xa][ya]);
if(a[xa][ya]>=cur)return false;
visited[xa][ya]=true;
ya++;
cur++;
}
xa=1-xa;
ya--;
while(ya>=y) {
//System.out.println(xa+" "+ya+" "+cur+" "+a[xa][ya]);
if(a[xa][ya]>=cur)return false;
visited[xa][ya]=true;
ya--;
cur++;
}
for(int i=0;i<2;i++) {
for(int j=0;j<m;j++)if(!visited[i][j])throw null;
}
return true;
}
static int[] ruffleSort(int a[]) {
ArrayList<Integer> al=new ArrayList<>();
for(int i:a)al.add(i);
Collections.sort(al);
for(int i=0;i<a.length;i++)a[i]=al.get(i);
return a;
}
static void print(int a[]) {
for(int e:a) {
System.out.print(e+" ");
}
System.out.println();
}
static class FastReader{
StringTokenizer st=new StringTokenizer("");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String next() {
while(!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
}
catch(IOException e){
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
int[] readArray(int n) {
int a[]=new int[n];
for(int i=0;i<n;i++)a[i]=sc.nextInt();
return a;
}
}
}
| Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 8 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | 42c5d7094bc1ce11a5397e5351685bae | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | import java.io.PrintWriter;
import java.util.Scanner;
public class Main02 {
static Scanner in = new Scanner(System.in);
static PrintWriter out = new PrintWriter(System.out);
static StringBuilder res = new StringBuilder();
public static void main(String[] args) {
int t = Integer.parseInt(in.nextLine());
int m = 0;
int mi = 0;
long oneRes = 0;
long[][] hallway = null;
long[][] upDown = null;
long[][] downUp = null;
for(int i = 0; i < t; i++){
m = Integer.parseInt(in.nextLine());
hallway = new long[2][m + 1];
upDown = new long[2][m + 1];
downUp = new long[2][m + 1];
oneRes = Long.MAX_VALUE;
mi = 1;
for(String col : in.nextLine().split(" ")){
hallway[0][mi] = Integer.parseInt(col);
if(mi > 1){
hallway[0][mi]++;
}
upDown[0][mi] = hallway[0][mi] - (mi - 1);
downUp[0][mi] = hallway[0][mi] - (m + m - mi);
mi++;
}
mi = 1;
for(String col : in.nextLine().split(" ")){
hallway[1][mi] = Integer.parseInt(col) + 1;
upDown[1][mi] = hallway[1][mi] - (m + m - mi);
downUp[1][mi] = hallway[1][mi] - (mi - 1);
mi++;
}
for(mi = m - 1; mi >= 1; mi--){
upDown[0][mi] = Math.max(upDown[0][mi], upDown[0][mi + 1]);
upDown[1][mi] = Math.max(upDown[1][mi], upDown[1][mi + 1]);
downUp[0][mi] = Math.max(downUp[0][mi], downUp[0][mi + 1]);
downUp[1][mi] = Math.max(downUp[1][mi], downUp[1][mi + 1]);
}
long now = 0;
for(mi = 1; mi <= m; mi++){
if(mi % 2 == 1){
oneRes = Math.min(oneRes, Math.max(now, Math.max(upDown[0][mi] - (mi - 1), upDown[1][mi] - (mi - 1))) + m + m - 1);
now = Math.max(now, hallway[0][mi] - (2L * mi - 2));
now = Math.max(now, hallway[1][mi] - (2L * mi - 1));
}else{
oneRes = Math.min(oneRes, Math.max(now, Math.max(downUp[0][mi] - (mi - 1), downUp[1][mi] - (mi - 1))) + m + m - 1);
now = Math.max(now, hallway[1][mi] - (2L * mi - 2));
now = Math.max(now, hallway[0][mi] - (2L * mi - 1));
}
}
oneRes = Math.min(oneRes, now + 2L * m - 1);
res.append(oneRes + "\n");
}
in.close();
out.print(res);
out.flush();
}
}
| Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 8 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | 6cb9bb42be7513c8594c0526e39399bf | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes |
import java.io.*;
import java.util.*;
public class Sol {
static Scanner rd = new Scanner(System.in);
public static void main(String[] args) {
int tt = rd.nextInt();
while (tt-- > 0) {
new Solution().solve();
}
}
static int INF = Integer.MAX_VALUE;
static class Solution {
int m;
int[][] g;
void solve() {
m = rd.nextInt();
g = new int[2][m];
memo = new Integer[2][m];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < m; j++) {
g[i][j] = rd.nextInt() + 1;
}
}
g[0][0]--;
// System.out.println(solve2(g, 0, 0, 0));
int cur = 0;
int ans = INF;
for (int i = 0; i < m; i++) {
if (i % 2 == 0) {
int step = (m - 1 - i) * 2 + 1;
int t = f2(0, i);
if (cur >= t) {
ans = Math.min(ans, cur + step);
} else {
ans = Math.min(ans, t + step);
}
// Utils.printf("i=%d cur=%d step=%d t=%d ans=%d\n", i, cur, step, t, ans);
cur = Math.max(cur, g[0][i]);
cur++;
cur = Math.max(cur, g[1][i]);
cur++;
} else {
int step = (m - 1 - i) * 2 + 1;
int t = f2(1, i);
if (cur >= t) {
ans = Math.min(ans, cur + step);
} else {
ans = Math.min(ans, t + step);
}
// Utils.printf("i=%d cur=%d step=%d t=%d ans=%d\n", i, cur, step, t, ans);
cur = Math.max(cur, g[1][i]);
cur++;
cur = Math.max(cur, g[0][i]);
cur++;
}
}
System.out.println(ans);
}
Integer[][] memo;
int f2(int x, int y) {
if (memo[x][y] != null) return memo[x][y];
int res = INF;
if (y == m - 1) {
res = Math.max(g[x][y], g[1 - x][y] - 1);
} else {
int t = f2(x, y + 1);
int step = 2 * (m - 1 - y) + 1;
if (g[x][y] + 1 >= t) {
int last = g[x][y] + step;
if (last < g[1 - x][y]) {
res = g[x][y] + g[1 - x][y] - last;
} else {
res = g[x][y];
}
} else {
int last = t + step - 1;
if (last < g[1 - x][y]) {
res = t - 1 + g[1 - x][y] - last;
} else {
res = t - 1;
}
}
}
memo[x][y] = res;
// Utils.printf("x=%d y=%d f2=%d\n", x, y, res);
return res;
}
}
static class Reader {
private BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
private StringTokenizer tokenizer = new StringTokenizer("");
private String innerNextLine() {
try {
return reader.readLine();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
public boolean hasNext() {
while (!tokenizer.hasMoreTokens()) {
String nextLine = innerNextLine();
if (nextLine == null) {
return false;
}
tokenizer = new StringTokenizer(nextLine);
}
return true;
}
public String nextLine() {
tokenizer = new StringTokenizer("");
return innerNextLine();
}
public String next() {
hasNext();
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.valueOf(next());
}
public long nextLong() {
return Long.valueOf(next());
}
public double nextDouble() {
return Double.valueOf(next());
}
}
}
| Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 8 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | 51729d147ed9f07dc2ab00c71e64d1a8 | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class c {
public static void main(String[] args) {
FastScanner scan=new FastScanner();
PrintWriter out=new PrintWriter(System.out);
/*
reframe your thinking.
instead of go*stop*go*stop*go*stop,
just wait for some amount of minutes at the beginning
and then do it all in one go.
how long do you have to wait at the start
so that you will never get stuck?
*/
int t=scan.nextInt();
for(int tt=0;tt<t;tt++) {
int n=scan.nextInt();
int[][] a=new int[2][n];
for(int i=0;i<2;i++) {
for(int j=0;j<n;j++) {
a[i][j]=scan.nextInt();
}
}
a[0][0]--;
di=new int[2][n];
dj=new int[2][n];
for(int i=0;i<n;i++) {
if(i%2==0) {
di[0][i]=1;
dj[1][i]=1;
}
else {
di[1][i]=-1;
dj[0][i]=1;
}
}
int best=-1;
int lo=0, hi=1_000_000_000;
while(hi>=lo) {
int mid=(hi+lo)/2;
if(canWait(a,mid)) {
hi=mid-1;
best=mid;
}
else lo=mid+1;
}
out.println(best+2*n-1);
}
out.close();
}
public static boolean canWait(int[][] a, int time) {
int ci=0, cj=0;
int step=0;
while(cj<a[0].length) {
if(a[ci][cj]>=time) {
if(step%2==0) {
return hook(a,1-ci,cj-1,time-2);
}
return hook(a,1-ci,cj,time-1);
}
time++;
step++;
int ni=di[ci][cj]+ci;
int nj=dj[ci][cj]+cj;
ci=ni;
cj=nj;
}
return true;
}
public static boolean hook(int[][] a, int ci, int cj, int time) {
for(int j=cj+1;j<a[0].length;j++) {
if(a[ci][j]<=time) {
time++;
}
else return false;
}
for(int j=a[0].length-1;j>=cj;j--) {
if(a[1-ci][j]<=time) {
time++;
}
else return false;
}
return true;
}
static int[][] di,dj;
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;
}
}
} | Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 8 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | 7952be42af38beda39daf3483cfc0f26 | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 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 tauros
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
RealFastReader in = new RealFastReader(inputStream);
FastWriter out = new FastWriter(outputStream);
CF1716C solver = new CF1716C();
solver.solve(1, in, out);
out.close();
}
static class CF1716C {
public void solve(int testNumber, RealFastReader in, FastWriter out) {
int cases = in.ni();
while (cases-- > 0) {
int m = in.ni();
int[][] grid = new int[2][];
for (int i = 0; i < 2; i++) {
grid[i] = in.na(m);
}
int[][] cw = new int[2][m];
for (int i = 1; i < m; i++) {
cw[0][i] = Math.max(grid[0][i], cw[0][i - 1]) + 1;
}
cw[1][m - 1] = Math.max(grid[1][m - 1], cw[0][m - 1]) + 1;
for (int i = m - 2; i >= 0; i--) {
cw[1][i] = Math.max(grid[1][i], cw[1][i + 1]) + 1;
}
int[][] ccw = new int[2][m];
ccw[1][1] = Math.max(grid[1][1], grid[1][0] + 1) + 1;
for (int i = 2; i < m; i++) {
ccw[1][i] = Math.max(grid[1][i], ccw[1][i - 1]) + 1;
}
ccw[0][m - 1] = Math.max(grid[0][m - 1], ccw[1][m - 1]) + 1;
for (int i = m - 2; i >= 1; i--) {
ccw[0][i] = Math.max(grid[0][i], ccw[0][i + 1]) + 1;
}
int ans = Math.min(cw[1][0], ccw[0][1]);
int dp = grid[1][0] + 1;
for (int i = 1; i < m; i++) {
if (i % 2 == 0) {
dp = Math.max(grid[0][i], dp) + 1;
dp = Math.max(grid[1][i], dp) + 1;
if (i < m - 1) {
int res = Math.max(dp + (m - i - 1) * 2, ccw[0][i + 1]);
ans = Math.min(ans, res);
}
} else {
dp = Math.max(grid[1][i], dp) + 1;
dp = Math.max(grid[0][i], dp) + 1;
if (i < m - 1) {
int res = Math.max(dp + (m - i - 1) * 2, cw[1][i + 1]);
ans = Math.min(ans, res);
}
}
}
out.println(Math.min(ans, dp));
}
out.flush();
}
}
static class RealFastReader {
InputStream is;
private byte[] inbuf = new byte[1024];
public int lenbuf = 0;
public int ptrbuf = 0;
public RealFastReader(final InputStream is) {
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 int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = ni();
}
return a;
}
public int ni() {
int 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();
}
}
}
static class FastWriter {
private final PrintWriter writer;
public FastWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public FastWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void println(int x) {
writer.println(x);
}
public void flush() {
writer.flush();
}
public void close() {
writer.flush();
try {
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
} | Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 8 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | 651e9fcde3a80fbcbfb41aac6623ab22 | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 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 tauros
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
RealFastReader in = new RealFastReader(inputStream);
FastWriter out = new FastWriter(outputStream);
CF1716C solver = new CF1716C();
solver.solve(1, in, out);
out.close();
}
static class CF1716C {
public void solve(int testNumber, RealFastReader in, FastWriter out) {
int cases = in.ni();
while (cases-- > 0) {
int m = in.ni();
int[][] grid = new int[2][];
for (int i = 0; i < 2; i++) {
grid[i] = in.na(m);
}
int[][] u = new int[2][m + 1];
for (int i = 0; i < 2; i++) {
for (int j = m - 1; j >= 0; j--) {
u[i][j] = Math.max(Math.max(grid[i][j] + 1 + 2 * (m - 1 - j), u[i][j + 1]) + 1, grid[i ^ 1][j] + 1);
}
}
int ans = Math.max(u[0][1] + 1, grid[1][0] + 1);
int dp = grid[1][0] + 1;
for (int i = 1; i < m; i++) {
int res = Math.max(dp + (m - i) * 2, u[i & 1][i]);
ans = Math.min(ans, res);
dp = Math.max(grid[i & 1][i], dp) + 1;
dp = Math.max(grid[(i & 1) ^ 1][i], dp) + 1;
}
out.println(Math.min(ans, dp));
}
out.flush();
}
}
static class FastWriter {
private final PrintWriter writer;
public FastWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public FastWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void println(int x) {
writer.println(x);
}
public void flush() {
writer.flush();
}
public void close() {
writer.flush();
try {
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
static class RealFastReader {
InputStream is;
private byte[] inbuf = new byte[1024];
public int lenbuf = 0;
public int ptrbuf = 0;
public RealFastReader(final InputStream is) {
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 int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = ni();
}
return a;
}
public int ni() {
int 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\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 8 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | 40ff1d3f1a9a7506b10959d22ef59a9c | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | /*==========================================================================
* AUTHOR: RonWonWon
* CREATED: 07.11.2022 17:26:56
/*==========================================================================*/
import java.io.*;
import java.util.*;
public class C {
public static void main(String[] args) throws IOException {
/*
in.ini();
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
*/
long startTime = System.nanoTime();
int t = in.nextInt(), T = 1;
while(t-->0) {
n = in.nextInt();
a = new int[2][n];
a[0] = in.readArray(n);
a[1] = in.readArray(n);
int ans = -1;
int val[][] = new int[n][2];
int p = 0;
//precalc
int m1 = 0;
for(int i=1;i<n;i++){
m1 = Math.max(m1+1,a[0][i]+1);
}
int m2 = a[1][0]+1;
for(int i=1;i<n;i++){
m2 = Math.max(m2+1,a[1][i]+1);
}
int l1[] = new int[n];
l1[n-1] = a[0][n-1]+1;
for(int i=n-2;i>=0;i--){
l1[i] = Math.max(l1[i+1]+1,a[0][i]+1);
}
int l2[] = new int[n];
l2[n-1] = a[1][n-1]+1;
for(int i=n-2;i>=0;i--){
l2[i] = Math.max(l2[i+1]+1,a[1][i]+1);
}
//precalc
for(int i=0;i<n;i++){
if(p==0){
if(i!=0) val[i][0] = Math.max(ans+1,a[0][i]+1);
val[i][1] = Math.max(val[i][0]+1,a[1][i]+1);
}
else{
val[i][1] = Math.max(ans+1,a[1][i]+1);
val[i][0] = Math.max(val[i][1]+1,a[0][i]+1);
}
p^=1;
ans = Math.max(val[i][1],val[i][0]);
}
p = 1;
for(int i=0;i<n-1;i++){
int len = (n-i-1)*2;
if(p==0){
ans = Math.min(ans,Math.max(l2[i+1],Math.max(m1+(n-i-1),len+val[i][0])));
}
else{
ans = Math.min(ans,Math.max(l1[i+1],Math.max(m2+(n-i-1),len+val[i][1])));
}
p^=1;
}
ans = Math.min(ans,Math.max(l2[0],m1+n));
out.println(ans);
//out.println("Case #"+T+": "+ans); T++;
}
/*
startTime = System.nanoTime() - startTime;
System.err.println("Time: "+(startTime/1000000));
*/
out.flush();
}
static int a[][], n, ans;
static FastScanner in = new FastScanner();
static PrintWriter out = new PrintWriter(System.out);
static int oo = Integer.MAX_VALUE;
static long ooo = Long.MAX_VALUE;
static long mod = 1_000_000_007; //998244353;
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
void ini() throws FileNotFoundException {
br = new BufferedReader(new FileReader("input.txt"));
}
String next() {
while(!st.hasMoreTokens())
try { st = new StringTokenizer(br.readLine()); }
catch(IOException e) {}
return st.nextToken();
}
String nextLine(){
try{ return br.readLine(); }
catch(IOException e) { } return "";
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int a[] = new int[n];
for(int i=0;i<n;i++) a[i] = nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
long[] readArrayL(int n) {
long a[] = new long[n];
for(int i=0;i<n;i++) a[i] = nextLong();
return a;
}
double nextDouble() {
return Double.parseDouble(next());
}
double[] readArrayD(int n) {
double a[] = new double[n];
for(int i=0;i<n;i++) a[i] = nextDouble();
return a;
}
}
static final Random random = new Random();
static void ruffleSort(int[] a){
int n = a.length;
for(int i=0;i<n;i++){
int j = random.nextInt(n), temp = a[j];
a[j] = a[i]; a[i] = temp;
}
Arrays.sort(a);
}
static void ruffleSortL(long[] a){
int n = a.length;
for(int i=0;i<n;i++){
int j = random.nextInt(n);
long temp = a[j];
a[j] = a[i]; a[i] = temp;
}
Arrays.sort(a);
}
} | Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 8 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | d87e7c70c7688f1abe0a5773150a14ee | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 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.BufferedReader;
import java.io.InputStreamReader;
/**
* 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;
FastI in = new FastI(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Problem solver = new Problem();
solver.solve(1, in, out);
out.close();
}
static class Problem {
public void solve(int testNumber, FastI sc, PrintWriter out) {
int t = sc.nextInt();
loop : while (t > 0) {
t--;
int n = sc.nextInt();
int[][] a = new int[2][n];
for (int i = 0 ; i < n ; i++){
a[0][i]=sc.nextInt();
}
for (int i = 0 ; i < n ; i++){
a[1][i]=sc.nextInt();
}
long l = 2*n-1;
long r = 2* (int)1e9 ;
long ans = -1;
while (l<=r){
long mid =(l+r)/2;
long passed = mid - 2*n + 1;
int idx=1;
int h=0;
boolean ok = true;
int i;
for (i=1;i<2*n;i++){
if (a[idx%2][i/2]>passed){
ok=false;
break;
}
else{
passed++;
if (h==0){
idx+=2;
h=1;
}
else{
idx++;
h=0;
}
}
}
if (ok){
ans = mid;
r= mid-1;
}
else{
boolean ok2= true;
i--;
if (h==0) {
idx--;
}
else{
idx-=2;
}
if (i%2==1){
idx--;
passed--;
}
for (int j=i/2+1;j<n;j++){
if (a[idx%2][j]>passed){
ok2= false;
break;
}
else{
passed++;
}
}
if (ok2) {
idx++;
if (a[idx%2][n-1]>passed){
l = mid + 1;
}
else{
for (int j=n-1;j>=i/2;j--){
if (a[idx%2][j]>passed){
ok2= false;
break;
}
else{
passed++;
}
}
if (ok2){
ans = mid;
r= mid-1;
}
else{
l = mid + 1;
}
}
}
else{
l = mid + 1;
}
}
}
out.println(ans);
}
}
}
static class FastI {
BufferedReader br;
StringTokenizer st;
public FastI(InputStream inputStream) {
br = new BufferedReader(new
InputStreamReader(inputStream));
}
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\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 8 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | 139b24cbeca859b4fa2c12d6d4a4504c | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | /*
Goal: Become better in CP!
Key: Consistency and Discipline
Desire: SDE @ Google USA
Motto: Do what i Love <=> Love what i do
If you don't use your brain 100%, it deteriorates gradually
*/
import java.util.*;
import java.io.*;
import java.math.*;
public class C {
static StringBuffer str=new StringBuffer();
static char c[];
static int m;
static long mat[][];
static void solve(){
long ans1, ans2;
ans1=ans2=0;
for(int i=1;i<m;i++){
ans1=Math.max(ans1+1, mat[0][i]);
}
for(int i=m-1;i>=0;i--){
ans1=Math.max(ans1+1, mat[1][i]);
}
for(int i=0;i<m;i++){
ans2=Math.max(ans2+1, mat[1][i]);
}
for(int i=m-1;i>0;i--){
ans2=Math.max(ans2+1, mat[0][i]);
}
long clk[]=new long[m];
long aclk[]=new long[m];
clk[m-1]=Math.max(mat[0][m-1]+1, mat[1][m-1]);
aclk[m-1]=Math.max(mat[1][m-1]+1, mat[0][m-1]);
long cnt=3;
for(int i=m-2;i>=0;i--){
clk[i]=Math.max(mat[0][i]+cnt, Math.max(mat[1][i], clk[i+1]+1));
aclk[i]=Math.max(mat[1][i]+cnt, Math.max(mat[0][i], aclk[i+1]+1));
cnt+=2;
}
long ans=Math.min(ans1, ans2);
cnt-=3;
long time=mat[1][0];
for(int i=1;i<m;i++){
if(i%2==1){
ans=Math.min(ans, Math.max(cnt+time, aclk[i]));
time=Math.max(time+1, mat[1][i]);
time=Math.max(time+1, mat[0][i]);
}else{
ans=Math.min(ans, Math.max(cnt+time, clk[i]));
time=Math.max(time+1, mat[0][i]);
time=Math.max(time+1, mat[1][i]);
}
cnt-=2;
}
str.append(ans).append("\n");
}
public static void main(String[] args) throws java.lang.Exception {
BufferedReader bf;
PrintWriter pw;
boolean lenv=false;
if(lenv){
bf = new BufferedReader(
new FileReader("input.txt"));
pw=new PrintWriter(new
BufferedWriter(new FileWriter("output.txt")));
}else{
bf = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new OutputStreamWriter(System.out));
}
int q1 = Integer.parseInt(bf.readLine().trim());
while (q1-- > 0) {
m=Integer.parseInt(bf.readLine().trim());
String s[]=bf.readLine().trim().split("\\s+");
mat=new long[2][m];
for(int i=0;i<m;i++) mat[0][i]=Long.parseLong(s[i])+1;
s=bf.readLine().trim().split("\\s+");
for(int i=0;i<m;i++) mat[1][i]=Long.parseLong(s[i])+1;
solve();
}
pw.println(str);
pw.flush();
// System.out.print(str);
}
} | Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 8 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | 26568623430e28d288869edf3c7aefc4 | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | /*
Goal: Become better in CP!
Key: Consistency and Discipline
Desire: SDE @ Google USA
Motto: Do what i Love <=> Love what i do
If you don't use your brain 100%, it deteriorates gradually
*/
import java.util.*;
import java.io.*;
import java.math.*;
public class C {
static StringBuffer str=new StringBuffer();
static char c[];
static int m;
static long mat[][];
static void solve(){
long ans1, ans2;
ans1=ans2=0;
for(int i=1;i<m;i++){
ans1=Math.max(ans1+1, mat[0][i]);
}
for(int i=m-1;i>=0;i--){
ans1=Math.max(ans1+1, mat[1][i]);
}
for(int i=0;i<m;i++){
ans2=Math.max(ans2+1, mat[1][i]);
}
for(int i=m-1;i>0;i--){
ans2=Math.max(ans2+1, mat[0][i]);
}
long clk[]=new long[m];
long aclk[]=new long[m];
clk[m-1]=Math.max(mat[0][m-1]+1, mat[1][m-1]);
aclk[m-1]=Math.max(mat[1][m-1]+1, mat[0][m-1]);
long cnt=3;
for(int i=m-2;i>=0;i--){
clk[i]=Math.max(mat[0][i]+cnt, Math.max(mat[1][i], clk[i+1]+1));
aclk[i]=Math.max(mat[1][i]+cnt, Math.max(mat[0][i], aclk[i+1]+1));
cnt+=2;
}
long ans=Math.min(ans1, ans2);
cnt-=3;
ans=Math.min(ans, Math.max(cnt-1, clk[0]));
long time=mat[1][0];
for(int i=1;i<m;i++){
if(i%2==1){
ans=Math.min(ans, Math.max(cnt+time, aclk[i]));
time=Math.max(time+1, mat[1][i]);
time=Math.max(time+1, mat[0][i]);
}else{
ans=Math.min(ans, Math.max(cnt+time, clk[i]));
time=Math.max(time+1, mat[0][i]);
time=Math.max(time+1, mat[1][i]);
}
cnt-=2;
}
str.append(ans).append("\n");
}
public static void main(String[] args) throws java.lang.Exception {
BufferedReader bf;
PrintWriter pw;
boolean lenv=false;
if(lenv){
bf = new BufferedReader(
new FileReader("input.txt"));
pw=new PrintWriter(new
BufferedWriter(new FileWriter("output.txt")));
}else{
bf = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new OutputStreamWriter(System.out));
}
int q1 = Integer.parseInt(bf.readLine().trim());
while (q1-- > 0) {
m=Integer.parseInt(bf.readLine().trim());
String s[]=bf.readLine().trim().split("\\s+");
mat=new long[2][m];
for(int i=0;i<m;i++) mat[0][i]=Long.parseLong(s[i])+1;
s=bf.readLine().trim().split("\\s+");
for(int i=0;i<m;i++) mat[1][i]=Long.parseLong(s[i])+1;
solve();
}
pw.println(str);
pw.flush();
// System.out.print(str);
}
} | Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 8 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | 059f3aa30ce74d39b10a4e8508cf6700 | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | import java.io.*;
import java.util.*;
public class RobotInAHallway {
private static final int START_TEST_CASE = 1;
public static void solveCase(FastIO io, int testCase) {
final int M = io.nextInt();
final long[][] A = {
io.nextLongArray(M),
io.nextLongArray(M),
};
long best = Long.MAX_VALUE;
{
Snaker uSnake = new Snaker(0);
for (int i = 1; i < M; ++i) {
uSnake.add(A[0][i] + 1);
}
for (int i = M - 1; i >= 0; --i) {
uSnake.add(A[1][i] + 1);
}
best = Math.min(best, uSnake.getEndTime(0));
Snaker mainSnake = new Snaker(0);
for (int i = 0; i + 1 < M; i += 2) {
if (i != 0) {
mainSnake.add(1 + A[0][i]);
}
mainSnake.add(1 + A[1][i]);
mainSnake.add(1 + A[1][i + 1]);
mainSnake.add(1 + A[0][i + 1]);
if (uSnake.queue.size() > 4) {
uSnake.queue.pollFirst();
uSnake.queue.pollFirst();
uSnake.queue.pollLast();
uSnake.queue.pollLast();
best = Math.min(best, uSnake.getEndTime(mainSnake.queue.peekLast() + 1));
} else {
best = Math.min(best, mainSnake.getEndTime(0));
}
}
}
{
Snaker mainSnake = new Snaker(0);
mainSnake.add(A[1][0] + 1);
Snaker uSnake = new Snaker(A[1][1] + 1);
for (int i = 2; i < M; ++i) {
uSnake.add(A[1][i] + 1);
}
for (int i = M - 1; i >= 1; --i) {
uSnake.add(A[0][i] + 1);
}
best = Math.min(best, uSnake.getEndTime(mainSnake.queue.peekLast() + 1));
for (int i = 1; i + 1 < M; i += 2) {
mainSnake.add(1 + A[1][i]);
mainSnake.add(1 + A[0][i]);
mainSnake.add(1 + A[0][i + 1]);
mainSnake.add(1 + A[1][i + 1]);
if (uSnake.queue.size() > 4) {
uSnake.queue.pollFirst();
uSnake.queue.pollFirst();
uSnake.queue.pollLast();
uSnake.queue.pollLast();
best = Math.min(best, uSnake.getEndTime(mainSnake.queue.peekLast() + 1));
} else {
best = Math.min(best, mainSnake.getEndTime(0));
}
}
}
io.println(best);
}
private static class Snaker {
public ArrayDeque<Long> queue = new ArrayDeque<>();
public Snaker(long init) {
queue.offerLast(init);
}
public void add(long minTerminal) {
long val = Math.max(minTerminal, queue.peekLast() + 1);
queue.offerLast(val);
}
public long getEndTime(long startTime) {
long steps = queue.size() - 1;
long waiting = queue.peekLast() - queue.peekFirst() - steps;
long offset = startTime - queue.peekFirst();
return startTime + Math.max(0, waiting - offset) + steps;
}
}
public static void solve(FastIO io) {
final int T = io.nextInt();
for (int t = 0; t < T; ++t) {
solveCase(io, START_TEST_CASE + t);
}
}
public static class FastIO {
private InputStream reader;
private PrintWriter writer;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastIO(InputStream r, OutputStream w) {
reader = r;
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w)));
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = reader.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 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;
}
// TODO: read this byte-by-byte like the other read functions.
public double nextDouble() {
return Double.parseDouble(nextString());
}
public int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
public int[] nextIntArray(int n, int off) {
int[] arr = new int[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
public long[] nextLongArray(int n, int off) {
long[] arr = new long[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = 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;
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printlnArray(int[] arr) {
printArray(arr);
writer.println();
}
public void printlnArray(long[] arr) {
printArray(arr);
writer.println();
}
public void printf(String format, Object... args) {
print(String.format(format, args));
}
public void flush() {
writer.flush();
}
}
public static void main(String[] args) {
FastIO io = new FastIO(System.in, System.out);
solve(io);
io.flush();
}
} | Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 8 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | 37c701f767ec9223e002e5efa40409be | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
public class RobotInAHallway {
private static final int START_TEST_CASE = 1;
public static void solveCase(FastIO io, int testCase) {
final int M = io.nextInt();
final long[][] A = {
io.nextLongArray(M),
io.nextLongArray(M),
};
long best = Long.MAX_VALUE;
{
Snaker uSnake = new Snaker(0);
for (int i = 1; i < M; ++i) {
uSnake.add(A[0][i] + 1);
}
for (int i = M - 1; i >= 0; --i) {
uSnake.add(A[1][i] + 1);
}
best = Math.min(best, uSnake.getEndTime(0));
// System.out.format("best = %d\n", best);
// System.out.format("uSnake = %s\n", uSnake.queue);
Snaker mainSnake = new Snaker(0);
for (int i = 0; i + 1 < M; i += 2) {
if (i != 0) {
mainSnake.add(1 + A[0][i]);
}
mainSnake.add(1 + A[1][i]);
mainSnake.add(1 + A[1][i + 1]);
mainSnake.add(1 + A[0][i + 1]);
if (uSnake.queue.size() > 4) {
uSnake.queue.pollFirst();
uSnake.queue.pollFirst();
uSnake.queue.pollLast();
uSnake.queue.pollLast();
// System.out.format("i = %d, mainSnake = %s, uSnake = %s, mainSnake last = %d, end time = %d\n", i, mainSnake.queue, uSnake.queue, mainSnake.queue.peekLast(), uSnake.getEndTime(mainSnake.queue.peekLast() + 1));
best = Math.min(best, uSnake.getEndTime(mainSnake.queue.peekLast() + 1));
} else {
// System.out.format("i = %d, mainSnake = %s, uSnake = %s, mainSnake end = %d\n", i, mainSnake.queue, uSnake.queue, mainSnake.getEndTime(0));
best = Math.min(best, mainSnake.getEndTime(0));
}
}
}
{
Snaker mainSnake = new Snaker(0);
mainSnake.add(A[1][0] + 1);
Snaker uSnake = new Snaker(A[1][1] + 1);
for (int i = 2; i < M; ++i) {
uSnake.add(A[1][i] + 1);
}
for (int i = M - 1; i >= 1; --i) {
uSnake.add(A[0][i] + 1);
}
// System.out.format("main = %s, uSnake = %s\n", mainSnake.queue, uSnake.queue);
// System.out.format("main snake last = %d, end end = %s\n", mainSnake.queue.peekLast(), uSnake.getEndTime(mainSnake.queue.peekLast() + 1));
best = Math.min(best, uSnake.getEndTime(mainSnake.queue.peekLast() + 1));
for (int i = 1; i + 1 < M; i += 2) {
mainSnake.add(1 + A[1][i]);
mainSnake.add(1 + A[0][i]);
mainSnake.add(1 + A[0][i + 1]);
mainSnake.add(1 + A[1][i + 1]);
if (uSnake.queue.size() > 4) {
uSnake.queue.pollFirst();
uSnake.queue.pollFirst();
uSnake.queue.pollLast();
uSnake.queue.pollLast();
best = Math.min(best, uSnake.getEndTime(mainSnake.queue.peekLast() + 1));
} else {
best = Math.min(best, mainSnake.getEndTime(0));
}
}
}
io.println(best);
}
private static class Snaker {
public ArrayDeque<Long> queue = new ArrayDeque<>();
public Snaker(long init) {
queue.offerLast(init);
}
public void add(long minTerminal) {
long val = Math.max(minTerminal, queue.peekLast() + 1);
queue.offerLast(val);
}
public long getEndTime(long startTime) {
long steps = queue.size() - 1;
long waiting = queue.peekLast() - queue.peekFirst() - steps;
long offset = startTime - queue.peekFirst();
return startTime + Math.max(0, waiting - offset) + steps;
}
}
public static void solve(FastIO io) {
final int T = io.nextInt();
for (int t = 0; t < T; ++t) {
solveCase(io, START_TEST_CASE + t);
}
}
public static class FastIO {
private InputStream reader;
private PrintWriter writer;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastIO(InputStream r, OutputStream w) {
reader = r;
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w)));
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = reader.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 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;
}
// TODO: read this byte-by-byte like the other read functions.
public double nextDouble() {
return Double.parseDouble(nextString());
}
public int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
public int[] nextIntArray(int n, int off) {
int[] arr = new int[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
public long[] nextLongArray(int n, int off) {
long[] arr = new long[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = 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;
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printlnArray(int[] arr) {
printArray(arr);
writer.println();
}
public void printlnArray(long[] arr) {
printArray(arr);
writer.println();
}
public void printf(String format, Object... args) {
print(String.format(format, args));
}
public void flush() {
writer.flush();
}
}
public static void main(String[] args) {
FastIO io = new FastIO(System.in, System.out);
solve(io);
io.flush();
}
} | Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 8 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | 3cd8853ed04b591ee932aa9e40355736 | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes |
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main {
static int N;
static Read s = new Read();
static int sum;
static int[][] dir = new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
public static void main(String[] args) throws IOException {
int T = s.nextInt();
while (T-- > 0) {
int m = s.nextInt();
N = m;
int[][] A = new int[2][m], B = new int[2][m], C = new int[2][m], V = new int[2][m];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < m; j++) {
V[i][j] = s.nextInt();
}
}
B[1][0] = V[1][0] + 1;
for (int i = 1; i < N; i++) {
A[0][i] = Math.max(A[0][i - 1] + 1, V[0][i] + 1);
B[1][i] = Math.max(B[1][i - 1] + 1, V[1][i] + 1);
}
A[1][N - 1] = Math.max(A[0][N - 1] + 1, V[1][N - 1] + 1);
B[0][N - 1] = Math.max(B[1][N - 1] + 1, V[0][N - 1] + 1);
for (int i = (N - 2); i >= 0; i--) {
A[1][i] = Math.max(A[1][i + 1] + 1, V[1][i] + 1);
B[0][i] = Math.max(B[0][i + 1] + 1, V[0][i] + 1);
}
int i1 = 0, j1 = 0;
for (int k = 0; k < (2 * N - 1); k++) {
int ni = i1, nj = j1;
if (k % 2 == 1) {
nj++;
} else {
ni = (ni + 1) % 2;
}
C[ni][nj] = Math.max(C[i1][j1] + 1, V[ni][nj] + 1);
i1 = ni;
j1 = nj;
}
int ans = 0x3f3f3f3f;
for (int i = 0; i < N; i++) {
int a = 0x3f3f3f3f, b = 0x3f3f3f3f;
int k = 2 * (N - i) - 1;
a = Math.min(a, C[0][i] + Math.max(A[1][i] - C[0][i], 2 * (N - i) - 1));
b = Math.min(b, C[1][i] + Math.max(B[0][i] - C[1][i], 2 * (N - i) - 1));
ans = Math.min(ans, a);
ans = Math.min(ans, b);
}
s.println(ans);
}
s.bw.flush();
}
static void swap(int[] a, int i, int j) {
int tep = a[i];
a[i] = a[j];
a[j] = tep;
}
static class Read {
BufferedReader bf;
StringTokenizer st;
BufferedWriter bw;
public Read() {
bf = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer("");
bw = new BufferedWriter(new OutputStreamWriter(System.out));
}
public String nextLine() throws IOException {
return bf.readLine();
}
public String next() throws IOException {
while (!st.hasMoreTokens()) {
st = new StringTokenizer(bf.readLine());
}
return st.nextToken();
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public float nextFloat() throws IOException {
return Float.parseFloat(next());
}
public byte nextByte() throws IOException {
return Byte.parseByte(next());
}
public short nextShort() throws IOException {
return Short.parseShort(next());
}
public BigInteger nextBigInteger() throws IOException {
return new BigInteger(next());
}
public void println(int a) throws IOException {
bw.write(String.valueOf(a));
bw.newLine();
return;
}
public void print(int a) throws IOException {
bw.write(String.valueOf(a));
return;
}
public void println(String a) throws IOException {
bw.write(a);
bw.newLine();
return;
}
public void print(String a) throws IOException {
bw.write(a);
return;
}
public void println(long a) throws IOException {
bw.write(String.valueOf(a));
bw.newLine();
return;
}
public void print(long a) throws IOException {
bw.write(String.valueOf(a));
return;
}
public void println(double a) throws IOException {
bw.write(String.valueOf(a));
bw.newLine();
return;
}
public void print(double a) throws IOException {
bw.write(String.valueOf(a));
return;
}
}
} | Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 8 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | 37e132be1a37f17e1ec5cb18e089fa2b | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | import java.io.*;
import java.util.StringTokenizer;
public class Main {
static Main2 admin = new Main2();
public static void main(String[] args) {
admin.start();
}
}
class Main2 {
//---------------------------------INPUT READER-----------------------------------------//
public BufferedReader br;
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens()) {
try { st = new StringTokenizer(br.readLine());} catch (IOException e) { e.printStackTrace(); }
}
return st.nextToken();
}
int ni() { return Integer.parseInt(next()); }
long nl() { return Long.parseLong(next()); }
double nd() { return Double.parseDouble(next()); }
String ns() { return next(); }
int[] na(long n) {int[]ret=new int[(int)n]; for(int i=0;i<n;i++) ret[i]=ni(); return ret;}
long[] nal(long n) {long[]ret=new long[(int)n]; for(int i=0;i<n;i++) ret[i]=nl(); return ret;}
Integer[] nA(long n) {Integer[]ret=new Integer[(int)n]; for(int i=0;i<n;i++) ret[i]=ni(); return ret;}
Long[] nAl(long n) {Long[]ret=new Long[(int)n]; for(int i=0;i<n;i++) ret[i]=nl(); return ret;}
//--------------------------------------PRINTER------------------------------------------//
PrintWriter w;
void p(int i) {w.println(i);} void p(long l) {w.println(l);}
void p(double d) {w.println(d);} void p(String s) { w.println(s);}
void pr(int i) {w.print(i);} void pr(long l) {w.print(l);}
void pr(double d) {w.print(d);} void pr(String s) { w.print(s);}
void pl() {w.println();}
//--------------------------------------VARIABLES-----------------------------------------//
long lma = Long.MAX_VALUE, lmi = Long.MIN_VALUE;
int ima = Integer.MAX_VALUE, imi = Integer.MIN_VALUE;
long mod = 1000000007;
{
w = new PrintWriter(System.out);
br = new BufferedReader(new InputStreamReader(System.in));
try {if(new File(System.getProperty("user.dir")).getName().equals("LOCAL")) {
w = new PrintWriter(new OutputStreamWriter(new FileOutputStream("output.txt")));
br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));}
} catch (Exception ignore) { }
}
//----------------------START---------------------//
void start() {
int t = ni(); while(t-- > 0)
solve();
w.close();
}
void solve() {
int n = ni();
long[] up = nal(n), down = nal(n);
long[] suff_up = up.clone(), suff_down = down.clone();
long[] pre_up = up.clone(), pre_down = down.clone();
for(int i = n-2; i >= 0; i--) {
long extra = n-i-1;
if(extra > 0) pre_up[i]-=extra;
if(extra > 0) pre_down[i]-=extra;
if(pre_up[i] < pre_up[i+1]) {
pre_up[i] = pre_up[i+1];
}
if(pre_down[i] < pre_down[i+1]) {
pre_down[i] = pre_down[i+1];
}
}
for(int i = n-2; i >= 0; i--) {
if(suff_up[i] < suff_up[i+1]-1) {
suff_up[i] = suff_up[i+1]-1;
}
if(suff_down[i] < suff_down[i+1]-1) {
suff_down[i] = suff_down[i+1]-1;
}
}
long best = lma;
long curr = 0;
for(int i = 0; i < n; i++) {
if(i == n-1) {
if(i%2==0) {
if (curr < down[i]) curr = down[i] + 1;
else curr++;
} else {
if (curr < up[i]) curr = up[i] + 1;
else curr++;
}
continue;
}
if(i%2==0) {
// from up
long from_up = suff_up[i + 1];
long from_down = pre_down[i]-(n-i-1); // pre_down[i] here since we have to come till here
long wait = Math.max(from_down, from_up);
long moves = (2L * (n-i-1))+1;
if (curr >= wait) {
best = Math.min(best, moves + curr);
} else {
long hold = wait - curr;
best = Math.min(best, moves + curr + hold);
}
if (curr < down[i]) curr = down[i] + 1;
else curr++;
if (i < n - 1) {
if (curr < down[i + 1]) curr = down[i + 1] + 1;
else curr++;
}
} else {
// from down
long from_down = suff_down[i + 1];
long from_up = pre_up[i]-(n-i-1);
long wait = Math.max(from_down, from_up);
long moves = (2L * (n-i-1))+1;
if (curr >= wait) {
best = Math.min(best, moves + curr);
} else {
long hold = wait - curr;
best = Math.min(best, moves+curr+hold);
}
if (curr < up[i]) curr = up[i] + 1;
else curr++;
if (i < n - 1) {
if (curr < up[i + 1]) curr = up[i + 1] + 1;
else curr++;
}
}
}
best = Math.min(best, curr);
p(best);
}
} | Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 8 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | 4fc1e90e21a0c9e33fed20bc6125f0db | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
static FastReader sc=new FastReader();
static PrintWriter out=new PrintWriter(System.out);
static int dx[]={0,0,-1,1},dy[]={-1,1,0,0};
static final double pi=3.1415926536;
static long mod=1000000007;
// static long mod=998244353;
static int MAX=Integer.MAX_VALUE;
static int MIN=Integer.MIN_VALUE;
static long MAXL=Long.MAX_VALUE;
static long MINL=Long.MIN_VALUE;
static ArrayList<Integer> graph[];
static long fact[];
static long seg[];
// static int dp[][];
static long dp[][];
public static void main (String[] args) throws java.lang.Exception
{
// code goes here
int t=I();
outer:while(t-->0)
{
int n=2;
int m=I();
long a[][]=new long[n][m];
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
a[i][j]=L();
}
}
long time[][]=new long[n][m];
time[0][m-1]=a[0][m-1];
if(a[0][m-1]>=a[1][m-1]){
time[0][m-1]++;
}else{
time[0][m-1]+=a[1][m-1]-a[0][m-1];
time[0][m-1]++;
}
// out.println(time[0][m-1])
time[1][m-1]=a[1][m-1];
if(a[1][m-1]>=a[0][m-1]){
time[1][m-1]++;
}else{
time[1][m-1]+=a[0][m-1]-a[1][m-1];
time[1][m-1]++;
}
for(int j=m-2;j>=0;j--){
long temp=0;
if(a[0][j]<=a[0][j+1]){
temp=a[0][j+1]+1;
}else{
temp=a[0][j]+1;
}
long time1=temp+(2*(m-j-1));
long time2=time[0][j+1];
// if(a[1][j]>=time[0][j+1]){
// time2++;
// }else{
// time2+=a[1][j]-time[0][j+1];
// time2++;
// }
if(time[0][j+1]>=a[1][j]){
time2++;
}else{
time2+=a[1][j]-time[0][j+1];
time2++;
}
time[0][j]=max(time1,time2);
temp=0;
if(a[1][j]<=a[1][j+1]){
temp=a[1][j+1]+1;
}else{
temp=a[1][j]+1;
}
time1=temp+(2*(m-j-1));
time2=time[1][j+1];
if(time[1][j+1]>=a[0][j]){
time2++;
}else{
time2+=a[0][j]-time[1][j+1];
time2++;
}
time[1][j]=max(time1,time2);
}
long ans=MAXL;
long timee=0;
for(int j=0;j<m;j++){
if(j%2==0){
long time1=timee+(2*(m-j-1)+1);
long time2=time[0][j];
ans=min(ans,max(time1,time2));
if(timee>=a[1][j]){
timee++;
}else{
timee+=a[1][j]-timee;
timee++;
}
if(j<m-1)
if(timee>=a[1][j+1]){
timee++;
}else{
timee+=a[1][j+1]-timee;
timee++;
}
}else{
long time1=timee+(2*(m-j-1)+1);
long time2=time[1][j];
ans=min(ans,max(time1,time2));
if(timee>=a[0][j]){
timee++;
}else{
timee+=a[0][j]-timee;
timee++;
}
if(j<m-1)
if(timee>=a[0][j+1]){
timee++;
}else{
timee+=a[0][j+1]-timee;
timee++;
}
}
}
out.println(ans);
}
out.close();
}
public static class pair
{
int a;
int b;
public pair(int aa,int bb)
{
a=aa;
b=bb;
}
}
public static class myComp implements Comparator<pair>
{
//sort in ascending order.
// public int compare(pair p1,pair p2)
// {
// if(p1.a==p2.a)
// return 0;
// else if(p1.a<p2.a)
// return -1;
// else
// return 1;
// }
// sort in descending order.
public int compare(pair p1,pair p2)
{
if(p1.b==p2.b)
return 0;
else if(p1.b<p2.b)
return 1;
else
return -1;
}
}
public static void setGraph(int n,int m)throws IOException
{
graph=new ArrayList[n+1];
for(int i=0;i<=n;i++){
graph[i]=new ArrayList<>();
}
for(int i=0;i<m;i++){
int u=I(),v=I();
graph[u].add(v);
graph[v].add(u);
}
}
//LOWER_BOUND and UPPER_BOUND functions
//It returns answer according to zero based indexing.
public static int lower_bound(ArrayList<Long> arr,long X,int start, int end) //start=0,end=n-1
{
if(start>end)return -1;
if(arr.get(end)<X)return end;
// if(arr[end]<X)return end;
if(arr.get(start)>X)return -1;
// if(arr[start]>X)return -1;
int left=start,right=end;
while(left<right){
int mid=(left+right)/2;
// if(arr[mid]==X){
if(arr.get(mid)==X){ //Returns last index of lower bound value.
// if(mid<end && arr[mid+1]==X){
if(mid<end && arr.get(mid+1)==X){
left=mid+1;
}else{
return mid;
}
}
// if(arr.get(mid)==X){ //Returns first index of lower bound value.
// if(arr[mid]==X){
// // if(mid>start && arr.get(mid-1)==X){
// if(mid>start && arr[mid-1]==X){
// right=mid-1;
// }else{
// return mid;
// }
// }
// else if(arr[mid]>X){
else if(arr.get(mid)>X){
// if(mid>start && arr[mid-1]<X){
if(mid>start && arr.get(mid-1)<X){
return mid-1;
}else{
right=mid-1;
}
}else{
// if(mid<end && arr[mid+1]>X){
if(mid<end && arr.get(mid+1)>X){
return mid;
}else{
left=mid+1;
}
}
}
return left;
}
//It returns answer according to zero based indexing.
public static int upper_bound(ArrayList<Integer> arr,int X,int start,int end) //start=0,end=n-1
{
if(arr.get(0)>=X)return start;
if(arr.get(arr.size()-1)<X)return -1;
int left=start,right=end;
while(left<right){
int mid=(left+right)/2;
if(arr.get(mid)==X){ //returns first index of upper bound value.
if(mid>start && arr.get(mid-1)==X){
right=mid-1;
}else{
return mid;
}
}
// if(arr[mid]==X){ //returns last index of upper bound value.
// if(mid<end && arr[mid+1]==X){
// left=mid+1;
// }else{
// return mid;
// }
// }
else if(arr.get(mid)>X){
if(mid>start && arr.get(mid-1)<X){
return mid;
}else{
right=mid-1;
}
}else{
if(mid<end && arr.get(mid+1)>X){
return mid+1;
}else{
left=mid+1;
}
}
}
return left;
}
//END
//Segment Tree Code
public static void buildTree(long a[],int si,int ss,int se)
{
if(ss==se){
seg[si]=a[ss];
return;
}
int mid=(ss+se)/2;
buildTree(a,2*si+1,ss,mid);
buildTree(a,2*si+2,mid+1,se);
seg[si]=max(seg[2*si+1],seg[2*si+2]);
}
// public static void update(int si,int ss,int se,int pos,int val)
// {
// if(ss==se){
// // seg[si]=val;
// return;
// }
// int mid=(ss+se)/2;
// if(pos<=mid){
// update(2*si+1,ss,mid,pos,val);
// }else{
// update(2*si+2,mid+1,se,pos,val);
// }
// // seg[si]=min(seg[2*si+1],seg[2*si+2]);
// if(seg[2*si+1].a < seg[2*si+2].a){
// seg[si].a=seg[2*si+1].a;
// seg[si].b=seg[2*si+1].b;
// }else{
// seg[si].a=seg[2*si+2].a;
// seg[si].b=seg[2*si+2].b;
// }
// }
public static long query1(int si,int ss,int se,int qs,int qe)
{
if(qs>se || qe<ss)return 0;
if(ss>=qs && se<=qe)return seg[si];
int mid=(ss+se)/2;
long p1=query1(2*si+1,ss,mid,qs,qe);
long p2=query1(2*si+2,mid+1,se,qs,qe);
return max(p1,p2);
}
public static void merge(ArrayList<Integer> f,ArrayList<Integer> a,ArrayList<Integer> b)
{
int i=0,j=0;
while(i<a.size() && j<b.size()){
if(a.get(i)<=b.get(j)){
f.add(a.get(i));
i++;
}else{
f.add(b.get(j));
j++;
}
}
while(i<a.size()){
f.add(a.get(i));
i++;
}
while(j<b.size()){
f.add(b.get(j));
j++;
}
}
//Segment Tree Code end
//Prefix Function of KMP Algorithm
public static int[] KMP(char c[],int n)
{
int pi[]=new int[n];
for(int i=1;i<n;i++){
int j=pi[i-1];
while(j>0 && c[i]!=c[j]){
j=pi[j-1];
}
if(c[i]==c[j])j++;
pi[i]=j;
}
return pi;
}
public static long kadane(long a[],int n) //largest sum subarray
{
long max_sum=Long.MIN_VALUE,max_end=0;
for(int i=0;i<n;i++){
max_end+=a[i];
if(max_sum<max_end){max_sum=max_end;}
if(max_end<0){max_end=0;}
}
return max_sum;
}
public static long nPr(int n,int r)
{
long ans=divide(fact(n),fact(n-r),mod);
return ans;
}
public static long nCr(int n,int r)
{
long ans=divide(fact[n],mul(fact[n-r],fact[r]),mod);
return ans;
}
public static boolean isSorted(int a[])
{
int n=a.length;
for(int i=0;i<n-1;i++){
if(a[i]>a[i+1])return false;
}
return true;
}
public static boolean isSorted(long a[])
{
int n=a.length;
for(int i=0;i<n-1;i++){
if(a[i]>a[i+1])return false;
}
return true;
}
public static int computeXOR(int n) //compute XOR of all numbers between 1 to n.
{
if (n % 4 == 0)
return n;
if (n % 4 == 1)
return 1;
if (n % 4 == 2)
return n + 1;
return 0;
}
public static int np2(int x)
{
x--;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
x++;
return x;
}
public static int hp2(int x)
{
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return x ^ (x >> 1);
}
public static long hp2(long x)
{
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return x ^ (x >> 1);
}
public static ArrayList<Integer> primeSieve(int n)
{
ArrayList<Integer> arr=new ArrayList<>();
boolean prime[] = new boolean[n + 1];
for (int i = 0; i <= n; i++)
prime[i] = true;
for (int p = 2; p * p <= n; p++)
{
if (prime[p] == true)
{
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
for (int i = 2; i <= n; i++)
{
if (prime[i] == true)
arr.add(i);
}
return arr;
}
// Fenwick / BinaryIndexed Tree USE IT - FenwickTree ft1=new FenwickTree(n);
public static class FenwickTree
{
int farr[];
int n;
public FenwickTree(int c)
{
n=c+1;
farr=new int[n];
}
// public void update_range(int l,int r,long p)
// {
// update(l,p);
// update(r+1,(-1)*p);
// }
public void update(int x,int p)
{
for(;x<n;x+=x&(-x))
{
farr[x]+=p;
}
}
public int get(int x)
{
int ans=0;
for(;x>0;x-=x&(-x))
{
ans=ans+farr[x];
}
return ans;
}
}
//Disjoint Set Union
public static class DSU
{
int par[],rank[];
public DSU(int c)
{
par=new int[c+1];
rank=new int[c+1];
for(int i=0;i<=c;i++)
{
par[i]=i;
rank[i]=0;
}
}
public int find(int a)
{
if(a==par[a])
return a;
return par[a]=find(par[a]);
}
public void union(int a,int b)
{
int a_rep=find(a),b_rep=find(b);
if(a_rep==b_rep)
return;
if(rank[a_rep]<rank[b_rep])
par[a_rep]=b_rep;
else if(rank[a_rep]>rank[b_rep])
par[b_rep]=a_rep;
else
{
par[b_rep]=a_rep;
rank[a_rep]++;
}
}
}
public static HashMap<Integer,Integer> primeFact(int a)
{
// HashSet<Long> arr=new HashSet<>();
HashMap<Integer,Integer> hm=new HashMap<>();
int p=0;
while(a%2==0){
// arr.add(2L);
p++;
a=a/2;
}
hm.put(2,hm.getOrDefault(2,0)+p);
for(int i=3;i*i<=a;i+=2){
p=0;
while(a%i==0){
// arr.add(i);
p++;
a=a/i;
}
hm.put(i,hm.getOrDefault(i,0)+p);
}
if(a>2){
// arr.add(a);
hm.put(a,hm.getOrDefault(a,0)+1);
}
// return arr;
return hm;
}
public static boolean isVowel(char c)
{
if(c=='a' || c=='e' || c=='i' || c=='u' || c=='o')return true;
return false;
}
public static boolean isInteger(double N)
{
int X = (int)N;
double temp2 = N - X;
if (temp2 > 0)
{
return false;
}
return true;
}
public static boolean isPalindrome(String s)
{
int n=s.length();
for(int i=0;i<=n/2;i++){
if(s.charAt(i)!=s.charAt(n-i-1)){
return false;
}
}
return true;
}
public static int gcd(int a,int b)
{
if(b==0)
return a;
else
return gcd(b,a%b);
}
public static long gcd(long a,long b)
{
if(b==0)
return a;
else
return gcd(b,a%b);
}
public static long fact(long n)
{
long fact=1;
for(long i=2;i<=n;i++){
fact=((fact%mod)*(i%mod))%mod;
}
return fact;
}
public static long fact(int n)
{
long fact=1;
for(int i=2;i<=n;i++){
fact=((fact%mod)*(i%mod))%mod;
}
return fact;
}
public static boolean isPrime(int n)
{
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
double sq=Math.sqrt(n);
for (int i = 5; i <= sq; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
public static boolean isPrime(long n)
{
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
double sq=Math.sqrt(n);
for (int i = 5; i <= sq; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
public static void printArray(long a[])
{
for(int i=0;i<a.length;i++){
out.print(a[i]+" ");
}
out.println();
}
public static void printArray(int a[])
{
for(int i=0;i<a.length;i++){
out.print(a[i]+" ");
}
out.println();
}
public static void printArray(char a[])
{
for(int i=0;i<a.length;i++){
out.print(a[i]);
}
out.println();
}
public static void printArray(String a[])
{
for(int i=0;i<a.length;i++){
out.print(a[i]+" ");
}
out.println();
}
public static void printArray(boolean a[])
{
for(int i=0;i<a.length;i++){
out.print(a[i]+" ");
}
out.println();
}
public static void printArray(pair a[])
{
for(pair p:a){
out.println(p.a+"->"+p.b);
}
}
public static void printArray(int a[][])
{
for(int i=0;i<a.length;i++){
for(int j=0;j<a[i].length;j++){
out.print(a[i][j]+" ");
}out.println();
}
}
public static void printArray(boolean a[][])
{
for(int i=0;i<a.length;i++){
for(int j=0;j<a[i].length;j++){
out.print(a[i][j]+" ");
}out.println();
}
}
public static void printArray(long a[][])
{
for(int i=0;i<a.length;i++){
for(int j=0;j<a[i].length;j++){
out.print(a[i][j]+" ");
}out.println();
}
}
public static void printArray(char a[][])
{
for(int i=0;i<a.length;i++){
for(int j=0;j<a[i].length;j++){
out.print(a[i][j]+" ");
}out.println();
}
}
public static void printArray(ArrayList<?> arr)
{
for(int i=0;i<arr.size();i++){
out.print(arr.get(i)+" ");
}
out.println();
}
public static void printMapI(HashMap<?,?> hm){
for(Map.Entry<?,?> e:hm.entrySet()){
out.println(e.getKey()+"->"+e.getValue());
}out.println();
}
public static void printMap(HashMap<Long,ArrayList<Integer>> hm){
for(Map.Entry<Long,ArrayList<Integer>> e:hm.entrySet()){
out.print(e.getKey()+"->");
ArrayList<Integer> arr=e.getValue();
for(int i=0;i<arr.size();i++){
out.print(arr.get(i)+" ");
}out.println();
}
}
public static void printGraph(ArrayList<Integer> graph[])
{
int n=graph.length;
for(int i=0;i<n;i++){
out.print(i+"->");
for(int j:graph[i]){
out.print(j+" ");
}out.println();
}
}
//Modular Arithmetic
public static long add(long a,long b)
{
a+=b;
if(a>=mod)a-=mod;
return a;
}
public static long sub(long a,long b)
{
a-=b;
if(a<0)a+=mod;
return a;
}
public static long mul(long a,long b)
{
return ((a%mod)*(b%mod))%mod;
}
public static long divide(long a,long b,long m)
{
a=mul(a,modInverse(b,m));
return a;
}
public static long modInverse(long a,long m)
{
int x=0,y=0;
own p=new own(x,y);
long g=gcdExt(a,m,p);
if(g!=1){
out.println("inverse does not exists");
return -1;
}else{
long res=((p.a%m)+m)%m;
return res;
}
}
public static long gcdExt(long a,long b,own p)
{
if(b==0){
p.a=1;
p.b=0;
return a;
}
int x1=0,y1=0;
own p1=new own(x1,y1);
long gcd=gcdExt(b,a%b,p1);
p.b=p1.a - (a/b) * p1.b;
p.a=p1.b;
return gcd;
}
public static long pwr(long m,long n)
{
long res=1;
if(m==0)
return 0;
while(n>0)
{
if((n&1)!=0)
{
res=(res*m);
}
n=n>>1;
m=(m*m);
}
return res;
}
public static long modpwr(long m,long n)
{
long res=1;
m=m%mod;
if(m==0)
return 0;
while(n>0)
{
if((n&1)!=0)
{
res=(res*m)%mod;
}
n=n>>1;
m=(m*m)%mod;
}
return res;
}
public static class own
{
long a;
long b;
public own(long val,long index)
{
a=val;
b=index;
}
}
//Modular Airthmetic
public static void sort(int[] A)
{
int n = A.length;
Random rnd = new Random();
for(int i=0; i<n; ++i)
{
int tmp = A[i];
int randomPos = i + rnd.nextInt(n-i);
A[i] = A[randomPos];
A[randomPos] = tmp;
}
Arrays.sort(A);
}
public static void sort(char[] A)
{
int n = A.length;
Random rnd = new Random();
for(int i=0; i<n; ++i)
{
char tmp = A[i];
int randomPos = i + rnd.nextInt(n-i);
A[i] = A[randomPos];
A[randomPos] = tmp;
}
Arrays.sort(A);
}
public static void sort(long[] A)
{
int n = A.length;
Random rnd = new Random();
for(int i=0; i<n; ++i)
{
long tmp = A[i];
int randomPos = i + rnd.nextInt(n-i);
A[i] = A[randomPos];
A[randomPos] = tmp;
}
Arrays.sort(A);
}
//max & min
public static int max(int a,int b){return Math.max(a,b);}
public static int min(int a,int b){return Math.min(a,b);}
public static int max(int a,int b,int c){return Math.max(a,Math.max(b,c));}
public static int min(int a,int b,int c){return Math.min(a,Math.min(b,c));}
public static long max(long a,long b){return Math.max(a,b);}
public static long min(long a,long b){return Math.min(a,b);}
public static long max(long a,long b,long c){return Math.max(a,Math.max(b,c));}
public static long min(long a,long b,long c){return Math.min(a,Math.min(b,c));}
public static int maxinA(int a[]){int n=a.length;int mx=a[0];for(int i=1;i<n;i++){mx=max(mx,a[i]);}return mx;}
public static long maxinA(long a[]){int n=a.length;long mx=a[0];for(int i=1;i<n;i++){mx=max(mx,a[i]);}return mx;}
public static int mininA(int a[]){int n=a.length;int mn=a[0];for(int i=1;i<n;i++){mn=min(mn,a[i]);}return mn;}
public static long mininA(long a[]){int n=a.length;long mn=a[0];for(int i=1;i<n;i++){mn=min(mn,a[i]);}return mn;}
public static long suminA(int a[]){int n=a.length;long sum=0;for(int i=0;i<n;i++){sum+=a[i];}return sum;}
public static long suminA(long a[]){int n=a.length;long sum=0;for(int i=0;i<n;i++){sum+=a[i];}return sum;}
//end
public static int[] I(int n){int a[]=new int[n];for(int i=0;i<n;i++){a[i]=I();}return a;}
public static long[] IL(int n){long a[]=new long[n];for(int i=0;i<n;i++){a[i]=L();}return a;}
public static long[] prefix(int a[]){int n=a.length;long pre[]=new long[n];pre[0]=a[0];for(int i=1;i<n;i++){pre[i]=pre[i-1]+a[i];}return pre;}
public static long[] prefix(long a[]){int n=a.length;long pre[]=new long[n];pre[0]=a[0];for(int i=1;i<n;i++){pre[i]=pre[i-1]+a[i];}return pre;}
public static int I(){return sc.I();}
public static long L(){return sc.L();}
public static String S(){return sc.S();}
public static double D(){return sc.D();}
}
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 I(){ return Integer.parseInt(next());}
long L(){ return Long.parseLong(next());}
double D(){return Double.parseDouble(next());}
String S(){
String str = "";
try {
str = br.readLine();
}
catch (IOException e){
e.printStackTrace();
}
return str;
}
}
| Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 8 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | 5c8d7cb021bf2b7c0ca823111626d4fa | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.*;
public class CF1{
public static void main(String[] args) {
FastScanner sc=new FastScanner();
// hamare saath shree raghunath to kis baat ki chinta...
int T=sc.nextInt();
// int T=1;
for (int tt=1; tt<=T; tt++){
int n =sc.nextInt();
int mat[][]= new int [2][n];
mat[0]=sc.readArray(n);
mat[1]= sc.readArray(n);
int max[][]=new int [2][n];
for (int i=0; i<2; i++){
for (int j=0; j<n; j++){
mat[i][j]++;
}
}
int temp=n*2;
int maxn=0;
for (int i=0; i<n; i++){
for (int j=0; j<=1; j++){
temp--;
if (i%2==1){
maxn=Math.max(maxn, mat[j^1][i]+temp);
if (i==0 && j==0) maxn=temp;
max[j^1][i]=maxn;
}
else {maxn=Math.max(maxn, mat[j][i]+temp);
if (i==0 && j==0) maxn=temp;
max[j][i]=maxn;}
}
}
int maxL[][]=new int [2][n];
maxn=0;
for (int i=n-1; i>=0; i--){
if (i<n-1) maxn=Math.max(maxn+1,Math.max(mat[0][i+1]+(n-i-1)*2-1, mat[1][i+1]));
if (i%2==1)maxL[0][i]=maxn;
else maxL[0][i]=Math.max(maxn+1, mat[1][i]);
}
maxn=0;
for (int i=n-1; i>=0; i--){
if (i<n-1) maxn=Math.max(maxn+1,Math.max(mat[0][i+1], mat[1][i+1]+(n-i-1)*2-1));
if (i%2==0)maxL[1][i]=maxn;
else maxL[1][i]=Math.max(maxn+1, mat[0][i]);
}
int ans=Integer.MAX_VALUE;
for (int i=0; i<2; i++){
for (int j=0; j<n; j++){
ans=Math.min(ans, Math.max(max[i][j],maxL[i][j]));
}
}
System.out.println(ans);
}
}
static long prime(long n){
for (long i=3; i*i<=n; i+=2){
if (n%i==0) return i;
}
return -1;
}
static long factorial (int x){
if (x==0) return 1;
long ans =x;
for (int i=x-1; i>=1; i--){
ans*=i;
ans%=mod;
}
return ans;
}
static boolean killMePls = false;
// public static void main(String[] args) throws Exception {
// Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() {
// public void uncaughtException(Thread t, Throwable e) {killMePls = true;}
// };
// Thread t = new Thread(null, ()->A(args), "", 1<<28);
// t.setUncaughtExceptionHandler(h);
// t.start();
// t.join();
// if(killMePls) throw null;
// }
static int mod2= 998244353;
static long mod=1000000007L;
static long power2 (long a, long b){
long res=1;
while (b>0){
if ((b&1)== 1){
res= (res * a % mod)%mod;
}
a=(a%mod * a%mod)%mod;
b=b>>1;
}
return res;
}
static void sort(int[] a){
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static void sortLong(long[] a){
ArrayList<Long> l=new ArrayList<>();
for (long i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static long gcd (long n, long m){
if (m==0) return n;
else return gcd(m, n%m);
}
static class Pair implements Comparable<Pair>{
int x,y;
private static final int hashMultiplier = BigInteger.valueOf(new Random().nextInt(1000) + 100).nextProbablePrime().intValue();
public Pair(int x, int y){
this.x = x;
this.y = y;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair pii = (Pair) o;
if (x != pii.x) return false;
return y == pii.y;
}
public int hashCode() {
return hashMultiplier * x + y;
}
public int compareTo(Pair o){
// if (this.x==o.x) return Integer.compare(this.y,o.y);
// else return Integer.compare(this.x,o.x);
return Integer.compare(this.y,o.y);
}
// this.x-o.x is ascending
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
} | Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 8 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | 061d54d7776ae241c0feb6e017775cfa | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | import java.util.*;
public class ACM {
private static int m;
private static int[][] lock;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
for (int t = in.nextInt(); t > 0; t--) {
m = in.nextInt();
lock = new int[2][m];
for (int i = 0; i < m;) lock[0][i++] = in.nextInt();
for (int i = 0; i < m;) lock[1][i++] = in.nextInt();
lock[0][0] = -1;
minTime();
}
}
private static void minTime() {
long l = 0, r = (long) 1e9;
while (l <= r) {
long m = (l + r) / 2;
if (waitTime(m)) r = m - 1;
else l = m + 1;
}
System.out.println(l + m * 2 - 1);
}
private static boolean waitTime(long t) {
int r = 0;
for (int c = 0; c < m; c++) {
if (t++ <= lock[r][c]) return hook(t - 3, r ^ 1, c -1);
if (t++ <= lock[r ^ 1][c]) return hook(t - 2, r, c);
r ^= 1;
}
return true;
}
private static boolean hook(long t, int row, int col) {
int c = col;
while (c < m && t > lock[row][c]) {
t++;
c++;
}
if (c-- < m) return false;
row ^= 1;
while (c >= col && t > lock[row][c]) {
t++;
c--;
}
return c < col;
}
} | Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 8 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | 8cc9b6b4f295b07b30ae50c7b94538ba | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | /* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
import javafx.util.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Codechef
{
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();
}
}
static int parent(int a , int p[])
{
if(a == p[a])
return a;
return p[a] = parent(p[a],p);
}
static void union(int a , int b , int p[] , int sz[] , int minpos[] , long min[])
{
a = parent(a,p);
b = parent(b,p);
if(a == b)
return;
if(sz[a] < sz[b])
{
int tmp = a;
a = b;
b = tmp;
}
p[b] = a;
sz[a] += sz[b];
min[a] = Math.min(min[a],min[b]);
if(min[b] < min[a])
minpos[a] = minpos[b];
}
static long pow(long a , long b , long c)
{
if(b == 0)
return 1;
long ans = pow(a,b/2,c);
if(b%2 == 0)
return ans*ans%c;
return ans*ans%c*a%c;
}
static long st[];
static long lazy[];
static int sz;
static void setMax(int l , int r , long v , int lx , int rx , int x)
{
if(lazy[x] != Long.MIN_VALUE)
{
st[x] = Math.max(st[x],lazy[x]);
if(lx != rx)
{
lazy[2*x+1] = Math.max(lazy[2*x+1],lazy[x]);
lazy[2*x+2] = Math.max(lazy[2*x+2],lazy[x]);
}
lazy[x] = Long.MIN_VALUE;
}
if(lx > r || rx < l)
return;
if(lx >= l && rx <= r)
{
st[x] = Math.max(st[x],v);
if(lx != rx)
{
lazy[2*x+1] = Math.max(lazy[2*x+1],v);
lazy[2*x+2] = Math.max(lazy[2*x+2],v);
}
return;
}
int mid = (lx+rx)/2;
setMax(l,r,v,lx,mid,2*x+1);
setMax(l,r,v,mid+1,rx,2*x+2);
st[x] = Math.max(st[2*x+1],st[2*x+2]);
}
static long getMax(int l , int r , int lx , int rx , int x)
{
if(lazy[x] != Long.MIN_VALUE)
{
st[x] = Math.max(st[x],lazy[x]);
if(lx != rx)
{
lazy[2*x+1] = Math.max(lazy[2*x+1],lazy[x]);
lazy[2*x+2] = Math.max(lazy[2*x+2],lazy[x]);
}
lazy[x] = Long.MIN_VALUE;
}
if(lx > r || rx < l)
return -1000000000000000L;
if(lx >= l && rx <= r)
return st[x];
int mid = (lx+rx)/2;
return Math.max(getMax(l,r,lx,mid,2*x+1),getMax(l,r,mid+1,rx,2*x+2));
}
static boolean check(int x , int a[] , int b[] , int g[][] , long s , int k)
{
long aa = Long.MAX_VALUE;
long bb = Long.MAX_VALUE;
for(int i = 1 ; i <= x ; i++)
{
aa = Math.min(aa,a[i]);
bb = Math.min(bb,b[i]);
}
long cost[] = new long[g.length];
for(int i = 0 ; i < g.length ; i++)
{
if(g[i][0] == 1)
cost[i] = aa*(long)g[i][1];
else
cost[i] = bb*(long)g[i][1];
}
Arrays.sort(cost);
for(int i = 0 ; i < k ; i++)
{
s -= cost[i];
if(s < 0)
return false;
}
return true;
}
public static void main(String []args) throws IOException
{
Reader sc = new Reader();
int q = sc.nextInt();
while(q-- > 0)
{
int n = sc.nextInt();
int arr[][] = new int[n][2];
for(int i = 0 ; i < n ; i++)
{
arr[i][0] = sc.nextInt();
}
for(int i = 0 ; i < n ; i++)
{
arr[i][1] = sc.nextInt();
}
int dp[][] = new int[n][2];
arr[0][0]--;
for(int i = n-1 ; i >= 0 ; i--)
{
for(int j = 0 ; j < 2 ; j++)
{
int t = arr[i][j]+1;
int add = 2*(n-i)-1;
if(t+add > arr[i][0]+arr[i][1]-arr[i][j])
{
dp[i][j] = t;
}
else
dp[i][j] = arr[i][0]+arr[i][1]-arr[i][j]+1-add;
if(i != n-1)
{
if(dp[i][j]+1 <= dp[i+1][j])
dp[i][j] = dp[i+1][j]-1;
}
}
}
int curr = 0;
// int ans = 0;
int ans = 0;
for(int i = 1 ; i < n ; i++)
{
if(ans > arr[i][0])
ans++;
else
ans = arr[i][0]+2;
// System.out.print(ans + " ");
}
// System.out.println();
// System.out.println(ans);
// System.out.println();
for(int i = n-1 ; i > 0 ; i--)
{
if(ans > arr[i][1])
ans++;
else
ans = arr[i][1]+2;
// System.out.print(ans + " ");
}
ans = Math.max(ans,dp[0][1]);
// System.out.println(ans + " lauda");
for(int i = 0 ; i < n ; i++)
{
int add = 2*(n-(i+1))-1;
if(i%2 == 0)
{
if(curr <= arr[i][0])
curr = arr[i][0]+2;
else
curr++;
if(curr <= arr[i][1])
curr = arr[i][1]+2;
else
curr++;
if(i+1 < n)
{
if(curr >= dp[i+1][1])
ans = Math.min(ans, curr+add);
else
ans = Math.min(ans,dp[i+1][1]+add);
}
}
else
{
if(curr <= arr[i][1])
curr = arr[i][1]+2;
else
curr++;
if(curr <= arr[i][0])
curr = arr[i][0]+2;
else
curr++;
if(i+1 < n)
{
if(curr >= dp[i+1][0])
ans = Math.min(ans, curr+add);
else
ans = Math.min(ans,dp[i+1][0]+add);
}
}
//System.out.println(curr + " " + ans);
}
System.out.println(ans);
}
}
} | Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 8 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | 3dfb72c92650e36de5163ea7686c0874 | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | import java.io.*;
import java.util.StringTokenizer;
/**
* C. Robot in a Hallway
*/
public class Main {
static class FastReader {
BufferedReader reader;
StringTokenizer tokenizer;
FastReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
// reads in the next string
String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
// reads in the next int
int nextInt() {
return Integer.parseInt(next());
}
// reads in the next long
long nextLong() {
return Long.parseLong(next());
}
// reads in the next double
double nextDouble() {
return Double.parseDouble(next());
}
void close() {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static FastReader in = new FastReader(System.in);
private static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
private static final int MAXN = (int) 2e5 + 10;
private static int[][] a = new int[2][MAXN], dp = new int[2][MAXN];
private static int[] dx = new int[]{1, 0, -1, 0}, dy = new int[]{0, 1, 0, 1};
private static int m;
private static int solve() {
a[0][0] = -1;
dp[0][m] = dp[1][m] = 0;
for (int i = 0; i < 2; i++) {
for (int j = m - 1; j >= 0; j--) {
dp[i][j] = Math.max(a[i ^ 1][j] + 1, Math.max(dp[i][j + 1] + 1, a[i][j] + 1 + 2 * (m - j) - 1));
}
}
int[] now = new int[2];
int ans = dp[0][0], len = 1, cost = 0, dir = 0;
while (now[1] < m) {
if (len % 2 == 0) ans = Math.min(ans, Math.max(cost + 2 * (m - 1 - now[1]), dp[now[0]][now[1] + 1]));
now[0] += dx[dir];
now[1] += dy[dir];
cost = Math.max(a[now[0]][now[1]] + 1, cost + 1);
dir = (dir + 1) % 4;
len++;
}
return ans;
}
public static void main(String[] args) {
int t = in.nextInt();
while (t-- > 0) {
m = in.nextInt();
for (int i = 0; i < m; i++) a[0][i] = in.nextInt();
for (int i = 0; i < m; i++) a[1][i] = in.nextInt();
out.println(solve());
}
out.flush();
out.close();
in.close();
}
}
| Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 8 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | e1e39539ddfce9b6e3fc0d0feb6a641f | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | import java.io.*;
import java.util.StringTokenizer;
/**
* C. Robot in a Hallway
*/
public class Main {
static class FastReader {
BufferedReader reader;
StringTokenizer tokenizer;
FastReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
// reads in the next string
String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
// reads in the next int
int nextInt() {
return Integer.parseInt(next());
}
// reads in the next long
long nextLong() {
return Long.parseLong(next());
}
// reads in the next double
double nextDouble() {
return Double.parseDouble(next());
}
void close() {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static FastReader in = new FastReader(System.in);
private static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
private static final int MAXN = (int) 2e5 + 10;
private static int[][] a = new int[2][MAXN], dp = new int[2][MAXN];
private static int[] dx = new int[]{1, 0, -1, 0}, dy = new int[]{0, 1, 0, 1};
private static int m;
private static int solve() {
a[0][0] = -1;
dp[0][m] = dp[1][m] = 0;
for (int i = 0; i < 2; i++) {
for (int j = m - 1; j >= 0; j--) {
dp[i][j] = Math.max(a[i][j] + 1, a[i ^ 1][j] + 1);
dp[i][j] = Math.max(dp[i][j], Math.max(dp[i][j + 1] + 1, a[i][j] + 1 + 2 * (m - j) - 1));
}
}
int[] now = new int[2];
int ans = dp[0][0], len = 1, cost = 0, dir = 0;
while (now[1] < m) {
if (len % 2 == 0) ans = Math.min(ans, Math.max(cost + 2 * (m - 1 - now[1]), dp[now[0]][now[1] + 1]));
now[0] += dx[dir];
now[1] += dy[dir];
cost = Math.max(cost, Math.max(a[now[0]][now[1]] + 1, cost + 1));
dir = (dir + 1) % 4;
len++;
}
return ans;
}
public static void main(String[] args) {
int t = in.nextInt();
while (t-- > 0) {
m = in.nextInt();
for (int i = 0; i < m; i++) a[0][i] = in.nextInt();
for (int i = 0; i < m; i++) a[1][i] = in.nextInt();
out.println(solve());
}
out.flush();
out.close();
in.close();
}
}
| Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 8 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | 4c65191889404c5a566d2786e56e5bc3 | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | import java.util.*;
import java.io.*;
// res.append("Case #"+(p+1)+": "+hh+" \n");
////***************************************************************************
/* public class E_Gardener_and_Tree implements Runnable{
public static void main(String[] args) throws Exception {
new Thread(null, new E_Gardener_and_Tree(), "E_Gardener_and_Tree", 1<<28).start();
}
public void run(){
WRITE YOUR CODE HERE!!!!
JUST WRITE EVERYTHING HERE WHICH YOU WRITE IN MAIN!!!
}
}
*/
/////**************************************************************************
public class C_Robot_in_a_Hallway{
public static void main(String[] args) {
FastScanner s= new FastScanner();
//PrintWriter out=new PrintWriter(System.out);
//end of program
//out.println(answer);
//out.close();
StringBuilder res = new StringBuilder();
int t=s.nextInt();
int p=0;
while(p<t){
int m=s.nextInt();
long matrix[][]= new long[2][m];
for(int i=0;i<2;i++){
for(int j=0;j<m;j++){
matrix[i][j]=s.nextLong();
}
}
long nice1[]= new long[m];//time which should have been elapsed if starting form i with first type of moves
long a1=Math.max(matrix[0][m-1]+2,matrix[1][m-1]+1);
nice1[m-1]=a1-2;
for(int i=m-2;i>=0;i--){
long blocks=m-i;
blocks=(2L*blocks);
long op1=matrix[0][i]+blocks;
long op2=nice1[i+1]+blocks-1;
long op3=matrix[1][i]+1;
long hh=Math.max(op1,Math.max(op2,op3));
hh-=blocks;
nice1[i]=hh;
}
long nice2[]= new long[m];//time which should have been elapsed if starting form i with second type of moves
a1=Math.max(matrix[1][m-1]+2,matrix[0][m-1]+1);
nice2[m-1]=a1-2;
for(int i=m-2;i>=0;i--){
long blocks=m-i;
blocks=(2L*blocks);
long op1=matrix[1][i]+blocks;
long op2=nice2[i+1]+blocks-1;
long op3=matrix[0][i]+1;
long hh=Math.max(op1,Math.max(op2,op3));
hh-=blocks;
nice2[i]=hh;
}
long ans=Math.max((matrix[1][0]+1),Math.max((matrix[0][0]+(2*m)-1),(nice1[1]+(2*m)-1)));
long hh=0;
for(int i=0;i<m;i+=2){
int col=i;
long blocks=m-col;
blocks=(2L*blocks);
if(hh>=nice1[col]){
long yoyo=hh+blocks;
ans=Math.min(ans,yoyo);
}
else{
long yoyo=nice1[col]+blocks;
ans=Math.min(ans,yoyo);
}
if(i>0){
{
long num=matrix[0][col];
if(hh>=num){
hh++;
}
else{
hh=num+1;
}
}
}
{
long num=matrix[1][col];
if(hh>=num){
hh++;
}
else{
hh=num+1;
}
}
col++;
if(col>=m){
break;
}
blocks=m-col;
blocks=(2L*blocks);
if(hh>=nice2[col]){
long yoyo=hh+blocks;
ans=Math.min(ans,yoyo);
}
else{
long yoyo=nice2[col]+blocks;
ans=Math.min(ans,yoyo);
}
{
long num=matrix[1][col];
if(hh>=num){
hh++;
}
else{
hh=num+1;
}
}
{
long num=matrix[0][col];
if(hh>=num){
hh++;
}
else{
hh=num+1;
}
}
}
ans=Math.min(ans,hh);
res.append(ans+"\n");
p++;
}
System.out.println(res);
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(String s) {
try {
br = new BufferedReader(new FileReader(s));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
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();
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
}
static long modpower(long x, long y, long p)
{
long res = 1; // Initialize result
x = x % p; // Update x if it is more than or
// equal to p
if (x == 0)
return 0; // In case x is divisible by p;
while (y > 0)
{
// If y is odd, multiply x with result
if ((y & 1) != 0)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
// SIMPLE POWER FUNCTION=>
static long power(long x, long y)
{
long res = 1; // Initialize result
while (y > 0)
{
// If y is odd, multiply x with result
if ((y & 1) != 0)
res = res * x;
// y must be even now
y = y >> 1; // y = y/2
x = x * x; // Change x to x^2
}
return res;
}
} | Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 8 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | 9568c1a160740c9065f831ffe740c3ff | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes |
import java.io.*;
import java.util.*;
public final class Main {
//int 2e9 - long 9e18
static PrintWriter out = new PrintWriter(System.out);
static FastReader in = new FastReader();
static Pair[] moves = new Pair[]{new Pair(-1, 0), new Pair(0, 1), new Pair(1, 0), new Pair(0, -1)};
static Pair[] movesDiagonal = new Pair[]{new Pair(-1, -1), new Pair(-1, 1), new Pair(1, -1), new Pair(1, 1)};
static int mod = (int) (1e9 + 7);
static int mod2 = 998244353;
public static void main(String[] args) {
int tt = i();
while (tt-- > 0) {
solve();
}
out.flush();
}
public static void solve() {
int n = i();
int[] a = input(n);
int[] b = input(n);
a[0] = -1;
PriorityQueue<int[]> pq = new PriorityQueue<>(new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return o2[2] - o1[2];
}
});
int idx = 0;
for (int i = 0; i < n; i++) {
pq.offer(new int[]{i, idx, a[i] - idx});
idx++;
}
for (int i = n - 1; i >= 0; i--) {
pq.offer(new int[]{i, idx, b[i] - idx});
idx++;
}
int ans = Integer.MAX_VALUE;
int cur = -1;
for (int i = 0; i < n; i += 2) {
while (pq.size() > 0) {
int[] peek = pq.peek();
if (peek[0] < i) {
pq.poll();
continue;
}
int ridx = 2 * n - i - 1;
ans = Math.min(ans, Math.max(cur + peek[1] - i + 1, peek[1] + peek[2] + 1) + (ridx - peek[1]));
break;
}
if (i + 2 < n) {
cur = Math.max(a[i] + 1, cur + 1);
cur = Math.max(b[i] + 1, cur + 1);
cur = Math.max(b[i + 1] + 1, cur + 1);
cur = Math.max(a[i + 1] + 1, cur + 1);
}
}
pq.clear();
idx = 0;
for (int i = 0; i < n; i++) {
pq.offer(new int[]{i, idx, b[i] - idx});
idx++;
}
for (int i = n - 1; i >= 0; i--) {
pq.offer(new int[]{i, idx, a[i] - idx});
idx++;
}
cur = Math.max(b[0] + 1, 1);
for (int i = 1; i < n; i += 2) {
while (pq.size() > 0) {
int[] peek = pq.peek();
if (peek[0] < i) {
pq.poll();
continue;
}
int ridx = 2 * n - i - 1;
ans = Math.min(ans, Math.max(cur + peek[1] - i + 1, peek[1] + peek[2] + 1) + (ridx - peek[1]));
break;
}
if (i + 2 < n) {
cur = Math.max(b[i] + 1, cur + 1);
cur = Math.max(a[i] + 1, cur + 1);
cur = Math.max(a[i + 1] + 1, cur + 1);
cur = Math.max(b[i + 1] + 1, cur + 1);
}
}
out.println(ans);
}
// (10,5) = 2 ,(11,5) = 3
static long upperDiv(long a, long b) {
return (a / b) + ((a % b == 0) ? 0 : 1);
}
static long sum(int[] a) {
long sum = 0;
for (int x : a) {
sum += x;
}
return sum;
}
static int[] preint(int[] a) {
int[] pre = new int[a.length + 1];
pre[0] = 0;
for (int i = 0; i < a.length; i++) {
pre[i + 1] = pre[i] + a[i];
}
return pre;
}
static long[] pre(int[] a) {
long[] pre = new long[a.length + 1];
pre[0] = 0;
for (int i = 0; i < a.length; i++) {
pre[i + 1] = pre[i] + a[i];
}
return pre;
}
static long[] post(int[] a) {
long[] post = new long[a.length + 1];
post[0] = 0;
for (int i = 0; i < a.length; i++) {
post[i + 1] = post[i] + a[a.length - 1 - i];
}
return post;
}
static long[] pre(long[] a) {
long[] pre = new long[a.length + 1];
pre[0] = 0;
for (int i = 0; i < a.length; i++) {
pre[i + 1] = pre[i] + a[i];
}
return pre;
}
static void print(char A[]) {
for (char c : A) {
out.print(c);
}
out.println();
}
static void print(boolean A[]) {
for (boolean c : A) {
out.print(c + " ");
}
out.println();
}
static void print(int A[]) {
for (int c : A) {
out.print(c + " ");
}
out.println();
}
static void print(long A[]) {
for (long i : A) {
out.print(i + " ");
}
out.println();
}
static void print(List<Integer> A) {
for (int a : A) {
out.print(a + " ");
}
}
static int i() {
return in.nextInt();
}
static long l() {
return in.nextLong();
}
static double d() {
return in.nextDouble();
}
static String s() {
return in.nextLine();
}
static String c() {
return in.next();
}
static int[][] inputWithIdx(int N) {
int A[][] = new int[N][2];
for (int i = 0; i < N; i++) {
A[i] = new int[]{i, in.nextInt()};
}
return A;
}
static int[] input(int N) {
int A[] = new int[N];
for (int i = 0; i < N; i++) {
A[i] = in.nextInt();
}
return A;
}
static long[] inputLong(int N) {
long A[] = new long[N];
for (int i = 0; i < A.length; i++) {
A[i] = in.nextLong();
}
return A;
}
static int GCD(int a, int b) {
if (b == 0) {
return a;
} else {
return GCD(b, a % b);
}
}
static long GCD(long a, long b) {
if (b == 0) {
return a;
} else {
return GCD(b, a % b);
}
}
static long LCM(int a, int b) {
return (long) a / GCD(a, b) * b;
}
static long LCM(long a, long b) {
return a / GCD(a, b) * b;
}
// find highest i which satisfy a[i]<=x
static int lowerbound(int[] a, int x) {
int l = 0;
int r = a.length - 1;
while (l < r) {
int m = (l + r + 1) / 2;
if (a[m] <= x) {
l = m;
} else {
r = m - 1;
}
}
return l;
}
static void shuffle(int[] arr) {
for (int i = 0; i < arr.length; i++) {
int rand = (int) (Math.random() * arr.length);
int temp = arr[rand];
arr[rand] = arr[i];
arr[i] = temp;
}
}
static void shuffleAndSort(int[] arr) {
for (int i = 0; i < arr.length; i++) {
int rand = (int) (Math.random() * arr.length);
int temp = arr[rand];
arr[rand] = arr[i];
arr[i] = temp;
}
Arrays.sort(arr);
}
static void shuffleAndSort(int[][] arr, Comparator<? super int[]> comparator) {
for (int i = 0; i < arr.length; i++) {
int rand = (int) (Math.random() * arr.length);
int[] temp = arr[rand];
arr[rand] = arr[i];
arr[i] = temp;
}
Arrays.sort(arr, comparator);
}
static void shuffleAndSort(long[] arr) {
for (int i = 0; i < arr.length; i++) {
int rand = (int) (Math.random() * arr.length);
long temp = arr[rand];
arr[rand] = arr[i];
arr[i] = temp;
}
Arrays.sort(arr);
}
static boolean isPerfectSquare(double number) {
double sqrt = Math.sqrt(number);
return ((sqrt - Math.floor(sqrt)) == 0);
}
static void swap(int A[], int a, int b) {
int t = A[a];
A[a] = A[b];
A[b] = t;
}
static void swap(char A[], int a, int b) {
char t = A[a];
A[a] = A[b];
A[b] = t;
}
static long pow(long a, long b, int mod) {
long pow = 1;
long x = a;
while (b != 0) {
if ((b & 1) != 0) {
pow = (pow * x) % mod;
}
x = (x * x) % mod;
b /= 2;
}
return pow;
}
static long pow(long a, long b) {
long pow = 1;
long x = a;
while (b != 0) {
if ((b & 1) != 0) {
pow *= x;
}
x = x * x;
b /= 2;
}
return pow;
}
static long modInverse(long x, int mod) {
return pow(x, mod - 2, mod);
}
static boolean isPrime(long N) {
if (N <= 1) {
return false;
}
if (N <= 3) {
return true;
}
if (N % 2 == 0 || N % 3 == 0) {
return false;
}
for (int i = 5; i * i <= N; i = i + 6) {
if (N % i == 0 || N % (i + 2) == 0) {
return false;
}
}
return true;
}
public static String reverse(String str) {
if (str == null) {
return null;
}
return new StringBuilder(str).reverse().toString();
}
public static void reverse(int[] arr) {
int l = 0;
int r = arr.length - 1;
while (l < r) {
swap(arr, l, r);
l++;
r--;
}
}
public static String repeat(char ch, int repeat) {
if (repeat <= 0) {
return "";
}
final char[] buf = new char[repeat];
for (int i = repeat - 1; i >= 0; i--) {
buf[i] = ch;
}
return new String(buf);
}
public static int[] manacher(String s) {
char[] chars = s.toCharArray();
int n = s.length();
int[] d1 = new int[n];
for (int i = 0, l = 0, r = -1; i < n; i++) {
int k = (i > r) ? 1 : Math.min(d1[l + r - i], r - i + 1);
while (0 <= i - k && i + k < n && chars[i - k] == chars[i + k]) {
k++;
}
d1[i] = k--;
if (i + k > r) {
l = i - k;
r = i + k;
}
}
return d1;
}
public static int[] kmp(String s) {
int n = s.length();
int[] res = new int[n];
for (int i = 1; i < n; ++i) {
int j = res[i - 1];
while (j > 0 && s.charAt(i) != s.charAt(j)) {
j = res[j - 1];
}
if (s.charAt(i) == s.charAt(j)) {
++j;
}
res[i] = j;
}
return res;
}
}
class Pair {
int i;
int j;
Pair(int i, int j) {
this.i = i;
this.j = j;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Pair pair = (Pair) o;
return i == pair.i && j == pair.j;
}
@Override
public int hashCode() {
return Objects.hash(i, j);
}
}
class ThreePair {
int i;
int j;
int k;
ThreePair(int i, int j, int k) {
this.i = i;
this.j = j;
this.k = k;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ThreePair pair = (ThreePair) o;
return i == pair.i && j == pair.j && k == pair.k;
}
@Override
public int hashCode() {
return Objects.hash(i, j);
}
}
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 Node {
int val;
public Node(int val) {
this.val = val;
}
}
class ST {
int n;
Node[] st;
ST(int n) {
this.n = n;
st = new Node[4 * Integer.highestOneBit(n)];
}
void build(Node[] nodes) {
build(0, 0, n - 1, nodes);
}
private void build(int id, int l, int r, Node[] nodes) {
if (l == r) {
st[id] = nodes[l];
return;
}
int mid = (l + r) >> 1;
build((id << 1) + 1, l, mid, nodes);
build((id << 1) + 2, mid + 1, r, nodes);
st[id] = comb(st[(id << 1) + 1], st[(id << 1) + 2]);
}
void update(int i, Node node) {
update(0, 0, n - 1, i, node);
}
private void update(int id, int l, int r, int i, Node node) {
if (i < l || r < i) {
return;
}
if (l == r) {
st[id] = node;
return;
}
int mid = (l + r) >> 1;
update((id << 1) + 1, l, mid, i, node);
update((id << 1) + 2, mid + 1, r, i, node);
st[id] = comb(st[(id << 1) + 1], st[(id << 1) + 2]);
}
Node get(int x, int y) {
return get(0, 0, n - 1, x, y);
}
private Node get(int id, int l, int r, int x, int y) {
if (x > r || y < l) {
return new Node(0);
}
if (x <= l && r <= y) {
return st[id];
}
int mid = (l + r) >> 1;
return comb(get((id << 1) + 1, l, mid, x, y), get((id << 1) + 2, mid + 1, r, x, y));
}
Node comb(Node a, Node b) {
if (a == null) {
return b;
}
if (b == null) {
return a;
}
return new Node(GCD(a.val, b.val));
}
static int GCD(int a, int b) {
if (b == 0) {
return a;
} else {
return GCD(b, a % b);
}
}
} | Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 8 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | 6746ad78afada458208ac1cfbcdad2b5 | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | import java.util.*;
public class ACM {
private static int m;
private static int[][] lock;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
for (int t = in.nextInt(); t > 0; t--) {
m = in.nextInt();
lock = new int[2][m];
for (int i = 0; i < m;) lock[0][i++] = in.nextInt();
for (int i = 0; i < m;) lock[1][i++] = in.nextInt();
lock[0][0] = -1;
minTime();
}
}
private static void minTime() {
long l = 0, r = (long) 1e9;
while (l <= r) {
long m = (l + r) / 2;
if (waitTime(m)) r = m - 1;
else l = m + 1;
}
System.out.println(l + m * 2 - 1);
}
private static boolean waitTime(long t) {
int r = 0;
for (int c = 0; c < m; c++) {
if (t++ <= lock[r][c]) return hook(t - 3, r ^ 1, c -1);
if (t++ <= lock[r ^ 1][c]) return hook(t - 2, r, c);
r ^= 1;
}
return true;
}
private static boolean hook(long t, int row, int col) {
int c = col;
while (c < m && t > lock[row][c]) {
t++;
c++;
}
if (c-- < m) return false;
row ^= 1;
while (c >= col && t > lock[row][c]) {
t++;
c--;
}
return c < col;
}
} | Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 8 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | ebd4c559a336fcaf3bdf6bf00d0a8e26 | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | import java.util.*;
public class ACM {
private static int m;
private static int[][] lock;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
for (int t = in.nextInt(); t > 0; t--) {
m = in.nextInt();
lock = new int[2][m];
for (int i = 0; i < m;) lock[0][i++] = in.nextInt();
for (int i = 0; i < m;) lock[1][i++] = in.nextInt();
lock[0][0] = -1;
minTime();
}
}
private static void minTime() {
long l = 0, r = (long) 1e9;
while (l <= r) {
long m = (l + r) / 2;
if (waitTime(m)) r = m - 1;
else l = m + 1;
}
System.out.println(l + m * 2 - 1);
}
private static boolean waitTime(long t) {
int r = 0;
for (int c = 0; c < m; c++) {
if (t++ <= lock[r][c]) return hook(t - 3, r ^ 1, c -1);
if (t++ <= lock[r ^ 1][c]) return hook(t - 2, r, c);
r ^= 1;
}
return true;
}
private static boolean hook(long t, int row, int col) {
int c = col;
while (c < m && t > lock[row][c]) {
t++;
c++;
}
if (c-- < m) return false;
row ^= 1;
while (c >= col && t > lock[row][c]) {
t++;
c--;
}
return c < col;
}
} | Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 8 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | 87bccabf6f385e7c25657365b201cc58 | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.TreeMap;
public class C {
static int[][]a,passed,rem,ans;
public static void main(String[]args) throws IOException {
Scanner sc=new Scanner(System.in);
PrintWriter out=new PrintWriter(System.out);
int t=sc.nextInt();
while(t-->0) {
int n=sc.nextInt();
a=new int[n][2];
passed=new int[n][2];
rem=new int[n][2];
ans=new int[n][2];
for(int i=0;i<n;i++) {
a[i][0]=sc.nextInt();
Arrays.fill(ans[i], -1);
}
for(int i=0;i<n;i++) {
a[i][1]=sc.nextInt();
}
int mrg=0;
for(int i=0,j=1;i<n;) {
// if(i==n-1&&n%2==j)break;
int extra=Math.max(1, a[i][j]-mrg+1);
mrg+=extra;
passed[i][j]=mrg;
if(i%2==0) {
if(j==0) {
j++;
}else {
i++;
}
}else {
if(j==0) {
i++;
}else {
j--;
}
}
}
// out.println(Arrays.deepToString(passed));
//rem to go right,down,left ]
// rem[n-1][0]=Math.max(1, a[n-1][1]-passed[n-1][0]+1);
// for(int i=n-2;i>=0;i--) {
// rem[i][0]=rem[i+1][0];
// rem[i][0]+=Math.max(1, a[i+1][0]-passed[i][0]+1);
// rem[i][0]+=Math.max(1, a[i][1]-passed[i+1][1]+1);
// }
//fill rem
int[][]rem2=new int[n][2];
mrg=0;
for(int i=1;i<n;i++) {
int extra=Math.max(1, a[i][0]-mrg+1);
mrg+=extra;rem2[i][0]=mrg;
}
mrg+=Math.max(1, a[n-1][1]-mrg+1);rem2[n-1][1]=mrg;
for(int i=n-2;i>=0;i--) {
int extra=Math.max(1, a[i][1]-mrg+1);
mrg+=extra;rem2[i][1]=mrg;
}
for(int i=0;i<n;i++) {
rem[i][0]=Math.max((n-1-i)*2+1,rem2[i][1]-passed[i][0]);
}
// out.println(Arrays.deepToString(passed));
// out.println(Arrays.deepToString(rem));
///////////
mrg=0;
for(int i=0;i<n;i++) {
int extra=Math.max(1, a[i][1]-mrg+1);
mrg+=extra;rem2[i][1]=mrg;
}
mrg+=Math.max(1, a[n-1][0]-mrg+1);rem2[n-1][0]=mrg;
for(int i=n-2;i>=0;i--) {
int extra=Math.max(1, a[i][0]-mrg+1);
mrg+=extra;rem2[i][0]=mrg;
}
for(int i=0;i<n;i++) {
rem[i][1]=Math.max((n-1-i)*2+1,rem2[i][0]-passed[i][1]);
}
out.println(dp(0,0));
}
out.close();
}
private static int dp(int i, int j) {
if(i==ans.length)return 0;
if(ans[i][j]!=-1)return ans[i][j];
int an=rem[i][j];
if(i<ans.length-1)
an=Math.min(an, passed[i+1][1-j]-passed[i][j]+dp(i+1,1-j));
return ans[i][j]=an;
}
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 boolean hasNext() {return st.hasMoreTokens();}
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\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 8 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | 856f783bda1a8893ecc3d7964d94ab13 | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | import java.io.*;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
Task solver = new Task();
solver.solve(in.nextInt(), in, out);
out.close();
}
static class Task {
public void solve(int testNumber, InputReader in, PrintWriter out) {
for (int t = 0; t < testNumber; t++) {
int m = in.nextInt();
int[][] a = new int[2][m];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < m; j++) {
a[i][j] = in.nextInt();
}
}
out.println(new Solution().solve(a));
}
}
}
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());
}
}
}
class Solution {
public int solve(int[][] a) {
int min;
int m = a[0].length;
int[] arr1 = new int[m * 2];
int[] arr2 = new int[m * 2];
for (int i = 0; i < m; i++) {
arr1[i] = a[0][i] - i;
arr1[m + i] = a[1][m - i - 1] - m - i;
arr2[i] = a[1][i] - i;
arr2[m + i] = a[0][m - i - 1] - m - i;
}
ST st1 = new ST(arr1);
ST st2 = new ST(arr2);
int[][] arr = new int[2][m];
arr[1][0] = Math.max(1, a[1][0] + 1);
for (int i = 1; i < m; i++) {
if (i % 2 == 0) {
arr[0][i] = Math.max(arr[0][i - 1], a[0][i]) + 1;
arr[1][i] = Math.max(arr[0][i], a[1][i]) + 1;
} else {
arr[1][i] = Math.max(arr[1][i - 1], a[1][i]) + 1;
arr[0][i] = Math.max(arr[1][i], a[0][i]) + 1;
}
}
if (m % 2 == 0) {
min = arr[0][m - 1];
} else {
min = arr[1][m - 1];
}
for (int i = 0; i < m - 1; i++) {
int cur = arr[i % 2][i];
int max;
if (i % 2 == 0) {
max = st1.query(i + 1, 2 * m - 1 - i);
} else {
max = st2.query(i + 1, 2 * m - 1 - i);
}
int t = i + max + 1;
t = Math.max(t, cur);
min = Math.min(min, t + (m - i - 1) * 2 + 1);
}
return min;
}
}
class ST {
int[][] f;
int[] log2;
public ST(int[] a) {
int n = a.length;
log2 = new int[n + 1];
int k = 0;
for (int i = 1; i <= n; i++) {
if (i >= (1 << (k + 1))) {
k++;
}
log2[i] = k;
}
int t = log2[n] + 1;
f = new int[n][t];
for (int i = 0; i < n; i++) {
f[i][0] = a[i];
}
for (int j = 1; j < t; j++) {
for (int i = 0; i < n - (1 << j) + 1; i++) {
f[i][j] = Math.max(f[i][j - 1], f[i + (1 << (j - 1))][j - 1]);
}
}
}
public int query(int l, int r) {
// 下标从0开始,左闭右闭
int k = log2[r - l + 1];
return Math.max(f[l][k], f[r - (1 << k) + 1][k]);
}
}
| Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 8 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | c685df3fa751ba4f4a992de8410288ab | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | import java.io.*;
import java.util.*;
public class Solution {
public static boolean useInFile = false;
public static boolean useOutFile = false;
public static void main(String args[]) throws IOException {
InOut inout = new InOut();
Resolver resolver = new Resolver(inout);
// long time = System.currentTimeMillis();
resolver.solve();
// resolver.print("\n" + (System.currentTimeMillis() - time));
inout.flush();
}
private static class Resolver {
final long LONG_INF = (long) 1e18;
final int INF = (int) (1e9 + 7);
final int MOD = 998244353;
long f[], inv[];
InOut inout;
Resolver(InOut inout) {
this.inout = inout;
}
void initF(int n, int mod) {
f = new long[n + 1];
f[1] = 1;
for (int i = 2; i <= n; i++) {
f[i] = (f[i - 1] * i) % mod;
}
}
void initInv(int n, int mod) {
inv = new long[n + 1];
inv[n] = pow(f[n], mod - 2, mod);
for (int i = inv.length - 2; i >= 0; i--) {
inv[i] = inv[i + 1] * (i + 1) % mod;
}
}
long cmn(int n, int m, int mod) {
return f[n] * inv[m] % mod * inv[n - m] % mod;
}
int d[] = {0, -1, 0, 1, 0};
boolean legal(int r, int c, int n, int m) {
return r >= 0 && r < n && c >= 0 && c < m;
}
int[] getBits(int n) {
int b[] = new int[31];
for (int i = 0; i < 31; i++) {
if ((n & (1 << i)) != 0) {
b[i] = 1;
}
}
return b;
}
private int[] ask1(int l, int r) throws IOException {
format("? %d %d\n", l, r);
flush();
return anInt(0, r - l);
}
private void dfs(int f, long a[], long b[], long c[], long s[]) {
List<Integer> es = adj[f];
long max = 0;
for (int i = 0; i < es.size(); i++) {
int t = es.get(i);
dfs(t, a, b, c, s);
max = Math.max(max, b[t]);
c[f] += c[t];
}
if (a[f] == 0) {
b[f] = Math.max(max, c[f]) + 1;
} else {
}
}
void solve() throws IOException {
int tt = 1;
boolean hvt = true;
if (hvt) {
tt = nextInt();
// tt = Integer.parseInt(nextLine());
}
// initF(300001, MOD);
// initInv(300001, MOD);
// boolean pri[] = generatePrime(40000);
for (int cs = 1; cs <= tt; cs++) {
long rs = 0;
boolean ok = true;
int n = nextInt();
int a[][] = new int[2][n];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = nextInt() + 1;
}
}
a[0][0] = 0;
long dst[][] = new long[2][n];
for (int i = 1; i < n; i++) {
dst[0][i] = Math.max(dst[0][i - 1] + 1, a[0][i]);
}
dst[1][n - 1] = Math.max(dst[0][n - 1] + 1, a[1][n - 1]);
for (int i = n - 2; i >= 0; i--) {
dst[1][i] = Math.max(dst[1][i + 1] + 1, a[1][i]);
}
long dp[][] = new long[2][n];
for (int i = 0; i < n; i++) {
dp[0][i] = dst[1][i];
}
//
dst[1][0] = Math.max(1, a[1][0]);
for (int i = 1; i < n; i++) {
dst[1][i] = Math.max(dst[1][i - 1] + 1, a[1][i]);
}
dst[0][n - 1] = Math.max(dst[1][n - 1] + 1, a[0][n - 1]);
for (int i = n - 2; i >= 0; i--) {
dst[0][i] = Math.max(dst[0][i + 1] + 1, a[0][i]);
}
for (int i = 0; i < n; i++) {
dp[1][i] = dst[0][i];
}
boolean up = true;
long cur = 0;
for (int i = 0; i < n; i++) {
if (up) {
long tmp = Math.max(dp[0][i], cur + (n - i) * 2 - 1);
if (rs == 0 || rs > tmp) {
rs = tmp;
}
cur = Math.max(cur + 1, a[1][i]);
if (i < n - 1) {
cur = Math.max(cur + 1, a[1][i + 1]);
}
} else {
long tmp = Math.max(dp[1][i], cur + (n - i) * 2 - 1);
if (rs > tmp) {
rs = tmp;
}
cur = Math.max(cur + 1, a[0][i]);
if (i < n - 1) {
cur = Math.max(cur + 1, a[0][i + 1]);
}
}
up = !up;
}
rs = Math.min(cur, rs);
// print(ok ? "Yes" : "No");
print("" + rs);
// format("Case #%d: %d", cs, rs);
if (cs < tt) {
format("\n");
// format(" ");
}
// flush();
}
}
private void updateSegTree(int n, long l, SegmentTree lft) {
long lazy;
lazy = 1;
for (int j = 1; j <= l; j++) {
lazy = (lazy + cmn((int) l, j, INF)) % INF;
lft.modify(1, j, j, lazy);
}
lft.modify(1, (int) (l + 1), n, lazy);
}
String next() throws IOException {
return inout.next();
}
String next(int n) throws IOException {
return inout.next(n);
}
String nextLine() throws IOException {
return inout.nextLine();
}
int nextInt() throws IOException {
return inout.nextInt();
}
long nextLong(int n) throws IOException {
return inout.nextLong(n);
}
int[] anInt(int i, int j) throws IOException {
int a[] = new int[j + 1];
for (int k = i; k <= j; k++) {
a[k] = nextInt();
}
return a;
}
long[] anLong(int i, int j) throws IOException {
long a[] = new long[j + 1];
for (int k = i; k <= j; k++) {
a[k] = nextInt();
}
return a;
}
long[] anLong(int i, int j, int len) throws IOException {
long a[] = new long[j + 1];
for (int k = i; k <= j; k++) {
a[k] = nextLong(len);
}
return a;
}
void print(int a[], int l, int r) {
for (int i = l; i <= r; i++) {
format("%s%d", i > l ? " " : "", a[i]);
}
}
void print(String s) {
inout.print(s, false);
}
void print(String s, boolean nextLine) {
inout.print(s, nextLine);
}
void format(String format, Object... obj) {
inout.format(format, obj);
}
void flush() {
inout.flush();
}
void swap(int a[], int i, int j) {
a[i] ^= a[j];
a[j] ^= a[i];
a[i] ^= a[j];
}
void swap(long a[], int i, int j) {
a[i] ^= a[j];
a[j] ^= a[i];
a[i] ^= a[j];
}
int getP(int x, int p[]) {
if (p[x] == 0 || p[x] == x) {
return x;
}
return p[x] = getP(p[x], p);
}
void union(int x, int y, int p[]) {
if (x < y) {
p[y] = x;
} else {
p[x] = y;
}
}
boolean topSort() {
int n = adj2.length - 1;
int d[] = new int[n + 1];
for (int i = 1; i <= n; i++) {
for (int j = 0; j < adj2[i].size(); j++) {
d[adj2[i].get(j)[0]]++;
}
}
List<Integer> list = new ArrayList<>();
for (int i = 1; i <= n; i++) {
if (d[i] == 0) {
list.add(i);
}
}
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j < adj2[list.get(i)].size(); j++) {
int t = adj2[list.get(i)].get(j)[0];
d[t]--;
if (d[t] == 0) {
list.add(t);
}
}
}
return list.size() == n;
}
class DSU {
int[] f, siz;
DSU(int n) {
f = new int[n];
siz = new int[n];
Arrays.fill(siz, 1);
}
int leader(int x) {
while (x != f[x]) x = f[x] = f[f[x]];
return x;
}
boolean same(int x, int y) {
return leader(x) == leader(y);
}
boolean merge(int x, int y) {
x = leader(x);
y = leader(y);
if (x == y) return false;
siz[x] += siz[y];
f[y] = x;
return true;
}
int size(int x) {
return siz[leader(x)];
}
}
;
class SegmentTreeNode {
long defaultVal = 0;
int l, r;
// long val = Integer.MAX_VALUE;
long val = 0;
long lazy = defaultVal;
SegmentTreeNode(int l, int r) {
this.l = l;
this.r = r;
}
}
class SegmentTree {
SegmentTreeNode tree[];
long inf = Long.MIN_VALUE;
long c[];
SegmentTree(int n) {
assert n > 0;
tree = new SegmentTreeNode[n * 3 + 1];
}
void setAn(long cn[]) {
c = cn;
}
SegmentTree build(int k, int l, int r) {
if (l > r) {
return this;
}
if (null == tree[k]) {
tree[k] = new SegmentTreeNode(l, r);
}
if (l == r) {
// tree[k].val = c[l];
return this;
}
int mid = (l + r) >> 1;
build(k << 1, l, mid);
build(k << 1 | 1, mid + 1, r);
tree[k].val = (tree[k << 1].val + tree[k << 1 | 1].val) % MOD;
// tree[k].val = Math.min(tree[k << 1].val, tree[k << 1 | 1].val);
return this;
}
void pushDown(int k) {
if (tree[k].l == tree[k].r) {
return;
}
long lazy = tree[k].lazy;
// tree[k << 1].val = ((c[tree[k << 1].l] - c[tree[k << 1].r + 1] + MOD) % MOD * lazy) % MOD;
tree[k << 1].val += lazy;
tree[k << 1].lazy += lazy;
// tree[k << 1 | 1].val = ((c[tree[k << 1 | 1].l] - c[tree[k << 1 | 1].r + 1] + MOD) % MOD * lazy) % MOD;
tree[k << 1 | 1].val += lazy;
tree[k << 1 | 1].lazy += lazy;
tree[k].lazy = 0;
}
void modify(int k, int l, int r, long change) {
if (tree[k].l >= l && tree[k].r <= r) {
// tree[k].val = ((c[tree[k].l] - c[tree[k].r + 1] + MOD) % MOD * val) % MOD;
tree[k].val += change;
tree[k].lazy += change;
return;
}
int mid = (tree[k].l + tree[k].r) >> 1;
if (tree[k].lazy != 0) {
pushDown(k);
}
if (mid >= l) {
modify(k << 1, l, r, change);
}
if (mid + 1 <= r) {
modify(k << 1 | 1, l, r, change);
}
tree[k].val = (tree[k << 1].val + tree[k << 1 | 1].val) % MOD;
// tree[k].val = Math.min(tree[k << 1].val, tree[k << 1 | 1].val);
}
long query(int k, int l, int r) {
if (tree[k].l > r || tree[k].r < l) {
return 0;
}
if (tree[k].lazy != 0) {
pushDown(k);
}
if (tree[k].l >= l && tree[k].r <= r) {
return tree[k].val;
}
long ans = (query(k << 1, l, r) + query(k << 1 | 1, l, r)) % MOD;
if (tree[k].l < tree[k].r) {
tree[k].val = (tree[k << 1].val + tree[k << 1 | 1].val) % MOD;
// tree[k].val = Math.min(tree[k << 1].val, tree[k << 1 | 1].val);
}
return ans;
}
}
class BitMap {
boolean[] vis = new boolean[32];
List<Integer> g[];
void init() {
for (int i = 0; i < 32; i++) {
g = new List[32];
g[i] = new ArrayList<>();
}
}
void dfs(int p) {
if (vis[p]) return;
vis[p] = true;
for (int it : g[p]) dfs(it);
}
boolean connected(int a[], int n) {
int m = 0;
for (int i = 0; i < n; i++) if (a[i] == 0) return false;
for (int i = 0; i < n; i++) m |= a[i];
for (int i = 0; i < 31; i++) g[i].clear();
for (int i = 0; i < n; i++) {
int last = -1;
for (int j = 0; j < 31; j++)
if ((a[i] & (1 << j)) > 0) {
if (last != -1) {
g[last].add(j);
g[j].add(last);
}
last = j;
}
}
Arrays.fill(vis, false);
for (int j = 0; j < 31; j++)
if (((1 << j) & m) > 0) {
dfs(j);
break;
}
for (int j = 0; j < 31; j++) if (((1 << j) & m) > 0 && !vis[j]) return false;
return true;
}
}
class BinaryIndexedTree {
int n = 1;
long C[];
BinaryIndexedTree(int sz) {
while (n <= sz) {
n <<= 1;
}
n = sz + 1;
C = new long[n];
}
int lowbit(int x) {
return x & -x;
}
void add(int x, long val) {
while (x < n) {
C[x] += val;
x += lowbit(x);
}
}
long getSum(int x) {
long res = 0;
while (x > 0) {
res += C[x];
x -= lowbit(x);
}
return res;
}
int binSearch(long sum) {
if (sum == 0) {
return 0;
}
int n = C.length;
int mx = 1;
while (mx < n) {
mx <<= 1;
}
int res = 0;
for (int i = mx / 2; i >= 1; i >>= 1) {
if (C[res + i] < sum) {
sum -= C[res + i];
res += i;
}
}
return res + 1;
}
}
static class TrieNode {
int cnt = 0;
TrieNode next[];
TrieNode() {
next = new TrieNode[2];
}
private void insert(TrieNode trie, int ch[], int i) {
while (i < ch.length) {
int idx = ch[i];
if (null == trie.next[idx]) {
trie.next[idx] = new TrieNode();
}
trie.cnt++;
trie = trie.next[idx];
i++;
}
}
private static int query(TrieNode trie) {
if (null == trie) {
return 0;
}
int ans[] = new int[2];
for (int i = 0; i < trie.next.length; i++) {
if (null == trie.next[i]) {
continue;
}
ans[i] = trie.next[i].cnt;
}
if (ans[0] == 0 && ans[0] == ans[1]) {
return 0;
}
if (ans[0] == 0) {
return query(trie.next[1]);
}
if (ans[1] == 0) {
return query(trie.next[0]);
}
return Math.min(ans[0] - 1 + query(trie.next[1]), ans[1] - 1 + query(trie.next[0]));
}
}
//Binary tree
class TreeNode {
int val;
int tier = -1;
TreeNode parent;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
//binary tree dfs
void tierTree(TreeNode root) {
if (null == root) {
return;
}
if (null != root.parent) {
root.tier = root.parent.tier + 1;
} else {
root.tier = 0;
}
tierTree(root.left);
tierTree(root.right);
}
//LCA start
TreeNode[][] lca;
TreeNode[] tree;
void lcaDfsTree(TreeNode root) {
if (null == root) {
return;
}
tree[root.val] = root;
TreeNode nxt = root.parent;
int idx = 0;
while (null != nxt) {
lca[root.val][idx] = nxt;
nxt = lca[nxt.val][idx];
idx++;
}
lcaDfsTree(root.left);
lcaDfsTree(root.right);
}
TreeNode lcaTree(TreeNode root, int n, TreeNode x, TreeNode y) throws IOException {
if (null == root) {
return null;
}
if (-1 == root.tier) {
tree = new TreeNode[n + 1];
tierTree(root);
}
if (null == lca) {
lca = new TreeNode[n + 1][31];
lcaDfsTree(root);
}
int z = Math.abs(x.tier - y.tier);
int xx = x.tier > y.tier ? x.val : y.val;
while (z > 0) {
final int zz = z;
int l = (int) BinSearch.bs(0, 31
, k -> zz < (1 << k));
xx = lca[xx][l].val;
z -= 1 << l;
}
int yy = y.val;
if (x.tier <= y.tier) {
yy = x.val;
}
while (xx != yy) {
final int xxx = xx;
final int yyy = yy;
int l = (int) BinSearch.bs(0, 31
, k -> (1 << k) <= tree[xxx].tier && lca[xxx][(int) k] != lca[yyy][(int) k]);
xx = lca[xx][l].val;
yy = lca[yy][l].val;
}
return tree[xx];
}
//LCA end
//graph
List<Integer> adj[];
List<int[]> adj2[];
void initGraph(int n) throws IOException {
initGraph(n, 0, false, false, 1, false);
}
void initGraph(int n, int m, boolean hasW, boolean directed, int type, boolean useInput) throws IOException {
if (type == 1) {
adj = new List[n + 1];
} else {
adj2 = new List[n + 1];
}
for (int i = 1; i <= n; i++) {
if (type == 1) {
adj[i] = new ArrayList<>();
} else {
adj2[i] = new ArrayList<>();
}
}
if (!useInput) return;
for (int i = 0; i < m; i++) {
int f = nextInt();
int t = nextInt();
if (type == 1) {
adj[f].add(t);
if (!directed) {
adj[t].add(f);
}
} else {
int w = hasW ? nextInt() : 0;
adj2[f].add(new int[]{t, w});
if (!directed) {
adj2[t].add(new int[]{f, w});
}
}
}
}
void getDiv(Map<Integer, Integer> map, long n) {
int sqrt = (int) Math.sqrt(n);
for (int i = 2; i <= sqrt; i++) {
int cnt = 0;
while (n % i == 0) {
cnt++;
n /= i;
}
if (cnt > 0) {
map.put(i, cnt);
}
}
if (n > 1) {
map.put((int) n, 1);
}
}
boolean[] generatePrime(int n) {
boolean p[] = new boolean[n + 1];
p[2] = true;
for (int i = 3; i <= n; i += 2) {
p[i] = true;
}
for (int i = 3; i <= Math.sqrt(n); i += 2) {
if (!p[i]) {
continue;
}
for (int j = i * i; j <= n; j += i << 1) {
p[j] = false;
}
}
return p;
}
boolean isPrime(long n) { //determines if n is a prime number
int p[] = {2, 3, 5, 233, 331};
int pn = p.length;
long s = 0, t = n - 1;//n - 1 = 2^s * t
while ((t & 1) == 0) {
t >>= 1;
++s;
}
for (int i = 0; i < pn; ++i) {
if (n == p[i]) {
return true;
}
long pt = pow(p[i], t, n);
for (int j = 0; j < s; ++j) {
long cur = llMod(pt, pt, n);
if (cur == 1 && pt != 1 && pt != n - 1) {
return false;
}
pt = cur;
}
if (pt != 1) {
return false;
}
}
return true;
}
long[] llAdd2(long a[], long b[], long mod) {
long c[] = new long[2];
c[1] = (a[1] + b[1]) % (mod * mod);
c[0] = (a[1] + b[1]) / (mod * mod) + a[0] + b[0];
return c;
}
long[] llMod2(long a, long b, long mod) {
long x1 = a / mod;
long y1 = a % mod;
long x2 = b / mod;
long y2 = b % mod;
long c = (x1 * y2 + x2 * y1) / mod;
c += x1 * x2;
long d = (x1 * y2 + x2 * y1) % mod * mod + y1 * y2;
return new long[]{c, d};
}
long llMod(long a, long b, long mod) {
if (a > mod || b > mod) {
return (a * b - (long) ((double) a / mod * b + 0.5) * mod + mod) % mod;
}
return a * b % mod;
// long r = 0;
// a %= mod;
// b %= mod;
// while (b > 0) {
// if ((b & 1) == 1) {
// r = (r + a) % mod;
// }
// b >>= 1;
// a = (a << 1) % mod;
// }
// return r;
}
long pow(long a, long n) {
long ans = 1;
while (n > 0) {
if ((n & 1) == 1) {
ans = ans * a;
}
a = a * a;
n >>= 1;
}
return ans;
}
long pow(long a, long n, long mod) {
long ans = 1;
while (n > 0) {
if ((n & 1) == 1) {
ans = llMod(ans, a, mod);
}
a = llMod(a, a, mod);
n >>= 1;
}
return ans;
}
private long[][] initC(int n) {
long c[][] = new long[n][n];
for (int i = 0; i < n; i++) {
c[i][0] = 1;
}
for (int i = 1; i < n; i++) {
for (int j = 1; j <= i; j++) {
c[i][j] = c[i - 1][j - 1] + c[i - 1][j];
}
}
return c;
}
/**
* ps: n >= m, choose m from n;
*/
// private int cmn(long n, long m) {
// if (m > n) {
// n ^= m;
// m ^= n;
// n ^= m;
// }
// m = Math.min(m, n - m);
//
// long top = 1;
// long bot = 1;
// for (long i = n - m + 1; i <= n; i++) {
// top = (top * i) % MOD;
// }
// for (int i = 1; i <= m; i++) {
// bot = (bot * i) % MOD;
// }
//
// return (int) ((top * pow(bot, MOD - 2, MOD)) % MOD);
// }
long[] exGcd(long a, long b) {
if (b == 0) {
return new long[]{a, 1, 0};
}
long[] ans = exGcd(b, a % b);
long x = ans[2];
long y = ans[1] - a / b * ans[2];
ans[1] = x;
ans[2] = y;
return ans;
}
long gcd(long a, long b) {
if (a < b) {
return gcd(b, a);
}
while (b != 0) {
long tmp = a % b;
a = b;
b = tmp;
}
return a;
}
int[] unique(int a[], Map<Integer, Integer> idx) {
int tmp[] = a.clone();
Arrays.sort(tmp);
int j = 0;
for (int i = 0; i < tmp.length; i++) {
if (i == 0 || tmp[i] > tmp[i - 1]) {
idx.put(tmp[i], j++);
}
}
int rs[] = new int[j];
j = 0;
for (int key : idx.keySet()) {
rs[j++] = key;
}
Arrays.sort(rs);
return rs;
}
boolean isEven(long n) {
return (n & 1) == 0;
}
static class BinSearch {
static long bs(long l, long r, IBinSearch sort) throws IOException {
while (l < r) {
long m = l + (r - l) / 2;
if (sort.binSearchCmp(m)) {
l = m + 1;
} else {
r = m;
}
}
return l;
}
interface IBinSearch {
boolean binSearchCmp(long k) throws IOException;
}
}
}
private static class InOut {
private BufferedReader br;
private StreamTokenizer st;
private PrintWriter pw;
InOut() throws FileNotFoundException {
if (useInFile) {
System.setIn(new FileInputStream("resources/inout/in.text"));
}
if (useOutFile) {
System.setOut(new PrintStream("resources/inout/out.text"));
}
br = new BufferedReader(new InputStreamReader(System.in));
st = new StreamTokenizer(br);
pw = new PrintWriter(new OutputStreamWriter(System.out));
st.ordinaryChar('\'');
st.ordinaryChar('\"');
st.ordinaryChar('/');
}
private boolean hasNext() throws IOException {
return st.nextToken() != StreamTokenizer.TT_EOF;
}
private String next() throws IOException {
if (st.nextToken() == StreamTokenizer.TT_EOF) {
throw new IOException();
}
return st.sval;
}
private String next(int n) throws IOException {
return next(n, false);
}
private String next(int len, boolean isDigit) throws IOException {
char ch[] = new char[len];
int cur = 0;
char c;
while ((c = (char) br.read()) == '\n' || c == '\r' || c == ' ' || c == '\t'
|| (isDigit && (c < '0' || c > '9') && c != '-')) ;
do {
ch[cur++] = c;
} while (!((c = (char) br.read()) == '\n' || c == '\r' || c == ' ' || c == '\t')
&& (!isDigit || c >= '0' && c <= '9'));
return String.valueOf(ch, 0, cur);
}
private int nextInt() throws IOException {
if (st.nextToken() == StreamTokenizer.TT_EOF) {
throw new IOException();
}
return (int) st.nval;
}
private long nextLong(int n) throws IOException {
return Long.parseLong(next(n, true));
}
private double nextDouble() throws IOException {
st.nextToken();
return st.nval;
}
private String[] nextSS(String reg) throws IOException {
return br.readLine().split(reg);
}
private String nextLine() throws IOException {
return br.readLine();
}
private void print(String s, boolean newLine) {
if (null != s) {
pw.print(s);
}
if (newLine) {
pw.println();
}
}
private void format(String format, Object... obj) {
pw.format(format, obj);
}
private void flush() {
pw.flush();
}
}
private static class FFT {
double[] roots;
int maxN;
public FFT(int maxN) {
this.maxN = maxN;
initRoots();
}
public long[] multiply(int[] a, int[] b) {
int minSize = a.length + b.length - 1;
int bits = 1;
while (1 << bits < minSize) bits++;
int N = 1 << bits;
double[] aa = toComplex(a, N);
double[] bb = toComplex(b, N);
fftIterative(aa, false);
fftIterative(bb, false);
double[] c = new double[aa.length];
for (int i = 0; i < N; i++) {
c[2 * i] = aa[2 * i] * bb[2 * i] - aa[2 * i + 1] * bb[2 * i + 1];
c[2 * i + 1] = aa[2 * i] * bb[2 * i + 1] + aa[2 * i + 1] * bb[2 * i];
}
fftIterative(c, true);
long[] ret = new long[minSize];
for (int i = 0; i < ret.length; i++) {
ret[i] = Math.round(c[2 * i]);
}
return ret;
}
static double[] toComplex(int[] arr, int size) {
double[] ret = new double[size * 2];
for (int i = 0; i < arr.length; i++) {
ret[2 * i] = arr[i];
}
return ret;
}
void initRoots() {
roots = new double[2 * (maxN + 1)];
double ang = 2 * Math.PI / maxN;
for (int i = 0; i <= maxN; i++) {
roots[2 * i] = Math.cos(i * ang);
roots[2 * i + 1] = Math.sin(i * ang);
}
}
int bits(int N) {
int ret = 0;
while (1 << ret < N) ret++;
if (1 << ret != N) throw new RuntimeException();
return ret;
}
void fftIterative(double[] array, boolean inv) {
int bits = bits(array.length / 2);
int N = 1 << bits;
for (int from = 0; from < N; from++) {
int to = Integer.reverse(from) >>> (32 - bits);
if (from < to) {
double tmpR = array[2 * from];
double tmpI = array[2 * from + 1];
array[2 * from] = array[2 * to];
array[2 * from + 1] = array[2 * to + 1];
array[2 * to] = tmpR;
array[2 * to + 1] = tmpI;
}
}
for (int n = 2; n <= N; n *= 2) {
int delta = 2 * maxN / n;
for (int from = 0; from < N; from += n) {
int rootIdx = inv ? 2 * maxN : 0;
double tmpR, tmpI;
for (int arrIdx = 2 * from; arrIdx < 2 * from + n; arrIdx += 2) {
tmpR = array[arrIdx + n] * roots[rootIdx] - array[arrIdx + n + 1] * roots[rootIdx + 1];
tmpI = array[arrIdx + n] * roots[rootIdx + 1] + array[arrIdx + n + 1] * roots[rootIdx];
array[arrIdx + n] = array[arrIdx] - tmpR;
array[arrIdx + n + 1] = array[arrIdx + 1] - tmpI;
array[arrIdx] += tmpR;
array[arrIdx + 1] += tmpI;
rootIdx += (inv ? -delta : delta);
}
}
}
if (inv) {
for (int i = 0; i < array.length; i++) {
array[i] /= N;
}
}
}
}
}
| Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 8 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | 75d7b9755c27f2423332f1930b6dfc9a | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static int mod = 998244353;
//static int mod = (int)1e9+7;
static boolean[] prime = new boolean[1];
static int[][] dir1 = new int[][]{{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
static int[][] dir2 = new int[][]{{0, 1}, {0, -1}, {1, 0}, {-1, 0}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1}};
static int inf = 0x3f3f3f3f;
static {
for (int i = 2; i < prime.length; i++)
prime[i] = true;
for (int i = 2; i < prime.length; i++) {
if (prime[i]) {
for (int k = 2; i * k < prime.length; k++) {
prime[i * k] = false;
}
}
}
}
static class DSU {
int[] fa;
DSU(int n) {
fa = new int[n];
for (int i = 0; i < n; i++)
fa[i] = i;
}
int find(int t) {
if (t != fa[t])
fa[t] = find(fa[t]);
return fa[t];
}
void join(int x, int y) {
x = find(x);
y = find(y);
fa[x] = y;
}
}
static List<Integer>[] lists;
static void init(int n) {
lists = new List[n];
for(int i = 0; i< n;i++){
lists[i] = new ArrayList<>();
}
}
static class LCA{
int[] dep;
int[][] fa;
int[] log;
boolean[] v;
public LCA(int n){
dep = new int[n+5];
log = new int[n+5];
fa = new int[n+5][31];
v = new boolean[n+5];
for (int i = 2; i <= n; ++i) {
log[i] = log[i/2] + 1;
}
dfs(1,0);
}
private void dfs(int cur, int pre){
if(v[cur]) return;
v[cur] = true;
dep[cur] = dep[pre]+1;
fa[cur][0] = pre;
for (int i = 1; i <= log[dep[cur]]; ++i) {
fa[cur][i] = fa[fa[cur][i - 1]][i - 1];
}
for(int i : lists[cur]){
dfs(i,cur);
}
}
private int lca(int a, int b){
if(dep[a] > dep[b]){
int t = a;
a = b;
b = t;
}
while (dep[a] != dep[b]){
b = fa[b][log[dep[b] - dep[a]]];
}
if(a == b) return a;
for (int k = log[dep[a]]; k >= 0; k--) {
if (fa[a][k] != fa[b][k]) {
a = fa[a][k]; b = fa[b][k];
}
}
return fa[a][0];
}
}
static BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
static long lcm(long a, long b) {
return a * b / gcd(a, b);
}
static int get() throws Exception {
String ss = bf.readLine();
if (ss.contains(" "))
ss = ss.substring(0, ss.indexOf(" "));
return Integer.parseInt(ss);
}
static long getx() throws Exception {
String ss = bf.readLine();
if (ss.contains(" "))
ss = ss.substring(0, ss.indexOf(" "));
return Long.parseLong(ss);
}
static int[] getint() throws Exception {
String[] s = bf.readLine().split(" ");
int[] a = new int[s.length];
for (int i = 0; i < a.length; i++) {
a[i] = Integer.parseInt(s[i]);
}
return a;
}
static long[] getlong() throws Exception {
String[] s = bf.readLine().split(" ");
long[] a = new long[s.length];
for (int i = 0; i < a.length; i++) {
a[i] = Long.parseLong(s[i]);
}
return a;
}
static String getstr() throws Exception {
return bf.readLine();
}
static void println() throws Exception {
bw.write("\n");
}
static void print(int a) throws Exception {
bw.write(a + "\n");
}
static void print(long a) throws Exception {
bw.write(a + "\n");
}
static void print(String a) throws Exception {
bw.write(a + "\n");
}
static void print(int[] a) throws Exception {
for (int i : a) {
bw.write(i + " ");
}
println();
}
static void print(long[] a) throws Exception {
for (long i : a) {
bw.write(i + " ");
}
println();
}
static void print(int[][] a) throws Exception {
for (int i[] : a)
print(i);
}
static void print(long[][] a) throws Exception {
for (long[] i : a)
print(i);
}
static void print(char[] a) throws Exception {
for (char i : a) {
bw.write(i + "");
}
println();
}
static long pow(long a, long b) {
long ans = 1;
while (b > 0) {
if ((b & 1) == 1) {
ans *= a;
}
a *= a;
b >>= 1;
}
return ans;
}
static int powmod(long a, long b, int mod) {
long ans = 1;
while (b > 0) {
if ((b & 1) == 1) {
ans = ans * a % mod;
}
a = a * a % mod;
b >>= 1;
}
return (int) ans;
}
static void sort(int[] a) {
int n = a.length;
Integer[] b = new Integer[n];
for (int i = 0; i < n; i++)
b[i] = a[i];
Arrays.sort(b);
for (int i = 0; i < n; i++)
a[i] = b[i];
}
static void sort(long[] a) {
int n = a.length;
Long[] b = new Long[n];
for (int i = 0; i < n; i++)
b[i] = a[i];
Arrays.sort(b);
for (int i = 0; i < n; i++)
a[i] = b[i];
}
static void resort(int[] a) {
int n = a.length;
Integer[] b = new Integer[n];
for (int i = 0; i < n; i++)
b[i] = a[i];
Arrays.sort(b);
for (int i = 0; i < n; i++)
a[i] = b[n - 1 - i];
}
static void resort(long[] a) {
int n = a.length;
Long[] b = new Long[n];
for (int i = 0; i < n; i++)
b[i] = a[i];
Arrays.sort(b);
for (int i = 0; i < n; i++)
a[i] = b[n - 1 - i];
}
static int max(int a, int b) {
return Math.max(a, b);
}
static int min(int a, int b) {
return Math.min(a, b);
}
static long max(long a, long b) {
return Math.max(a, b);
}
static long min(long a, long b) {
return Math.min(a, b);
}
static int max(int[] a) {
int max = a[0];
for (int i : a)
max = max(max, i);
return max;
}
static int min(int[] a) {
int min = a[0];
for (int i : a)
min = min(min, i);
return min;
}
static long max(long[] a) {
long max = a[0];
for (long i : a)
max = max(max, i);
return max;
}
static long min(long[] a) {
long min = a[0];
for (long i : a)
min = min(min, i);
return min;
}
static int abs(int a) {
return Math.abs(a);
}
static long abs(long a) {
return Math.abs(a);
}
static void yes() throws Exception {
print("Yes");
}
static void no() throws Exception {
print("No");
}
static int[] getarr(List<Integer> list) {
int n = list.size();
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = list.get(i);
return a;
}
public static void main(String[] args) throws Exception {
int T = 1;
T = get();
while (T-- > 0) {
int n = get();
int[][] a = new int[2][n], b = new int[2][n+1];
for(int i = 0;i < 2;i++) a[i] = getint();
a[0][0] = -1;
for (int i = 0; i < 2; i++) {
for (int j = n - 1; j >= 0; j--) {
b[i][j] = max(new int[]{
a[i ^ 1][j] + 1,
a[i][j] + 1 + 2 * (n - j) - 1,
b[i][j + 1] + 1});
}
}
int ans = inf;
int cur = 0;
for (int j = 0; j < n; j++) {
int k = j & 1;
ans = min(ans, max(cur + 2 * (n - j) - 1, b[k][j]));
cur = max(cur , a[k][j] + 1);
cur++;//模拟
cur = max(cur, a[k ^ 1][j] + 1);
cur++;//模拟
}
print(ans);
}
bw.flush();
}
} | Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 11 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | 5740199a61084497d5921d5744d72381 | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | import java.io.*;
import java.util.*;
public class Codeforces
{
public static void main(String args[])throws Exception
{
BufferedReader bu=new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb=new StringBuilder();
int t=Integer.parseInt(bu.readLine());
while(t-->0)
{
int n=Integer.parseInt(bu.readLine());
int a[][]=new int[2][n],i;
String s[]=bu.readLine().split(" ");
for(i=0;i<n;i++) a[0][i]=Integer.parseInt(s[i]);
s=bu.readLine().split(" ");
for(i=0;i<n;i++) a[1][i]=Integer.parseInt(s[i]);
long l=2*n-1,r=(long)1e15,mid,ans=r;
while(l<=r)
{
mid=(l+r)>>1;
if(possible(a,mid))
{
ans=mid;
r=mid-1;
}
else l=mid+1;
}
sb.append(ans+"\n");
}
System.out.print(sb);
}
static boolean possible(int a[][],long m)
{
long cur=m; int i,n=a[0].length;
cur-=2*n;
for(i=0;i<n;i++)
{
int u=i%2,v=u^1;
if(a[u][i]<=cur || cur==-1) cur++;
else
{
cur--;
int j;
for(j=i;j<n;j++)
if(a[v][j]<=cur) cur++;
else return false;
for(j=n-1;j>=i-1;j--)
if(a[u][j]<=cur) cur++;
else return false;
return cur<=m;
}
if(a[v][i]<=cur) cur++;
else
{
int j;
for(j=i+1;j<n;j++)
if(a[u][j]<=cur) cur++;
else return false;
for(j=n-1;j>=i;j--)
if(a[v][j]<=cur) cur++;
else return false;
return cur<=m;
}
}
return cur<=m;
}
} | Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 11 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | 338c8d18f6b3b76871a811560498dc72 | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
static ContestScanner sc = new ContestScanner(System.in);
static PrintWriter pw = new PrintWriter(System.out);
static StringBuilder sb = new StringBuilder();
static long mod = (long) 1e9 + 7;
public static void main(String[] args) throws Exception {
int T = sc.nextInt();
for(int i = 0; i < T; i++)solve();
//solve();
pw.flush();
}
static int[] mx = {0,1,0,1};
static int[] my = {1,0,-1,0};
public static void solve() {
int m = sc.nextInt();
long[] clockwise = new long[m*2];
long[] counter = new long[m*2];
long[][] field = new long[2][m];
for(int i = 0; i < 2; i++){
field[i] = sc.nextLongArray(m);
}
for(int i = 1; i < m; i++){
clockwise[i] = Math.max(field[0][i]+1,clockwise[i-1]+1);
}
for(int i = m-1; i >= 0; i--){
clockwise[m*2-1-i] = Math.max(field[1][i]+1,clockwise[m*2-2-i]+1);
}
counter[0] = Math.max(1,field[1][0]+1);
for(int i = 1; i < m; i++){
counter[i] = Math.max(field[1][i]+1,counter[i-1]+1);
}
for(int i = m-1; i >= 0; i--){
counter[m*2-1-i] = Math.max(field[0][i]+1,counter[m*2-2-i]+1);
}
int cwLast = m*2-1;
int ccwLast = m*2-2;
int x = 0;
int y = 0;
int index = 0;
long ans = Long.MAX_VALUE;
long turn = 0;
long rem = 2*m-1;
while(x < m){
//pw.println(x + " " + y + " " + ans);
if(y == 0){
ans = Math.min(ans,Math.max(clockwise[cwLast],turn+rem));
}else{
ans = Math.min(ans,Math.max(counter[ccwLast],turn+rem));
}
x += mx[index];
y += my[index];
if(y == 0){
ccwLast--;
}else{
cwLast--;
}
index++;
index%=4;
if(x >= m) break;
turn = Math.max(turn+1,field[y][x]+1);
rem--;
}
pw.println(ans);
}
static class GeekInteger {
public static void save_sort(int[] array) {
shuffle(array);
Arrays.sort(array);
}
public static int[] shuffle(int[] array) {
int n = array.length;
Random random = new Random();
for (int i = 0, j; i < n; i++) {
j = i + random.nextInt(n - i);
int randomElement = array[j];
array[j] = array[i];
array[i] = randomElement;
}
return array;
}
public static void save_sort(long[] array) {
shuffle(array);
Arrays.sort(array);
}
public static long[] shuffle(long[] array) {
int n = array.length;
Random random = new Random();
for (int i = 0, j; i < n; i++) {
j = i + random.nextInt(n - i);
long randomElement = array[j];
array[j] = array[i];
array[i] = randomElement;
}
return array;
}
}
}
/**
* refercence : https://github.com/NASU41/AtCoderLibraryForJava/blob/master/ContestIO/ContestScanner.java
*/
class ContestScanner {
private final java.io.InputStream in;
private final byte[] buffer = new byte[1024];
private int ptr = 0;
private int buflen = 0;
private static final long LONG_MAX_TENTHS = 922337203685477580L;
private static final int LONG_MAX_LAST_DIGIT = 7;
private static final int LONG_MIN_LAST_DIGIT = 8;
public ContestScanner(java.io.InputStream in){
this.in = in;
}
public ContestScanner(java.io.File file) throws java.io.FileNotFoundException {
this(new java.io.BufferedInputStream(new java.io.FileInputStream(file)));
}
public ContestScanner(){
this(System.in);
}
private boolean hasNextByte() {
if (ptr < buflen) {
return true;
}else{
ptr = 0;
try {
buflen = in.read(buffer);
} catch (java.io.IOException e) {
e.printStackTrace();
}
if (buflen <= 0) {
return false;
}
}
return true;
}
private int readByte() {
if (hasNextByte()) return buffer[ptr++]; else return -1;
}
private static boolean isPrintableChar(int c) {
return 33 <= c && c <= 126;
}
public boolean hasNext() {
while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++;
return hasNextByte();
}
public String next() {
if (!hasNext()) throw new java.util.NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = readByte();
while(isPrintableChar(b)) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public long nextLong() {
if (!hasNext()) throw new java.util.NoSuchElementException();
long n = 0;
boolean minus = false;
int b = readByte();
if (b == '-') {
minus = true;
b = readByte();
}
if (b < '0' || '9' < b) {
throw new NumberFormatException();
}
while (true) {
if ('0' <= b && b <= '9') {
int digit = b - '0';
if (n >= LONG_MAX_TENTHS) {
if (n == LONG_MAX_TENTHS) {
if (minus) {
if (digit <= LONG_MIN_LAST_DIGIT) {
n = -n * 10 - digit;
b = readByte();
if (!isPrintableChar(b)) {
return n;
} else if (b < '0' || '9' < b) {
throw new NumberFormatException(
String.format("%d%s... is not number", n, Character.toString(b))
);
}
}
} else {
if (digit <= LONG_MAX_LAST_DIGIT) {
n = n * 10 + digit;
b = readByte();
if (!isPrintableChar(b)) {
return n;
} else if (b < '0' || '9' < b) {
throw new NumberFormatException(
String.format("%d%s... is not number", n, Character.toString(b))
);
}
}
}
}
throw new ArithmeticException(
String.format("%s%d%d... overflows long.", minus ? "-" : "", n, digit)
);
}
n = n * 10 + digit;
}else if(b == -1 || !isPrintableChar(b)){
return minus ? -n : n;
}else{
throw new NumberFormatException();
}
b = readByte();
}
}
public int nextInt() {
long nl = nextLong();
if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException();
return (int) nl;
}
public double nextDouble() {
return Double.parseDouble(next());
}
public long[] nextLongArray(int length){
long[] array = new long[length];
for(int i=0; i<length; i++) array[i] = this.nextLong();
return array;
}
public long[] nextLongArray(int length, java.util.function.LongUnaryOperator map){
long[] array = new long[length];
for(int i=0; i<length; i++) array[i] = map.applyAsLong(this.nextLong());
return array;
}
public int[] nextIntArray(int length){
int[] array = new int[length];
for(int i=0; i<length; i++) array[i] = this.nextInt();
return array;
}
public int[] nextIntArray(int length, java.util.function.IntUnaryOperator map){
int[] array = new int[length];
for(int i=0; i<length; i++) array[i] = map.applyAsInt(this.nextInt());
return array;
}
public double[] nextDoubleArray(int length){
double[] array = new double[length];
for(int i=0; i<length; i++) array[i] = this.nextDouble();
return array;
}
public double[] nextDoubleArray(int length, java.util.function.DoubleUnaryOperator map){
double[] array = new double[length];
for(int i=0; i<length; i++) array[i] = map.applyAsDouble(this.nextDouble());
return array;
}
public long[][] nextLongMatrix(int height, int width){
long[][] mat = new long[height][width];
for(int h=0; h<height; h++) for(int w=0; w<width; w++){
mat[h][w] = this.nextLong();
}
return mat;
}
public int[][] nextIntMatrix(int height, int width){
int[][] mat = new int[height][width];
for(int h=0; h<height; h++) for(int w=0; w<width; w++){
mat[h][w] = this.nextInt();
}
return mat;
}
public double[][] nextDoubleMatrix(int height, int width){
double[][] mat = new double[height][width];
for(int h=0; h<height; h++) for(int w=0; w<width; w++){
mat[h][w] = this.nextDouble();
}
return mat;
}
public char[][] nextCharMatrix(int height, int width){
char[][] mat = new char[height][width];
for(int h=0; h<height; h++){
String s = this.next();
for(int w=0; w<width; w++){
mat[h][w] = s.charAt(w);
}
}
return mat;
}
}
| Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 11 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | 1839d6eab97d6ff2c7e71e515bd6c54d | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;
import java.util.Scanner;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class Main {
public static void main(String[]args) throws IOException {
new Main().run();
}
void run() throws IOException{
new solve().setIO(System.in, System.out).run();
}
class solve extends ioTask{
int t,n,s,k,i,j,len,h,m;
int[]ans= {
0,1,1,1,2,2
};
void p(int []a) {
out.print(a[1]);
for(int i=2;i<a.length;i++) {
out.print(" "+a[i]);
}
out.println();
}
int[]a;
void swap(int x,int y) {
int tmp=a[x];
a[x]=a[y];
a[y]=tmp;
}
public void run() throws IOException {
t=in.in();
while(t-->0)
{
n=in.in();
int[][]a=new int[2][n+1];
int[]k=new int[n+1];
for(int i=0;i<2;i++)
{
for(int j=1;j<=n;j++)
{
a[i][j]=in.in();
}
}
k[0]=-1;
k[1]=Math.max(1, a[1][1]+1);
for(int i=2;i<=n;i++) {
if(i%2==0) {
k[i]=Math.max(k[i-1]+1, a[1][i]+1);
k[i]=Math.max(k[i]+1, a[0][i]+1);
}else {
k[i]=Math.max(k[i-1]+1, a[0][i]+1);
k[i]=Math.max(k[i]+1, a[1][i]+1);
}
}
int ans=k[n];
// out.println(ans);
int[][]x=new int[2][2];
x[0][0]=a[0][n]+1;
x[0][1]=Math.max(x[0][0]+1, a[1][n]+1);
x[0][0]=x[0][1]-1;
x[1][0]=a[1][n]+1;
x[1][1]=Math.max(x[1][0]+1, a[0][n]+1);
x[1][0]=x[1][1]-1;
for(int i=n-1;i>=0;i--) {
int l=i%2;
// out.println(k[i]+" "+x[l][0]+" "+x[l][1]);
ans=Math.min(ans, Math.max(0, k[i]-x[l][0]+1)+x[l][1]);
for(int j=0,p;j<2;j++) {
p=j^1;
if(i==1);
else if(a[j][i]+1<x[j][0]) {
x[j][0]--;
}else {
int y=a[j][i]+1-x[j][0]+1;
x[j][0]+=y;
x[j][1]+=y;
x[j][0]--;
}
if(a[p][i]>x[j][1]) {
int y=a[p][i]-x[j][1];
x[j][0]+=y;
x[j][1]+=y;
x[j][1]++;
}else {
x[j][1]++;
}
}
}
out.println(ans);
out.flush();
}
out.close();
}
}
class In{
private StringTokenizer in=new StringTokenizer("");
private InputStream is;
private BufferedReader bf;
public In(File file) throws IOException {
is=new FileInputStream(file);
init();
}
public In(InputStream is) throws IOException
{
this.is=is;
init();
}
private void init() throws IOException {
bf=new BufferedReader(new InputStreamReader(is));
}
boolean hasNext() throws IOException {
return in.hasMoreTokens()||bf.ready();
}
String ins() throws IOException {
while(!in.hasMoreTokens()) {
in=new StringTokenizer(bf.readLine());
}
return in.nextToken();
}
int in() throws IOException {
return Integer.parseInt(ins());
}
long inl() throws IOException {
return Long.parseLong(ins());
}
double ind() throws IOException {
return Double.parseDouble(ins());
}
}
class Out{
PrintWriter out;
private OutputStream os;
private void init() {
out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(os)));
}
public Out(File file) throws IOException {
os=new FileOutputStream(file);
init();
}
public Out(OutputStream os) throws IOException
{
this.os=os;
init();
}
}
class graph{
int[]to,nxt,head;
int cnt;
void init(int n) {
cnt=1;
for(int i=1;i<=n;i++)
{
head[i]=0;
}
}
public graph(int n,int m) {
to=new int[m+1];
nxt=new int[m+1];
head=new int[n+1];
cnt=1;
}
void add(int u,int v) {
to[cnt]=v;
nxt[cnt]=head[u];
head[u]=cnt++;
}
}
abstract class ioTask{
In in;
PrintWriter out;
public ioTask setIO(File in,File out) throws IOException{
this.in=new In(in);
this.out=new Out(out).out;
return this;
}
public ioTask setIO(File in,OutputStream out) throws IOException{
this.in=new In(in);
this.out=new Out(out).out;
return this;
}
public ioTask setIO(InputStream in,OutputStream out) throws IOException{
this.in=new In(in);
this.out=new Out(out).out;
return this;
}
public ioTask setIO(InputStream in,File out) throws IOException{
this.in=new In(in);
this.out=new Out(out).out;
return this;
}
void run()throws IOException{
}
}
}
| Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 11 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | ce6659aa2a0664e1bdfb808c468ea53d | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes |
import java.io.*;
import java.util.*;
public class TimePass {
public static void main (String[] args) throws java.lang.Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
PrintWriter out=new PrintWriter(System.out);
int testCases=Integer.parseInt(br.readLine());
// int testCases=1;
while(testCases-->0){
int n=Integer.parseInt(br.readLine());
int arr[][]=new int[2][n];
for(int i=0;i<2;i++) {
String input[]=br.readLine().split(" ");
for(int j=0;j<n;j++) {
arr[i][j]=Integer.parseInt(input[j])+1;
}
}
arr[0][0]=0;
long clockWise[]=new long[n+1];
long antiClockWise[]=new long[n+1];
clockWise[n-1]=Math.max(arr[0][n-1]+1, arr[1][n-1]);
antiClockWise[n-1]=Math.max(arr[1][n-1]+1,arr[0][n-1]);
for(int i=n-2;i>=0;i--) {
clockWise[i]=Math.max(arr[0][i]+2*(n-i-1)+1,Math.max(arr[1][i], clockWise[i+1]+1));
antiClockWise[i]=Math.max(arr[1][i]+2*(n-i-1)+1, Math.max(arr[0][i], antiClockWise[i+1]+1));
}
long total=0;
long ans=0;
ans=clockWise[0];
int x=1;
int y=0;
while(y<n) {
total+=Math.max(1, arr[x][y]-total);
if(x==1) {
ans=Math.min(ans,Math.max(total+2*(n-y-1),antiClockWise[y+1]));
y++;
if(y<n) total+=Math.max(1,arr[x][y]-total);
x=0;
}else {
ans=Math.min(ans, Math.max(total+2*(n-y-1) ,clockWise[y+1]));
y++;
if(y<n) total+=Math.max(1, arr[x][y]-total);
x=1;
}
}
out.println(ans);
}
out.close();
}
}
//class DSU{
// int parent[];
// int rank[];
// int totalComponents;
// public DSU(int n) {
// parent=new int[n];
// rank=new int[n];
// totalComponents=n;
// for(int i=0;i<n;i++) {
// parent[i]=i;
// }
// }
// public int find(int v) {
// if(parent[v]==v) return v;
// return parent[v]=find(parent[v]);
// }
// public void union(int v1,int v2) {
// int p1=find(v1);
// int p2=find(v2);
// if(p1==p2) return;
// if(rank[p1]>rank[p2]) {
// parent[p2]=p1;
// }else if(rank[p2]>rank[p1]) {
// parent[p1]=p2;
// }else {
// rank[p1]++;
// parent[p2]=p1;
// }
// totalComponents--;
// }
//}
| Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 11 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | 32cd01f90f79e7b0bd5ecac074e86b7b | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | import java.util.*;
import java.io.*;
import java.lang.*;
public class Main {
//-----------PrintWriter for faster output---------------------------------
public static PrintWriter out;
public static int cnt;
//-----------MyScanner class for faster input----------
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static void main(String args[]) {
int mod = 1000000007;
MyScanner sc = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out));
int set[][] = new int[][]{{1,0},{0,1},{-1,0},{0,1}};
int q = sc.nextInt();
while(q-->0){
int n = sc.nextInt();
int a[][] = new int[2][n];
for(int j=0;j<2;j++){
for(int i=0;i<n;i++){
a[j][i] = sc.nextInt();
}
}
int b1[][] = new int[2][n];
for(int i=n-2;i>=0;i--){
b1[0][i] = Math.max(b1[0][i+1]-1,a[0][i+1]);
b1[1][i] = Math.max(b1[1][i+1]-1,a[1][i+1]);
}
int b2[][] = new int[2][n];
b2[1][0] = a[1][0];
for(int i=1;i<n;i++){
b2[0][i] = Math.max(b2[0][i-1]-1,a[0][i]);
b2[1][i] = Math.max(b2[1][i-1]-1,a[1][i]);
}
a[0][0] = -1;
long t = -1,ans = Integer.MAX_VALUE;;
int i = 0,j = 0,k = 0;
while(j<n){
t = Math.max(a[i][j],t)+1;
long cst = 0;
if(j%2==0 && i==0){
cst = Math.max(t,b1[i][j])+n-j-1;
cst = Math.max(cst,b2[1][n-1])+n-j;
ans = Math.min(ans,cst);
}
else if(j%2==1 && i==1){
cst = Math.max(t,b1[i][j])+n-j-1;
cst = Math.max(cst,b2[0][n-1])+n-j;
ans = Math.min(ans,cst);
}
// out.println(i+" "+j+" "+ans+" "+cst);
i = (set[k][0]+i)%2;
j += set[k][1];
k = (k+1)%4;
}
out.println(ans);
}
out.close();
}
} | Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 11 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | fbf9409880c69cc647c099b8043b116d | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class First {
public static void main(String[] args) throws Exception{
FastReader f = new FastReader();
StringBuilder str = new StringBuilder();
int cases = f.nextInt();
for (int i = 0; i < cases; i++) {
int columns = f.nextInt();
int[][] array = new int[2][columns];
for (int j = 0; j < columns; j++) {
array[0][j] = f.nextInt();
}
for (int j = 0; j < columns; j++) {
array[1][j] = f.nextInt();
}
int answer = Integer.MAX_VALUE;
//Case 1
int time = 0;
for (int j = 1; j < columns; j++) {
if (array[0][j] > time) {
time = array[0][j] + 1;
} else {
time++;
}
}
for (int j = columns - 1; j >= 0; j--) {
if (array[1][j] > time) {
time = array[1][j] + 1;
} else {
time++;
}
}
answer = Math.min(time, answer);
//Case 2
time = 0;
for (int j = 0; j < columns; j++) {
if (array[1][j] > time) {
time = array[1][j] + 1;
} else {
time++;
}
}
for (int j = columns - 1; j > 0; j--) {
if (array[0][j] > time) {
time = array[0][j] + 1;
} else {
time++;
}
}
answer = Math.min(time, answer);
//case 4
int[] arrayTop = new int[columns];
int[] arrayBot = new int[columns];
int temp = 0;
for (int j = 1; j < columns; j++) {
if ((columns - j) % 2 == 1 % 2 && j != 1) {
arrayTop[columns - j] = Math.max(array[0][columns - j] + j, temp);
temp = arrayTop[columns - j];
} else {
temp = Math.max(array[0][columns - j] + j, temp);
}
}
temp = 0;
for (int j = 1; j < columns; j++) {
if ((columns - j) % 2 == 0 && j != 1) {
arrayTop[columns - j] = Math.max(array[1][columns - j] + 1, temp + 1);
temp = arrayTop[columns - j];
} else {
temp = Math.max(array[1][columns - j] + 1, temp + 1);
}
}
temp = 0;
for (int j = 1; j < columns; j++) {
if ((columns - j) % 2 == 0 && j != 1) {
arrayBot[columns - j] = Math.max(array[1][columns - j] + j, temp);
temp = arrayBot[columns - j];
} else {
temp = Math.max(array[1][columns - j] + j, temp);
}
}
temp = 0;
for (int j = 1; j < columns; j++) {
if ((columns - j) % 2 == 1 % 2 && j != 1) {
arrayBot[columns - j] = Math.max(array[0][columns - j] + 1, temp + 1);
temp = arrayBot[columns - j];
} else {
temp = Math.max(array[0][columns - j] + 1, temp + 1);
}
}
for (int j = 1; j < columns - 1; j++) {
if (j % 2 == 1) {
if (j == columns - 2) {
arrayTop[j] = Math.max(arrayTop[j] + 1, array[1][columns - 1] + 1);
} else {
arrayTop[j] = Math.max(arrayTop[j] + columns - j - 1, arrayTop[j + 1]);
}
} else {
if (j == columns - 2) {
arrayBot[j] = Math.max(arrayBot[j] + 1, array[0][columns - 1] + 1);
} else {
arrayBot[j] = Math.max(arrayBot[j] + columns - j - 1, arrayBot[j + 1]);
}
}
}
//Case 3
time = 0;
for (int j = 0; j < columns * 2 - 1; j++) {
int x;
int y;
if (j % 4 == 2 || j % 4 == 3) {
x = 0;
} else {
x = 1;
}
if (j % 2 == 0) {
y = j / 2;
} else {
y = j / 2 + 1;
}
if (array[x][y] > time) {
time = array[x][y] + 1;
} else {
time++;
}
if (j <= 0 || j >= columns * 2 - 3) {
continue;
}
if (j % 4 == 0) {
int hello = Math.max(time + columns * 2 - 1 - j - 1, arrayBot[y]);
answer = Math.min(answer, hello);
} else if (j % 4 == 2) {
int hello = Math.max(time + columns * 2 - 1 - j - 1, arrayTop[y]);
answer = Math.min(answer, hello);
}
}
answer = Math.min(time, answer);
str.append(answer + "\n");
}
System.out.print(str);
}
static int max(int[][] segment, int l, int r, int index) {
if (l <= segment[index][1] && r >= segment[index][2]) {
return segment[index][0];
} else if (l > segment[index][2] || r < segment[index][1]){
return 0;
} else {
return Math.max(max(segment, l, r, index * 2), max(segment, l, r, index * 2 + 1));
}
}
//FastReader
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 {
if(st.hasMoreTokens()){
str = st.nextToken("\n");
}
else{
str = br.readLine();
}
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 11 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | 54d72c8a7c2758aa16ce8b24a6c12e61 | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static FastScanner sc;
static PrintWriter out;
public static void main(String[] args) {
sc = new FastScanner(System.in);
out = new PrintWriter(System.out);
int t = 1;
if (true) {
t = sc.nextInt();
}
for(int i=0; i<t; i++) {
new Main().solve();
}
out.flush();
}
public void solve() {
int m = sc.nextInt();
int[][] a = new int[2][m];
Arrays.setAll(a[0], i->sc.nextInt());
Arrays.setAll(a[1], i->sc.nextInt());
TreeMap<Integer, Integer> map1 = new TreeMap<>();
TreeMap<Integer, Integer> map2 = new TreeMap<>();
int[][] b = new int[2][m];
int[][] c = new int[2][m];
int[] tt = new int[m];
int res = Integer.MAX_VALUE;
for(int i=1; i<m; i++) {
b[0][i] = a[0][i] - i + 1;
}
for(int i=m-1; i>=0; i--) {
b[1][i] = a[1][i] - m - (m-1-i) + 1;
}
for(int i=2; i<m; i++) {
c[1][i] = a[1][i] - i + 2;
}
for(int i=m-1; i>=1; i--) {
c[0][i] = a[0][i] - m - (m-1-i) + 2;
}
/*
out.println(Arrays.toString(a[0]));
out.println(Arrays.toString(a[1]));
out.println(Arrays.toString(b[0]));
out.println(Arrays.toString(b[1]));
out.println(Arrays.toString(c[0]));
out.println(Arrays.toString(c[1]));
*/
int t = 0;
for(int i=0; i<m; i++) {
tt[i] = t;
if(i%2 == 0) {
if(i+1<m) {
t = Math.max(t+1, a[1][i] + 1);
t = Math.max(t+1, a[1][i+1] + 1);
}
} else {
if(i+1<m) {
t = Math.max(t+1, a[0][i] + 1);
t = Math.max(t+1, a[0][i+1] + 1);
}
}
}
if(m%2 == 0) {
add(map1, b[0][m-1]);
add(map1, b[1][m-1]);
add(map1, b[1][m-2]);
add(map2, c[0][m-1]);
} else {
add(map1, b[1][m-1]);
add(map2, c[0][m-1]);
add(map2, c[1][m-1]);
add(map2, c[0][m-2]);
}
for(int i=m-1; i>=0; i--) {
if(i%2 == 0) {
int d = tt[i] + Math.max(map1.lastKey()-tt[i]+i, 0) + (m-i) * 2 - 1;
res = Math.min(res, d);
if(i-2>=0) {
add(map1, b[1][i-2]);
add(map1, b[1][i-1]);
add(map1, b[0][i-1]);
add(map1, b[0][i]);
}
} else {
int d = tt[i] + Math.max(map2.lastKey()-tt[i]+i-1, 0) + (m-i) * 2 - 1;
res = Math.min(res, d);
if(i-2>=0) {
add(map2, c[0][i-2]);
add(map2, c[0][i-1]);
add(map2, c[1][i-1]);
add(map2, c[1][i]);
}
}
}
out.println(res);
}
void add(Map<Integer, Integer> map, int num) {
map.put(num, map.getOrDefault(num, 0) + 1);
}
void del(Map<Integer, Integer> map, int num) {
int next = map.get(num) -1;
if(next == 0) {
map.remove(num);
} else {
map.put(num, next);
}
}
}
class FastScanner {
private final InputStream in;
private final byte[] buffer = new byte[1024];
private int ptr = 0;
private int buflen = 0;
private boolean hasNextByte() {
if (ptr < buflen) {
return true;
}else{
ptr = 0;
try {
buflen = in.read(buffer);
} catch (IOException e) {
e.printStackTrace();
}
if (buflen <= 0) {
return false;
}
}
return true;
}
public FastScanner(InputStream in) {
this.in = in;
}
private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;}
private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;}
private void skipUnprintable() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++;}
public boolean hasNext() { skipUnprintable(); return hasNextByte();}
public String next() {
if (!hasNext()) throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = readByte();
while(isPrintableChar(b)) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public int nextInt() {
return (int) nextLong();
}
public long nextLong() {
if (!hasNext()) throw new NoSuchElementException();
long n = 0;
boolean minus = false;
int b = readByte();
if (b == '-') {
minus = true;
b = readByte();
}
if (b < '0' || '9' < b) {
throw new NumberFormatException();
}
while(true){
if ('0' <= b && b <= '9') {
n *= 10;
n += b - '0';
}else if(b == -1 || !isPrintableChar(b)){
return minus ? -n : n;
}else{
throw new NumberFormatException();
}
b = readByte();
}
}
} | Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 11 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | 2b8e6f3e2b159dda56ce636112659ed8 | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Codechef
{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());
}
float nextFloat(){
return Float.parseFloat(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
static int mod = 1000000007;
static int N = 100005;
static long factorial_num_inv[] = new long[N+1];
static long natual_num_inv[] = new long[N+1];
static long fact[] = new long[N+1];
static void InverseofNumber()
{
natual_num_inv[0] = 1;
natual_num_inv[1] = 1;
for (int i = 2; i <= N; i++)
natual_num_inv[i] = natual_num_inv[mod % i] * (mod - mod / i) % mod;
}
static void InverseofFactorial()
{
factorial_num_inv[0] = factorial_num_inv[1] = 1;
for (int i = 2; i <= N; i++)
factorial_num_inv[i] = (natual_num_inv[i] * factorial_num_inv[i - 1]) % mod;
}
static long nCrModP(long N, long R)
{
long ans = ((fact[(int)N] * factorial_num_inv[(int)R]) % mod * factorial_num_inv[(int)(N - R)]) % mod;
return ans%mod;
}
static boolean prime[];
static void sieveOfEratosthenes(int n)
{
prime = new boolean[n+1];
for (int i = 0; i <= n; i++)
prime[i] = true;
for (int p = 2; p * p <= n; p++)
{
// If prime[p] is not changed, then it is a
// prime
if (prime[p] == true)
{
// Update all multiples of p
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
}
static long st[];
static int ans[];
public static void main (String[] args)
{
// InverseofNumber();
// InverseofFactorial();
// fact[0] = 1;
// for (long i = 1; i <= 3*100000; i++)
// {
// fact[(int)i] = (fact[(int)i - 1] * i) % mod;
// }
FastReader scan = new FastReader();
PrintWriter pw = new PrintWriter(System.out);
int t = scan.nextInt();
while(t-->0){
int n = scan.nextInt();
long a[][] = new long[2][n];
for(int i=0;i<n;i++){
a[0][i] = scan.nextLong();
}
for(int i=0;i<n;i++){
a[1][i] = scan.nextLong();
}
long clock[][] = new long[2][n];
long anti[][] = new long[2][n];
long curr = 0;
for(int i=1;i<n;i++){
curr = Math.max(curr+1,a[0][i]+1);
clock[0][i] = curr;
}
for(int i=n-1;i>=0;i--){
curr = Math.max(curr+1,a[1][i]+1);
clock[1][i] = curr;
}
curr = a[1][0]+1;
for(int i=1;i<n;i++){
curr = Math.max(curr+1,a[1][i]+1);
anti[1][i] = curr;
}
for(int i=n-1;i>=1;i--){
curr = Math.max(curr+1,a[0][i]+1);
anti[0][i] = curr;
}
long ans = Math.min(clock[1][0],anti[0][1]);
int down = 1;
curr = 0;
for(int i=0;i<n-1;i++){
if(down==1){
down = 0;
curr = Math.max(curr+1,a[1][i]+1);
curr = Math.max(curr+1,a[1][i+1]+1);
ans = Math.min(ans,Math.max(anti[0][i+1],curr+2*(n-i-1)-1));
}
else{
down = 1;
curr = Math.max(curr+1,a[0][i]+1);
curr = Math.max(curr+1,a[0][i+1]+1);
ans = Math.min(ans,Math.max(clock[1][i+1],curr+2*(n-i-1)-1));
}
}
pw.println(ans);
}
pw.flush();
}
//static long bin_exp_mod(long a,long n){
// long mod = 998244353;
// long res = 1;
// while(n!=0){
// if(n%2==1){
// res = ((res%mod)*(a%mod))%mod;
// }
// n = n/2;
// a = ((a%mod)*(a%mod))%mod;
// }
// res = res%mod;
// return res;
//}
static long gcd(long a,long b){
if(a==0)
return b;
return gcd(b%a,a);
}
static long lcm(long a,long b){
return (a/gcd(a,b))*b;
}
}
class Details{
int x,b,r;
Details(int x,int b,int r){
this.x = x;
this.b = b;
this.r = r;
}
}
class Pair{
int x,dis;
Pair(int x,int y){
this.x = x;
this.dis = y;
}
// public boolean equals(Object obj) {
// // TODO Auto-generated method stub
// if(obj instanceof Pair)
// {
// Pair temp = (Pair) obj;
// if(this.x.equals(temp.x) && this.y.equals(temp.y))
// return true;
// }
// return false;
// }
// @Override
// public int hashCode() {
// // TODO Auto-generated method stub
// return (this.x.hashCode() + this.y.hashCode());
// }
}
class Compar implements Comparator<Pair>{
public int compare(Pair p1,Pair p2){
return p1.dis-p2.dis;
}
}
// class DisjointSet{
// Map<Long,Node> map = new HashMap<>();
// class Node{
// long data;
// Node parent;
// int rank;
// }
// public void makeSet(long data){
// Node node = new Node();
// node.data = data;
// node.parent = node;
// node.rank = 0;
// map.put(data,node);
// }
// //here we just need the rank of parent to be exact
// public void union(long data1,long data2){
// Node node1 = map.get(data1);
// Node node2 = map.get(data2);
// Node parent1 = findSet(node1);
// Node parent2 = findSet(node2);
// if(parent1.data==parent2.data){
// return;
// }
// if(parent1.rank>=parent2.rank){
// parent1.rank = (parent1.rank==parent2.rank)?parent1.rank+1:parent1.rank;
// parent2.parent = parent1;
// }
// else{
// parent1.parent = parent2;
// }
// }
// public long findSet(long data){
// return findSet(map.get(data)).data;
// }
// private Node findSet(Node node){
// Node parent = node.parent;
// if(parent==node){
// return parent;
// }
// node.parent = findSet(node.parent);
// return node.parent;
// }
// }
| Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 11 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | 3858019ad2188967dff5ee2083da2155 | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | // package c1716;
//
// Educational Codeforces Round 133 (Rated for Div. 2) 2022-08-04 07:35
// C. Robot in a Hallway
// https://codeforces.com/contest/1716/problem/C
// time limit per test 2 seconds; memory limit per test 256 megabytes
// public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*'
//
// There is a grid, consisting of 2 rows and m columns. The rows are numbered from 1 to 2 from top
// to bottom. The columns are numbered from 1 to m from left to right.
//
// The robot starts in a cell (1, 1). In one second, it can perform either of two actions:
// * move into a cell adjacent by a side: up, right, down or left;
// * remain in the same cell.
//
// The robot is not allowed to move outside the grid.
//
// Initially, all cells, except for the cell (1, 1), are locked. Each cell (i, j) contains a value
// a_{i,j}-- the moment that this cell gets unlocked. The robot can only move into a cell (i, j) if
// at least a_{i,j} seconds have passed before the move.
//
// The robot should visit all cells (cell (1, 1) is considered entered at the start). It can finish
// in any cell.
//
// What is the fastest the robot can achieve that?
//
// Input
//
// The first line contains a single integer t (1 <= t <= 10^4)-- the number of testcases.
//
// The first line of each testcase contains a single integer m (2 <= m <= 2 * 10^5)-- the number of
// columns of the grid.
//
// The i-th of the next 2 lines contains m integers a_{i,1}, a_{i,2}, ..., a_{i,m} (0 <= a_{i,j} <=
// 10^9)-- the moment of time each cell gets unlocked. a_{1,1} = 0. If a_{i,j} = 0, then cell (i, j)
// is unlocked from the start.
//
// The sum of m over all testcases doesn't exceed 2 * 10^5.
//
// Output
//
// For each testcase, print a single integer-- the minimum amount of seconds that the robot can take
// to visit all cells without entering any cell twice or more.
//
// Example
/*
input:
4
3
0 0 1
4 3 2
5
0 4 8 12 16
2 6 10 14 18
4
0 10 10 10
10 10 10 10
2
0 0
0 0
output:
5
19
17
3
*/
//
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.invoke.MethodHandles;
import java.util.Arrays;
import java.util.Random;
import java.util.StringTokenizer;
public class C1716C {
static final int MOD = 998244353;
static final Random RAND = new Random();
static int solve(int[][] a) {
int m = a[0].length;
int[][][] dom = getDominate(a);
// System.out.format("%s\n", Utils.trace(dom));
int t = 0;
int ans = Integer.MAX_VALUE;
for (int j = 0; j < m; j++) {
if (j % 2 == 0) {
// from (0,j) to (1, j)
int r = dom[0][j][0];
int c = dom[0][j][1];
int d = dist(0,j,r,c,m);
if (t + d > min(r,c,a)) {
ans = Math.min(ans, t + dist(0, j, 1, j, m));
} else {
ans = Math.min(ans, min(r,c,a) + dist(r,c,1,j,m));
}
// move down and move right
if (j == m - 1) {
break;
}
t = Math.max(t, a[1][j]) + 1;
t = Math.max(t, a[1][j+1]) + 1;
} else {
// from (1,j) to (0,j)
int r = dom[1][j][0];
int c = dom[1][j][1];
int d = dist(1,j,r,c,m);
if (t + d > min(r,c,a)) {
ans = Math.min(ans, t + dist(1, j, 0, j, m));
} else {
ans = Math.min(ans, min(r,c,a) + dist(r,c,0,j,m));
}
// move up and right
if (j == m - 1) {
break;
}
t = Math.max(t, a[0][j]) + 1;
t = Math.max(t, a[0][j+1]) + 1;
}
}
return ans;
}
// For each (i,j), get the dominate cell to the terminal (1-i,j)
static int[][][] getDominate(int[][] a) {
int m = a[0].length;
int[][][] dom = new int[2][m][2];
// j m-1
// o -> . -> . -> .
// v
// . <- . <- .
//
dom[0][m-1][0] = a[0][m-1] >= a[1][m-1] ? 0 : 1;
dom[0][m-1][1] = m-1;
dom[1][m-1][0] = a[1][m-1] >= a[0][m-1] ? 1 : 0;
dom[1][m-1][1] = m-1;
for (int j = m - 2; j >= 0; j--) {
{
// (0,j) -> ... -> (r,c) -> ... -> (1,j)
int r = dom[0][j+1][0];
int c = dom[0][j+1][1];
int d0 = dist(0,j,r,c,m);
if (min(0,j,a) + d0 > min(r, c, a)) {
r = 0;
c = j;
}
int d1 = dist(r,c,1,j,m);
if (min(r,c,a) + d1 < min(1,j,a)) {
r = 1;
c = j;
}
dom[0][j][0] = r;
dom[0][j][1] = c;
}
{
// (1,j) -> ... -> (r,c) -> ... -> (0,j)
int r = dom[1][j+1][0];
int c = dom[1][j+1][1];
int d0 = dist(1,j,r,c,m);
if (min(1,j,a) + d0 > min(r, c, a)) {
r = 1;
c = j;
}
int d1 = dist(r,c,0,j,m);
if (min(r,c,a) + d1 < min(0,j,a)) {
r = 0;
c = j;
}
dom[1][j][0] = r;
dom[1][j][1] = c;
}
}
return dom;
}
static int min(int r, int c, int[][] a) {
return r == 0 && c == 0 ? 0 : a[r][c] + 1;
}
// Get distance from (r0,c0) to (r1,c1)
static int dist(int r0, int c0, int r1, int c1, int m) {
int min = Math.min(c0, c1);
int max = Math.max(c0, c1);
if (r0 == r1) {
return max - min;
} else {
return max - min + (m - 1 - max) * 2 + 1;
}
}
static void test(int[][] a) {
System.out.format("%s\n", Arrays.toString(a[0]));
System.out.format("%s\n", Arrays.toString(a[1]));
int ans = solve(a);
System.out.println(ans);
}
static boolean test = false;
static void doTest() {
if (!test) {
return;
}
long t0 = System.currentTimeMillis();
test(new int[][] {{0, 4, 8, 12, 16}, {2, 6, 10, 14, 18}});
// test(new int[][] {{0, 1}, {1, 0}});
System.out.format("%d msec\n", System.currentTimeMillis() - t0);
System.exit(0);
}
public static void main(String[] args) {
doTest();
MyScanner in = new MyScanner();
int T = in.nextInt();
for (int t = 1; t <= T; t++) {
int m = in.nextInt();
int[][] a = new int[2][m];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < m; j++) {
a[i][j] = in.nextInt();
}
}
int ans = solve(a);
System.out.println(ans);
}
}
static void output(int[] a) {
if (a == null) {
System.out.println("-1");
return;
}
StringBuilder sb = new StringBuilder();
for (int v : a) {
sb.append(v);
sb.append(' ');
if (sb.length() > 500) {
System.out.print(sb.toString());
sb.setLength(0);
}
}
System.out.println(sb.toString());
}
static void myAssert(boolean cond) {
if (!cond) {
throw new RuntimeException("Unexpected");
}
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
try {
final String USERDIR = System.getProperty("user.dir");
String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(".MyScanner", "");
cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname;
final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in");
br = new BufferedReader(new InputStreamReader(fin.exists()
? new FileInputStream(fin) : System.in));
} catch (Exception e) {
br = new BufferedReader(new InputStreamReader(System.in));
}
}
public String next() {
try {
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 11 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | 00c0083e0f6790f586a90c5b35484d66 | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | // package c1716;
//
// Educational Codeforces Round 133 (Rated for Div. 2) 2022-08-04 07:35
// C. Robot in a Hallway
// https://codeforces.com/contest/1716/problem/C
// time limit per test 2 seconds; memory limit per test 256 megabytes
// public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*'
//
// There is a grid, consisting of 2 rows and m columns. The rows are numbered from 1 to 2 from top
// to bottom. The columns are numbered from 1 to m from left to right.
//
// The robot starts in a cell (1, 1). In one second, it can perform either of two actions:
// * move into a cell adjacent by a side: up, right, down or left;
// * remain in the same cell.
//
// The robot is not allowed to move outside the grid.
//
// Initially, all cells, except for the cell (1, 1), are locked. Each cell (i, j) contains a value
// a_{i,j}-- the moment that this cell gets unlocked. The robot can only move into a cell (i, j) if
// at least a_{i,j} seconds have passed before the move.
//
// The robot should visit all cells (cell (1, 1) is considered entered at the start). It can finish
// in any cell.
//
// What is the fastest the robot can achieve that?
//
// Input
//
// The first line contains a single integer t (1 <= t <= 10^4)-- the number of testcases.
//
// The first line of each testcase contains a single integer m (2 <= m <= 2 * 10^5)-- the number of
// columns of the grid.
//
// The i-th of the next 2 lines contains m integers a_{i,1}, a_{i,2}, ..., a_{i,m} (0 <= a_{i,j} <=
// 10^9)-- the moment of time each cell gets unlocked. a_{1,1} = 0. If a_{i,j} = 0, then cell (i, j)
// is unlocked from the start.
//
// The sum of m over all testcases doesn't exceed 2 * 10^5.
//
// Output
//
// For each testcase, print a single integer-- the minimum amount of seconds that the robot can take
// to visit all cells without entering any cell twice or more.
//
// Example
/*
input:
4
3
0 0 1
4 3 2
5
0 4 8 12 16
2 6 10 14 18
4
0 10 10 10
10 10 10 10
2
0 0
0 0
output:
5
19
17
3
*/
//
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.invoke.MethodHandles;
import java.util.Arrays;
import java.util.Random;
import java.util.StringTokenizer;
public class C1716C {
static final int MOD = 998244353;
static final Random RAND = new Random();
static int solve(int[][] a) {
int m = a[0].length;
int[][][] dom = getDominate(a);
// System.out.format("%s\n", Utils.trace(dom));
int t = 0;
int ans = Integer.MAX_VALUE;
for (int j = 0; j < m; j++) {
if (j % 2 == 0) {
// from (0,j) to (1, j)
int r = dom[0][j][0];
int c = dom[0][j][1];
int d = dist(0,j,r,c,m);
if (t + d > min(r,c,a)) {
ans = Math.min(ans, t + dist(0, j, 1, j, m));
} else {
ans = Math.min(ans, min(r,c,a) + dist(r,c,1,j,m));
}
// move down and move right
if (j == m - 1) {
break;
}
t = Math.max(t, a[1][j]) + 1;
t = Math.max(t, a[1][j+1]) + 1;
} else {
// from (1,j) to (0,j)
int r = dom[1][j][0];
int c = dom[1][j][1];
int d = dist(1,j,r,c,m);
if (t + d > min(r,c,a)) {
ans = Math.min(ans, t + dist(1, j, 0, j, m));
} else {
ans = Math.min(ans, min(r,c,a) + dist(r,c,0,j,m));
}
// move up and right
if (j == m - 1) {
break;
}
t = Math.max(t, a[0][j]) + 1;
t = Math.max(t, a[0][j+1]) + 1;
}
}
return ans;
}
static int[][][] getDominate(int[][] a) {
int m = a[0].length;
int[][][] dom = new int[2][m][2];
// j m-1
// o -> . -> . -> .
// v
// . <- . <- .
//
dom[0][m-1][0] = a[0][m-1] >= a[1][m-1] ? 0 : 1;
dom[0][m-1][1] = m-1;
dom[1][m-1][0] = a[1][m-1] >= a[0][m-1] ? 1 : 0;
dom[1][m-1][1] = m-1;
for (int j = m - 2; j >= 0; j--) {
{
// (0,j) -> ... -> (r,c) -> ... -> (1,j)
int r = dom[0][j+1][0];
int c = dom[0][j+1][1];
int d0 = dist(0,j,r,c,m);
if (min(0,j,a) + d0 > min(r, c, a)) {
r = 0;
c = j;
}
int d1 = dist(r,c,1,j,m);
if (min(r,c,a) + d1 < min(1,j,a)) {
r = 1;
c = j;
}
dom[0][j][0] = r;
dom[0][j][1] = c;
}
{
// (1,j) -> ... -> (r,c) -> ... -> (0,j)
int r = dom[1][j+1][0];
int c = dom[1][j+1][1];
int v = a[r][c] + 1;
int d0 = dist(1,j,r,c,m);
if (min(1,j,a) + d0 > min(r, c, a)) {
r = 1;
c = j;
}
int d1 = dist(r,c,0,j,m);
if (min(r,c,a) + d1 < min(0,j,a)) {
r = 0;
c = j;
}
dom[1][j][0] = r;
dom[1][j][1] = c;
}
}
return dom;
}
static int min(int r, int c, int[][] a) {
return r == 0 && c == 0 ? 0 : a[r][c] + 1;
}
static int dist(int r0, int c0, int r1, int c1, int m) {
// System.out.format(" dist %d %d %d %d %d\n", r0, c0, r1, c1, m);
// myAssert(c0 <= c1);
int min = Math.min(c0, c1);
int max = Math.max(c0, c1);
if (r0 == r1) {
return max - min;
} else {
return max - min + (m - 1 - max) * 2 + 1;
}
}
static int[][] getDominate(int[] a, int[] b) {
// System.out.format(" a:%s\n", Arrays.toString(a));
// System.out.format(" a:%s\n", Arrays.toString(b));
int m = a.length;
int[][] dom = new int[m][2];
// j m-1
// o -> . -> . -> .
// v
// . <- . <- .
//
// (r,c) is the position of the dominate cell
int r = a[m-1] + 1 > b[m-1] ? 0 : 1;
int c = m - 1;
dom[m-1][0] = r;
dom[m-1][1] = c;
for (int j = m-2; j >= 0; j--) {
int v = (r == 0 ? a[c] : b[c]) + 1;
int v0 = a[j] + 2 * (m - j) - 1;
int v1 = b[j];
// System.out.format(" j:%d v:%2d v0:%2d v1:%2d\n", j, v, v0, v1);
int max = Math.max(Math.max(v0, v1), v);
if (v == max) {
} else if (v0 == max) {
r = 0;
c = j;
} else {
r = 1;
c = j;
}
dom[j][0] = r;
dom[j][1] = c;
}
return dom;
}
static int[] getForward(int[] a, int[] b) {
// System.out.format(" a:%s\n", Arrays.toString(a));
// System.out.format(" a:%s\n", Arrays.toString(b));
int m = a.length;
int[] f = new int[m];
// j m-1
// o -> . -> . -> .
// v
// . <- . <- .
//
// (r,c) is the position of the dominate cell
int r = a[m-1] - 1 > b[m-1] ? 0 : 1;
int c = m - 1;
f[m-1] = r == 0 ? a[c] + 1 : b[c];
for (int j = m-2; j >= 0; j--) {
int v = (r == 0 ? a[c] : b[c]) - 1;
int v0 = a[j] - 2 * (m - j) + 1;
int v1 = b[j];
int max = Math.max(Math.max(v0, v1), v);
if (v == max) {
} else if (v0 == max) {
r = 0;
c = j;
} else {
r = 1;
c = j;
}
// Given the dominate cell (r,c), what's the arrival time at [1,j]?
int d = (r == 0 ? (m - 1 - c) * 2 : 0) + c - j;
f[j] = (r == 0 ? a[c] + 1 : b[c]) + d;
// System.out.format(" j:%d v0:%2d v1:%2d v:%2d r:%d c:%d d:%2d f:%2d\n", j, v0, v1, v, r, c, d, f[j]);
}
System.out.format(" f:%s\n", Arrays.toString(f));
return f;
}
static void test(int[][] a) {
System.out.format("%s\n", Arrays.toString(a[0]));
System.out.format("%s\n", Arrays.toString(a[1]));
int ans = solve(a);
System.out.println(ans);
}
static boolean test = false;
static void doTest() {
if (!test) {
return;
}
long t0 = System.currentTimeMillis();
test(new int[][] {{0, 4, 8, 12, 16}, {2, 6, 10, 14, 18}});
// test(new int[][] {{0, 1}, {1, 0}});
System.out.format("%d msec\n", System.currentTimeMillis() - t0);
System.exit(0);
}
public static void main(String[] args) {
doTest();
MyScanner in = new MyScanner();
int T = in.nextInt();
for (int t = 1; t <= T; t++) {
int m = in.nextInt();
int[][] a = new int[2][m];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < m; j++) {
a[i][j] = in.nextInt();
}
}
int ans = solve(a);
System.out.println(ans);
}
}
static void output(int[] a) {
if (a == null) {
System.out.println("-1");
return;
}
StringBuilder sb = new StringBuilder();
for (int v : a) {
sb.append(v);
sb.append(' ');
if (sb.length() > 500) {
System.out.print(sb.toString());
sb.setLength(0);
}
}
System.out.println(sb.toString());
}
static void myAssert(boolean cond) {
if (!cond) {
throw new RuntimeException("Unexpected");
}
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
try {
final String USERDIR = System.getProperty("user.dir");
String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(".MyScanner", "");
cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname;
final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in");
br = new BufferedReader(new InputStreamReader(fin.exists()
? new FileInputStream(fin) : System.in));
} catch (Exception e) {
br = new BufferedReader(new InputStreamReader(System.in));
}
}
public String next() {
try {
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 11 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | c4e44c92e08b29ffb2c12d06aef0be5c | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
public static Scanner obj = new Scanner(System.in);
public static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) {
int len = obj.nextInt();
while (len-- != 0) {
int n=obj.nextInt();
int[] a=new int[n];
int[] b=new int[n];
for(int i=0;i<n;i++)a[i]=obj.nextInt();
for(int i=0;i<n;i++)b[i]=obj.nextInt();
int[] pa=new int[n];
int[] pb=new int[n];
int[] sa=new int[n];
int[] sb=new int[n];
int ma=a[0]-1,mb=b[0]-1;
for(int i=0;i<n;i++)
{
pa[i]=Math.max(ma+1,a[i]+1);
pb[i]=Math.max(mb+1,b[i]+1);
if(i==0) {
pa[i]=a[0];
pb[i]=b[0];
}
ma=pa[i];
mb=pb[i];
}
ma=a[n-1]-1;
mb=b[n-1]-1;
for(int i=n-1;i>=0;i--)
{
sa[i]=Math.max(ma+1,a[i]+1);
sb[i]=Math.max(mb+1,b[i]+1);
ma=sa[i];
mb=sb[i];
}
pa[0]=a[0];
int i=0,j=0,val=0;
int time=-1;
i=0;j=0;
val=0;
long ans=Integer.MAX_VALUE;
i=0;
j=0;
while(i<2 && j<n)
{
if(val==0)
{
if(i==0 && j==0) time=0;
else
{
if(time<a[j])time=a[j]+1;
else time=time+1;
}
long last=Math.max(time+n-1-j,pa[n-1]);
if(b[n-1]>last)last=b[n-1]+1;
else last+=1;
last=Math.max(last+n-1-j,sb[j]);
ans=Math.min(ans,last);
val=1;
i+=1;
}
else if(val==1)
{
if(time<b[j])time=b[j]+1;
else time=time+1;
val=2;
j+=1;
}
else if(val==2)
{
if(time<b[j])time=b[j]+1;
else time=time+1;
long last=Math.max(time+n-1-j,pb[n-1]);
if(a[n-1]>last)last=a[n-1]+1;
else last+=1;
last=Math.max(last+n-1-j,sa[j]);
ans=Math.min(ans,last);
val=3;
i-=1;
}
else
{
if(time<a[j])time=a[j]+1;
else time=time+1;
val=0;
j+=1;
}
}
out.println(ans);
}
out.flush();
}
} | Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 11 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | a0a9440cde9159cc5068b604b0a453d3 | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
public static Scanner obj = new Scanner(System.in);
public static PrintWriter out = new PrintWriter(System.out);
public static void debug(int[] a)
{
for(int i=0;i<a.length;i++)
{
System.out.print(a[i]+" ");
}
System.out.println();
}
public static void main(String[] args) {
int len = obj.nextInt();
while (len-- != 0) {
int n=obj.nextInt();
int[] a=new int[n];
int[] b=new int[n];
for(int i=0;i<n;i++)a[i]=obj.nextInt();
for(int i=0;i<n;i++)b[i]=obj.nextInt();
int[] pa=new int[n];
int[] pb=new int[n];
int[] sa=new int[n];
int[] sb=new int[n];
int ma=a[0]-1,mb=b[0]-1;
for(int i=0;i<n;i++)
{
pa[i]=Math.max(ma+1,a[i]+1);
pb[i]=Math.max(mb+1,b[i]+1);
if(i==0) {
pa[i]=a[0];
pb[i]=b[0];
}
ma=pa[i];
mb=pb[i];
}
ma=a[n-1]-1;
mb=b[n-1]-1;
for(int i=n-1;i>=0;i--)
{
sa[i]=Math.max(ma+1,a[i]+1);
sb[i]=Math.max(mb+1,b[i]+1);
ma=sa[i];
mb=sb[i];
}
pa[0]=a[0];
//debug(pa);
//debug(pb);
//debug(sa);
//debug(sb);
int i=0,j=0,val=0;
int time=-1;
long tut=Integer.MAX_VALUE;
long[][] tt=new long[2][n];
while(i<2 && j<n)
{
//System.out.println("i is:"+i+" j is:"+j+" time is:"+time);
if(val==0)
{
val=1;
if(i==0 && j==0) time=0;
else
{
if(time<a[j])time=a[j]+1;
else time=time+1;
}
tt[i][j]=time;
i+=1;
}
else if(val==1)
{
if(time<b[j])time=b[j]+1;
else time=time+1;
val=2;
tt[i][j]=time;
j+=1;
}
else if(val==2)
{
if(time<b[j])time=b[j]+1;
else time=time+1;
val=3;
tt[i][j]=time;
i-=1;
}
else
{
if(time<a[j])time=a[j]+1;
else time=time+1;
val=0;
tt[i][j]=time;
j+=1;
}
}
i=0;j=0;
val=0;
long ans=time;
/*
for(i=0;i<2;i++)
{
for(j=0;j<n;j++)System.out.print(tt[i][j]+" - ");
System.out.println();
}
//System.out.println("ans is:"+ans);
*/
i=0;
j=0;
while(i<2 && j<n)
{
//System.out.println("i is:"+i+" j is:"+j+" ans is :"+ans);
if(val==0)
{
long last=Math.max(tt[i][j]+n-1-j,pa[n-1]);
//System.out.println("last is:"+last);
if(b[n-1]>last)last=b[n-1]+1;
else last+=1;
//System.out.println("last is:"+last);
last=Math.max(last+n-1-j,sb[j]);
//System.out.println(" v1 +v2 is:"+last);
ans=Math.min(ans,last);
val=1;
i+=1;
}
else if(val==1)
{
val=2;
j+=1;
}
else if(val==2)
{
long last=Math.max(tt[i][j]+n-1-j,pb[n-1]);
if(a[n-1]>last)last=a[n-1]+1;
else last+=1;
last=Math.max(last+n-1-j,sa[j]);
//System.out.println(" v1 +v2 is:"+last);
ans=Math.min(ans,last);
val=3;
i-=1;
}
else
{
val=0;
j+=1;
}
//System.out.println("i is:"+i+" j is:"+j+" ans is:-"+ans);
}
out.println(ans);
}
out.flush();
}
} | Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 11 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | 07ad045917cb6239265eaff4653e3808 | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | import java.util.*;
public class quesC {
public static void main(String[] args) throws Exception {;
Scanner scn= new Scanner(System.in);
int t= scn.nextInt();
while(t-->0){
int n= scn.nextInt();
int[][] arr= new int[2][n];
for(int i=0; i<arr.length; i++)
for(int j=0; j<arr[0].length; j++)arr[i][j]= scn.nextInt();
int [][] dp= new int[2][n];
dp[0][n-1]= Math.max(arr[0][n-1], arr[1][n-1]-1);
dp[1][n-1]= Math.max(arr[1][n-1], arr[0][n-1]-1);
for(int i=n-2; i>=0; i--){
dp[0][i]= Math.max(dp[0][i+1]-1, Math.max(arr[0][i], arr[1][i]- (2*(n-i)-1)));
dp[1][i]= Math.max(dp[1][i+1]-1, Math.max(arr[1][i], arr[0][i]-(2*(n-i)-1)));
}
// for(int i=0; i<dp.length; i++){
// for(int j=0; j<dp[0].length; j++)System.err.print(dp[i][j]+" ");
// System.out.println();
// }
// System.out.println();
int min=Integer.MAX_VALUE;
int ans=0;
for(int i=0; i<arr[0].length-1; i++){
if(i%2==0){
if(i!=0)
{if(ans>arr[0][i]){
ans++;
}
else{
ans= arr[0][i]+1;
}}
if(ans>arr[1][i]){
ans++;
}
else{
ans= arr[1][i]+1;
}
if(ans>dp[1][i+1]){
min= Math.min(min, ans+ 2*(n-i-1));
}
else{
min= Math.min(min, dp[1][i+1]+2*(n-i-1));
}
}
else{
if(ans>arr[1][i]){
ans++;
}
else{
ans= arr[1][i]+1;
}
if(ans>arr[0][i]){
ans++;
}
else{
ans= arr[0][i]+1;
}
if(ans>dp[0][i+1]){
min= Math.min(min, ans+ 2*(n-i-1));
}
else{
min= Math.min(min, dp[0][i+1]+2*(n-i-1));
}
}
}
int max2=0;
for(int i=1; i<arr[0].length; i++){
if(max2>arr[0][i]){
max2++;
}
else{
max2= arr[0][i]+1;
}
}
for(int i=arr[0].length-1; i>=0; i--){
if(max2>arr[1][i]){
max2++;
}
else{
max2= arr[1][i]+1;
}
}
System.out.println(Math.min(min, max2));
}
}
} | Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 11 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | 01215ec271f6edb04d2c765430b265c1 | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes |
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main {
static int N;
static Read s = new Read();
static int sum;
static int[][] dir = new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
public static void main(String[] args) throws IOException {
int T = s.nextInt();
while (T-- > 0) {
int m = s.nextInt();
N = m;
int[][] A = new int[2][m], B = new int[2][m], C = new int[2][m], V = new int[2][m];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < m; j++) {
V[i][j] = s.nextInt();
}
}
B[1][0] = V[1][0] + 1;
for (int i = 1; i < N; i++) {
A[0][i] = Math.max(A[0][i - 1] + 1, V[0][i] + 1);
B[1][i] = Math.max(B[1][i - 1] + 1, V[1][i] + 1);
}
A[1][N - 1] = Math.max(A[0][N - 1] + 1, V[1][N - 1] + 1);
B[0][N - 1] = Math.max(B[1][N - 1] + 1, V[0][N - 1] + 1);
for (int i = (N - 2); i >= 0; i--) {
A[1][i] = Math.max(A[1][i + 1] + 1, V[1][i] + 1);
B[0][i] = Math.max(B[0][i + 1] + 1, V[0][i] + 1);
}
int i1 = 0, j1 = 0;
for (int k = 0; k < (2 * N - 1); k++) {
int ni = i1, nj = j1;
if (k % 2 == 1) {
nj++;
} else {
ni = (ni + 1) % 2;
}
C[ni][nj] = Math.max(C[i1][j1] + 1, V[ni][nj] + 1);
i1 = ni;
j1 = nj;
}
int ans = 0x3f3f3f3f;
for (int i = 0; i < N; i++) {
int a = 0x3f3f3f3f, b = 0x3f3f3f3f;
int k = 2 * (N - i) - 1;
a = Math.min(a, C[0][i] + Math.max(A[1][i] - C[0][i], 2 * (N - i) - 1));
b = Math.min(b, C[1][i] + Math.max(B[0][i] - C[1][i], 2 * (N - i) - 1));
ans = Math.min(ans, a);
ans = Math.min(ans, b);
}
s.println(ans);
}
s.bw.flush();
}
static void swap(int[] a, int i, int j) {
int tep = a[i];
a[i] = a[j];
a[j] = tep;
}
static class Read {
BufferedReader bf;
StringTokenizer st;
BufferedWriter bw;
public Read() {
bf = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer("");
bw = new BufferedWriter(new OutputStreamWriter(System.out));
}
public String nextLine() throws IOException {
return bf.readLine();
}
public String next() throws IOException {
while (!st.hasMoreTokens()) {
st = new StringTokenizer(bf.readLine());
}
return st.nextToken();
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public float nextFloat() throws IOException {
return Float.parseFloat(next());
}
public byte nextByte() throws IOException {
return Byte.parseByte(next());
}
public short nextShort() throws IOException {
return Short.parseShort(next());
}
public BigInteger nextBigInteger() throws IOException {
return new BigInteger(next());
}
public void println(int a) throws IOException {
bw.write(String.valueOf(a));
bw.newLine();
return;
}
public void print(int a) throws IOException {
bw.write(String.valueOf(a));
return;
}
public void println(String a) throws IOException {
bw.write(a);
bw.newLine();
return;
}
public void print(String a) throws IOException {
bw.write(a);
return;
}
public void println(long a) throws IOException {
bw.write(String.valueOf(a));
bw.newLine();
return;
}
public void print(long a) throws IOException {
bw.write(String.valueOf(a));
return;
}
public void println(double a) throws IOException {
bw.write(String.valueOf(a));
bw.newLine();
return;
}
public void print(double a) throws IOException {
bw.write(String.valueOf(a));
return;
}
}
} | Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 11 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | 3e0011cc53224a1f98473956359c7375 | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | //Utilities
import java.io.*;
import java.util.*;
public class a {
static int t;
static int m;
static int[][] a;
static int[][] sfmax1; // max of a[i][j] - j
static int[][] sfmax2; // max of a[i][j] + j
static int min;
public static void main(String[] args) throws IOException {
t = in.iscan();
while (t-- > 0) {
m = in.iscan();
a = new int[2][m]; sfmax1 = new int[2][m]; sfmax2 = new int[2][m];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < m; j++) {
a[i][j] = in.iscan();
}
for (int j = m-1; j >= 0; j--) {
sfmax1[i][j] = a[i][j] - j;
sfmax2[i][j] = a[i][j] + j;
if (j + 1 < m) {
sfmax1[i][j] = Math.max(sfmax1[i][j], sfmax1[i][j+1]);
sfmax2[i][j] = Math.max(sfmax2[i][j], sfmax2[i][j+1]);
}
}
}
min = Integer.MAX_VALUE;
int r = 0, c = 0, curTime = 0;
while (c < m) {
if (c + 1 < m) {
int curMax;
if (r == 0) {
curMax = Math.max(sfmax1[r][c+1] + 2 * m - c, sfmax2[r+1][c] - c + 1);
}
else {
curMax = Math.max(sfmax1[r][c+1] + 2 * m - c, sfmax2[r-1][c] - c + 1);
}
curMax = Math.max(curMax, curTime + 2 * (m-1-c) + 1);
// out.println(r + " " + c + " " + curMax);
min = Math.min(min, curMax);
}
if (r == 0) {
curTime = Math.max(curTime+1, a[r+1][c] + 1);
if (c + 1 < m) {
curTime = Math.max(curTime+1, a[r+1][c+1] + 1);
}
r++;
c++;
}
else {
curTime = Math.max(curTime+1, a[r-1][c] + 1);
if (c + 1 < m) {
curTime = Math.max(curTime+1, a[r-1][c+1] + 1);
}
r--;
c++;
}
}
min = Math.min(min, curTime);
out.println(min);
}
out.close();
}
static INPUT in = new INPUT(System.in);
static PrintWriter out = new PrintWriter(System.out);
private static class INPUT {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar, numChars;
public INPUT (InputStream stream) {
this.stream = stream;
}
public INPUT (String file) throws IOException {
this.stream = new FileInputStream (file);
}
public int cscan () throws IOException {
if (curChar >= numChars) {
curChar = 0;
numChars = stream.read (buf);
}
if (numChars == -1)
return numChars;
return buf[curChar++];
}
public int iscan () throws IOException {
int c = cscan (), sgn = 1;
while (space (c))
c = cscan ();
if (c == '-') {
sgn = -1;
c = cscan ();
}
int res = 0;
do {
res = (res << 1) + (res << 3);
res += c - '0';
c = cscan ();
}
while (!space (c));
return res * sgn;
}
public String sscan () throws IOException {
int c = cscan ();
while (space (c))
c = cscan ();
StringBuilder res = new StringBuilder ();
do {
res.appendCodePoint (c);
c = cscan ();
}
while (!space (c));
return res.toString ();
}
public double dscan () throws IOException {
int c = cscan (), sgn = 1;
while (space (c))
c = cscan ();
if (c == '-') {
sgn = -1;
c = cscan ();
}
double res = 0;
while (!space (c) && c != '.') {
if (c == 'e' || c == 'E')
return res * UTILITIES.fast_pow (10, iscan ());
res *= 10;
res += c - '0';
c = cscan ();
}
if (c == '.') {
c = cscan ();
double m = 1;
while (!space (c)) {
if (c == 'e' || c == 'E')
return res * UTILITIES.fast_pow (10, iscan ());
m /= 10;
res += (c - '0') * m;
c = cscan ();
}
}
return res * sgn;
}
public long lscan () throws IOException {
int c = cscan (), sgn = 1;
while (space (c))
c = cscan ();
if (c == '-') {
sgn = -1;
c = cscan ();
}
long res = 0;
do {
res = (res << 1) + (res << 3);
res += c - '0';
c = cscan ();
}
while (!space (c));
return res * sgn;
}
public boolean space (int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
public static class UTILITIES {
static final double EPS = 10e-6;
public static void sort(int[] a, boolean increasing) {
ArrayList<Integer> arr = new ArrayList<Integer>();
int n = a.length;
for (int i = 0; i < n; i++) {
arr.add(a[i]);
}
Collections.sort(arr);
for (int i = 0; i < n; i++) {
if (increasing) {
a[i] = arr.get(i);
}
else {
a[i] = arr.get(n-1-i);
}
}
}
public static void sort(long[] a, boolean increasing) {
ArrayList<Long> arr = new ArrayList<Long>();
int n = a.length;
for (int i = 0; i < n; i++) {
arr.add(a[i]);
}
Collections.sort(arr);
for (int i = 0; i < n; i++) {
if (increasing) {
a[i] = arr.get(i);
}
else {
a[i] = arr.get(n-1-i);
}
}
}
public static void sort(double[] a, boolean increasing) {
ArrayList<Double> arr = new ArrayList<Double>();
int n = a.length;
for (int i = 0; i < n; i++) {
arr.add(a[i]);
}
Collections.sort(arr);
for (int i = 0; i < n; i++) {
if (increasing) {
a[i] = arr.get(i);
}
else {
a[i] = arr.get(n-1-i);
}
}
}
public static int lower_bound (int[] arr, int x) {
int low = 0, high = arr.length, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] >= x)
high = mid;
else
low = mid + 1;
}
return low;
}
public static int upper_bound (int[] arr, int x) {
int low = 0, high = arr.length, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] > x)
high = mid;
else
low = mid + 1;
}
return low;
}
public static void updateMap(HashMap<Integer, Integer> map, int key, int v) {
if (!map.containsKey(key)) {
map.put(key, v);
}
else {
map.put(key, map.get(key) + v);
}
if (map.get(key) == 0) {
map.remove(key);
}
}
public static long gcd (long a, long b) {
return b == 0 ? a : gcd (b, a % b);
}
public static long lcm (long a, long b) {
return a * b / gcd (a, b);
}
public static long fast_pow_mod (long b, long x, int mod) {
if (x == 0) return 1;
if (x == 1) return b;
if (x % 2 == 0) return fast_pow_mod (b * b % mod, x / 2, mod) % mod;
return b * fast_pow_mod (b * b % mod, x / 2, mod) % mod;
}
public static long fast_pow (long b, long x) {
if (x == 0) return 1;
if (x == 1) return b;
if (x % 2 == 0) return fast_pow (b * b, x / 2);
return b * fast_pow (b * b, x / 2);
}
public static long choose (long n, long k) {
k = Math.min (k, n - k);
long val = 1;
for (int i = 0; i < k; ++i)
val = val * (n - i) / (i + 1);
return val;
}
public static long permute (int n, int k) {
if (n < k) return 0;
long val = 1;
for (int i = 0; i < k; ++i)
val = (val * (n - i));
return val;
}
// start of permutation and lower/upper bound template
public static void nextPermutation(int[] nums) {
//find first decreasing digit
int mark = -1;
for (int i = nums.length - 1; i > 0; i--) {
if (nums[i] > nums[i - 1]) {
mark = i - 1;
break;
}
}
if (mark == -1) {
reverse(nums, 0, nums.length - 1);
return;
}
int idx = nums.length-1;
for (int i = nums.length-1; i >= mark+1; i--) {
if (nums[i] > nums[mark]) {
idx = i;
break;
}
}
swap(nums, mark, idx);
reverse(nums, mark + 1, nums.length - 1);
}
public static void swap(int[] nums, int i, int j) {
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
public static void reverse(int[] nums, int i, int j) {
while (i < j) {
swap(nums, i, j);
i++;
j--;
}
}
static int lower_bound (int[] arr, int hi, int cmp) {
int low = 0, high = hi, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] >= cmp) high = mid;
else low = mid + 1;
}
return low;
}
static int upper_bound (int[] arr, int hi, int cmp) {
int low = 0, high = hi, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] > cmp) high = mid;
else low = mid + 1;
}
return low;
}
// end of permutation and lower/upper bound template
}
} | Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 11 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | c99f46f4ea6e2c0a8b6a6fd99e4b8a59 | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | import java.io.*;
import java.util.*;
public class Main implements Runnable {
int[][] a;
int m;
public void solve() throws IOException {
int t = readInt();
for (int tt = 0; tt < t; tt++) {
m = readInt();
a = new int[m][2];
for (int i = 0; i < m; i++) {
a[i][0] = readInt();
}
for (int i = 0; i < m; i++) {
a[i][1] = readInt();
}
a[0][0] = -1;
int[] last = new int[m + 2];
last[m - 1] = Math.max(a[m - 1][0] + 1, a[m - 1][1]);
for (int i = m - 2; i >= 0; i--) {
last[i] = Math.max(last[i + 1] - 1, Math.max(a[i][0] + 1, a[i][1] - (m - 1 - i) * 2));
}
int[] lastInverse = new int[m + 2];
lastInverse[m - 1] = Math.max(a[m - 1][1] + 1, a[m - 1][0]);
for (int i = m - 2; i >= 0; i--) {
lastInverse[i] = Math.max(lastInverse[i + 1] - 1, Math.max(a[i][1] + 1, a[i][0] - (m - 1 - i) * 2));
}
int min = Integer.MAX_VALUE;
int curmax = 0;
for (int i = 0; i < m; i += 2) {
min = Math.min(min, Math.max(curmax, last[i] - (i * 2)));
if (i < m - 1) {
int cur = 0;
cur = Math.max(cur, a[i][0] - (i * 2) + 1);
cur = Math.max(cur, a[i][1] - (i * 2));
cur = Math.max(cur, a[i + 1][1] - (i * 2) - 1);
cur = Math.max(cur, a[i + 1][0] - (i * 2) - 2);
curmax = Math.max(cur, curmax);
}
}
curmax = Math.max(a[0][0] + 1, a[0][1]);
for (int i = 1; i < m; i += 2) {
min = Math.min(min, Math.max(curmax, lastInverse[i] - (i * 2)));
if (i < m - 1) {
int cur = 0;
cur = Math.max(cur, a[i][1] - (i * 2) + 1);
cur = Math.max(cur, a[i][0] - (i * 2));
cur = Math.max(cur, a[i + 1][0] - (i * 2) - 1);
cur = Math.max(cur, a[i + 1][1] - (i * 2) - 2);
curmax = Math.max(cur, curmax);
}
}
min += m*2;
out.println(min - 1);
}
out.close();
}
/////////////////////////////////////////
boolean trackTime = false;
// int mod = 1000_000_007;
int mod = 998244353;
@Override
public void run() {
try {
if (ONLINE_JUDGE || !new File("input.txt").exists()) {
reader = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
reader = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
}
long time = 0;
if (trackTime) {
time = System.currentTimeMillis();
}
solve();
if (trackTime) {
out.println("time = " + (System.currentTimeMillis() - time));
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
reader.close();
} catch (IOException e) {
// nothing
}
out.close();
}
}
private String readString() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
@SuppressWarnings("unused")
private int readInt() throws IOException {
return Integer.parseInt(readString());
}
@SuppressWarnings("unused")
private long readLong() throws IOException {
return Long.parseLong(readString());
}
@SuppressWarnings("unused")
private double readDouble() throws IOException {
return Double.parseDouble(readString());
}
private BufferedReader reader;
private StringTokenizer tokenizer;
private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
private PrintWriter out;
public static void main(String[] args) {
new Thread(null, new Main(), "", 256 * (1L << 20)).start();
}
} | Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 11 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | c8b817a881b8043b773771e0c17f1e95 | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import java.util.StringTokenizer;
public class codeforces_Edu133_C {
private static void solve(FastIOAdapter in, PrintWriter out) {
int m = in.nextInt();
int[] a1 = in.readArray(m);
int[] a2 = in.readArray(m);
int a1end = a1[0], a2end = a2[0] + 1;
for (int i = 1; i < m; i++) {
a1end = Math.max(a1end, a1[i]) + 1;
a2end = Math.max(a2end, a2[i]) + 1;
}
int a1Change = Math.max(a1end, a2[m - 1]) + 1;
int a2Change = Math.max(a2end, a1[m - 1]) + 1;
int[] sufA1 = new int[m];
sufA1[m - 1] = a2Change;
int[] sufA2 = new int[m];
sufA2[m - 1] = a1Change;
for (int i = m - 2; i >= 0; i--) {
sufA1[i] = Math.max(sufA1[i + 1], a1[i]) + 1;
sufA2[i] = Math.max(sufA2[i + 1], a2[i]) + 1;
}
int ans = Integer.MAX_VALUE;
int cur = 0;
boolean up = true;
for (int i = 0; i < m; i++) {
int temp;
if (up) {
temp = sufA2[i];
} else {
temp = sufA1[i];
}
int freeWalk = cur + 2 * (m - i);
if (i == 0) freeWalk--;
ans = Math.min(ans, Math.max(temp, freeWalk));
if (up) {
if (i != 0)
cur = Math.max(a1[i], cur) + 1;
cur = Math.max(a2[i], cur) + 1;
} else {
cur = Math.max(a2[i], cur) + 1;
cur = Math.max(a1[i], cur) + 1;
}
up = !up;
}
ans = Math.min(ans, cur);
out.println(ans);
}
public static void main(String[] args) throws Exception {
try (FastIOAdapter ioAdapter = new FastIOAdapter()) {
int count = 1;
count = ioAdapter.nextInt();
while (count-- > 0) {
solve(ioAdapter, ioAdapter.out);
}
}
}
static void ruffleSort(int[] arr) {
int n = arr.length;
Random rnd = new Random();
for (int i = 0; i < n; ++i) {
int tmp = arr[i];
int randomPos = i + rnd.nextInt(n - i);
arr[i] = arr[randomPos];
arr[randomPos] = tmp;
}
Arrays.sort(arr);
}
static class FastIOAdapter implements AutoCloseable {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter((System.out))));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
String nextLine() {
try {
return br.readLine();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
long[] readArrayLong(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
@Override
public void close() throws Exception {
out.flush();
out.close();
br.close();
}
}
}
| Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 11 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | d7bf1bcd9ea440d48040fc2ed4355867 | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | import java.util.*;
import java.io.*;
public class _1716_C {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int t = Integer.parseInt(in.readLine());
while(t-- > 0) {
int m = Integer.parseInt(in.readLine());
int[][] grid = new int[2][m];
for(int i = 0; i < 2; i++) {
StringTokenizer line = new StringTokenizer(in.readLine());
for(int j = 0; j < m; j++) {
grid[i][j] = Integer.parseInt(line.nextToken()) + 1;
}
}
grid[0][0] = 0;
int min1 = minTime(grid, m);
int time = Math.max(grid[1][0] + 1, grid[1][1]);
int[][] grid2 = new int[2][m - 1];
for(int i = 0; i < 2; i++) {
for(int j = 1; j < m; j++) {
grid2[1 - i][j - 1] = Math.max(grid[i][j] - time, 0);
}
}
int min2 = minTime(grid2, m - 1);
out.println(Math.min(min1, min2 + time));
}
in.close();
out.close();
}
static int minTime(int[][] grid, int m) {
TreeSet<Point> barriers = new TreeSet<Point>();
Point[][] points = new Point[2][m];
for(int i = 0; i < m * 2; i++) {
if(i < m) {
points[0][i] = new Point(i, grid[0][i], i);
barriers.add(points[0][i]);
}else {
points[1][m * 2 - i - 1] = new Point(i, grid[1][m * 2 - i - 1], m * 3 - i - 1);
barriers.add(points[1][m * 2 - i - 1]);
}
}
int r = 0;
int c = 0;
int time = 0;
int best = Integer.MAX_VALUE;
for(int i = 0; i < m * 2; i++) {
if(i == 0 || i % 4 == 3) {
Point highest = barriers.last();
int dist = highest.x - c;
int endTime = time + (m * 2 - i - 1) + Math.max(0, highest.y - (time + dist));
best = Math.min(best, endTime);
}
barriers.remove(points[r][c]);
if(r == 0) {
if(i % 4 == 0) {
r++;
}else {
c++;
}
}else {
if(i % 4 == 1) {
c++;
}else {
r--;
}
}
if(i < m * 2 - 1) {
time = Math.max(time + 1, grid[r][c]);
}
}
return Math.min(best, time);
}
static class Point implements Comparable<Point> {
int x, y, id;
Point(int xx, int yy, int i) {
x = xx;
y = yy;
id = i;
}
@Override
public int compareTo(Point o) {
if(x - y == o.x - o.y) {
return id - o.id;
}
return y - x - (o.y - o.x);
}
}
}
| Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 11 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | 7821cfc50c821ef201de836c96aa3561 | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | import java.io.*;
import java.util.*;
public class Solution extends PrintWriter {
void solve() {
int t = sc.nextInt();
for(int tc = 1; tc <= t; tc++) {
test_case();
}
}
void test_case() {
int m = sc.nextInt();
int[][] grid = new int[2][m];
for(int i = 0; i < 2; i++) {
for(int j = 0; j < m; j++) grid[i][j] = sc.nextInt();
}
grid[0][0] = -1;
MaxQueue UD_U = new MaxQueue();
MaxQueue UD_D = new MaxQueue();
MaxQueue DU_D = new MaxQueue();
MaxQueue DU_U = new MaxQueue();
for(int i = 0; i < m; i++) {
UD_U.add(grid[0][i]-i);
UD_D.add(grid[1][i]-(2*m-1-i));
DU_D.add(grid[1][i]-i);
DU_U.add(grid[0][i]-(2*m-1-i));
}
long ans = 1L<<60;
long t = -1;
for(int i = 0; i < m; i++) {
if(i%2 == 0) {
long cur = t + 2*(m-i) - 1 + Math.max(max(UD_U, UD_D)-(t-i)+1, 0);
ans = Math.min(ans, cur);
t = Math.max(t, grid[1][i])+1;
if(i+1 < m) t = Math.max(t, grid[1][i+1])+1;
} else {
long cur = t + 2*(m-i) - 1 + Math.max(max(DU_U, DU_D)-(t-i)+1, 0);
ans = Math.min(ans, cur);
t = Math.max(t, grid[0][i])+1;
if(i+1 < m) t = Math.max(t, grid[0][i+1])+1;
}
UD_U.remove(); UD_D.remove();
DU_U.remove(); DU_D.remove();
}
ans = Math.min(ans, t);
println(ans);
}
int max(MaxQueue U, MaxQueue D) {
return (int)Math.max(U.max(), D.max());
}
class MaxQueue{
ArrayDeque<Long> queue = new ArrayDeque<Long>();
ArrayDeque<Long> max = new ArrayDeque<Long>();
void add(long x) {
queue.add(x);
while(!max.isEmpty() && x > max.getLast()) max.removeLast();
max.add(x);
}
long remove() {
long x = queue.remove();
if(max.getFirst() == x) max.remove();
return x;
}
long max() {
return max.getFirst();
}
}
// Solution() throws FileNotFoundException { super(new File("saida_6.txt")); }
// InputReader sc = new InputReader(new FileInputStream("saida5.txt"));
Solution() { super(System.out); }
InputReader sc = new InputReader(System.in);
static class InputReader {
InputReader(InputStream in) { this.in = in; } InputStream in;
private byte[] buf = new byte[16384];
private int curChar;
private int numChars;
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = in.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
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;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1 || c == ';' ;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
public static void main(String[] $) {
new Thread(null, new Runnable() {
public void run() {
long start = System.nanoTime();
try {Solution solution = new Solution(); solution.solve(); solution.flush();}
catch (Exception e) {e.printStackTrace(); System.exit(1);}
System.err.println((System.nanoTime()-start)/1E9);
}
}, "1", 1 << 27).start();
}
} | Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 11 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | 759577774f5597932772adee42557b73 | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.sort;
/*
* 11223456
*
*
*/
public class Codeforces {
static int max = (int) (2e5) + 5;
public static void main(String[] args) {
FastReader fastReader = new FastReader();
PrintWriter out = new PrintWriter(System.out);
int t = fastReader.nextInt();
while (t-- > 0) {
int n = fastReader.nextInt();
int a[][] = new int[2][n];
for (int i = 0; i <= 1; i++) {
for (int j = 0; j < n; j++) {
int x = fastReader.nextInt();
// out.print(x + " ");
a[i][j] = x + 1;
}
// out.println();
}
// out.println(Arrays.toString(a[0]));
// out.println(Arrays.toString(a[1]));
a[0][0] = 0;
long clk[] = new long[n];
long anti_clk[] = new long[n];
long cells = 2;
for (int i = n - 1; i >= 0; i--) {
if (i == n - 1) {
// out.println((a[0][i] + 1) + " " + a[1][i]);
clk[i] = max(a[0][i] + 1, a[1][i]);
anti_clk[i] = max(a[0][i], a[1][i] + 1);
} else {
cells += 2;
clk[i] = maxof(clk[i + 1] + 1, a[0][i] + cells - 1, a[1][i]);
anti_clk[i] = maxof(anti_clk[i + 1] + 1, a[1][i] + cells - 1, a[0][i]);
}
}
// out.println(Arrays.toString(clk));
// out.println(Arrays.toString(anti_clk));
// out.println(cells);
long ans = LMAX;
long curr_time = -1;
for (int i = 0; i < n; i++, cells -= 2) {
if ((i & 1) == 1) {
ans = min(ans, max(anti_clk[i], curr_time + cells));
curr_time = max(curr_time + 1, a[1][i]);
curr_time = max(curr_time + 1, a[0][i]);
} else {
ans = min(ans, max(clk[i], curr_time + cells));
curr_time = max(curr_time + 1, a[0][i]);
curr_time = max(curr_time + 1, a[1][i]);
}
}
out.println(ans);
}
out.close();
}
// constants
static final int IBIG = 1000000007;
static final int IMAX = 2147483647;
static final long LMAX = 9223372036854775807L;
static Random __r = new Random();
// math util
static int minof(int a, int b, int c) {
return min(a, min(b, c));
}
static int minof(int... x) {
if (x.length == 1)
return x[0];
if (x.length == 2)
return min(x[0], x[1]);
if (x.length == 3)
return min(x[0], min(x[1], x[2]));
int min = x[0];
for (int i = 1; i < x.length; ++i)
if (x[i] < min)
min = x[i];
return min;
}
static long minof(long a, long b, long c) {
return min(a, min(b, c));
}
static long minof(long... x) {
if (x.length == 1)
return x[0];
if (x.length == 2)
return min(x[0], x[1]);
if (x.length == 3)
return min(x[0], min(x[1], x[2]));
long min = x[0];
for (int i = 1; i < x.length; ++i)
if (x[i] < min)
min = x[i];
return min;
}
static int maxof(int a, int b, int c) {
return max(a, max(b, c));
}
static int maxof(int... x) {
if (x.length == 1)
return x[0];
if (x.length == 2)
return max(x[0], x[1]);
if (x.length == 3)
return max(x[0], max(x[1], x[2]));
int max = x[0];
for (int i = 1; i < x.length; ++i)
if (x[i] > max)
max = x[i];
return max;
}
static long maxof(long a, long b, long c) {
return max(a, max(b, c));
}
static long maxof(long... x) {
if (x.length == 1)
return x[0];
if (x.length == 2)
return max(x[0], x[1]);
if (x.length == 3)
return max(x[0], max(x[1], x[2]));
long max = x[0];
for (int i = 1; i < x.length; ++i)
if (x[i] > max)
max = x[i];
return max;
}
static int powi(int a, int b) {
if (a == 0)
return 0;
int ans = 1;
while (b > 0) {
if ((b & 1) > 0)
ans *= a;
a *= a;
b >>= 1;
}
return ans;
}
static long powl(long a, int b) {
if (a == 0)
return 0;
long ans = 1;
while (b > 0) {
if ((b & 1) > 0)
ans *= a;
a *= a;
b >>= 1;
}
return ans;
}
static int fli(double d) {
return (int) d;
}
static int cei(double d) {
return (int) ceil(d);
}
static long fll(double d) {
return (long) d;
}
static long cel(double d) {
return (long) ceil(d);
}
static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
static int lcm(int a, int b) {
return (a / gcd(a, b)) * b;
}
static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
static long lcm(long a, long b) {
return (a / gcd(a, b)) * b;
}
static int[] exgcd(int a, int b) {
if (b == 0)
return new int[] { 1, 0 };
int[] y = exgcd(b, a % b);
return new int[] { y[1], y[0] - y[1] * (a / b) };
}
static long[] exgcd(long a, long b) {
if (b == 0)
return new long[] { 1, 0 };
long[] y = exgcd(b, a % b);
return new long[] { y[1], y[0] - y[1] * (a / b) };
}
static int randInt(int min, int max) {
return __r.nextInt(max - min + 1) + min;
}
static long mix(long x) {
x += 0x9e3779b97f4a7c15L;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L;
x = (x ^ (x >> 27)) * 0x94d049bb133111ebL;
return x ^ (x >> 31);
}
public static boolean[] findPrimes(int limit) {
assert limit >= 2;
final boolean[] nonPrimes = new boolean[limit];
nonPrimes[0] = true;
nonPrimes[1] = true;
int sqrt = (int) Math.sqrt(limit);
for (int i = 2; i <= sqrt; i++) {
if (nonPrimes[i])
continue;
for (int j = i; j < limit; j += i) {
if (!nonPrimes[j] && i != j)
nonPrimes[j] = true;
}
}
return nonPrimes;
}
// array util
static void reverse(int[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
int swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void reverse(long[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
long swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void reverse(double[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
double swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void reverse(char[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
char swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void shuffle(int[] a) {
int n = a.length - 1;
for (int i = 0; i < n; ++i) {
int ind = randInt(i, n);
int swap = a[i];
a[i] = a[ind];
a[ind] = swap;
}
}
static void shuffle(long[] a) {
int n = a.length - 1;
for (int i = 0; i < n; ++i) {
int ind = randInt(i, n);
long swap = a[i];
a[i] = a[ind];
a[ind] = swap;
}
}
static void shuffle(double[] a) {
int n = a.length - 1;
for (int i = 0; i < n; ++i) {
int ind = randInt(i, n);
double swap = a[i];
a[i] = a[ind];
a[ind] = swap;
}
}
static void rsort(int[] a) {
shuffle(a);
sort(a);
}
static void rsort(long[] a) {
shuffle(a);
sort(a);
}
static void rsort(double[] a) {
shuffle(a);
sort(a);
}
static int[] copy(int[] a) {
int[] ans = new int[a.length];
for (int i = 0; i < a.length; ++i)
ans[i] = a[i];
return ans;
}
static long[] copy(long[] a) {
long[] ans = new long[a.length];
for (int i = 0; i < a.length; ++i)
ans[i] = a[i];
return ans;
}
static double[] copy(double[] a) {
double[] ans = new double[a.length];
for (int i = 0; i < a.length; ++i)
ans[i] = a[i];
return ans;
}
static char[] copy(char[] a) {
char[] ans = new char[a.length];
for (int i = 0; i < a.length; ++i)
ans[i] = a[i];
return ans;
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] ria(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = Integer.parseInt(next());
return a;
}
long nextLong() {
return Long.parseLong(next());
}
long[] rla(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = Long.parseLong(next());
return a;
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 11 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | c1ae3af2b5a029126b7c32b70074dbd1 | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.security.SecureRandom;
import java.util.InputMismatchException;
import java.util.Random;
import java.util.StringTokenizer;
public class AMain {
private QuickReader in;
private PrintWriter out;
public AMain(QuickReader in, PrintWriter out) {
this.in = in;
this.out = out;
}
public static void main(String[] args) throws IOException {
QuickReader in = new QuickReader(System.in);
try(PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));)
{
new AMain(in, out).solve();
}
}
private void solve() throws IOException {
int t = in.nextInt();
// Random rand = new SecureRandom();
while(t-->0)
{
int n = in.nextInt();
int[][] a = new int[2][];
a[0] = in.nextInts(n);
a[1] = in.nextInts(n);
// int n = 8;
// int[][] a = new int[2][n];
// for(int i=0;i<n;i++)
// a[0][i] = rand.nextInt(20);
// for(int i=0;i<n;i++)
// a[1][i] = rand.nextInt(20);
// a[0][0] = 0;
// int bruteRes = brutesolve(a);
for(int i=0;i<n;i++)
{
a[0][i]++;
a[1][i]++;
}
a[0][0]--;
int[][] aPlusI = new int[2][n+1];
int[][] aMinusI = new int[2][n+1];
for(int j=0;j<2;j++)
{
for(int i=0;i<n;i++)
{
aPlusI[j][i] = a[j][i] + i;
aMinusI[j][i] = a[j][i] - i;
}
aPlusI[j][n] = 0;
aMinusI[j][n] = 0;
for(int i=n-1;i>=0;i--)
{
aPlusI[j][i] = Math.max(aPlusI[j][i], aPlusI[j][i+1]);
aMinusI[j][i] = Math.max(aMinusI[j][i], aMinusI[j][i+1]);
}
}
int res = Integer.MAX_VALUE;
int cur = a[0][0] + 2*n-1;
for(int i=0;i<n;i++)
{
if(i%2 == 0)
{
res = Math.min(res,
Math.max(cur, Math.max(aMinusI[0][i] + 2*(n-i-1)+1 + i,
aPlusI[1][i] - i ) )
);
}
else
{
res = Math.min(res,
Math.max(cur, Math.max(aMinusI[1][i] + 2*(n-i-1)+1 + i,
aPlusI[0][i] - i ) )
);
}
if(i+1<n)
{
if(i%2 == 0)
{
cur = Math.max(cur, a[1][i] + 2*n-1 - 2*i-1);
cur = Math.max(cur, a[1][i+1] + 2*n-1 - 2*i-2);
}
else
{
cur = Math.max(cur, a[0][i] + 2*n-1 - 2*i-1);
cur = Math.max(cur, a[0][i+1] + 2*n-1 - 2*i-2);
}
}
}
out.println(res);
// if(res != bruteRes)
// {
// for(int i=0;i<n;i++)
// {
// a[0][i]--;
// a[1][i]--;
// }
// a[0][0]++;
// out.println(n);
// print(a[0]);
// print(a[1]);
// out.println(bruteRes);
// throw new IllegalStateException();
// }
}
}
void print(int[] a)
{
for(int i=0;i<a.length;i++)
{
if(i>0)
out.print(' ');
out.print(a[i]);
}
out.println();
}
public int brutesolve(int[][] a)
{
int n = a[0].length;
boolean[][] used = new boolean[2][n];
return recSolve(0, 0, 0, a, used);
}
public static int[] dx = {1,-1,0,0}, dy = {0,0,1,-1};
int floodCount(int x, int y, boolean[][] used)
{
if(used[x][y])
return 0;
int res = 1;
used[x][y] = true;
for(int i=0;i<4;i++)
{
int nx = x + dx[i];
int ny = y + dy[i];
if(0<=nx && nx < 2 && 0<=ny && ny < used[nx].length)
res += floodCount(nx, ny, used);
}
return res;
}
int recSolve(int curt,int x, int y, int[][] a, boolean[][] used)
{
int n = a[0].length;
int cnt = floodCount(x, y, new boolean[][] {used[0].clone(), used[1].clone()});
for(int i=0;i<n;i++)
{
if(!used[0][i])
cnt--;
if(!used[1][i])
cnt--;
}
if(cnt != 0)
return Integer.MAX_VALUE;
used[x][y] = true;
boolean isDone = true;
for(int i=0;i<n;i++)
if(!used[0][i] || !used[1][i])
isDone = false;
if(isDone)
{
used[x][y] = false;
return curt;
}
int res = Integer.MAX_VALUE;
for(int i=0;i<4;i++)
{
int nx = x + dx[i];
int ny = y + dy[i];
if(0<=nx && nx < 2 && 0<=ny && ny < n && !used[nx][ny])
res = Math.min(res, recSolve(Math.max(curt, a[nx][ny])+1, nx, ny, a, used));
}
used[x][y] = false;
return res;
}
}
class QuickReader
{
BufferedReader in;
StringTokenizer token;
public QuickReader(InputStream ins)
{
in=new BufferedReader(new InputStreamReader(ins));
token=new StringTokenizer("");
}
public boolean hasNext()
{
while (!token.hasMoreTokens())
{
try
{
String s = in.readLine();
if (s == null) return false;
token = new StringTokenizer(s);
} catch (IOException e)
{
throw new InputMismatchException();
}
}
return true;
}
public String next()
{
hasNext();
return token.nextToken();
}
public double nextDouble()
{
return Double.parseDouble(next());
}
public int nextInt()
{
return Integer.parseInt(next());
}
public int[] nextInts(int n)
{
int[] res = new int[n];
for (int i = 0; i < n; i++)
res[i] = nextInt();
return res;
}
public long nextLong() {
return Long.parseLong(next());
}
public long[] nextLongs(int n)
{
long[] res = new long[n];
for (int i = 0; i < n; i++)
res[i] = nextLong();
return res;
}
}
| Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 11 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | d565d12d2b29ce6aa2a4edf72097f621 | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | import java.util.*;
import java.io.*;
public class codeforce {
static boolean multipleTC = true;
final static int Mod = 1000000007;
final static int Mod2 = 998244353;
final double PI = 3.14159265358979323846;
int MAX = 1000000007;
void pre() throws Exception {
}
long combination(int n, int r, long fact[], long ifact[]) {
long val1 = fact[n];
long val2 = ifact[(n - r)];
long val3 = ifact[r];
return (((val1 * val2) % Mod) * val3) % Mod;
}
long expo(long a, long b, long mod) {
long res = 1;
while (b != 0) {
if ((b & 1) == 1)
res = (res * a) % mod;
a = (a * a) % mod;
b >>= 1;
}
return res;
}
long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
long mminvprime(long a, long b) {
return expo(a, b - 2, b);
}
void solve(int t) throws Exception {
int m = ni();
long cells = 2, ans = Long.MAX_VALUE;
long arr[][] = new long[2][m];
for(int i=0;i<2;i++) {
for(int j=0;j<m;j++) {
arr[i][j] = nl();
arr[i][j]++;
}
}
arr[0][0] = 0;
long clk[] = new long[m];
long ant_clk[] = new long[m];
clk[m-1] = Math.max(arr[0][m-1]+1, arr[1][m-1]);
ant_clk[m-1] = Math.max(arr[1][m-1]+1, arr[0][m-1]);
for(int i=m-2;i>=0;i--) {
cells += 2;
clk[i] = Math.max(clk[i+1]+1, Math.max(arr[0][i]+cells-1, arr[1][i]));
ant_clk[i] = Math.max(ant_clk[i+1]+1, Math.max(arr[1][i]+cells-1, arr[0][i]));
}
long currtime = -1;
for(int i=0;i<m;i++,cells-=2) {
if(i%2 == 0) {
ans = Math.min(ans, Math.max(currtime+cells, clk[i]));
currtime = Math.max(currtime+1, arr[0][i]);
currtime = Math.max(currtime+1, arr[1][i]);
}
else {
ans = Math.min(ans, Math.max(currtime+cells, ant_clk[i]));
currtime = Math.max(currtime+1, arr[1][i]);
currtime = Math.max(currtime+1, arr[0][i]);
}
}
pn(ans);
}
double dist(int x1, int y1, int x2, int y2) {
double a = x1 - x2, b = y1 - y2;
return Math.sqrt((a * a) + (b * b));
}
long xor_sum_upton(long n) {
if (n % 4 == 0)
return n;
if (n % 4 == 1)
return 1;
if (n % 4 == 2)
return n + 1;
return 0;
}
int[] readArr(int n) throws Exception {
int arr[] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = ni();
}
return arr;
}
void sort(int arr[], int left, int right) {
ArrayList<Integer> list = new ArrayList<>();
for (int i = left; i <= right; i++)
list.add(arr[i]);
Collections.sort(list);
for (int i = left; i <= right; i++)
arr[i] = list.get(i - left);
}
void sort(int arr[]) {
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < arr.length; i++)
list.add(arr[i]);
Collections.sort(list);
for (int i = 0; i < arr.length; i++)
arr[i] = list.get(i);
}
public long max(long... arr) {
long max = arr[0];
for (long itr : arr)
max = Math.max(max, itr);
return max;
}
public int max(int... arr) {
int max = arr[0];
for (int itr : arr)
max = Math.max(max, itr);
return max;
}
public long min(long... arr) {
long min = arr[0];
for (long itr : arr)
min = Math.min(min, itr);
return min;
}
public int min(int... arr) {
int min = arr[0];
for (int itr : arr)
min = Math.min(min, itr);
return min;
}
public long sum(long... arr) {
long sum = 0;
for (long itr : arr)
sum += itr;
return sum;
}
public long sum(int... arr) {
long sum = 0;
for (int itr : arr)
sum += itr;
return sum;
}
String bin(long n) {
return Long.toBinaryString(n);
}
String bin(int n) {
return Integer.toBinaryString(n);
}
static int bitCount(int x) {
return x == 0 ? 0 : (1 + bitCount(x & (x - 1)));
}
static void dbg(Object... o) {
System.err.println(Arrays.deepToString(o));
}
int bit(long n) {
return (n == 0) ? 0 : (1 + bit(n & (n - 1)));
}
int abs(int a) {
return (a < 0) ? -a : a;
}
long abs(long a) {
return (a < 0) ? -a : a;
}
void p(Object o) {
out.print(o);
}
void pn(Object o) {
out.println(o);
}
void pni(Object o) {
out.println(o);
out.flush();
}
void pn(int[] arr) {
int n = arr.length;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(arr[i] + " ");
}
pn(sb);
}
void pn(long[] arr) {
int n = arr.length;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(arr[i] + " ");
}
pn(sb);
}
String n() throws Exception {
return in.next();
}
String nln() throws Exception {
return in.nextLine();
}
char c() throws Exception {
return in.next().charAt(0);
}
int ni() throws Exception {
return Integer.parseInt(in.next());
}
long nl() throws Exception {
return Long.parseLong(in.next());
}
double nd() throws Exception {
return Double.parseDouble(in.next());
}
public static void main(String[] args) throws Exception {
new codeforce().run();
}
FastReader in;
PrintWriter out;
void run() throws Exception {
in = new FastReader();
out = new PrintWriter(System.out);
int T = (multipleTC) ? ni() : 1;
pre();
for (int t = 1; t <= T; t++)
solve(t);
out.flush();
out.close();
}
class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws Exception {
br = new BufferedReader(new FileReader(s));
}
String next() throws Exception {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new Exception(e.toString());
}
}
return st.nextToken();
}
String nextLine() throws Exception {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
throw new Exception(e.toString());
}
return str;
}
}
} | Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 11 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | 7f979dfe6d7c799fb57c8724125f3279 | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | import java.io.*;
import java.text.DecimalFormat;
import java.util.*;
public class UWI {
//#0.00代表保留两位小数
static DecimalFormat df = new DecimalFormat("#0.00000000");
void solve() {
for (int T = ni(); T > 0; T--) go();
}
void go() {
int n = ni();
int[][] nums = new int[n + 1][2];
for (int k = 0; k < 2; k++) {
for (int i = 1; i <= n; i++) {
nums[i][k] = ni();
}
}
nums[1][0] = -1;
int[][] dp = new int[n + 1][2];// 从位置i ']'形状 完成的最小时间 从上面/下面开始
// n
dp[n][1] = Math.max(nums[n][1] + 2, nums[n][0] + 1);
dp[n][0] = Math.max(nums[n][0] + 2, nums[n][1] + 1);
for (int i = n - 1; i > 0; i--) {
for (int s = 0; s < 2; s++)
dp[i][s] = Math.max(
Math.max(nums[i][s] + 2 * (n - i + 1), dp[i + 1][s] + 1),
nums[i][s ^ 1] + 1);
}
//全部走 ]
int ans = dp[1][0];
//左边走s 右边走 ]
int t = -1;
for (int i = 1; i <= n; i++) {
int s = i % 2 == 1 ? 0 : 1;
t = Math.max(t + 1, nums[i][s] + 1);
t = Math.max(t + 1, nums[i][s ^ 1] + 1);
if (i < n)
ans = Math.min(ans, Math.max(t + 2 * (n - i), dp[i + 1][s ^ 1]));
else //全部走s
ans = Math.min(ans, t);
}
out.println(ans);
}
public static void main(String[] args) throws Exception {
new UWI().run();
}
void run() throws Exception {
if (INPUT.length() > 0)
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
else is = oj ? System.in : new ByteArrayInputStream(new FileInputStream("input/a.test").readAllBytes());
out = new FastWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis() - s + "ms");
}
InputStream is;
FastWriter out;
String INPUT = "";
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 String nextLine() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b) && b != ' ')) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = ni();
return a;
}
private long[] nal(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nl();
return a;
}
//二维数组
private char[][] nm(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++) map[i] = ns(m);
return map;
}
private int[][] nmi(int n, int m) {
int[][] map = new int[n][];
for (int i = 0; i < n; i++) map[i] = na(m);
return map;
}
//int
private int ni() {
return (int) nl();
}
//long
private long nl() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
public static class FastWriter {
private static final int BUF_SIZE = 1 << 13;
private final byte[] buf = new byte[BUF_SIZE];
private final OutputStream out;
private int ptr = 0;
private FastWriter() {
out = null;
}
public FastWriter(OutputStream os) {
this.out = os;
}
public FastWriter(String path) {
try {
this.out = new FileOutputStream(path);
} catch (FileNotFoundException e) {
throw new RuntimeException("FastWriter");
}
}
public FastWriter write(byte b) {
buf[ptr++] = b;
if (ptr == BUF_SIZE) innerflush();
return this;
}
public FastWriter write(char c) {
return write((byte) c);
}
public FastWriter write(char[] s) {
for (char c : s) {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
}
return this;
}
public FastWriter write(String s) {
s.chars().forEach(c -> {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
});
return this;
}
private static int countDigits(int l) {
if (l >= 1000000000) return 10;
if (l >= 100000000) return 9;
if (l >= 10000000) return 8;
if (l >= 1000000) return 7;
if (l >= 100000) return 6;
if (l >= 10000) return 5;
if (l >= 1000) return 4;
if (l >= 100) return 3;
if (l >= 10) return 2;
return 1;
}
public FastWriter write(int x) {
if (x == Integer.MIN_VALUE) {
return write((long) x);
}
if (ptr + 12 >= BUF_SIZE) innerflush();
if (x < 0) {
write((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
private static int countDigits(long l) {
if (l >= 1000000000000000000L) return 19;
if (l >= 100000000000000000L) return 18;
if (l >= 10000000000000000L) return 17;
if (l >= 1000000000000000L) return 16;
if (l >= 100000000000000L) return 15;
if (l >= 10000000000000L) return 14;
if (l >= 1000000000000L) return 13;
if (l >= 100000000000L) return 12;
if (l >= 10000000000L) return 11;
if (l >= 1000000000L) return 10;
if (l >= 100000000L) return 9;
if (l >= 10000000L) return 8;
if (l >= 1000000L) return 7;
if (l >= 100000L) return 6;
if (l >= 10000L) return 5;
if (l >= 1000L) return 4;
if (l >= 100L) return 3;
if (l >= 10L) return 2;
return 1;
}
public FastWriter write(long x) {
if (x == Long.MIN_VALUE) {
return write("" + x);
}
if (ptr + 21 >= BUF_SIZE) innerflush();
if (x < 0) {
write((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
public FastWriter write(double x, int precision) {
if (x < 0) {
write('-');
x = -x;
}
x += Math.pow(10, -precision) / 2;
// if(x < 0){ x = 0; }
write((long) x).write(".");
x -= (long) x;
for (int i = 0; i < precision; i++) {
x *= 10;
write((char) ('0' + (int) x));
x -= (int) x;
}
return this;
}
public FastWriter writeln(char c) {
return write(c).writeln();
}
public FastWriter writeln(int x) {
return write(x).writeln();
}
public FastWriter writeln(long x) {
return write(x).writeln();
}
public FastWriter writeln(double x, int precision) {
return write(x, precision).writeln();
}
public FastWriter write(int... xs) {
boolean first = true;
for (int x : xs) {
if (!first) write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter write(long... xs) {
boolean first = true;
for (long x : xs) {
if (!first) write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter writeln() {
return write((byte) '\n');
}
public FastWriter writeln(int... xs) {
return write(xs).writeln();
}
public FastWriter writeln(long... xs) {
return write(xs).writeln();
}
public FastWriter writeln(char[] line) {
return write(line).writeln();
}
public FastWriter writeln(char[]... map) {
for (char[] line : map) write(line).writeln();
return this;
}
public FastWriter writeln(String s) {
return write(s).writeln();
}
private void innerflush() {
try {
out.write(buf, 0, ptr);
ptr = 0;
} catch (IOException e) {
throw new RuntimeException("innerflush");
}
}
public void flush() {
innerflush();
try {
out.flush();
} catch (IOException e) {
throw new RuntimeException("flush");
}
}
public FastWriter print(byte b) {
return write(b);
}
public FastWriter print(char c) {
return write(c);
}
public FastWriter print(char[] s) {
return write(s);
}
public FastWriter print(String s) {
return write(s);
}
public FastWriter print(int x) {
return write(x);
}
public FastWriter print(long x) {
return write(x);
}
public FastWriter print(double x, int precision) {
return write(x, precision);
}
public FastWriter println(char c) {
return writeln(c);
}
public FastWriter println(int x) {
return writeln(x);
}
public FastWriter println(long x) {
return writeln(x);
}
public FastWriter println(double x, int precision) {
return writeln(x, precision);
}
public FastWriter print(int... xs) {
return write(xs);
}
public FastWriter print(long... xs) {
return write(xs);
}
public FastWriter println(int... xs) {
return writeln(xs);
}
public FastWriter println(long... xs) {
return writeln(xs);
}
public FastWriter println(char[] line) {
return writeln(line);
}
public FastWriter println(char[]... map) {
return writeln(map);
}
public FastWriter println(String s) {
return writeln(s);
}
public FastWriter println() {
return writeln();
}
}
//打印非零?
public void trnz(int... o) {
for (int i = 0; i < o.length; i++) if (o[i] != 0) System.out.print(i + ":" + o[i] + " ");
System.out.println();
}
// print ids which are 1
public void trt(long... o) {
Queue<Integer> stands = new ArrayDeque<>();
for (int i = 0; i < o.length; i++) {
for (long x = o[i]; x != 0; x &= x - 1) stands.add(i << 6 | Long.numberOfTrailingZeros(x));
}
System.out.println(stands);
}
public void tf(boolean... r) {
for (boolean x : r) System.out.print(x ? '#' : '.');
System.out.println();
}
public void tf(boolean[]... b) {
for (boolean[] r : b) {
for (boolean x : r) System.out.print(x ? '#' : '.');
System.out.println();
}
System.out.println();
}
public void tf(long[]... b) {
if (INPUT.length() != 0) {
for (long[] r : b) {
for (long x : r) {
for (int i = 0; i < 64; i++) {
System.out.print(x << ~i < 0 ? '#' : '.');
}
}
System.out.println();
}
System.out.println();
}
}
public void tf(long... b) {
if (INPUT.length() != 0) {
for (long x : b) {
for (int i = 0; i < 64; i++) {
System.out.print(x << ~i < 0 ? '#' : '.');
}
}
System.out.println();
}
}
private final boolean oj = !local();
boolean local() {
try {
String user = System.getProperty("user.name");
return user.contains("dpz");
} catch (Exception ignored) {
}
return false;
}
//调试的时候打印
private void tr(Object... o) {
if (!oj) System.out.println(Arrays.deepToString(o));
}
}
| Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 11 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | 8bd23873c167bc44b54fcae27aca65d8 | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | // JAI SHREE RAM, HAR HAR MAHADEV, HARE KRISHNA
import java.util.*;
import java.util.Map.Entry;
import java.util.stream.*;
import java.lang.*;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.io.*;
public class CodeForces {
static private final String INPUT = "input.txt";
static private final String OUTPUT = "output.txt";
static BufferedReader BR = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer ST;
static PrintWriter out = new PrintWriter(System.out);
static DecimalFormat df = new DecimalFormat("0.00");
final static int MAX = Integer.MAX_VALUE, MIN = Integer.MIN_VALUE, mod = (int) (1e9 + 7);
final static long LMAX = Long.MAX_VALUE, LMIN = Long.MIN_VALUE;
final static long INF = (long) 1e18, Neg_INF = (long) -1e18;
static Random rand = new Random();
// ======================= MAIN ==================================
public static void main(String[] args) throws IOException {
long time = System.currentTimeMillis();
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
// ==== start ====
input();
preprocess();
int t = 1;
t = readInt();
while (t-- > 0) {
solve();
}
out.flush();
// ==== end ====
if (!oj)
System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" }));
}
private static void solve() throws IOException {
int n = readInt();
int[][] arr = read2DIntArray(2, n), dp = new int[2][n];
for (int i = 0; i < n; i++) {
if (arr[0][i] == 0)
arr[0][i] = -1;
if (arr[1][i] == 0)
arr[1][i] = -1;
}
dp[0][n - 1] = Math.max(arr[0][n - 1] + 2, arr[1][n - 1] + 1);
dp[1][n - 1] = Math.max(arr[1][n - 1] + 2, arr[0][n - 1] + 1);
for (int i = n - 2; i >= 0; i--) {
dp[0][i] = Math.max(dp[0][i + 1] + 1, Math.max(arr[0][i] + 2 * (n - i), arr[1][i] + 1));
dp[1][i] = Math.max(dp[1][i + 1] + 1, Math.max(arr[1][i] + 2 * (n - i), arr[0][i] + 1));
}
int ans = MAX, curr = -1;
for (int i = 0; i < n; i++) {
if ((i & 1) == 0) {
ans = Math.min(ans, Math.max(dp[0][i], curr + 2 * (n - i)));
curr = Math.max(curr + 2, Math.max(arr[0][i] + 2, arr[1][i] + 1));
} else {
ans = Math.min(ans, Math.max(dp[1][i], curr + 2 * (n - i)));
curr = Math.max(curr + 2, Math.max(arr[1][i] + 2, arr[0][i] + 1));
}
}
out.println(ans);
}
private static void preprocess() throws IOException {
}
// cd C:\Users\Eshan Bhatt\Visual Studio Code\Competitive Programming\CodeForces
// javac CodeForces.java && java CodeForces
// change Stack size -> java -Xss16M CodeForces.java
// ==================== CUSTOM CLASSES ================================
static class Pair implements Comparable<Pair> {
int first, second;
Pair(int f, int s) {
first = f;
second = s;
}
public int compareTo(Pair o) {
if (this.first == o.first)
return this.second - o.second;
return this.first - o.first;
}
@Override
public boolean equals(Object obj) {
if (obj == this)
return true;
if (obj == null)
return false;
if (this.getClass() != obj.getClass())
return false;
Pair other = (Pair) (obj);
if (this.first != other.first)
return false;
if (this.second != other.second)
return false;
return true;
}
@Override
public int hashCode() {
return this.first ^ this.second;
}
@Override
public String toString() {
return this.first + " " + this.second;
}
}
static class DequeNode {
DequeNode prev, next;
int val;
DequeNode(int val) {
this.val = val;
}
DequeNode(int val, DequeNode prev, DequeNode next) {
this.val = val;
this.prev = prev;
this.next = next;
}
}
// ======================= FOR INPUT ==================================
private static void input() {
FileInputStream instream = null;
PrintStream outstream = null;
try {
instream = new FileInputStream(INPUT);
outstream = new PrintStream(new FileOutputStream(OUTPUT));
System.setIn(instream);
System.setOut(outstream);
} catch (Exception e) {
System.err.println("Error Occurred.");
}
BR = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
static String next() throws IOException {
while (ST == null || !ST.hasMoreTokens())
ST = new StringTokenizer(readLine());
return ST.nextToken();
}
static long readLong() throws IOException {
return Long.parseLong(next());
}
static int readInt() throws IOException {
return Integer.parseInt(next());
}
static double readDouble() throws IOException {
return Double.parseDouble(next());
}
static char readCharacter() throws IOException {
return next().charAt(0);
}
static String readString() throws IOException {
return next();
}
static String readLine() throws IOException {
return BR.readLine().trim();
}
static int[] readIntArray(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = readInt();
return arr;
}
static int[][] read2DIntArray(int n, int m) throws IOException {
int[][] arr = new int[n][m];
for (int i = 0; i < n; i++)
arr[i] = readIntArray(m);
return arr;
}
static List<Integer> readIntList(int n) throws IOException {
List<Integer> list = new ArrayList<>(n);
for (int i = 0; i < n; i++)
list.add(readInt());
return list;
}
static long[] readLongArray(int n) throws IOException {
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = readLong();
return arr;
}
static long[][] read2DLongArray(int n, int m) throws IOException {
long[][] arr = new long[n][m];
for (int i = 0; i < n; i++)
arr[i] = readLongArray(m);
return arr;
}
static List<Long> readLongList(int n) throws IOException {
List<Long> list = new ArrayList<>(n);
for (int i = 0; i < n; i++)
list.add(readLong());
return list;
}
static char[] readCharArray() throws IOException {
return readString().toCharArray();
}
static char[][] readMatrix(int n, int m) throws IOException {
char[][] mat = new char[n][m];
for (int i = 0; i < n; i++)
mat[i] = readCharArray();
return mat;
}
// ========================= FOR OUTPUT ==================================
private static void printIList(List<Integer> list) {
for (int i = 0; i < list.size(); i++)
out.print(list.get(i) + " ");
out.println(" ");
}
private static void printLList(List<Long> list) {
for (int i = 0; i < list.size(); i++)
out.print(list.get(i) + " ");
out.println(" ");
}
private static void printIArray(int[] arr) {
for (int i = 0; i < arr.length; i++)
out.print(arr[i] + " ");
out.println(" ");
}
private static void print2DIArray(int[][] arr) {
for (int i = 0; i < arr.length; i++)
printIArray(arr[i]);
}
private static void printLArray(long[] arr) {
for (int i = 0; i < arr.length; i++)
out.print(arr[i] + " ");
out.println(" ");
}
private static void print2DLArray(long[][] arr) {
for (int i = 0; i < arr.length; i++)
printLArray(arr[i]);
}
private static void yes() {
out.println("YES");
}
private static void no() {
out.println("NO");
}
// ====================== TO CHECK IF STRING IS NUMBER ========================
private static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch (NumberFormatException e) {
return false;
} catch (NullPointerException e) {
return false;
}
return true;
}
private static boolean isLong(String s) {
try {
Long.parseLong(s);
} catch (NumberFormatException e) {
return false;
} catch (NullPointerException e) {
return false;
}
return true;
}
// ==================== FASTER SORT ================================
private static void sort(int[] arr) {
int n = arr.length;
List<Integer> list = new ArrayList<>(n);
for (int i = 0; i < n; i++)
list.add(arr[i]);
Collections.sort(list);
for (int i = 0; i < n; i++)
arr[i] = list.get(i);
}
private static void reverseSort(int[] arr) {
int n = arr.length;
List<Integer> list = new ArrayList<>(n);
for (int i = 0; i < n; i++)
list.add(arr[i]);
Collections.sort(list, Collections.reverseOrder());
for (int i = 0; i < n; i++)
arr[i] = list.get(i);
}
private static void sort(long[] arr) {
int n = arr.length;
List<Long> list = new ArrayList<>(n);
for (int i = 0; i < n; i++)
list.add(arr[i]);
Collections.sort(list);
for (int i = 0; i < n; i++)
arr[i] = list.get(i);
}
private static void reverseSort(long[] arr) {
int n = arr.length;
List<Long> list = new ArrayList<>(n);
for (int i = 0; i < n; i++)
list.add(arr[i]);
Collections.sort(list, Collections.reverseOrder());
for (int i = 0; i < n; i++)
arr[i] = list.get(i);
}
// ==================== MATHEMATICAL FUNCTIONS ===========================
private static int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
private static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
private static int lcm(int a, int b) {
return (a / gcd(a, b)) * b;
}
private static long lcm(long a, long b) {
return (a / gcd(a, b)) * b;
}
private static int mod_pow(long a, long b, int mod) {
if (b == 0)
return 1;
int temp = mod_pow(a, b >> 1, mod);
temp %= mod;
temp = (int) ((1L * temp * temp) % mod);
if ((b & 1) == 1)
temp = (int) ((1L * temp * a) % mod);
return temp;
}
private static long multiply(long a, long b) {
return (((a % mod) * (b % mod)) % mod);
}
private static long divide(long a, long b) {
return multiply(a, mod_pow(b, mod - 2, mod));
}
private static boolean isPrime(long n) {
for (long i = 2; i * i <= n; i++)
if (n % i == 0)
return false;
return true;
}
private static long nCr(long n, long r) {
if (n - r > r)
r = n - r;
long ans = 1L;
for (long i = r + 1; i <= n; i++)
ans *= i;
for (long i = 2; i <= n - r; i++)
ans /= i;
return ans;
}
private static List<Integer> factors(int n) {
List<Integer> list = new ArrayList<>();
for (int i = 1; 1L * i * i <= n; i++)
if (n % i == 0) {
list.add(i);
if (i != n / i)
list.add(n / i);
}
return list;
}
private static List<Long> factors(long n) {
List<Long> list = new ArrayList<>();
for (long i = 1; i * i <= n; i++)
if (n % i == 0) {
list.add(i);
if (i != n / i)
list.add(n / i);
}
return list;
}
// ==================== Primes using Seive =====================
private static List<Integer> getPrimes(int n) {
boolean[] prime = new boolean[n + 1];
Arrays.fill(prime, true);
for (int i = 2; 1L * i * i <= n; i++)
if (prime[i])
for (int j = i * i; j <= n; j += i)
prime[j] = false;
// return prime;
List<Integer> list = new ArrayList<>();
for (int i = 2; i <= n; i++)
if (prime[i])
list.add(i);
return list;
}
private static int[] SeivePrime(int n) {
int[] primes = new int[n];
for (int i = 0; i < n; i++)
primes[i] = i;
for (int i = 2; 1L * i * i < n; i++) {
if (primes[i] != i)
continue;
for (int j = i * i; j < n; j += i)
if (primes[j] == j)
primes[j] = i;
}
return primes;
}
// ==================== STRING FUNCTIONS ================================
private static boolean isPalindrome(String str) {
int i = 0, j = str.length() - 1;
while (i < j)
if (str.charAt(i++) != str.charAt(j--))
return false;
return true;
}
// check if a is subsequence of b
private static boolean isSubsequence(String a, String b) {
int idx = 0;
for (int i = 0; i < b.length() && idx < a.length(); i++)
if (a.charAt(idx) == b.charAt(i))
idx++;
return idx == a.length();
}
private static String reverseString(String str) {
StringBuilder sb = new StringBuilder(str);
return sb.reverse().toString();
}
private static String sortString(String str) {
int[] arr = new int[256];
for (char ch : str.toCharArray())
arr[ch]++;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 256; i++)
while (arr[i]-- > 0)
sb.append((char) i);
return sb.toString();
}
// ==================== LIS & LNDS ================================
private static int LIS(int arr[], int n) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
int idx = find1(list, arr[i]);
if (idx < list.size())
list.set(idx, arr[i]);
else
list.add(arr[i]);
}
return list.size();
}
private static int find1(List<Integer> list, int val) {
int ret = list.size(), i = 0, j = list.size() - 1;
while (i <= j) {
int mid = (i + j) / 2;
if (list.get(mid) >= val) {
ret = mid;
j = mid - 1;
} else {
i = mid + 1;
}
}
return ret;
}
private static int LNDS(int[] arr, int n) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
int idx = find2(list, arr[i]);
if (idx < list.size())
list.set(idx, arr[i]);
else
list.add(arr[i]);
}
return list.size();
}
private static int find2(List<Integer> list, int val) {
int ret = list.size(), i = 0, j = list.size() - 1;
while (i <= j) {
int mid = (i + j) / 2;
if (list.get(mid) <= val) {
i = mid + 1;
} else {
ret = mid;
j = mid - 1;
}
}
return ret;
}
// =============== Lower Bound & Upper Bound ===========
// less than or equal
private static int lower_bound(List<Integer> list, int val) {
int ans = -1, lo = 0, hi = list.size() - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (list.get(mid) <= val) {
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return ans;
}
private static int lower_bound(List<Long> list, long val) {
int ans = -1, lo = 0, hi = list.size() - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (list.get(mid) <= val) {
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return ans;
}
private static int lower_bound(int[] arr, int val) {
int ans = -1, lo = 0, hi = arr.length - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid] <= val) {
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return ans;
}
private static int lower_bound(long[] arr, long val) {
int ans = -1, lo = 0, hi = arr.length - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid] <= val) {
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return ans;
}
// greater than or equal
private static int upper_bound(List<Integer> list, int val) {
int ans = list.size(), lo = 0, hi = ans - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (list.get(mid) >= val) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return ans;
}
private static int upper_bound(List<Long> list, long val) {
int ans = list.size(), lo = 0, hi = ans - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (list.get(mid) >= val) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return ans;
}
private static int upper_bound(int[] arr, int val) {
int ans = arr.length, lo = 0, hi = ans - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid] >= val) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return ans;
}
private static int upper_bound(long[] arr, long val) {
int ans = arr.length, lo = 0, hi = ans - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid] >= val) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return ans;
}
// ==================== UNION FIND =====================
private static int find(int x, int[] parent) {
if (parent[x] == x)
return x;
return parent[x] = find(parent[x], parent);
}
private static boolean union(int x, int y, int[] parent, int[] rank) {
int lx = find(x, parent), ly = find(y, parent);
if (lx == ly)
return false;
if (rank[lx] > rank[ly])
parent[ly] = lx;
else if (rank[lx] < rank[ly])
parent[lx] = ly;
else {
parent[lx] = ly;
rank[ly]++;
}
return true;
}
// ==================== TRIE ================================
static class Trie {
class Node {
Node[] children;
boolean isEnd;
Node() {
children = new Node[26];
}
}
Node root;
Trie() {
root = new Node();
}
boolean insert(String word) {
Node curr = root;
boolean ans = true;
for (char ch : word.toCharArray()) {
if (curr.children[ch - 'a'] == null)
curr.children[ch - 'a'] = new Node();
curr = curr.children[ch - 'a'];
if (curr.isEnd)
ans = false;
}
curr.isEnd = true;
return ans;
}
boolean find(String word) {
Node curr = root;
for (char ch : word.toCharArray()) {
if (curr.children[ch - 'a'] == null)
return false;
curr = curr.children[ch - 'a'];
}
return curr.isEnd;
}
}
// ================== SEGMENT TREE (RANGE SUM & RANGE UPDATE) ==================
public static class SegmentTree {
int n;
long[] arr, tree, lazy;
SegmentTree(long arr[]) {
this.arr = arr;
this.n = arr.length;
this.tree = new long[(n << 2)];
this.lazy = new long[(n << 2)];
build(1, 0, n - 1);
}
void build(int id, int start, int end) {
if (start == end)
tree[id] = arr[start];
else {
int mid = (start + end) / 2, left = (id << 1), right = left + 1;
build(left, start, mid);
build(right, mid + 1, end);
tree[id] = tree[left] + tree[right];
}
}
void update(int l, int r, long val) {
update(1, 0, n - 1, l, r, val);
}
void update(int id, int start, int end, int l, int r, long val) {
distribute(id, start, end);
if (end < l || r < start)
return;
if (start == end)
tree[id] += val;
else if (l <= start && end <= r) {
lazy[id] += val;
distribute(id, start, end);
} else {
int mid = (start + end) / 2, left = (id << 1), right = left + 1;
update(left, start, mid, l, r, val);
update(right, mid + 1, end, l, r, val);
tree[id] = tree[left] + tree[right];
}
}
long query(int l, int r) {
return query(1, 0, n - 1, l, r);
}
long query(int id, int start, int end, int l, int r) {
if (end < l || r < start)
return 0L;
distribute(id, start, end);
if (start == end)
return tree[id];
else if (l <= start && end <= r)
return tree[id];
else {
int mid = (start + end) / 2, left = (id << 1), right = left + 1;
return query(left, start, mid, l, r) + query(right, mid + 1, end, l, r);
}
}
void distribute(int id, int start, int end) {
if (start == end)
tree[id] += lazy[id];
else {
tree[id] += lazy[id] * (end - start + 1);
lazy[(id << 1)] += lazy[id];
lazy[(id << 1) + 1] += lazy[id];
}
lazy[id] = 0;
}
}
// ==================== FENWICK TREE ================================
static class FT {
int n;
int[] arr;
int[] tree;
FT(int[] arr, int n) {
this.arr = arr;
this.n = n;
this.tree = new int[n + 1];
for (int i = 1; i <= n; i++) {
update(i, arr[i - 1]);
}
}
FT(int n) {
this.n = n;
this.tree = new int[n + 1];
}
// 1 based indexing
void update(int idx, int val) {
while (idx <= n) {
tree[idx] += val;
idx += idx & -idx;
}
}
// 1 based indexing
int query(int l, int r) {
return getSum(r) - getSum(l - 1);
}
int getSum(int idx) {
int ans = 0;
while (idx > 0) {
ans += tree[idx];
idx -= idx & -idx;
}
return ans;
}
}
// ==================== BINARY INDEX TREE ================================
static class BIT {
long[][] tree;
int n, m;
BIT(int[][] mat, int n, int m) {
this.n = n;
this.m = m;
tree = new long[n + 1][m + 1];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
update(i, j, mat[i - 1][j - 1]);
}
}
}
void update(int x, int y, int val) {
while (x <= n) {
int t = y;
while (t <= m) {
tree[x][t] += val;
t += t & -t;
}
x += x & -x;
}
}
long query(int x1, int y1, int x2, int y2) {
return getSum(x2, y2) - getSum(x1 - 1, y2) - getSum(x2, y1 - 1) + getSum(x1 - 1, y1 - 1);
}
long getSum(int x, int y) {
long ans = 0L;
while (x > 0) {
int t = y;
while (t > 0) {
ans += tree[x][t];
t -= t & -t;
}
x -= x & -x;
}
return ans;
}
}
} | Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 11 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | 3391241206cc8926b4bf49152a57a99d | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | // Problem: C. Robot in a Hallway
// Contest: Codeforces - Educational Codeforces Round 133 (Rated for Div. 2)
// URL: https://codeforces.com/contest/1716/problem/C
// Memory Limit: 256 MB
// Time Limit: 2000 ms
import java.io.*;
import java.util.*;
public class Main {
static IntReader in;
static FastWriter out;
static String INPUT = "";
static int N = 200010;
static int[] a = new int[N], b = new int[N];
static int[] dp = new int[N];
static int[][] f = new int[N][2];
static int n;
static void solve() {
int T = ni();
while (T-- > 0) {
n = ni();
a[n + 1] = b[n + 1] = 0;
f[n + 1][0] = f[n + 1][1] = 0;
for (int i = 1; i <= n; i++) a[i] = ni();
for (int i = 1; i <= n; i++) b[i] = ni();
dp[1] = b[1] + 1;
for (int i = 2; i <= n; i++) {
if (i % 2 != 0) {
dp[i] = max(dp[i - 1] + 2, b[i] + 1, a[i] + 2);
} else {
dp[i] = max(dp[i - 1] + 2, a[i] + 1, b[i] + 2);
}
}
// for (int i = 1; i <= n; i++)
// out.println(i + " " + dp[i]);
for (int i = n; i >= 1; i--) {
f[i][1] = max(a[i] + 2 * (n - i + 1), f[i + 1][1] + 1, b[i] + 1);
f[i][0] = max(b[i] + 2 * (n - i + 1), f[i + 1][0] + 1, a[i] + 1);
}
// for (int i = 1; i <= n; i++)
// out.println(i + " " + f[i][0] + " " + f[i][1]);
//
int min = 0;
for (int i = 2; i <= n; i++) {
min = Math.max(min + 1, a[i] + 1);
}
for (int i = n; i > 0; i--) {
min = Math.max(min + 1, b[i] + 1);
}
for (int i = 1; i <= n; i++) {
if (i % 2 == 1) {
min = Math.min(min, max(dp[i] + 2 * (n - i), f[i + 1][0]));
} else {
min = Math.min(min, max(dp[i] + 2 * (n - i), f[i + 1][1]));
}
}
out.println(min);
}
}
static int max(int ... a) {
int res = 0;
for (int x : a)
res = Math.max(res, x);
return res;
}
public static void main(String[] args) throws Exception {
in = INPUT.isEmpty() ? new IntReader(System.in) : new IntReader(new ByteArrayInputStream(INPUT.getBytes()));
out = new FastWriter(System.out);
solve();
out.flush();
}
public static class IntReader {
private InputStream is;
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
public IntReader(InputStream is) {
this.is = is;
}
private int readByte() {
if (lenbuf == -1) throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0) return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b)) ;
return b;
}
private double nd() {
return Double.parseDouble(ns());
}
private char nc() {
return (char) skip();
}
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private int ni() {
return (int) nl();
}
private long nl() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
}
public static class FastWriter {
private static final int BUF_SIZE = 1 << 13;
private final byte[] buf = new byte[BUF_SIZE];
private final OutputStream out;
private int ptr = 0;
private FastWriter() {
out = null;
}
public FastWriter(OutputStream os) {
this.out = os;
}
public FastWriter(String path) {
try {
this.out = new FileOutputStream(path);
} catch (FileNotFoundException e) {
throw new RuntimeException("FastWriter");
}
}
public FastWriter write(byte b) {
buf[ptr++] = b;
if (ptr == BUF_SIZE) innerflush();
return this;
}
public FastWriter write(char c) {
return write((byte) c);
}
public FastWriter write(char[] s) {
for (char c : s) {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
}
return this;
}
public FastWriter write(String s) {
s.chars().forEach(c -> {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
});
return this;
}
private static int countDigits(int l) {
if (l >= 1000000000) return 10;
if (l >= 100000000) return 9;
if (l >= 10000000) return 8;
if (l >= 1000000) return 7;
if (l >= 100000) return 6;
if (l >= 10000) return 5;
if (l >= 1000) return 4;
if (l >= 100) return 3;
if (l >= 10) return 2;
return 1;
}
public FastWriter write(int x) {
if (x == Integer.MIN_VALUE) {
return write((long) x);
}
if (ptr + 12 >= BUF_SIZE) innerflush();
if (x < 0) {
write((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
private static int countDigits(long l) {
if (l >= 1000000000000000000L) return 19;
if (l >= 100000000000000000L) return 18;
if (l >= 10000000000000000L) return 17;
if (l >= 1000000000000000L) return 16;
if (l >= 100000000000000L) return 15;
if (l >= 10000000000000L) return 14;
if (l >= 1000000000000L) return 13;
if (l >= 100000000000L) return 12;
if (l >= 10000000000L) return 11;
if (l >= 1000000000L) return 10;
if (l >= 100000000L) return 9;
if (l >= 10000000L) return 8;
if (l >= 1000000L) return 7;
if (l >= 100000L) return 6;
if (l >= 10000L) return 5;
if (l >= 1000L) return 4;
if (l >= 100L) return 3;
if (l >= 10L) return 2;
return 1;
}
public FastWriter write(long x) {
if (x == Long.MIN_VALUE) {
return write("" + x);
}
if (ptr + 21 >= BUF_SIZE) innerflush();
if (x < 0) {
write((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
public FastWriter write(double x, int precision) {
if (x < 0) {
write('-');
x = -x;
}
x += Math.pow(10, -precision) / 2;
// if(x < 0){ x = 0; }
write((long) x).write(".");
x -= (long) x;
for (int i = 0; i < precision; i++) {
x *= 10;
write((char) ('0' + (int) x));
x -= (int) x;
}
return this;
}
public FastWriter writeln(char c) {
return write(c).writeln();
}
public FastWriter writeln(int x) {
return write(x).writeln();
}
public FastWriter writeln(long x) {
return write(x).writeln();
}
public FastWriter writeln(double x, int precision) {
return write(x, precision).writeln();
}
public FastWriter write(int... xs) {
boolean first = true;
for (int x : xs) {
if (!first) write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter write(long... xs) {
boolean first = true;
for (long x : xs) {
if (!first) write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter writeln() {
return write((byte) '\n');
}
public FastWriter writeln(int... xs) {
return write(xs).writeln();
}
public FastWriter writeln(long... xs) {
return write(xs).writeln();
}
public FastWriter writeln(char[] line) {
return write(line).writeln();
}
public FastWriter writeln(char[]... map) {
for (char[] line : map) write(line).writeln();
return this;
}
public FastWriter writeln(String s) {
return write(s).writeln();
}
private void innerflush() {
try {
out.write(buf, 0, ptr);
ptr = 0;
} catch (IOException e) {
throw new RuntimeException("innerflush");
}
}
public void flush() {
innerflush();
try {
out.flush();
} catch (IOException e) {
throw new RuntimeException("flush");
}
}
public FastWriter print(byte b) {
return write(b);
}
public FastWriter print(char c) {
return write(c);
}
public FastWriter print(char[] s) {
return write(s);
}
public FastWriter print(String s) {
return write(s);
}
public FastWriter print(int x) {
return write(x);
}
public FastWriter print(long x) {
return write(x);
}
public FastWriter print(double x, int precision) {
return write(x, precision);
}
public FastWriter println(char c) {
return writeln(c);
}
public FastWriter println(int x) {
return writeln(x);
}
public FastWriter println(long x) {
return writeln(x);
}
public FastWriter println(double x, int precision) {
return writeln(x, precision);
}
public FastWriter print(int... xs) {
return write(xs);
}
public FastWriter print(long... xs) {
return write(xs);
}
public FastWriter println(int... xs) {
return writeln(xs);
}
public FastWriter println(long... xs) {
return writeln(xs);
}
public FastWriter println(char[] line) {
return writeln(line);
}
public FastWriter println(char[]... map) {
return writeln(map);
}
public FastWriter println(String s) {
return writeln(s);
}
public FastWriter println() {
return writeln();
}
}
static int ni() {
return in.ni();
}
static long nl() {
return in.nl();
}
static String ns() {
return in.ns();
}
static double nd() {
return Double.parseDouble(in.ns());
}
}
| Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 11 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | efefb489ffcfc6cfdebe3dd5f1cdcfac | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | import java.io.*;
import java.util.*;
public class C {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int t = Integer.parseInt(br.readLine());
while(t --> 0) {
int m = Integer.parseInt(br.readLine());
int[][] ar = new int[2][m];
int[][] tm = new int[2][m];
StringTokenizer st1 = new StringTokenizer(br.readLine());
StringTokenizer st2 = new StringTokenizer(br.readLine());
for(int i = 0; i < m; i++) {
ar[0][i] = Integer.parseInt(st1.nextToken());
ar[1][i] = Integer.parseInt(st2.nextToken());
}
tm[0][0] = 0;
tm[1][0] = Math.max(ar[1][0] + 1, tm[0][0]+1);
//System.out.println(tm[0][0] + " " + tm[1][0]);
for(int i = 1; i < m; i++) {
if(i % 2 == 0) {
tm[0][i] = Math.max(ar[0][i]+1, tm[0][i-1]+1);
tm[1][i] = Math.max(ar[1][i] + 1, tm[0][i]+1);
}else {
tm[1][i] = Math.max(ar[1][i]+1, tm[1][i-1]+1);
tm[0][i] = Math.max(ar[0][i] + 1, tm[1][i]+1);
}
}
int min = m % 2 == 1 ? tm[1][m-1] : tm[0][m-1];
int udmax = -1;
int dumax = -1;
for(int i = m-1; i > 0; i--) {
udmax = Math.max(udmax+1, Math.max(ar[0][i]+2*(m-i), ar[1][i]+1));
dumax = Math.max(dumax+1, Math.max(ar[1][i]+2*(m-i), ar[0][i]+1));
if(i % 2 == 1 && i > 0) {
min = Math.min(min, Math.max(tm[1][i-1] + 2*(m-i), dumax));
}else if(i > 0){
min = Math.min(min, Math.max(tm[0][i-1] + 2*(m-i), udmax));
}
}
udmax = Math.max(udmax+1, Math.max(ar[0][0]+2*m-1, ar[1][0]+1));
min = Math.min(min, udmax);
pw.println(min);
}
pw.close();
}
}
| Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 11 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | d0a5f352bc75e3c5b85880518cbd3276 | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | // O(NN)
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.NoSuchElementException;
import java.util.Random;
public class Main implements Runnable {
public static void main(String[] args) {
new Thread(null, new Main(), "", Runtime.getRuntime().maxMemory()).start();
}
long dfs(int[][] a, boolean[][] vis, int h, int w, long t) {
int cnt=0;
long ret=Long.MAX_VALUE/3;
for (var arr : vis) for (var v : arr) if (v) ++cnt;
if (cnt == a.length * a[0].length) return t;
for (int dh=-1;dh<=1;++dh) {
for (int dw=-1;dw<=1;++dw) {
if (Math.abs(dh)+Math.abs(dw) != 1) continue;
int nh=h+dh;
int nw=w+dw;
if (nh<0||nw<0||nh>=a.length||nw>=a[0].length) continue;
if (vis[nh][nw]) continue;
long nt=t+1;
nt=Math.max(nt, a[nh][nw]);
vis[nh][nw]=true;
ret=Math.min(ret, dfs(a, vis, nh, nw, nt));
vis[nh][nw]=false;
}
}
return ret;
}
long solve2(int[][] a) {
boolean[][] vis = new boolean[a.length][a[0].length];
vis[0][0] = true;
return dfs(a, vis, 0, 0, 0L);
}
long solve(int[][] a) {
int m = a[0].length;
long[][] f = new long[2][m];
long INF = Long.MAX_VALUE/3;
for (int i=0;i<f.length;++i) for (int j=0;j<f[i].length;++j) f[i][j] = a[i][j];
for (int i = 0; i < m; ++i) {
if (i % 2 == 0) {
if (i != 0) f[0][i] = Math.max(f[0][i], f[0][i - 1] + 1);
f[1][i] = Math.max(f[1][i], f[0][i] + 1);
} else {
f[1][i] = Math.max(f[1][i], f[1][i - 1] + 1);
f[0][i] = Math.max(f[0][i], f[1][i] + 1);
}
}
long ans = f[m % 2][m - 1];
long all = 2 * m - 1;
{
long max = -INF;
for (int i = m - 1; i >= 0; --i) {
max = Math.max(max, a[0][i] - i);
max = Math.max(max, a[1][i] - (m + (m - 1 - i)));
if (i % 2 == 0 && i != m - 1) {
long excess = f[0][i] - (2 * (i + 1) - 2);
excess = Math.max(excess, max - i);
ans = Math.min(ans, all + excess);
}
}
}
{
long max = -INF;
for (int i = m - 1; i >= 0; --i) {
max = Math.max(max, a[1][i] - i);
max = Math.max(max, a[0][i] - (m + (m - 1 - i)));
if (i % 2 == 1 && i != m - 1) {
long excess = f[1][i] - (2 * (i + 1) - 2);
excess = Math.max(excess, max - i);
ans = Math.min(ans, all + excess);
}
}
}
return ans;
}
int[][] rnd(int n) {
Random rnd=new Random();
int[][] a = new int[2][n];
for (int i=0;i<2;++i) {
for (int j=0;j<n;++j) {
a[i][j]=rnd.nextInt(6);
}
}
a[0][0]=0;
return a;
}
public void run() {
FastScanner sc = new FastScanner();
PrintWriter pw = new PrintWriter(System.out);
// while (true) {
// int n=5;
// int[][] a=rnd(n);
//
// for (int i=0;i<a.length;++i)for (int j=0;j<a[i].length;++j) a[i][j] +=1;
// a[0][0]=0;
//
// long v1=solve(a);
// long v2=solve2(a);
// if (v1 != v2) {
// tr(a);
// tr(v1, v2);
// throw new AssertionError();
// } else {
// tr("OK");
// }
// }
int T=sc.nextInt();
while (T-->0) {
int m =sc.nextInt();
int[][] a = new int[2][m];
for (int i=0;i<2;++i) {
for (int j=0;j<m;++j) {
a[i][j]=sc.nextInt() + 1;
}
}
a[0][0] = 0;
pw.println(solve(a));
}
pw.close();
}
void tr(Object... objects) {
System.err.println(Arrays.deepToString(objects));
}
}
class FastScanner {
private final InputStream in = System.in;
private final byte[] buffer = new byte[1024];
private int ptr = 0;
private int buflen = 0;
private boolean hasNextByte() {
if (ptr < buflen) {
return true;
} else {
ptr = 0;
try {
buflen = in.read(buffer);
} catch (IOException e) {
e.printStackTrace();
}
if (buflen <= 0) {
return false;
}
}
return true;
}
private int readByte() {
if (hasNextByte())
return buffer[ptr++];
else
return -1;
}
private static boolean isPrintableChar(int c) {
return 33 <= c && c <= 126;
}
private void skipUnprintable() {
while (hasNextByte() && !isPrintableChar(buffer[ptr]))
ptr++;
}
public boolean hasNext() {
skipUnprintable();
return hasNextByte();
}
public String next() {
if (!hasNext())
throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = readByte();
while (isPrintableChar(b)) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public long nextLong() {
if (!hasNext())
throw new NoSuchElementException();
long n = 0;
boolean minus = false;
int b = readByte();
if (b == '-') {
minus = true;
b = readByte();
}
if (b < '0' || '9' < b) {
throw new NumberFormatException();
}
while (true) {
if ('0' <= b && b <= '9') {
n *= 10;
n += b - '0';
} else if (b == -1 || !isPrintableChar(b)) {
return minus ? -n : n;
} else {
throw new NumberFormatException();
}
b = readByte();
}
}
public int nextInt() {
return (int) nextLong();
}
} | Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 17 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | 7cac469e61c29062d26cfc4a60e28630 | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | import java.util.Scanner;
public class problem {
private static final Scanner sc = new Scanner(System.in);
public static void solve() {
int m = sc.nextInt();
int [][]a = new int[2][m];
for(int i = 0; i < 2; i++) {
for(int j = 0; j < m; j++)
a[i][j] = sc.nextInt();
}
int ans = Integer.MAX_VALUE;
int[] upper_suffix = new int[m];
upper_suffix[m - 1] = Math.max(a[0][m - 1] + 2, a[1][m - 1] + 1);
for(int i = m - 2; i >= 0; i--) {
if(i == 0) {
upper_suffix[i] = Math.max(a[0][i] + (m - 1 - i) + 1 + (m - 1 - i), upper_suffix[i]);
}
else {
upper_suffix[i] = Math.max(a[0][i] + 1 + (m - 1 - i) + 1 + (m - 1 - i), upper_suffix[i]);
}
upper_suffix[i] = Math.max(a[1][i] + 1, upper_suffix[i]);
upper_suffix[i] = Math.max(upper_suffix[i + 1] + 1, upper_suffix[i]);
}
int[] lower_suffix = new int[m];
lower_suffix[m - 1] = Math.max(a[1][m - 1] + 2, a[0][m - 1] + 1);
for(int i = m - 2; i >= 0; i--) {
lower_suffix[i] = Math.max(a[1][i] + 1 + (m - 1 - i) + 1 + (m - 1 - i), lower_suffix[i]);
lower_suffix[i] = Math.max(a[0][i] + 1, lower_suffix[i]);
lower_suffix[i] = Math.max(lower_suffix[i + 1] + 1, lower_suffix[i]);
}
int cur_time = 0;
for(int i = 0; i < m; i++) {
if(i % 2 == 0) {
if(i != 0)
cur_time = Math.max(cur_time + 1, a[0][i] + 1);
int val = Math.max(cur_time + 2 * (m - i - 1) + 1, upper_suffix[i]);
ans = Math.min(ans, val);
cur_time = Math.max(cur_time + 1, a[1][i] + 1);
}
else {
cur_time = Math.max(cur_time + 1, a[1][i] + 1);
int val = Math.max(cur_time + 2 * (m - i - 1) + 1, lower_suffix[i]);
ans = Math.min(ans, val);
cur_time = Math.max(cur_time + 1, a[0][i] + 1);
}
}
ans = Math.min(cur_time, ans);
System.out.println(ans);
}
public static void main(String[] args) {
int t = sc.nextInt();
while(t > 0) {
solve();
t--;
}
sc.close();
}
}
| Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 17 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | 4710ed0daaa16e16974a322375a99c5d | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | import java.io.*;
import java.util.*;
public class CF1716C extends PrintWriter {
CF1716C() { super(System.out); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF1716C o = new CF1716C(); o.main(); o.flush();
}
static final int INF = 0x3f3f3f3f;
void main() {
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
int[] aa = new int[n];
int[] bb = new int[n];
for (int i = 0; i < n; i++)
aa[i] = sc.nextInt() + 1;
aa[0] = 0;
for (int i = 0; i < n; i++)
bb[i] = sc.nextInt() + 1;
int[] ra = new int[n + 1];
int[] rb = new int[n + 1];
int[] la = new int[n + 1];
int[] lb = new int[n + 1];
ra[n] = rb[n] = la[n] = lb[n] = -INF;
for (int i = n - 1; i >= 0; i--) {
ra[i] = Math.max(ra[i + 1], aa[i] - i);
rb[i] = Math.max(rb[i + 1], bb[i] - i);
la[i] = Math.max(la[i + 1], aa[i] - (n - 1 - i));
lb[i] = Math.max(lb[i + 1], bb[i] - (n - 1 - i));
}
for (int i = 0; i < n; i++) {
ra[i] += i;
rb[i] += i;
}
int d = INF;
for (int x = 0, c = 0, i = 0; i < n; i++)
if (i % 2 == 0) {
c = Math.max(c, aa[i] - x);
int a = Math.max(ra[i], lb[i] - (n - i)) - x;
d = Math.min(d, Math.max(a, c));
x++;
c = Math.max(c, bb[i] - x);
int b = Math.max(rb[i], la[i + 1] - (n - i)) - x;
d = Math.min(d, Math.max(b, c));
x++;
} else {
c = Math.max(c, bb[i] - x);
int b = Math.max(rb[i], la[i] - (n - i)) - x;
d = Math.min(d, Math.max(b, c));
x++;
c = Math.max(c, aa[i] - x);
int a = Math.max(ra[i], lb[i + 1] - (n - i)) - x;
d = Math.min(d, Math.max(a, c));
x++;
}
println(d + n * 2 - 1);
}
}
}
| Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 17 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | b70984fc8c3888cbd9abe8c4db145c6b | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | import java.util.*;
import java.util.function.*;
import java.io.*;
// you can compare with output.txt and expected out
public class RoundEdu133C {
MyPrintWriter out;
MyScanner in;
// final static long FIXED_RANDOM;
// static {
// FIXED_RANDOM = System.currentTimeMillis();
// }
final static String IMPOSSIBLE = "IMPOSSIBLE";
final static String POSSIBLE = "POSSIBLE";
final static String YES = "YES";
final static String NO = "NO";
private void initIO(boolean isFileIO) {
if (System.getProperty("ONLINE_JUDGE") == null && isFileIO) {
try{
in = new MyScanner(new FileInputStream("input.txt"));
out = new MyPrintWriter(new FileOutputStream("output.txt"));
}
catch(FileNotFoundException e){
e.printStackTrace();
}
}
else{
in = new MyScanner(System.in);
out = new MyPrintWriter(new BufferedOutputStream(System.out));
}
}
public static void main(String[] args){
// Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
RoundEdu133C sol = new RoundEdu133C();
sol.run();
}
private void run() {
boolean isDebug = false;
boolean isFileIO = true;
boolean hasMultipleTests = true;
initIO(isFileIO);
int t = hasMultipleTests? in.nextInt() : 1;
for (int i = 1; i <= t; ++i) {
if(isDebug){
out.printf("Test %d\n", i);
}
getInput();
solve();
printOutput();
}
in.close();
out.close();
}
// use suitable one between matrix(2, n) or matrix(n, 2) for graph edges, pairs, ...
int m;
int[][] a;
void getInput() {
m = in.nextInt();
a = in.nextMatrix(2, m);
}
void printOutput() {
out.printlnAns(ans);
}
int ans;
void solve(){
// a[0][0] -> a[0][1]
// a[1][1] -> a[1][2]
// a[2][0] -> a[2][1]
// a[3][1]
int time = Math.max(0, Math.max(a[1][0], a[1][1]-1)) + 2;
int[][] b = new int[2][m-1];
for(int i=0; i<2; i++)
for(int j=0; j<m-1; j++) {
b[i][j] = Math.max(0, a[1-i][j+1] - time);
}
int even = solve(a, m);
int odd = solve(b, m-1) + time;
ans = Math.min(even, odd);
}
int solve(int[][] a, int m) {
int[] arr = new int[m*2];
int idx = 1;
for(int j=1; j<m; j++) {
arr[idx] = Math.max(0, a[0][j]-idx+1);
idx++;
}
for(int j=m-1; j>=0; j--) {
arr[idx] = Math.max(0, a[1][j]-idx+1);
idx++;
}
SegmentTree maxSegTree = new SegmentTree((x, y) -> Math.max(x, y), arr);
int min = Math.max(0, maxSegTree.getRange(getIdx(0, 0, m), getIdx(1, 0, m)));
min += m*2-1;
int time = 0;
int max = 0;
idx = 0;
for(int j=2; j<m; j+=2) {
max = Math.max(max, a[1][j-2]-idx); idx++;
max = Math.max(max, a[1][j-1]-idx); idx++;
max = Math.max(max, a[0][j-1]-idx); idx++;
max = Math.max(max, a[0][j]-idx); idx++;
time = max + j*2;
int val = Math.max(0, maxSegTree.getRange(getIdx(0, j+1, m), getIdx(1, j, m)));
val += j;
min = Math.min(min, Math.max(time, val) + (m-j)*2 -1);
}
return min;
}
int getIdx(int i, int j, int m) {
if(i == 0)
return j;
else
return m + (m-1-j);
}
class SegmentTree {
BiFunction<Integer, Integer, Integer> function;
//int identity;
int n;
int[] tree;
//public SegmentTree(BiFunction<Integer, Integer, Integer> function, int[] arr, int identity){
public SegmentTree(BiFunction<Integer, Integer, Integer> function, int[] arr){
this.function = function;
//this.identity = identity;
this.n = arr.length;
int m = n<=1? 8: Integer.highestOneBit(n-1)*4;
// int m = Integer.highestOneBit(n-1)*4;
tree = new int[m];
//Arrays.fill(tree, identity);
// O(n)
build(arr, 1, 0, n-1);
// O(nlgn)
// for(int i=0; i<n; i++)
// update(i, arr[i]);
}
private void build(int[] arr, int treeIdx, int left, int right) {
if(left == right) {
tree[treeIdx] = arr[left];
return;
}
int mid = (left+right)>>1;
// int treeIdxLeftMid = treeIdx*2;
// int treeIdxMidRight = treeIdx*2+1;
int treeIdxLeftMid = treeIdx<<1;
int treeIdxMidRight = (treeIdx<<1)+1;
build(arr, treeIdxLeftMid, left, mid);
build(arr, treeIdxMidRight, mid+1, right);
tree[treeIdx] = function.apply(tree[treeIdxLeftMid], tree[treeIdxMidRight]);
}
public void update(int idx, int val){
update(idx+1, val, 1, 1, n);
// same as update(idx, val, 1, 0, n-1)
}
private int update(int idx, int val, int treeIdx, int left, int right) {
// no need to update, not containing idx
if(left > idx || idx > right)
return tree[treeIdx];
// base case
if(left == right){
tree[treeIdx] = val;
return val;
}
// update [left, right] containing idx
int mid = (left+right)>>1;
int val1 = update(idx, val, treeIdx<<1, left, mid);
int val2 = update(idx, val, (treeIdx<<1) + 1, mid+1, right);
val = function.apply(val1, val2);
tree[treeIdx] = val;
return val;
}
public int getRange(int start, int end){
return getRange(start+1, end+1, 1, 1, n);
// same as getRange(start, end, 1, 0, n-1);
}
private int getRange(int start, int end, int treeIdx, int left, int right) {
// guaranteed: left <= start <= end <= right
// alternative: just return identity for the case of out of range
if(start == left && end == right)
return tree[treeIdx];
int mid = (left+right)>>1;
if(end <= mid)
return getRange(start, end, treeIdx<<1, left, mid);
else if(start <= mid){
int val1 = getRange(start, mid, treeIdx<<1, left, mid);
int val2 = getRange(mid+1, end, (treeIdx<<1)+1, mid+1, right);
return function.apply(val1, val2);
}
else
return getRange(start, end, (treeIdx<<1)+1, mid+1, right);
}
}
static class Pair implements Comparable<Pair>{
final static long FIXED_RANDOM = System.currentTimeMillis();
int first, second;
public Pair(int first, int second) {
this.first = first;
this.second = second;
}
@Override
public int hashCode() {
// http://xorshift.di.unimi.it/splitmix64.c
long x = first;
x <<= 32;
x += second;
x += FIXED_RANDOM;
x += 0x9e3779b97f4a7c15l;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9l;
x = (x ^ (x >> 27)) * 0x94d049bb133111ebl;
return (int)(x ^ (x >> 31));
}
@Override
public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
Pair other = (Pair) obj;
return first == other.first && second == other.second;
}
@Override
public String toString() {
return "[" + first + "," + second + "]";
}
@Override
public int compareTo(Pair o) {
int cmp = Integer.compare(first, o.first);
return cmp != 0? cmp: Integer.compare(second, o.second);
}
}
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
// 32768?
public MyScanner(InputStream is, int bufferSize) {
br = new BufferedReader(new InputStreamReader(is), bufferSize);
}
public MyScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
// br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));
}
public void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[][] nextMatrix(int n, int m) {
return nextMatrix(n, m, 0);
}
int[][] nextMatrix(int n, int m, int offset) {
int[][] mat = new int[n][m];
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
mat[i][j] = nextInt()+offset;
}
}
return mat;
}
int[] nextIntArray(int len) {
return nextIntArray(len, 0);
}
int[] nextIntArray(int len, int offset){
int[] a = new int[len];
for(int j=0; j<len; j++)
a[j] = nextInt()+offset;
return a;
}
long[] nextLongArray(int len) {
return nextLongArray(len, 0);
}
long[] nextLongArray(int len, int offset){
long[] a = new long[len];
for(int j=0; j<len; j++)
a[j] = nextLong()+offset;
return a;
}
String[] nextStringArray(int len) {
String[] s = new String[len];
for(int i=0; i<len; i++)
s[i] = next();
return s;
}
}
public static class MyPrintWriter extends PrintWriter{
public MyPrintWriter(OutputStream os) {
super(os);
}
public void printlnAns(long ans) {
println(ans);
}
public void printlnAns(int ans) {
println(ans);
}
public void printlnAns(boolean ans) {
if(ans)
println(YES);
else
println(NO);
}
public void printAns(long[] arr){
if(arr != null && arr.length > 0){
print(arr[0]);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]);
}
}
}
public void printlnAns(long[] arr){
printAns(arr);
println();
}
public void printAns(int[] arr){
if(arr != null && arr.length > 0){
print(arr[0]);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]);
}
}
}
public void printlnAns(int[] arr){
printAns(arr);
println();
}
public <T> void printAns(ArrayList<T> arr){
if(arr != null && arr.size() > 0){
print(arr.get(0));
for(int i=1; i<arr.size(); i++){
print(" ");
print(arr.get(i));
}
}
}
public <T> void printlnAns(ArrayList<T> arr){
printAns(arr);
println();
}
public void printAns(int[] arr, int add){
if(arr != null && arr.length > 0){
print(arr[0]+add);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]+add);
}
}
}
public void printlnAns(int[] arr, int add){
printAns(arr, add);
println();
}
public void printAns(ArrayList<Integer> arr, int add) {
if(arr != null && arr.size() > 0){
print(arr.get(0)+add);
for(int i=1; i<arr.size(); i++){
print(" ");
print(arr.get(i)+add);
}
}
}
public void printlnAns(ArrayList<Integer> arr, int add){
printAns(arr, add);
println();
}
public void printlnAnsSplit(long[] arr, int split){
if(arr != null){
for(int i=0; i<arr.length; i+=split){
print(arr[i]);
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr[j]);
}
println();
}
}
}
public void printlnAnsSplit(int[] arr, int split){
if(arr != null){
for(int i=0; i<arr.length; i+=split){
print(arr[i]);
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr[j]);
}
println();
}
}
}
public <T> void printlnAnsSplit(ArrayList<T> arr, int split){
if(arr != null && !arr.isEmpty()){
for(int i=0; i<arr.size(); i+=split){
print(arr.get(i));
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr.get(j));
}
println();
}
}
}
}
static private void permutateAndSort(long[] a) {
int n = a.length;
Random R = new Random(System.currentTimeMillis());
for(int i=0; i<n; i++) {
int t = R.nextInt(n-i);
long temp = a[n-1-i];
a[n-1-i] = a[t];
a[t] = temp;
}
Arrays.sort(a);
}
static private void permutateAndSort(int[] a) {
int n = a.length;
Random R = new Random(System.currentTimeMillis());
for(int i=0; i<n; i++) {
int t = R.nextInt(n-i);
int temp = a[n-1-i];
a[n-1-i] = a[t];
a[t] = temp;
}
Arrays.sort(a);
}
static private int[][] constructChildren(int n, int[] parent, int parentRoot){
int[][] childrens = new int[n][];
int[] numChildren = new int[n];
for(int i=0; i<parent.length; i++) {
if(parent[i] != parentRoot)
numChildren[parent[i]]++;
}
for(int i=0; i<n; i++) {
childrens[i] = new int[numChildren[i]];
}
int[] idx = new int[n];
for(int i=0; i<parent.length; i++) {
if(parent[i] != parentRoot)
childrens[parent[i]][idx[parent[i]]++] = i;
}
return childrens;
}
static private int[][][] constructDirectedNeighborhood(int n, int[][] e){
int[] inDegree = new int[n];
int[] outDegree = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
outDegree[u]++;
inDegree[v]++;
}
int[][] inNeighbors = new int[n][];
int[][] outNeighbors = new int[n][];
for(int i=0; i<n; i++) {
inNeighbors[i] = new int[inDegree[i]];
outNeighbors[i] = new int[outDegree[i]];
}
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
outNeighbors[u][--outDegree[u]] = v;
inNeighbors[v][--inDegree[v]] = u;
}
return new int[][][] {inNeighbors, outNeighbors};
}
static private int[][] constructNeighborhood(int n, int[][] e) {
int[] degree = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
degree[u]++;
degree[v]++;
}
int[][] neighbors = new int[n][];
for(int i=0; i<n; i++)
neighbors[i] = new int[degree[i]];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
neighbors[u][--degree[u]] = v;
neighbors[v][--degree[v]] = u;
}
return neighbors;
}
static private void drawGraph(int[][] e) {
makeDotUndirected(e);
try {
final Process process = new ProcessBuilder("dot", "-Tpng", "graph.dot")
.redirectOutput(new File("graph.png"))
.start();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
static private void makeDotUndirected(int[][] e) {
MyPrintWriter out2 = null;
try {
out2 = new MyPrintWriter(new FileOutputStream("graph.dot"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
out2.println("strict graph {");
for(int i=0; i<e.length; i++){
out2.println(e[i][0] + "--" + e[i][1] + ";");
}
out2.println("}");
out2.close();
}
static private void makeDotDirected(int[][] e) {
MyPrintWriter out2 = null;
try {
out2 = new MyPrintWriter(new FileOutputStream("graph.dot"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
out2.println("strict digraph {");
for(int i=0; i<e.length; i++){
out2.println(e[i][0] + "->" + e[i][1] + ";");
}
out2.println("}");
out2.close();
}
}
| Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 17 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | 19f20f93280d7290658188d15075e243 | train_109.jsonl | 1659623700 | There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that? | 256 megabytes | import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import java.util.*;
import java.io.*;
import java.math.*;
/**
*
* @Har_Har_Mahadev
*/
public class C {
public static void process() throws IOException {
int n = sc.nextInt();
int arr[] = sc.readArray(n);
int b[] = sc.readArray(n);
int pref1[] = new int[n];
pref1[0] = arr[0];
for(int i = 1; i<n; i++) {
pref1[i] = max(pref1[i-1] + 1, arr[i]+1);
}
int pref2[] = new int[n];
pref2[0] = b[0]+1;
for(int i = 1; i<n; i++) {
pref2[i] = max(pref2[i-1] + 1, b[i]+1);
}
int suf1[] = new int[n];
suf1[n-1] = arr[n-1]+1;
for(int i = n-2; i>=0; i--) {
suf1[i] = max(suf1[i+1] + 1, arr[i]+1);
}
int suf2[] = new int[n];
suf2[n-1] = b[n-1]+1;
for(int i = n-2; i>=0; i--) {
suf2[i] = max(suf2[i+1] + 1, b[i]+1);
}
long ans = pref1[n-1];
ans = max(ans + n, suf2[0]);
boolean flag = false;
int i = 0;
int time = b[i]+1;
while(i<n) {
long res = time;
if(flag) {
res = max(res + (n-i-1), pref1[n-1]);
if(i+1<n) {
res = max(res + (n-i-1), suf2[i+1]);
}
ans = min(ans, res);
flag = false;
i++;
if(i<n) {
time = max(time+1, arr[i]+1);
time = max(time+1, b[i]+1);
}
}
else {
res = max(res + (n-i-1), pref2[n-1]);
if(i+1<n) {
res = max(res + (n-i-1), suf1[i+1]);
}
ans = min(ans, res);
flag = true;
i++;
if(i<n) {
time = max(time+1, b[i]+1);
time = max(time+1, arr[i]+1);
}
}
}
System.out.println(ans);
}
//=============================================================================
//--------------------------The End---------------------------------
//=============================================================================
private static long INF = 2000000000000000000L, M = 1000000007, MM = 998244353;
private static int N = 0;
private static void google(int tt) {
System.out.print("Case #" + (tt) + ": ");
}
static FastScanner sc;
static FastWriter out;
public static void main(String[] args) throws IOException {
boolean oj = true;
if (oj) {
sc = new FastScanner();
out = new FastWriter(System.out);
} else {
sc = new FastScanner("input.txt");
out = new FastWriter("output.txt");
}
long s = System.currentTimeMillis();
int t = 1;
t = sc.nextInt();
int TTT = 1;
while (t-- > 0) {
// google(TTT++);
process();
}
out.flush();
// tr(System.currentTimeMillis()-s+"ms");
}
private static boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private static void tr(Object... o) {
if (!oj)
System.err.println(Arrays.deepToString(o));
}
static class Pair implements Comparable<Pair> {
int x, y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Pair o) {
return Integer.compare(this.x, o.x);
}
/*
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Pair)) return false;
Pair key = (Pair) o;
return x == key.x && y == key.y;
}
@Override
public int hashCode() {
int result = x;
result = 31 * result + y;
return result;
}
*/
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
static int ceil(int x, int y) {
return (x % y == 0 ? x / y : (x / y + 1));
}
static long ceil(long x, long y) {
return (x % y == 0 ? x / y : (x / y + 1));
}
static long sqrt(long z) {
long sqz = (long) Math.sqrt(z);
while (sqz * 1L * sqz < z) {
sqz++;
}
while (sqz * 1L * sqz > z) {
sqz--;
}
return sqz;
}
static int log2(int N) {
int result = (int) (Math.log(N) / Math.log(2));
return result;
}
public static long gcd(long a, long b) {
if (a > b)
a = (a + b) - (b = a);
if (a == 0L)
return b;
return gcd(b % a, a);
}
public static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
public static int lower_bound(int[] arr, int x) {
int low = 0, high = arr.length - 1, mid = -1;
int ans = -1;
while (low <= high) {
mid = (low + high) / 2;
if (arr[mid] > x) {
high = mid - 1;
} else {
ans = mid;
low = mid + 1;
}
}
return ans;
}
public static int upper_bound(int[] arr, int x) {
int low = 0, high = arr.length - 1, mid = -1;
int ans = arr.length;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] >= x) {
ans = mid;
high = mid - 1;
} else {
low = mid + 1;
}
}
return ans;
}
static void ruffleSort(int[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
Arrays.sort(a);
}
static void ruffleSort(long[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
long temp = a[i];
a[i] = a[r];
a[r] = temp;
}
Arrays.sort(a);
}
static void reverseArray(int[] a) {
int n = a.length;
int arr[] = new int[n];
for (int i = 0; i < n; i++)
arr[i] = a[n - i - 1];
for (int i = 0; i < n; i++)
a[i] = arr[i];
}
static void reverseArray(long[] a) {
int n = a.length;
long arr[] = new long[n];
for (int i = 0; i < n; i++)
arr[i] = a[n - i - 1];
for (int i = 0; i < n; i++)
a[i] = arr[i];
}
//custom multiset (replace with HashMap if needed)
public static void push(TreeMap<Integer, Integer> map, int k, int v) {
//map[k] += v;
if (!map.containsKey(k))
map.put(k, v);
else
map.put(k, map.get(k) + v);
}
public static void pull(TreeMap<Integer, Integer> map, int k, int v) {
//assumes map[k] >= v
//map[k] -= v
int lol = map.get(k);
if (lol == v)
map.remove(k);
else
map.put(k, lol - v);
}
// compress Big value to Time Limit
public static int[] compress(int[] arr) {
ArrayList<Integer> ls = new ArrayList<Integer>();
for (int x : arr)
ls.add(x);
Collections.sort(ls);
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int boof = 1; //min value
for (int x : ls)
if (!map.containsKey(x))
map.put(x, boof++);
int[] brr = new int[arr.length];
for (int i = 0; i < arr.length; i++)
brr[i] = map.get(arr[i]);
return brr;
}
// Fast Writer
public static class FastWriter {
private static final int BUF_SIZE = 1 << 13;
private final byte[] buf = new byte[BUF_SIZE];
private final OutputStream out;
private int ptr = 0;
private FastWriter() {
out = null;
}
public FastWriter(OutputStream os) {
this.out = os;
}
public FastWriter(String path) {
try {
this.out = new FileOutputStream(path);
} catch (FileNotFoundException e) {
throw new RuntimeException("FastWriter");
}
}
public FastWriter write(byte b) {
buf[ptr++] = b;
if (ptr == BUF_SIZE)
innerflush();
return this;
}
public FastWriter write(char c) {
return write((byte) c);
}
public FastWriter write(char[] s) {
for (char c : s) {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE)
innerflush();
}
return this;
}
public FastWriter write(String s) {
s.chars().forEach(c -> {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE)
innerflush();
});
return this;
}
private static int countDigits(int l) {
if (l >= 1000000000)
return 10;
if (l >= 100000000)
return 9;
if (l >= 10000000)
return 8;
if (l >= 1000000)
return 7;
if (l >= 100000)
return 6;
if (l >= 10000)
return 5;
if (l >= 1000)
return 4;
if (l >= 100)
return 3;
if (l >= 10)
return 2;
return 1;
}
public FastWriter write(int x) {
if (x == Integer.MIN_VALUE) {
return write((long) x);
}
if (ptr + 12 >= BUF_SIZE)
innerflush();
if (x < 0) {
write((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
private static int countDigits(long l) {
if (l >= 1000000000000000000L)
return 19;
if (l >= 100000000000000000L)
return 18;
if (l >= 10000000000000000L)
return 17;
if (l >= 1000000000000000L)
return 16;
if (l >= 100000000000000L)
return 15;
if (l >= 10000000000000L)
return 14;
if (l >= 1000000000000L)
return 13;
if (l >= 100000000000L)
return 12;
if (l >= 10000000000L)
return 11;
if (l >= 1000000000L)
return 10;
if (l >= 100000000L)
return 9;
if (l >= 10000000L)
return 8;
if (l >= 1000000L)
return 7;
if (l >= 100000L)
return 6;
if (l >= 10000L)
return 5;
if (l >= 1000L)
return 4;
if (l >= 100L)
return 3;
if (l >= 10L)
return 2;
return 1;
}
public FastWriter write(long x) {
if (x == Long.MIN_VALUE) {
return write("" + x);
}
if (ptr + 21 >= BUF_SIZE)
innerflush();
if (x < 0) {
write((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
public FastWriter write(double x, int precision) {
if (x < 0) {
write('-');
x = -x;
}
x += Math.pow(10, -precision) / 2;
// if(x < 0){ x = 0; }
write((long) x).write(".");
x -= (long) x;
for (int i = 0; i < precision; i++) {
x *= 10;
write((char) ('0' + (int) x));
x -= (int) x;
}
return this;
}
public FastWriter writeln(char c) {
return write(c).writeln();
}
public FastWriter writeln(int x) {
return write(x).writeln();
}
public FastWriter writeln(long x) {
return write(x).writeln();
}
public FastWriter writeln(double x, int precision) {
return write(x, precision).writeln();
}
public FastWriter write(int... xs) {
boolean first = true;
for (int x : xs) {
if (!first)
write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter write(long... xs) {
boolean first = true;
for (long x : xs) {
if (!first)
write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter writeln() {
return write((byte) '\n');
}
public FastWriter writeln(int... xs) {
return write(xs).writeln();
}
public FastWriter writeln(long... xs) {
return write(xs).writeln();
}
public FastWriter writeln(char[] line) {
return write(line).writeln();
}
public FastWriter writeln(char[]... map) {
for (char[] line : map)
write(line).writeln();
return this;
}
public FastWriter writeln(String s) {
return write(s).writeln();
}
private void innerflush() {
try {
out.write(buf, 0, ptr);
ptr = 0;
} catch (IOException e) {
throw new RuntimeException("innerflush");
}
}
public void flush() {
innerflush();
try {
out.flush();
} catch (IOException e) {
throw new RuntimeException("flush");
}
}
public FastWriter print(byte b) {
return write(b);
}
public FastWriter print(char c) {
return write(c);
}
public FastWriter print(char[] s) {
return write(s);
}
public FastWriter print(String s) {
return write(s);
}
public FastWriter print(int x) {
return write(x);
}
public FastWriter print(long x) {
return write(x);
}
public FastWriter print(double x, int precision) {
return write(x, precision);
}
public FastWriter println(char c) {
return writeln(c);
}
public FastWriter println(int x) {
return writeln(x);
}
public FastWriter println(long x) {
return writeln(x);
}
public FastWriter println(double x, int precision) {
return writeln(x, precision);
}
public FastWriter print(int... xs) {
return write(xs);
}
public FastWriter print(long... xs) {
return write(xs);
}
public FastWriter println(int... xs) {
return writeln(xs);
}
public FastWriter println(long... xs) {
return writeln(xs);
}
public FastWriter println(char[] line) {
return writeln(line);
}
public FastWriter println(char[]... map) {
return writeln(map);
}
public FastWriter println(String s) {
return writeln(s);
}
public FastWriter println() {
return writeln();
}
}
// Fast Inputs
static 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[] readArray(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] readArrayLong(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public int[][] readArrayMatrix(int N, int M, int Index) {
if (Index == 0) {
int[][] res = new int[N][M];
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++)
res[i][j] = (int) nextLong();
}
return res;
}
int[][] res = new int[N][M];
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= M; j++)
res[i][j] = (int) nextLong();
}
return res;
}
public long[][] readArrayMatrixLong(int N, int M, int Index) {
if (Index == 0) {
long[][] res = new long[N][M];
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++)
res[i][j] = nextLong();
}
return res;
}
long[][] res = new long[N][M];
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= M; j++)
res[i][j] = 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[] readArrayDouble(int N) {
double[] res = new double[N];
for (int i = 0; i < N; i++) {
res[i] = nextDouble();
}
return res;
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32)
c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32)
c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
public boolean hasNext() {
if (c > 32)
return true;
while (true) {
c = getChar();
if (c == NC)
return false;
else if (c > 32)
return true;
}
}
}
}
| Java | ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"] | 2 seconds | ["5\n19\n17\n3"] | null | Java 17 | standard input | [
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | f9f82c16e4024a207bc7ad80af10c0fe | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | 2,000 | For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. | standard output | |
PASSED | ce1bd4cf519b629d28631d060b00da80 | train_109.jsonl | 1659623700 | There are $$$n$$$ bags, each bag contains $$$m$$$ balls with numbers from $$$1$$$ to $$$m$$$. For every $$$i \in [1, m]$$$, there is exactly one ball with number $$$i$$$ in each bag.You have to take exactly one ball from each bag (all bags are different, so, for example, taking the ball $$$1$$$ from the first bag and the ball $$$2$$$ from the second bag is not the same as taking the ball $$$2$$$ from the first bag and the ball $$$1$$$ from the second bag). After that, you calculate the number of balls with odd numbers among the ones you have taken. Let the number of these balls be $$$F$$$.Your task is to calculate the sum of $$$F^k$$$ over all possible ways to take $$$n$$$ balls, one from each bag. | 512 megabytes | import java.util.*;
import java.util.function.*;
import java.io.*;
// you can compare with output.txt and expected out
public class RoundEdu133F {
MyPrintWriter out;
MyScanner in;
// final static long FIXED_RANDOM;
// static {
// FIXED_RANDOM = System.currentTimeMillis();
// }
final static String IMPOSSIBLE = "IMPOSSIBLE";
final static String POSSIBLE = "POSSIBLE";
final static String YES = "YES";
final static String NO = "NO";
private void initIO(boolean isFileIO) {
if (System.getProperty("ONLINE_JUDGE") == null && isFileIO) {
try{
in = new MyScanner(new FileInputStream("input.txt"));
out = new MyPrintWriter(new FileOutputStream("output.txt"));
}
catch(FileNotFoundException e){
e.printStackTrace();
}
}
else{
in = new MyScanner(System.in);
out = new MyPrintWriter(new BufferedOutputStream(System.out));
}
}
public static void main(String[] args){
// Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
RoundEdu133F sol = new RoundEdu133F();
sol.run();
}
private void run() {
boolean isDebug = false;
boolean isFileIO = true;
boolean hasMultipleTests = true;
initIO(isFileIO);
int t = hasMultipleTests? in.nextInt() : 1;
final int MAX = 2000;
precompute(MAX);
for (int i = 1; i <= t; ++i) {
if(isDebug){
out.printf("Test %d\n", i);
}
getInput();
solve();
printOutput();
}
in.close();
out.close();
}
long[][] S;
private void precompute(final int MAX) {
S = new long[MAX+1][MAX+1];
// S(k, i) = iS(k-1, i) + S(k-1, i-1)
// S(k, k) = S(k, 1) = 1
S[0][0] = 1;
for(int k=1; k<=MAX; k++) {
for(int i=1; i<=k; i++) {
S[k][i] = S[k-1][i]*i + S[k-1][i-1];
S[k][i] %= MOD;
}
}
}
final long MOD = 998244353;
// use suitable one between matrix(2, n) or matrix(n, 2) for graph edges, pairs, ...
int n, m, k;
void getInput() {
n = in.nextInt();
m = in.nextInt();
k = in.nextInt();
}
void printOutput() {
out.printlnAns(ans);
}
long ans;
void solve(){
// f^k * #odd^f * #even^(n-f) * nCf
// (#odd + #even)^n = sum #odd^f*#even^(n-f)*nCf
// (1+x)^n = sum nCk * x^k
// n(1+x)^(n-1) = sum k * nCk * x^(k-1)
// (#odd + #even)^n = sum #odd^f*#even^(n-f)*nCf
// (x+y)^n = sum x^f*y^(n-f)*nCf = S0
// n(x+y)^(n-1) = sum f*x^(f-1)*y^(n-f)*nCf = S1/x
// n(n-1)(x+y)^(n-2) = sum f(f-1)x^(f-2)y^(n-f)nCf = S2/x^2
// nPk*(x+y)^(n-k)*x^k = sum fPk*x^f*y^(n-f)*nCf = g(k)
// sum f^k*x^f*y^(n-f)*nCf = sum S(k, i) g(i)
ans = 0;
long p = 1;
long xi = 1;
long x = (m+1)/2;
int bound = Math.min(n, k);
long[] mi = new long[bound+1]; // pow(m, n-i, MOD) % MOD;
mi[bound] = pow(m, n-bound, MOD);
for(int i=bound-1; i>0; i--)
mi[i] = mi[i+1] * m % MOD;
for(int i=1; i<=k && i<=n; i++) {
p = p * (n-i+1) % MOD;
long temp = p * mi[i] % MOD;
xi = xi * x % MOD;
temp = temp * xi % MOD;
ans += temp * S[k][i] % MOD;
}
ans %= MOD;
}
static long pow(long a, int k, long p) {
long m = k;
long ans = 1;
// curr = k^(2^i)
long curr = a;
// k^(2x+1) = (k^x)^2 * k
while(m > 0) {
if( (m&1) == 1 ) {
ans *= curr;
ans %= p;
}
m >>= 1;
curr *= curr;
curr %= p;
}
return ans;
}
// computes a^(p-2)
static long inverse(int a, long p) {
return pow(a, (int)(p-2), p);
}
// Optional<T> solve()
// return Optional.empty();
static class Pair implements Comparable<Pair>{
final static long FIXED_RANDOM = System.currentTimeMillis();
int first, second;
public Pair(int first, int second) {
this.first = first;
this.second = second;
}
@Override
public int hashCode() {
// http://xorshift.di.unimi.it/splitmix64.c
long x = first;
x <<= 32;
x += second;
x += FIXED_RANDOM;
x += 0x9e3779b97f4a7c15l;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9l;
x = (x ^ (x >> 27)) * 0x94d049bb133111ebl;
return (int)(x ^ (x >> 31));
}
@Override
public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
Pair other = (Pair) obj;
return first == other.first && second == other.second;
}
@Override
public String toString() {
return "[" + first + "," + second + "]";
}
@Override
public int compareTo(Pair o) {
int cmp = Integer.compare(first, o.first);
return cmp != 0? cmp: Integer.compare(second, o.second);
}
}
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
// 32768?
public MyScanner(InputStream is, int bufferSize) {
br = new BufferedReader(new InputStreamReader(is), bufferSize);
}
public MyScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
// br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));
}
public void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[][] nextMatrix(int n, int m) {
return nextMatrix(n, m, 0);
}
int[][] nextMatrix(int n, int m, int offset) {
int[][] mat = new int[n][m];
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
mat[i][j] = nextInt()+offset;
}
}
return mat;
}
int[][] nextTransposedMatrix(int n, int m){
return nextTransposedMatrix(n, m, 0);
}
int[][] nextTransposedMatrix(int n, int m, int offset){
int[][] mat = new int[m][n];
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
mat[j][i] = nextInt()+offset;
}
}
return mat;
}
int[] nextIntArray(int len) {
return nextIntArray(len, 0);
}
int[] nextIntArray(int len, int offset){
int[] a = new int[len];
for(int j=0; j<len; j++)
a[j] = nextInt()+offset;
return a;
}
long[] nextLongArray(int len) {
return nextLongArray(len, 0);
}
long[] nextLongArray(int len, int offset){
long[] a = new long[len];
for(int j=0; j<len; j++)
a[j] = nextLong()+offset;
return a;
}
String[] nextStringArray(int len) {
String[] s = new String[len];
for(int i=0; i<len; i++)
s[i] = next();
return s;
}
}
public static class MyPrintWriter extends PrintWriter{
public MyPrintWriter(OutputStream os) {
super(os);
}
// public <T> void printlnAns(Optional<T> ans) {
// if(ans.isEmpty())
// println(-1);
// else
// printlnAns(ans.get());
// }
public void printlnAns(OptionalInt ans) {
println(ans.orElse(-1));
}
public void printlnAns(long ans) {
println(ans);
}
public void printlnAns(int ans) {
println(ans);
}
public void printlnAns(boolean ans) {
if(ans)
println(YES);
else
println(NO);
}
public void printAns(long[] arr){
if(arr != null && arr.length > 0){
print(arr[0]);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]);
}
}
}
public void printlnAns(long[] arr){
printAns(arr);
println();
}
public void printAns(int[] arr){
if(arr != null && arr.length > 0){
print(arr[0]);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]);
}
}
}
public void printlnAns(int[] arr){
printAns(arr);
println();
}
public <T> void printAns(ArrayList<T> arr){
if(arr != null && arr.size() > 0){
print(arr.get(0));
for(int i=1; i<arr.size(); i++){
print(" ");
print(arr.get(i));
}
}
}
public <T> void printlnAns(ArrayList<T> arr){
printAns(arr);
println();
}
public void printAns(int[] arr, int add){
if(arr != null && arr.length > 0){
print(arr[0]+add);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]+add);
}
}
}
public void printlnAns(int[] arr, int add){
printAns(arr, add);
println();
}
public void printAns(ArrayList<Integer> arr, int add) {
if(arr != null && arr.size() > 0){
print(arr.get(0)+add);
for(int i=1; i<arr.size(); i++){
print(" ");
print(arr.get(i)+add);
}
}
}
public void printlnAns(ArrayList<Integer> arr, int add){
printAns(arr, add);
println();
}
public void printlnAnsSplit(long[] arr, int split){
if(arr != null){
for(int i=0; i<arr.length; i+=split){
print(arr[i]);
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr[j]);
}
println();
}
}
}
public void printlnAnsSplit(int[] arr, int split){
if(arr != null){
for(int i=0; i<arr.length; i+=split){
print(arr[i]);
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr[j]);
}
println();
}
}
}
public <T> void printlnAnsSplit(ArrayList<T> arr, int split){
if(arr != null && !arr.isEmpty()){
for(int i=0; i<arr.size(); i+=split){
print(arr.get(i));
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr.get(j));
}
println();
}
}
}
}
static private void permutateAndSort(long[] a) {
int n = a.length;
Random R = new Random(System.currentTimeMillis());
for(int i=0; i<n; i++) {
int t = R.nextInt(n-i);
long temp = a[n-1-i];
a[n-1-i] = a[t];
a[t] = temp;
}
Arrays.sort(a);
}
static private void permutateAndSort(int[] a) {
int n = a.length;
Random R = new Random(System.currentTimeMillis());
for(int i=0; i<n; i++) {
int t = R.nextInt(n-i);
int temp = a[n-1-i];
a[n-1-i] = a[t];
a[t] = temp;
}
Arrays.sort(a);
}
static private int[][] constructChildren(int n, int[] parent, int parentRoot){
int[][] childrens = new int[n][];
int[] numChildren = new int[n];
for(int i=0; i<parent.length; i++) {
if(parent[i] != parentRoot)
numChildren[parent[i]]++;
}
for(int i=0; i<n; i++) {
childrens[i] = new int[numChildren[i]];
}
int[] idx = new int[n];
for(int i=0; i<parent.length; i++) {
if(parent[i] != parentRoot)
childrens[parent[i]][idx[parent[i]]++] = i;
}
return childrens;
}
static private int[][][] constructDirectedNeighborhood(int n, int[][] e){
int[] inDegree = new int[n];
int[] outDegree = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
outDegree[u]++;
inDegree[v]++;
}
int[][] inNeighbors = new int[n][];
int[][] outNeighbors = new int[n][];
for(int i=0; i<n; i++) {
inNeighbors[i] = new int[inDegree[i]];
outNeighbors[i] = new int[outDegree[i]];
}
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
outNeighbors[u][--outDegree[u]] = v;
inNeighbors[v][--inDegree[v]] = u;
}
return new int[][][] {inNeighbors, outNeighbors};
}
static private int[][] constructNeighborhood(int n, int[][] e) {
int[] degree = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
degree[u]++;
degree[v]++;
}
int[][] neighbors = new int[n][];
for(int i=0; i<n; i++)
neighbors[i] = new int[degree[i]];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
neighbors[u][--degree[u]] = v;
neighbors[v][--degree[v]] = u;
}
return neighbors;
}
static private void drawGraph(int[][] e) {
makeDotUndirected(e);
try {
final Process process = new ProcessBuilder("dot", "-Tpng", "graph.dot")
.redirectOutput(new File("graph.png"))
.start();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
static private void makeDotUndirected(int[][] e) {
MyPrintWriter out2 = null;
try {
out2 = new MyPrintWriter(new FileOutputStream("graph.dot"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
out2.println("strict graph {");
for(int i=0; i<e.length; i++){
out2.println(e[i][0] + "--" + e[i][1] + ";");
}
out2.println("}");
out2.close();
}
static private void makeDotDirected(int[][] e) {
MyPrintWriter out2 = null;
try {
out2 = new MyPrintWriter(new FileOutputStream("graph.dot"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
out2.println("strict digraph {");
for(int i=0; i<e.length; i++){
out2.println(e[i][0] + "->" + e[i][1] + ";");
}
out2.println("}");
out2.close();
}
}
| Java | ["5\n\n2 3 8\n\n1 1 1\n\n1 5 10\n\n3 7 2000\n\n1337666 42424242 2000"] | 3 seconds | ["1028\n1\n3\n729229716\n652219904"] | null | Java 17 | standard input | [
"combinatorics",
"dp",
"math",
"number theory"
] | fc8381e8c97190749b356f10cf80209e | The first line contains one integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of test cases. Each test case consists of one line containing three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n, m \le 998244352$$$; $$$1 \le k \le 2000$$$). | 2,500 | For each test case, print one integer — the sum of $$$F^k$$$ over all possible ways to take $$$n$$$ balls, one from each bag. Since it can be huge, print it modulo $$$998244353$$$. | standard output | |
PASSED | 142114f6220174d58db8eac3fcae3650 | train_109.jsonl | 1659623700 | There are $$$n$$$ bags, each bag contains $$$m$$$ balls with numbers from $$$1$$$ to $$$m$$$. For every $$$i \in [1, m]$$$, there is exactly one ball with number $$$i$$$ in each bag.You have to take exactly one ball from each bag (all bags are different, so, for example, taking the ball $$$1$$$ from the first bag and the ball $$$2$$$ from the second bag is not the same as taking the ball $$$2$$$ from the first bag and the ball $$$1$$$ from the second bag). After that, you calculate the number of balls with odd numbers among the ones you have taken. Let the number of these balls be $$$F$$$.Your task is to calculate the sum of $$$F^k$$$ over all possible ways to take $$$n$$$ balls, one from each bag. | 512 megabytes | // package c1716;
//
// Educational Codeforces Round 133 (Rated for Div. 2) 2022-08-04 07:35
// F. Bags with Balls
// https://codeforces.com/contest/1716/problem/F
// time limit per test 3 seconds; memory limit per test 512 megabytes
// public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*'
//
// There are n bags, each bag contains m balls with numbers from 1 to m. For every i \in [1, m],
// there is exactly one ball with number i in each bag.
//
// You have to take exactly one ball from each bag (all bags are different, so, for example, taking
// the ball 1 from the first bag and the ball 2 from the second bag is not the same as taking the
// ball 2 from the first bag and the ball 1 from the second bag). After that, you calculate the
// number of balls with numbers among the ones you have taken. Let the number of these balls be F.
//
// Your task is to calculate the sum of F^k over all possible ways to take n balls, one from each
// bag.
//
// Input
//
// The first line contains one integer t (1 <= t <= 5000)-- the number of test cases.
//
// Each test case consists of one line containing three integers n, m and k (1 <= n, m <= 998244352;
// 1 <= k <= 2000).
//
// Output
//
// For each test case, print one integer-- the sum of F^k over all possible ways to take n balls,
// one from each bag. Since it can be huge, print it modulo 998244353.
//
// Example
/*
input:
5
2 3 8
1 1 1
1 5 10
3 7 2000
1337666 42424242 2000
output:
1028
1
3
729229716
652219904
*/
//
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.invoke.MethodHandles;
import java.util.Random;
import java.util.StringTokenizer;
public class C1716F {
static final int MOD = 998244353;
static final Random RAND = new Random();
final static int[][] CO = computeCoeff();
static final long[] F = new long[2001];
static int solve(int n, int m, int k) {
// In the example of (3,7,2000)
// we have (4x+3)^3 = 64x^3 + 144x^2 + 108x + 27
// -> 64*3^2000 + 144*2^2000 + 108*1^2000 + 27 * 0^2000
int a = (m + 1) / 2;
long ans = 0;
// ** For n <= 2000, compute directly based on binomial distribution increased
// runtime from 1045 to 1242 msec likely due to the call of power(e, k) ***
// consider all (n+1) terms of (ax+b)^n: C(n,e)*a^e*b^(n-e)*x^e for e in [0,n]
// Denote c(e) as C(n,e)*a^e*b^(n-e), we have f_n(x) = (ax+b)^n = sum(c(e)*x^e)
// Denote s(k) as sum(F^k) = sum(c(e)*e^k)
// we have s(0) = sum(c(e)) = (a+b)^n
// f[j] is value of f's j-th derivative at 1 where f = (ax+b)^n, that is,
// f[0] = f(1) = m^n
// f[1] = f'(1) = na(ax+b)^(n-1) = na(a+b)^(n-1) = nam^(n-1)
// f[2] = f''(1) = n(n-1)a^2(ax+b)^(n-2) = n(n-1)a^2(a+b)^n-2 = n(n-1)a^2m^(n-2)
// ...
// f[j] = f(j)(1) = n(n-1)...(n-j+1) a^j m^(n-j)
// *** Be cautious to not unnecessarily call power() in loop below to avoid TLE ***
long mul = power(m, n);
long invm = inverse(m);
long v0 = 1;
for (int j = 1; j <= k; j++) {
v0 = v0 * invm % MOD;
mul = (mul * (n - j + 1) % MOD) * a % MOD;
F[j] = mul * v0 % MOD;
}
// s(k) = \sum_{1,n}c(e)*e^k
// s(0) = \sum_{1,n}c(e) =
// s(1) = \sum_{1,n}c(e)*e = f(1)
// s(2) = \sum_{1,n}c(e)*e^2 = f(2) + s(1)
// s(3) = \sum_{1,n}c(e)*e^3 = f(3) + 3s(2) - 2s(1)
// f = \sum_{0,n}c(e)x^e
// f' = \sum_{1,n}c(e)*e*x^(e-1) -> f(1)=\sum_{1,n}c(e)*e
// f'' = \sum_{2,n}c(e)*e*(e-1)x^(e-2) ->
// f(2) = \sum_{2,n}c(e)*(e^2-e)
// = \sum_{1,n}c(e)*(e^2-e) - \sum_{1,1}c(e)*(e^2-e)
// = \sum_{1,n}c(e)*(e^2-e)
// = s(2) - s(1)
// f'''= \sum_{3,n}c(e)*e*(e-1)*(e-2)x^(e-3) ->
// f(3) = \sum_{3,n}c(e)*e*(e-1)*(e-2)
// = \sum_{1,n}c(e)*e*(e-1)*(e-2) - \sum_{1,2}c(e)*e*(e-1)*(e-2)
// = \sum_{1,n}c(e)*e*(e-1)*(e-2)
// = \sum_{1,n}c(e)*(e^3-3e^2+2e)
// = s(3) - 3s(2) + 2s(1)
int[] co = CO[k];
for (int i = 1; i < co.length; i++) {
ans = (ans + co[i] * F[i]) % MOD;
}
return (int) ans;
}
// compute coefficient of s[j] = e(e-1)(e-2)...(e-j+1) in terms of f[]
static int[][] computeCoeff() {
// Use a1 to refer to f[1] etc, we have
// s0 don't really care
// s1 = a1
// s2 = a2 + a1
// s3 = a1 + 3*a2 + a3
// s4 = a1 + 7a2 + 6a3 + a4
//
// 1 1
// 2 1 1
// 3 1 3 1
// 4 1 7 6 1
// 5 1 15 25 10 1
// 6 1 31 90 65 15 1
// 7 1 63 301 350 140 21 1
// 8 1 127 966 1701 1050 266 28 1
// ...
int[][] arr = new int[2001][];
for (int i = 0; i < 2001; i++) {
arr[i] = new int[i+1];
}
arr[0][0] = 1;
for (int i = 1; i < 2001; i++) {
for(int j = 1; j < i; j++) {
arr[i][j] = (int) ((1L * arr[i-1][j] * j % MOD + arr[i-1][j-1]) % MOD);
}
arr[i][i] = 1;
if (i < 20) {
// System.out.format(" i:%2d %s\n", i, Arrays.toString(arr[i]));
}
}
return arr;
}
// compute x such that x * a == 1 % MOD
public static int inverse(long a) {
return power(a, MOD - 2);
}
// To compute x^y % MOD
public static int power(long x, int y) {
if (y == 0) {
return 1;
}
long w = power(x, y / 2);
w = (w * w) % MOD;
return (int) (y % 2 == 0 ? w : (w * x) % MOD);
}
static int solveA(int n, int m, int k) {
long a = (m + 1)/2;
long q = a * inverse(m) % MOD;
long ans = 0;
long mul = 1;
for (int i = 1; i <= k; i++) {
mul = mul * q % MOD * (n-i+1) % MOD;
ans = (ans + CO[k][i] * mul % MOD) % MOD;
}
return (int) (ans * power(m,n) % MOD);
}
static void test(int exp, int n, int m, int k) {
int ans = solve(n, m, k);
System.out.format("%9d %9d %9d => %d %s\n", n, m, k, ans, ans == exp ? "" : "Expected " + exp);
myAssert(ans == exp);
}
static boolean test = false;
static void doTest() {
if (!test) {
return;
}
long t0 = System.currentTimeMillis();
// test(652219904, 1337666, 42424242, 2000);
test(485812953, 3825, 476, 2000);
test(75131880, 1317, 8974, 2000);
test(515879741, 9550, 4026, 2000);
test(34049613, 8133, 129, 2000);
test(631767740, 6429, 5211, 2000);
test(330122212, 2715, 5907, 2000);
test(31026911, 6815, 2681, 2000);
test(772513405, 3674, 4043, 2000);
test(546776189, 1614, 1664, 2000);
test(273860898, 4845, 4622, 2000);
test(987134517, 4568, 508, 2000);
test(585535066, 6740, 4691, 2000);
test(303481469, 8401, 2520, 2000);
test(942774678, 5518, 1225, 2000);
test(611130133, 5818, 6963, 2000);
test(884718389, 409, 1798, 2000);
test(61887968, 5932, 597, 2000);
test(391461706, 2489, 8196, 2000);
test(655612215, 9961, 4627, 2000);
test(413770298, 2245, 6151, 2000);
test(960818414, 2549, 2543, 2000);
test(359085754, 743, 3202, 2000);
test(298890537, 6032, 67, 2000);
test(313703051, 5605, 7867, 2000);
test(82535400, 8935, 7951, 2000);
test(379388626, 2411, 123, 2000);
test(351929892, 7627, 4689, 2000);
test(636574771, 5579, 2554, 2000);
test(812449761, 7330, 340, 2000);
test(742447387, 5176, 4410, 2000);
test(762551061, 6781, 7020, 2000);
test(591374949, 2447, 7826, 2000);
System.out.format("%d msec\n", System.currentTimeMillis() - t0);
System.exit(0);
}
public static void main(String[] args) {
doTest();
MyScanner in = new MyScanner();
int T = in.nextInt();
for (int t = 1; t <= T; t++) {
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
int ans = solve(n, m, k);
System.out.println(ans);
}
}
static void output(int[] a) {
if (a == null) {
System.out.println("-1");
return;
}
StringBuilder sb = new StringBuilder();
for (int v : a) {
sb.append(v);
sb.append(' ');
if (sb.length() > 500) {
System.out.print(sb.toString());
sb.setLength(0);
}
}
System.out.println(sb.toString());
}
static void myAssert(boolean cond) {
if (!cond) {
throw new RuntimeException("Unexpected");
}
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
try {
final String USERDIR = System.getProperty("user.dir");
String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(".MyScanner", "");
cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname;
final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in");
br = new BufferedReader(new InputStreamReader(fin.exists()
? new FileInputStream(fin) : System.in));
} catch (Exception e) {
br = new BufferedReader(new InputStreamReader(System.in));
}
}
public String next() {
try {
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["5\n\n2 3 8\n\n1 1 1\n\n1 5 10\n\n3 7 2000\n\n1337666 42424242 2000"] | 3 seconds | ["1028\n1\n3\n729229716\n652219904"] | null | Java 11 | standard input | [
"combinatorics",
"dp",
"math",
"number theory"
] | fc8381e8c97190749b356f10cf80209e | The first line contains one integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of test cases. Each test case consists of one line containing three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n, m \le 998244352$$$; $$$1 \le k \le 2000$$$). | 2,500 | For each test case, print one integer — the sum of $$$F^k$$$ over all possible ways to take $$$n$$$ balls, one from each bag. Since it can be huge, print it modulo $$$998244353$$$. | standard output | |
PASSED | 0e43fc1f6717031286295e1c7e525500 | train_109.jsonl | 1659623700 | There are $$$n$$$ bags, each bag contains $$$m$$$ balls with numbers from $$$1$$$ to $$$m$$$. For every $$$i \in [1, m]$$$, there is exactly one ball with number $$$i$$$ in each bag.You have to take exactly one ball from each bag (all bags are different, so, for example, taking the ball $$$1$$$ from the first bag and the ball $$$2$$$ from the second bag is not the same as taking the ball $$$2$$$ from the first bag and the ball $$$1$$$ from the second bag). After that, you calculate the number of balls with odd numbers among the ones you have taken. Let the number of these balls be $$$F$$$.Your task is to calculate the sum of $$$F^k$$$ over all possible ways to take $$$n$$$ balls, one from each bag. | 512 megabytes | // package c1716;
//
// Educational Codeforces Round 133 (Rated for Div. 2) 2022-08-04 07:35
// F. Bags with Balls
// https://codeforces.com/contest/1716/problem/F
// time limit per test 3 seconds; memory limit per test 512 megabytes
// public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*'
//
// There are n bags, each bag contains m balls with numbers from 1 to m. For every i \in [1, m],
// there is exactly one ball with number i in each bag.
//
// You have to take exactly one ball from each bag (all bags are different, so, for example, taking
// the ball 1 from the first bag and the ball 2 from the second bag is not the same as taking the
// ball 2 from the first bag and the ball 1 from the second bag). After that, you calculate the
// number of balls with numbers among the ones you have taken. Let the number of these balls be F.
//
// Your task is to calculate the sum of F^k over all possible ways to take n balls, one from each
// bag.
//
// Input
//
// The first line contains one integer t (1 <= t <= 5000)-- the number of test cases.
//
// Each test case consists of one line containing three integers n, m and k (1 <= n, m <= 998244352;
// 1 <= k <= 2000).
//
// Output
//
// For each test case, print one integer-- the sum of F^k over all possible ways to take n balls,
// one from each bag. Since it can be huge, print it modulo 998244353.
//
// Example
/*
input:
5
2 3 8
1 1 1
1 5 10
3 7 2000
1337666 42424242 2000
output:
1028
1
3
729229716
652219904
*/
//
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.invoke.MethodHandles;
import java.util.Random;
import java.util.StringTokenizer;
public class C1716F {
static final int MOD = 998244353;
static final Random RAND = new Random();
final static int[][] CO = computeCoeff();
static final long[] F = new long[2001];
static int solve(int n, int m, int k) {
// In the example of (3,7,2000)
// we have (4x+3)^3 = 64x^3 + 144x^2 + 108x + 27
// -> 64*3^2000 + 144*2^2000 + 108*1^2000 + 27 * 0^2000
int a = (m + 1) / 2;
long ans = 0;
// ** For n <= 2000, compute directly based on binomial distribution increased
// runtime from 1045 to 1242 msec likely due to the call of power(e, k) ***
// consider all (n+1) terms of (ax+b)^n: C(n,e)*a^e*b^(n-e)*x^e for e in [0,n]
// Denote c(e) as C(n,e)*a^e*b^(n-e), we have f_n(x) = (ax+b)^n = sum(c(e)*x^e)
// Denote s(k) as sum(F^k) = sum(c(e)*e^k)
// we have s(0) = sum(c(e)) = (a+b)^n
// f[j] is value of f's j-th derivative at 1 where f = (ax+b)^n, that is,
// f[0] = f(1) = m^n
// f[1] = f'(1) = na(ax+b)^(n-1) = na(a+b)^(n-1) = nam^(n-1)
// f[2] = f''(1) = n(n-1)a^2(ax+b)^(n-2) = n(n-1)a^2(a+b)^n-2 = n(n-1)a^2m^(n-2)
// ...
// f[j] = f(j)(1) = n(n-1)...(n-j+1) a^j m^(n-j)
// *** Be cautious to not unnecessarily call power() in loop below to avoid TLE ***
/*
long mul = power(m, n);
long invm = inverse(m);
long v0 = 1;
for (int j = 1; j <= k; j++) {
v0 = v0 * invm % MOD;
mul = (mul * (n - j + 1) % MOD) * a % MOD;
F[j] = mul * v0 % MOD;
}
*/
// s(k) = \sum_{1,n}c(e)*e^k
// s(0) = \sum_{1,n}c(e) =
// s(1) = \sum_{1,n}c(e)*e = f(1)
// s(2) = \sum_{1,n}c(e)*e^2 = f(2) + s(1)
// s(3) = \sum_{1,n}c(e)*e^3 = f(3) + 3s(2) - 2s(1)
// f = \sum_{0,n}c(e)x^e
// f' = \sum_{1,n}c(e)*e*x^(e-1) -> f(1)=\sum_{1,n}c(e)*e
// f'' = \sum_{2,n}c(e)*e*(e-1)x^(e-2) ->
// f(2) = \sum_{2,n}c(e)*(e^2-e)
// = \sum_{1,n}c(e)*(e^2-e) - \sum_{1,1}c(e)*(e^2-e)
// = \sum_{1,n}c(e)*(e^2-e)
// = s(2) - s(1)
// f'''= \sum_{3,n}c(e)*e*(e-1)*(e-2)x^(e-3) ->
// f(3) = \sum_{3,n}c(e)*e*(e-1)*(e-2)
// = \sum_{1,n}c(e)*e*(e-1)*(e-2) - \sum_{1,2}c(e)*e*(e-1)*(e-2)
// = \sum_{1,n}c(e)*e*(e-1)*(e-2)
// = \sum_{1,n}c(e)*(e^3-3e^2+2e)
// = s(3) - 3s(2) + 2s(1)
int[] co = CO[k];
// *** Be cautious to not unnecessarily call power() in loop below to avoid TLE ***
long mul = power(m, n);
long invm = inverse(m);
long v0 = 1;
for (int i = 1; i < co.length; i++) {
v0 = v0 * invm % MOD;
mul = (mul * (n - i + 1) % MOD) * a % MOD;
long fi = mul * v0 % MOD;
ans = (ans + co[i] * fi) % MOD;
}
return (int) ans;
}
// compute coefficient of s[j] = e(e-1)(e-2)...(e-j+1) in terms of f[]
static int[][] computeCoeff() {
// Use a1 to refer to f[1] etc, we have
// s0 don't really care
// s1 = a1
// s2 = a2 + a1
// s3 = a1 + 3*a2 + a3
// s4 = a1 + 7a2 + 6a3 + a4
//
// 1 1
// 2 1 1
// 3 1 3 1
// 4 1 7 6 1
// 5 1 15 25 10 1
// 6 1 31 90 65 15 1
// 7 1 63 301 350 140 21 1
// 8 1 127 966 1701 1050 266 28 1
// ...
int[][] arr = new int[2001][];
for (int i = 0; i < 2001; i++) {
arr[i] = new int[i+1];
}
arr[0][0] = 1;
for (int i = 1; i < 2001; i++) {
for(int j = 1; j < i; j++) {
arr[i][j] = (int) ((1L * arr[i-1][j] * j % MOD + arr[i-1][j-1]) % MOD);
}
arr[i][i] = 1;
if (i < 20) {
// System.out.format(" i:%2d %s\n", i, Arrays.toString(arr[i]));
}
}
return arr;
}
// compute x such that x * a == 1 % MOD
public static int inverse(long a) {
return power(a, MOD - 2);
}
// To compute x^y % MOD
public static int power(long x, int y) {
if (y == 0) {
return 1;
}
long w = power(x, y / 2);
w = (w * w) % MOD;
return (int) (y % 2 == 0 ? w : (w * x) % MOD);
}
static int solveA(int n, int m, int k) {
long a = (m + 1)/2;
long q = a * inverse(m) % MOD;
long ans = 0;
long mul = 1;
for (int i = 1; i <= k; i++) {
mul = mul * q % MOD * (n-i+1) % MOD;
ans = (ans + CO[k][i] * mul % MOD) % MOD;
}
return (int) (ans * power(m,n) % MOD);
}
static void test(int exp, int n, int m, int k) {
int ans = solve(n, m, k);
System.out.format("%9d %9d %9d => %d %s\n", n, m, k, ans, ans == exp ? "" : "Expected " + exp);
myAssert(ans == exp);
}
static boolean test = false;
static void doTest() {
if (!test) {
return;
}
long t0 = System.currentTimeMillis();
// test(652219904, 1337666, 42424242, 2000);
test(485812953, 3825, 476, 2000);
test(75131880, 1317, 8974, 2000);
test(515879741, 9550, 4026, 2000);
test(34049613, 8133, 129, 2000);
test(631767740, 6429, 5211, 2000);
test(330122212, 2715, 5907, 2000);
test(31026911, 6815, 2681, 2000);
test(772513405, 3674, 4043, 2000);
test(546776189, 1614, 1664, 2000);
test(273860898, 4845, 4622, 2000);
test(987134517, 4568, 508, 2000);
test(585535066, 6740, 4691, 2000);
test(303481469, 8401, 2520, 2000);
test(942774678, 5518, 1225, 2000);
test(611130133, 5818, 6963, 2000);
test(884718389, 409, 1798, 2000);
test(61887968, 5932, 597, 2000);
test(391461706, 2489, 8196, 2000);
test(655612215, 9961, 4627, 2000);
test(413770298, 2245, 6151, 2000);
test(960818414, 2549, 2543, 2000);
test(359085754, 743, 3202, 2000);
test(298890537, 6032, 67, 2000);
test(313703051, 5605, 7867, 2000);
test(82535400, 8935, 7951, 2000);
test(379388626, 2411, 123, 2000);
test(351929892, 7627, 4689, 2000);
test(636574771, 5579, 2554, 2000);
test(812449761, 7330, 340, 2000);
test(742447387, 5176, 4410, 2000);
test(762551061, 6781, 7020, 2000);
test(591374949, 2447, 7826, 2000);
System.out.format("%d msec\n", System.currentTimeMillis() - t0);
System.exit(0);
}
public static void main(String[] args) {
doTest();
MyScanner in = new MyScanner();
int T = in.nextInt();
for (int t = 1; t <= T; t++) {
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
int ans = solve(n, m, k);
System.out.println(ans);
}
}
static void output(int[] a) {
if (a == null) {
System.out.println("-1");
return;
}
StringBuilder sb = new StringBuilder();
for (int v : a) {
sb.append(v);
sb.append(' ');
if (sb.length() > 500) {
System.out.print(sb.toString());
sb.setLength(0);
}
}
System.out.println(sb.toString());
}
static void myAssert(boolean cond) {
if (!cond) {
throw new RuntimeException("Unexpected");
}
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
try {
final String USERDIR = System.getProperty("user.dir");
String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(".MyScanner", "");
cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname;
final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in");
br = new BufferedReader(new InputStreamReader(fin.exists()
? new FileInputStream(fin) : System.in));
} catch (Exception e) {
br = new BufferedReader(new InputStreamReader(System.in));
}
}
public String next() {
try {
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["5\n\n2 3 8\n\n1 1 1\n\n1 5 10\n\n3 7 2000\n\n1337666 42424242 2000"] | 3 seconds | ["1028\n1\n3\n729229716\n652219904"] | null | Java 11 | standard input | [
"combinatorics",
"dp",
"math",
"number theory"
] | fc8381e8c97190749b356f10cf80209e | The first line contains one integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of test cases. Each test case consists of one line containing three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n, m \le 998244352$$$; $$$1 \le k \le 2000$$$). | 2,500 | For each test case, print one integer — the sum of $$$F^k$$$ over all possible ways to take $$$n$$$ balls, one from each bag. Since it can be huge, print it modulo $$$998244353$$$. | standard output | |
PASSED | 70119cbcf48ced9a83b429d89592f79f | train_109.jsonl | 1659623700 | There are $$$n$$$ bags, each bag contains $$$m$$$ balls with numbers from $$$1$$$ to $$$m$$$. For every $$$i \in [1, m]$$$, there is exactly one ball with number $$$i$$$ in each bag.You have to take exactly one ball from each bag (all bags are different, so, for example, taking the ball $$$1$$$ from the first bag and the ball $$$2$$$ from the second bag is not the same as taking the ball $$$2$$$ from the first bag and the ball $$$1$$$ from the second bag). After that, you calculate the number of balls with odd numbers among the ones you have taken. Let the number of these balls be $$$F$$$.Your task is to calculate the sum of $$$F^k$$$ over all possible ways to take $$$n$$$ balls, one from each bag. | 512 megabytes | // package c1716;
//
// Educational Codeforces Round 133 (Rated for Div. 2) 2022-08-04 07:35
// F. Bags with Balls
// https://codeforces.com/contest/1716/problem/F
// time limit per test 3 seconds; memory limit per test 512 megabytes
// public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*'
//
// There are n bags, each bag contains m balls with numbers from 1 to m. For every i \in [1, m],
// there is exactly one ball with number i in each bag.
//
// You have to take exactly one ball from each bag (all bags are different, so, for example, taking
// the ball 1 from the first bag and the ball 2 from the second bag is not the same as taking the
// ball 2 from the first bag and the ball 1 from the second bag). After that, you calculate the
// number of balls with numbers among the ones you have taken. Let the number of these balls be F.
//
// Your task is to calculate the sum of F^k over all possible ways to take n balls, one from each
// bag.
//
// Input
//
// The first line contains one integer t (1 <= t <= 5000)-- the number of test cases.
//
// Each test case consists of one line containing three integers n, m and k (1 <= n, m <= 998244352;
// 1 <= k <= 2000).
//
// Output
//
// For each test case, print one integer-- the sum of F^k over all possible ways to take n balls,
// one from each bag. Since it can be huge, print it modulo 998244353.
//
// Example
/*
input:
5
2 3 8
1 1 1
1 5 10
3 7 2000
1337666 42424242 2000
output:
1028
1
3
729229716
652219904
*/
//
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.invoke.MethodHandles;
import java.util.Random;
import java.util.StringTokenizer;
public class C1716F {
static final int MOD = 998244353;
static final Random RAND = new Random();
final static int[][] CO = computeCoeff();
static final int LOW = 2000;
static final Combination COMB = new Combination(LOW);
static final long[] F = new long[2001];
static int solve(int n, int m, int k) {
// Take exactly one ball from each of n bags.
// Let F be number of odd balls with odd numbers among the ones taken
// we like to calculate sum(F^k) over all ways
if (m == 1) {
return power(n, k);
}
// In the example of (3,7,2000)
// we have (4x+3)^3 = 64x^3 + 144x^2 + 108x + 27
// -> 64*3^2000 + 144*2^2000 + 108*1^2000 + 27 * 0^2000
int a = (m + 1) / 2;
int b = m / 2;
long ans = 0;
/*
if (n <= LOW) {
long v0 = (long)a * inverse(b) % MOD;
long v1 = power(b, n);
long v2 = v1;
for (int e = 0; e <= n; e++) {
long v = COMB.choose(n, e) * v2 % MOD;
v2 = v2 * v0 % MOD;
ans = (ans + v * power(e, k)) % MOD;
}
return (int) ans;
}
*/
// consider all (n+1) terms of (ax+b)^n: C(n,e)*a^e*b^(n-e)*x^e for e in [0,n]
// Denote c(e) as C(n,e)*a^e*b^(n-e), we have f_n(x) = (ax+b)^n = sum(c(e)*x^e)
// Denote s(k) as sum(F^k) = sum(c(e)*e^k)
// we have s(0) = sum(c(e)) = (a+b)^n
// f[j] is value of f's j-th derivative at 1 where f = (ax+b)^n, that is,
// f[0] = f(1) = m^n
// f[1] = f'(1) = na(ax+b)^(n-1) = na(a+b)^(n-1) = nam^(n-1)
// f[2] = f''(1) = n(n-1)a^2(ax+b)^(n-2) = n(n-1)a^2(a+b)^n-2 = n(n-1)a^2m^(n-2)
// ...
// f[j] = f(j)(1) = n(n-1)...(n-j+1) a^j m^(n-j)
// *** Be cautious to not unnecessarily call power() in loop below to avoid TLE ***
long mul = power(m, n);
long invm = inverse(m);
long v0 = 1;
for (int j = 1; j <= k; j++) {
v0 = v0 * invm % MOD;
mul = (mul * (n - j + 1) % MOD) * a % MOD;
F[j] = mul * v0 % MOD;
}
// s(k) = \sum_{1,n}c(e)*e^k
// s(0) = \sum_{1,n}c(e) =
// s(1) = \sum_{1,n}c(e)*e = f(1)
// s(2) = \sum_{1,n}c(e)*e^2 = f(2) + s(1)
// s(3) = \sum_{1,n}c(e)*e^3 = f(3) + 3s(2) - 2s(1)
// f = \sum_{0,n}c(e)x^e
// f' = \sum_{1,n}c(e)*e*x^(e-1) -> f(1)=\sum_{1,n}c(e)*e
// f'' = \sum_{2,n}c(e)*e*(e-1)x^(e-2) ->
// f(2) = \sum_{2,n}c(e)*(e^2-e)
// = \sum_{1,n}c(e)*(e^2-e) - \sum_{1,1}c(e)*(e^2-e)
// = \sum_{1,n}c(e)*(e^2-e)
// = s(2) - s(1)
// f'''= \sum_{3,n}c(e)*e*(e-1)*(e-2)x^(e-3) ->
// f(3) = \sum_{3,n}c(e)*e*(e-1)*(e-2)
// = \sum_{1,n}c(e)*e*(e-1)*(e-2) - \sum_{1,2}c(e)*e*(e-1)*(e-2)
// = \sum_{1,n}c(e)*e*(e-1)*(e-2)
// = \sum_{1,n}c(e)*(e^3-3e^2+2e)
// = s(3) - 3s(2) + 2s(1)
int[] co = CO[k];
for (int i = 1; i < co.length; i++) {
ans = (ans + co[i] * F[i]) % MOD;
}
return (int) ans;
}
// compute coefficient of s[j] = e(e-1)(e-2)...(e-j+1) in terms of f[]
static int[][] computeCoeff() {
// Use a1 to refer to f[1] etc, we have
// s0 don't really care
// s1 = a1
// s2 = a2 + a1
// s3 = a1 + 3*a2 + a3
// s4 = a1 + 7a2 + 6a3 + a4
//
// 1 1
// 2 1 1
// 3 1 3 1
// 4 1 7 6 1
// 5 1 15 25 10 1
// 6 1 31 90 65 15 1
// 7 1 63 301 350 140 21 1
// 8 1 127 966 1701 1050 266 28 1
// ...
int[][] arr = new int[2001][];
for (int i = 0; i < 2001; i++) {
arr[i] = new int[i+1];
}
arr[0][0] = 1;
for (int i = 1; i < 2001; i++) {
for(int j = 1; j < i; j++) {
arr[i][j] = (int) ((1L * arr[i-1][j] * j % MOD + arr[i-1][j-1]) % MOD);
}
arr[i][i] = 1;
if (i < 20) {
// System.out.format(" i:%2d %s\n", i, Arrays.toString(arr[i]));
}
}
return arr;
}
// compute x such that x * a == 1 % MOD
public static int inverse(long a) {
return power(a, MOD - 2);
}
// To compute x^y % MOD
public static int power(long x, int y) {
if (y == 0) {
return 1;
}
long w = power(x, y / 2);
w = (w * w) % MOD;
return (int) (y % 2 == 0 ? w : (w * x) % MOD);
}
static int solveA(int n, int m, int k) {
long a = (m + 1)/2;
long q = a * inverse(m) % MOD;
long ans = 0;
long mul = 1;
for (int i = 1; i <= k; i++) {
mul = mul * q % MOD * (n-i+1) % MOD;
ans = (ans + CO[k][i] * mul % MOD) % MOD;
}
return (int) (ans * power(m,n) % MOD);
}
static class Combination {
final int n;
int[] fact;
int[] finv;
public Combination(int n) {
this.n = n;
this.fact = new int[n+1];
this.finv = new int[n+1];
fact[0] = 1;
finv[0] = 1;
for (int i = 1; i <= n; i++) {
fact[i] = (int) (((long) fact[i-1] * i) % MOD);
finv[i] = (int) (((long) finv[i-1] * inverse(i)) % MOD);
}
}
// Compute (m choose k) % MOD.
public int choose(int m, int k) {
return (int) ((((long)fact[m] * finv[k] % MOD) * finv[m-k]) % MOD);
}
}
private static long[][] computeTailCoeffs(int N) {
// 1 -> 1
// e -> 0 1
// e*(e-1) -> 0 -1 1
// e*(e-1)*(e-2) -> 0 2 -3 1
// ...
//
long[][] ta = new long[N][];
for (int i = 0; i < N; i++) {
ta[i] = new long[i+1];
if (i == 0) {
ta[i][0] = 1;
} else {
// multiple ta[i-1] by (e-(i-1))
System.arraycopy(ta[i-1], 0, ta[i], 1, ta[i-1].length);
for (int h = 0; h < i; h++) {
ta[i][h] = (ta[i][h] + MOD - (i-1) * ta[i-1][h] % MOD) % MOD;
}
}
if (i < 10) {
// System.out.format(" tail %d %s\n", i, Arrays.toString(ta[i]));
}
}
return ta;
}
static void test(int exp, int n, int m, int k) {
int ans = solve(n, m, k);
System.out.format("%9d %9d %9d => %d %s\n", n, m, k, ans, ans == exp ? "" : "Expected " + exp);
myAssert(ans == exp);
}
static boolean test = false;
static void doTest() {
if (!test) {
return;
}
long t0 = System.currentTimeMillis();
// test(652219904, 1337666, 42424242, 2000);
test(485812953, 3825, 476, 2000);
test(75131880, 1317, 8974, 2000);
test(515879741, 9550, 4026, 2000);
test(34049613, 8133, 129, 2000);
test(631767740, 6429, 5211, 2000);
test(330122212, 2715, 5907, 2000);
test(31026911, 6815, 2681, 2000);
test(772513405, 3674, 4043, 2000);
test(546776189, 1614, 1664, 2000);
test(273860898, 4845, 4622, 2000);
test(987134517, 4568, 508, 2000);
test(585535066, 6740, 4691, 2000);
test(303481469, 8401, 2520, 2000);
test(942774678, 5518, 1225, 2000);
test(611130133, 5818, 6963, 2000);
test(884718389, 409, 1798, 2000);
test(61887968, 5932, 597, 2000);
test(391461706, 2489, 8196, 2000);
test(655612215, 9961, 4627, 2000);
test(413770298, 2245, 6151, 2000);
test(960818414, 2549, 2543, 2000);
test(359085754, 743, 3202, 2000);
test(298890537, 6032, 67, 2000);
test(313703051, 5605, 7867, 2000);
test(82535400, 8935, 7951, 2000);
test(379388626, 2411, 123, 2000);
test(351929892, 7627, 4689, 2000);
test(636574771, 5579, 2554, 2000);
test(812449761, 7330, 340, 2000);
test(742447387, 5176, 4410, 2000);
test(762551061, 6781, 7020, 2000);
test(591374949, 2447, 7826, 2000);
System.out.format("%d msec\n", System.currentTimeMillis() - t0);
System.exit(0);
}
public static void main(String[] args) {
doTest();
MyScanner in = new MyScanner();
int T = in.nextInt();
for (int t = 1; t <= T; t++) {
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
int ans = solve(n, m, k);
System.out.println(ans);
}
}
static void output(int[] a) {
if (a == null) {
System.out.println("-1");
return;
}
StringBuilder sb = new StringBuilder();
for (int v : a) {
sb.append(v);
sb.append(' ');
if (sb.length() > 500) {
System.out.print(sb.toString());
sb.setLength(0);
}
}
System.out.println(sb.toString());
}
static void myAssert(boolean cond) {
if (!cond) {
throw new RuntimeException("Unexpected");
}
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
try {
final String USERDIR = System.getProperty("user.dir");
String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(".MyScanner", "");
cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname;
final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in");
br = new BufferedReader(new InputStreamReader(fin.exists()
? new FileInputStream(fin) : System.in));
} catch (Exception e) {
br = new BufferedReader(new InputStreamReader(System.in));
}
}
public String next() {
try {
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["5\n\n2 3 8\n\n1 1 1\n\n1 5 10\n\n3 7 2000\n\n1337666 42424242 2000"] | 3 seconds | ["1028\n1\n3\n729229716\n652219904"] | null | Java 11 | standard input | [
"combinatorics",
"dp",
"math",
"number theory"
] | fc8381e8c97190749b356f10cf80209e | The first line contains one integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of test cases. Each test case consists of one line containing three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n, m \le 998244352$$$; $$$1 \le k \le 2000$$$). | 2,500 | For each test case, print one integer — the sum of $$$F^k$$$ over all possible ways to take $$$n$$$ balls, one from each bag. Since it can be huge, print it modulo $$$998244353$$$. | standard output | |
PASSED | 98de395b299d635cd44d5876b7e7820e | train_109.jsonl | 1659623700 | There are $$$n$$$ bags, each bag contains $$$m$$$ balls with numbers from $$$1$$$ to $$$m$$$. For every $$$i \in [1, m]$$$, there is exactly one ball with number $$$i$$$ in each bag.You have to take exactly one ball from each bag (all bags are different, so, for example, taking the ball $$$1$$$ from the first bag and the ball $$$2$$$ from the second bag is not the same as taking the ball $$$2$$$ from the first bag and the ball $$$1$$$ from the second bag). After that, you calculate the number of balls with odd numbers among the ones you have taken. Let the number of these balls be $$$F$$$.Your task is to calculate the sum of $$$F^k$$$ over all possible ways to take $$$n$$$ balls, one from each bag. | 512 megabytes | // package c1716;
//
// Educational Codeforces Round 133 (Rated for Div. 2) 2022-08-04 07:35
// F. Bags with Balls
// https://codeforces.com/contest/1716/problem/F
// time limit per test 3 seconds; memory limit per test 512 megabytes
// public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*'
//
// There are n bags, each bag contains m balls with numbers from 1 to m. For every i \in [1, m],
// there is exactly one ball with number i in each bag.
//
// You have to take exactly one ball from each bag (all bags are different, so, for example, taking
// the ball 1 from the first bag and the ball 2 from the second bag is not the same as taking the
// ball 2 from the first bag and the ball 1 from the second bag). After that, you calculate the
// number of balls with numbers among the ones you have taken. Let the number of these balls be F.
//
// Your task is to calculate the sum of F^k over all possible ways to take n balls, one from each
// bag.
//
// Input
//
// The first line contains one integer t (1 <= t <= 5000)-- the number of test cases.
//
// Each test case consists of one line containing three integers n, m and k (1 <= n, m <= 998244352;
// 1 <= k <= 2000).
//
// Output
//
// For each test case, print one integer-- the sum of F^k over all possible ways to take n balls,
// one from each bag. Since it can be huge, print it modulo 998244353.
//
// Example
/*
input:
5
2 3 8
1 1 1
1 5 10
3 7 2000
1337666 42424242 2000
output:
1028
1
3
729229716
652219904
*/
//
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.invoke.MethodHandles;
import java.util.Random;
import java.util.StringTokenizer;
public class C1716F {
static final int MOD = 998244353;
static final Random RAND = new Random();
final static int[][] CO = computeCoeff();
static final int LOW = 2000;
static final Combination COMB = new Combination(LOW);
static final long[] F = new long[2001];
// Time limit exceeded on test 9
static int solve(int n, int m, int k) {
// Take exactly one ball from each of n bags.
// Let F be number of odd balls with odd numbers among the ones taken
// we like to calculate sum(F^k) over all ways
if (m == 1) {
return power(n, k);
}
// In the example of (3,7,2000)
// we have (4x+3)^3 = 64x^3 + 144x^2 + 108x + 27
// -> 64*3^2000 + 144*2^2000 + 108*1^2000 + 27 * 0^2000
int a = (m + 1) / 2;
int b = m / 2;
long ans = 0;
if (n <= LOW) {
long v0 = (long)a * inverse(b) % MOD;
long v1 = power(b, n);
long v2 = v1;
for (int e = 0; e <= n; e++) {
long v = COMB.choose(n, e) * v2 % MOD;
v2 = v2 * v0 % MOD;
ans = (ans + v * power(e, k)) % MOD;
}
return (int) ans;
}
// consider all (n+1) terms of (ax+b)^n: C(n,e)*a^e*b^(n-e)*x^e for e in [0,n]
// Denote c(e) as C(n,e)*a^e*b^(n-e), we have f_n(x) = (ax+b)^n = sum(c(e)*x^e)
// Denote s(k) as sum(F^k) = sum(c(e)*e^k)
// we have s(0) = sum(c(e)) = (a+b)^n
// f[j] is value of f's j-th derivative at 1 where f = (ax+b)^n, that is,
// f[0] = f(1) = m^n
// f[1] = f'(1) = na(ax+b)^(n-1) = na(a+b)^(n-1) = nam^(n-1)
// f[2] = f''(1) = n(n-1)a^2(ax+b)^(n-2) = n(n-1)a^2(a+b)^n-2 = n(n-1)a^2m^(n-2)
// ...
// f[j] = f(j)(1) = n(n-1)...(n-j+1) a^j m^(n-j)
long mul = power(m, n);
long invm = inverse(m);
long v0 = 1;
for (int j = 1; j <= k; j++) {
v0 = v0 * invm % MOD;
mul = (mul * (n - j + 1) % MOD) * a % MOD;
F[j] = mul * v0 % MOD;
}
// s(k) = \sum_{1,n}c(e)*e^k
// s(0) = \sum_{1,n}c(e) =
// s(1) = \sum_{1,n}c(e)*e = f(1)
// s(2) = \sum_{1,n}c(e)*e^2 = f(2) + s(1)
// s(3) = \sum_{1,n}c(e)*e^3 = f(3) + 3s(2) - 2s(1)
// f = \sum_{0,n}c(e)x^e
// f' = \sum_{1,n}c(e)*e*x^(e-1) -> f(1)=\sum_{1,n}c(e)*e
// f'' = \sum_{2,n}c(e)*e*(e-1)x^(e-2) ->
// f(2) = \sum_{2,n}c(e)*(e^2-e)
// = \sum_{1,n}c(e)*(e^2-e) - \sum_{1,1}c(e)*(e^2-e)
// = \sum_{1,n}c(e)*(e^2-e)
// = s(2) - s(1)
// f'''= \sum_{3,n}c(e)*e*(e-1)*(e-2)x^(e-3) ->
// f(3) = \sum_{3,n}c(e)*e*(e-1)*(e-2)
// = \sum_{1,n}c(e)*e*(e-1)*(e-2) - \sum_{1,2}c(e)*e*(e-1)*(e-2)
// = \sum_{1,n}c(e)*e*(e-1)*(e-2)
// = \sum_{1,n}c(e)*(e^3-3e^2+2e)
// = s(3) - 3s(2) + 2s(1)
int[] co = CO[k];
for (int i = 1; i < co.length; i++) {
ans = (ans + co[i] * F[i]) % MOD;
}
return (int) ans;
}
// compute coefficient of s[j] = e(e-1)(e-2)...(e-j+1) in terms of f[]
static int[][] computeCoeff() {
// Use a1 to refer to f[1] etc, we have
// s0 don't really care
// s1 = a1
// s2 = a2 + a1
// s3 = a1 + 3*a2 + a3
// s4 = a1 + 7a2 + 6a3 + a4
//
// 1 1
// 2 1 1
// 3 1 3 1
// 4 1 7 6 1
// 5 1 15 25 10 1
// 6 1 31 90 65 15 1
// 7 1 63 301 350 140 21 1
// 8 1 127 966 1701 1050 266 28 1
// ...
int[][] arr = new int[2001][];
for (int i = 0; i < 2001; i++) {
arr[i] = new int[i+1];
}
arr[0][0] = 1;
for (int i = 1; i < 2001; i++) {
for(int j = 1; j < i; j++) {
arr[i][j] = (int) ((1L * arr[i-1][j] * j % MOD + arr[i-1][j-1]) % MOD);
}
arr[i][i] = 1;
if (i < 20) {
// System.out.format(" i:%2d %s\n", i, Arrays.toString(arr[i]));
}
}
return arr;
}
// compute x such that x * a == 1 % MOD
public static int inverse(long a) {
return power(a, MOD - 2);
}
// To compute x^y % MOD
public static int power(long x, int y) {
if (y == 0) {
return 1;
}
long w = power(x, y / 2);
w = (w * w) % MOD;
return (int) (y % 2 == 0 ? w : (w * x) % MOD);
}
static int solveA(int n, int m, int k) {
long a = (m + 1)/2;
long q = a * inverse(m) % MOD;
long ans = 0;
long mul = 1;
for (int i = 1; i <= k; i++) {
mul = mul * q % MOD * (n-i+1) % MOD;
ans = (ans + CO[k][i] * mul % MOD) % MOD;
}
return (int) (ans * power(m,n) % MOD);
}
static class Combination {
final int n;
int[] fact;
int[] finv;
public Combination(int n) {
this.n = n;
this.fact = new int[n+1];
this.finv = new int[n+1];
fact[0] = 1;
finv[0] = 1;
for (int i = 1; i <= n; i++) {
fact[i] = (int) (((long) fact[i-1] * i) % MOD);
finv[i] = (int) (((long) finv[i-1] * inverse(i)) % MOD);
}
}
// Compute (m choose k) % MOD.
public int choose(int m, int k) {
return (int) ((((long)fact[m] * finv[k] % MOD) * finv[m-k]) % MOD);
}
}
private static long[][] computeTailCoeffs(int N) {
// 1 -> 1
// e -> 0 1
// e*(e-1) -> 0 -1 1
// e*(e-1)*(e-2) -> 0 2 -3 1
// ...
//
long[][] ta = new long[N][];
for (int i = 0; i < N; i++) {
ta[i] = new long[i+1];
if (i == 0) {
ta[i][0] = 1;
} else {
// multiple ta[i-1] by (e-(i-1))
System.arraycopy(ta[i-1], 0, ta[i], 1, ta[i-1].length);
for (int h = 0; h < i; h++) {
ta[i][h] = (ta[i][h] + MOD - (i-1) * ta[i-1][h] % MOD) % MOD;
}
}
if (i < 10) {
// System.out.format(" tail %d %s\n", i, Arrays.toString(ta[i]));
}
}
return ta;
}
static void test(int exp, int n, int m, int k) {
int ans = solve(n, m, k);
System.out.format("%9d %9d %9d => %d %s\n", n, m, k, ans, ans == exp ? "" : "Expected " + exp);
myAssert(ans == exp);
}
static boolean test = false;
static void doTest() {
if (!test) {
return;
}
long t0 = System.currentTimeMillis();
// test(652219904, 1337666, 42424242, 2000);
test(485812953, 3825, 476, 2000);
test(75131880, 1317, 8974, 2000);
test(515879741, 9550, 4026, 2000);
test(34049613, 8133, 129, 2000);
test(631767740, 6429, 5211, 2000);
test(330122212, 2715, 5907, 2000);
test(31026911, 6815, 2681, 2000);
test(772513405, 3674, 4043, 2000);
test(546776189, 1614, 1664, 2000);
test(273860898, 4845, 4622, 2000);
test(987134517, 4568, 508, 2000);
test(585535066, 6740, 4691, 2000);
test(303481469, 8401, 2520, 2000);
test(942774678, 5518, 1225, 2000);
test(611130133, 5818, 6963, 2000);
test(884718389, 409, 1798, 2000);
test(61887968, 5932, 597, 2000);
test(391461706, 2489, 8196, 2000);
test(655612215, 9961, 4627, 2000);
test(413770298, 2245, 6151, 2000);
test(960818414, 2549, 2543, 2000);
test(359085754, 743, 3202, 2000);
test(298890537, 6032, 67, 2000);
test(313703051, 5605, 7867, 2000);
test(82535400, 8935, 7951, 2000);
test(379388626, 2411, 123, 2000);
test(351929892, 7627, 4689, 2000);
test(636574771, 5579, 2554, 2000);
test(812449761, 7330, 340, 2000);
test(742447387, 5176, 4410, 2000);
test(762551061, 6781, 7020, 2000);
test(591374949, 2447, 7826, 2000);
System.out.format("%d msec\n", System.currentTimeMillis() - t0);
System.exit(0);
}
public static void main(String[] args) {
doTest();
MyScanner in = new MyScanner();
int T = in.nextInt();
for (int t = 1; t <= T; t++) {
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
int ans = solve(n, m, k);
System.out.println(ans);
}
}
static void output(int[] a) {
if (a == null) {
System.out.println("-1");
return;
}
StringBuilder sb = new StringBuilder();
for (int v : a) {
sb.append(v);
sb.append(' ');
if (sb.length() > 500) {
System.out.print(sb.toString());
sb.setLength(0);
}
}
System.out.println(sb.toString());
}
static void myAssert(boolean cond) {
if (!cond) {
throw new RuntimeException("Unexpected");
}
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
try {
final String USERDIR = System.getProperty("user.dir");
String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(".MyScanner", "");
cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname;
final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in");
br = new BufferedReader(new InputStreamReader(fin.exists()
? new FileInputStream(fin) : System.in));
} catch (Exception e) {
br = new BufferedReader(new InputStreamReader(System.in));
}
}
public String next() {
try {
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["5\n\n2 3 8\n\n1 1 1\n\n1 5 10\n\n3 7 2000\n\n1337666 42424242 2000"] | 3 seconds | ["1028\n1\n3\n729229716\n652219904"] | null | Java 11 | standard input | [
"combinatorics",
"dp",
"math",
"number theory"
] | fc8381e8c97190749b356f10cf80209e | The first line contains one integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of test cases. Each test case consists of one line containing three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n, m \le 998244352$$$; $$$1 \le k \le 2000$$$). | 2,500 | For each test case, print one integer — the sum of $$$F^k$$$ over all possible ways to take $$$n$$$ balls, one from each bag. Since it can be huge, print it modulo $$$998244353$$$. | standard output | |
PASSED | b73d7f50e1b61a8053fc8b587a299676 | train_109.jsonl | 1659623700 | There are $$$n$$$ bags, each bag contains $$$m$$$ balls with numbers from $$$1$$$ to $$$m$$$. For every $$$i \in [1, m]$$$, there is exactly one ball with number $$$i$$$ in each bag.You have to take exactly one ball from each bag (all bags are different, so, for example, taking the ball $$$1$$$ from the first bag and the ball $$$2$$$ from the second bag is not the same as taking the ball $$$2$$$ from the first bag and the ball $$$1$$$ from the second bag). After that, you calculate the number of balls with odd numbers among the ones you have taken. Let the number of these balls be $$$F$$$.Your task is to calculate the sum of $$$F^k$$$ over all possible ways to take $$$n$$$ balls, one from each bag. | 512 megabytes | // package c1716;
//
// Educational Codeforces Round 133 (Rated for Div. 2) 2022-08-04 07:35
// F. Bags with Balls
// https://codeforces.com/contest/1716/problem/F
// time limit per test 3 seconds; memory limit per test 512 megabytes
// public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*'
//
// There are n bags, each bag contains m balls with numbers from 1 to m. For every i \in [1, m],
// there is exactly one ball with number i in each bag.
//
// You have to take exactly one ball from each bag (all bags are different, so, for example, taking
// the ball 1 from the first bag and the ball 2 from the second bag is not the same as taking the
// ball 2 from the first bag and the ball 1 from the second bag). After that, you calculate the
// number of balls with numbers among the ones you have taken. Let the number of these balls be F.
//
// Your task is to calculate the sum of F^k over all possible ways to take n balls, one from each
// bag.
//
// Input
//
// The first line contains one integer t (1 <= t <= 5000)-- the number of test cases.
//
// Each test case consists of one line containing three integers n, m and k (1 <= n, m <= 998244352;
// 1 <= k <= 2000).
//
// Output
//
// For each test case, print one integer-- the sum of F^k over all possible ways to take n balls,
// one from each bag. Since it can be huge, print it modulo 998244353.
//
// Example
/*
input:
5
2 3 8
1 1 1
1 5 10
3 7 2000
1337666 42424242 2000
output:
1028
1
3
729229716
652219904
*/
//
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.invoke.MethodHandles;
import java.util.Random;
import java.util.StringTokenizer;
public class C1716F {
static final int MOD = 998244353;
static final Random RAND = new Random();
final static int[][] CO = computeCoeff();
static final int LOW = 2000;
static final Combination COMB = new Combination(LOW);
static final long[] F = new long[2001];
static int solveA(int n, int m, int k) {
// Take exactly one ball from each of n bags.
// Let F be number of odd balls with odd numbers among the ones taken
// we like to calculate sum(F^k) over all ways
if (m == 1) {
return power(n, k);
}
// In the example of (3,7,2000)
// we have (4x+3)^3 = 64x^3 + 144x^2 + 108x + 27
// -> 64*3^2000 + 144*2^2000 + 108*1^2000 + 27 * 0^2000
int a = (m + 1) / 2;
int b = m / 2;
long ans = 0;
if (n <= LOW) {
long v0 = (long)a * inverse(b) % MOD;
long v1 = power(b, n);
long v2 = v1;
for (int e = 0; e <= n; e++) {
long v = COMB.choose(n, e) * v2 % MOD;
v2 = v2 * v0 % MOD;
ans = (ans + v * power(e, k)) % MOD;
}
return (int) ans;
}
// consider all (n+1) terms of (ax+b)^n: C(n,e)*a^e*b^(n-e)*x^e for e in [0,n]
// Denote c(e) as C(n,e)*a^e*b^(n-e), we have f_n(x) = (ax+b)^n = sum(c(e)*x^e)
// Denote s(k) as sum(F^k) = sum(c(e)*e^k)
// we have s(0) = sum(c(e)) = (a+b)^n
// f[j] is value of f's j-th derivative at 1 where f = (ax+b)^n, that is,
// f[0] = f(1) = m^n
// f[1] = f'(1) = na(ax+b)^(n-1) = na(a+b)^(n-1) = nam^(n-1)
// f[2] = f''(1) = n(n-1)a^2(ax+b)^(n-2) = n(n-1)a^2(a+b)^n-2 = n(n-1)a^2m^(n-2)
// ...
// f[j] = f(j)(1) = n(n-1)...(n-j+1) a^j m^(n-j)
F[0] = power(m, n);
long mul = 1;
for (int j = 1; j <= k; j++) {
mul = (mul * (n - j + 1) % MOD) * a % MOD;
F[j] = mul * power(m, n-j) % MOD;
}
// s(k) = \sum_{1,n}c(e)*e^k
// s(0) = \sum_{1,n}c(e) =
// s(1) = \sum_{1,n}c(e)*e = f(1)
// s(2) = \sum_{1,n}c(e)*e^2 = f(2) + s(1)
// s(3) = \sum_{1,n}c(e)*e^3 = f(3) + 3s(2) - 2s(1)
// f = \sum_{0,n}c(e)x^e
// f' = \sum_{1,n}c(e)*e*x^(e-1) -> f(1)=\sum_{1,n}c(e)*e
// f'' = \sum_{2,n}c(e)*e*(e-1)x^(e-2) ->
// f(2) = \sum_{2,n}c(e)*(e^2-e)
// = \sum_{1,n}c(e)*(e^2-e) - \sum_{1,1}c(e)*(e^2-e)
// = \sum_{1,n}c(e)*(e^2-e)
// = s(2) - s(1)
// f'''= \sum_{3,n}c(e)*e*(e-1)*(e-2)x^(e-3) ->
// f(3) = \sum_{3,n}c(e)*e*(e-1)*(e-2)
// = \sum_{1,n}c(e)*e*(e-1)*(e-2) - \sum_{1,2}c(e)*e*(e-1)*(e-2)
// = \sum_{1,n}c(e)*e*(e-1)*(e-2)
// = \sum_{1,n}c(e)*(e^3-3e^2+2e)
// = s(3) - 3s(2) + 2s(1)
int[] co = CO[k];
for (int i = 0; i < co.length; i++) {
ans = (ans + co[i] * F[i]) % MOD;
}
return (int) ans;
}
// compute coefficient of s[j] = e(e-1)(e-2)...(e-j+1) in terms of f[]
static int[][] computeCoeff() {
// Use a1 to refer to f[1] etc, we have
// s0 don't really care
// s1 = a1
// s2 = a2 + a1
// s3 = a1 + 3*a2 + a3
// s4 = a1 + 7a2 + 6a3 + a4
//
// 1 1
// 2 1 1
// 3 1 3 1
// 4 1 7 6 1
// 5 1 15 25 10 1
// 6 1 31 90 65 15 1
// 7 1 63 301 350 140 21 1
// 8 1 127 966 1701 1050 266 28 1
// ...
int[][] arr = new int[2001][];
for (int i = 0; i < 2001; i++) {
arr[i] = new int[i+1];
}
arr[0][0] = 1;
for (int i = 1; i < 2001; i++) {
for(int j = 1; j < i; j++) {
arr[i][j] = (int) ((1L * arr[i-1][j] * j % MOD + arr[i-1][j-1]) % MOD);
}
arr[i][i] = 1;
if (i < 20) {
// System.out.format(" i:%2d %s\n", i, Arrays.toString(arr[i]));
}
}
return arr;
}
// compute x such that x * a == 1 % MOD
public static int inverse(long a) {
return power(a, MOD - 2);
}
// To compute x^y % MOD
public static int power(long x, int y) {
if (y == 0) {
return 1;
}
long w = power(x, y / 2);
w = (w * w) % MOD;
return (int) (y % 2 == 0 ? w : (w * x) % MOD);
}
static int solve(int n, int m, int k) {
long a = (m + 1)/2;
long q = a * inverse(m) % MOD;
long ans = 0;
long mul = 1;
for (int i = 1; i <= k; i++) {
mul = mul * q % MOD * (n-i+1) % MOD;
ans = (ans + CO[k][i] * mul % MOD) % MOD;
}
return (int) (ans * power(m,n) % MOD);
}
static class Combination {
final int n;
int[] fact;
int[] finv;
public Combination(int n) {
this.n = n;
this.fact = new int[n+1];
this.finv = new int[n+1];
fact[0] = 1;
finv[0] = 1;
for (int i = 1; i <= n; i++) {
fact[i] = (int) (((long) fact[i-1] * i) % MOD);
finv[i] = (int) (((long) finv[i-1] * inverse(i)) % MOD);
}
}
// Compute (m choose k) % MOD.
public int choose(int m, int k) {
return (int) ((((long)fact[m] * finv[k] % MOD) * finv[m-k]) % MOD);
}
}
private static long[][] computeTailCoeffs(int N) {
// 1 -> 1
// e -> 0 1
// e*(e-1) -> 0 -1 1
// e*(e-1)*(e-2) -> 0 2 -3 1
// ...
//
long[][] ta = new long[N][];
for (int i = 0; i < N; i++) {
ta[i] = new long[i+1];
if (i == 0) {
ta[i][0] = 1;
} else {
// multiple ta[i-1] by (e-(i-1))
System.arraycopy(ta[i-1], 0, ta[i], 1, ta[i-1].length);
for (int h = 0; h < i; h++) {
ta[i][h] = (ta[i][h] + MOD - (i-1) * ta[i-1][h] % MOD) % MOD;
}
}
if (i < 10) {
// System.out.format(" tail %d %s\n", i, Arrays.toString(ta[i]));
}
}
return ta;
}
static void test(int exp, int n, int m, int k) {
int ans = solve(n, m, k);
System.out.format("%9d %9d %9d => %d %s\n", n, m, k, ans, ans == exp ? "" : "Expected " + exp);
myAssert(ans == exp);
}
static boolean test = false;
static void doTest() {
if (!test) {
return;
}
long t0 = System.currentTimeMillis();
// test(652219904, 1337666, 42424242, 2000);
test(485812953, 3825, 476, 2000);
test(75131880, 1317, 8974, 2000);
test(515879741, 9550, 4026, 2000);
test(34049613, 8133, 129, 2000);
test(631767740, 6429, 5211, 2000);
test(330122212, 2715, 5907, 2000);
test(31026911, 6815, 2681, 2000);
test(772513405, 3674, 4043, 2000);
test(546776189, 1614, 1664, 2000);
test(273860898, 4845, 4622, 2000);
test(987134517, 4568, 508, 2000);
test(585535066, 6740, 4691, 2000);
test(303481469, 8401, 2520, 2000);
test(942774678, 5518, 1225, 2000);
test(611130133, 5818, 6963, 2000);
test(884718389, 409, 1798, 2000);
test(61887968, 5932, 597, 2000);
test(391461706, 2489, 8196, 2000);
test(655612215, 9961, 4627, 2000);
test(413770298, 2245, 6151, 2000);
test(960818414, 2549, 2543, 2000);
test(359085754, 743, 3202, 2000);
test(298890537, 6032, 67, 2000);
test(313703051, 5605, 7867, 2000);
test(82535400, 8935, 7951, 2000);
test(379388626, 2411, 123, 2000);
test(351929892, 7627, 4689, 2000);
test(636574771, 5579, 2554, 2000);
test(812449761, 7330, 340, 2000);
test(742447387, 5176, 4410, 2000);
test(762551061, 6781, 7020, 2000);
test(591374949, 2447, 7826, 2000);
System.out.format("%d msec\n", System.currentTimeMillis() - t0);
System.exit(0);
}
public static void main(String[] args) {
doTest();
MyScanner in = new MyScanner();
int T = in.nextInt();
for (int t = 1; t <= T; t++) {
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
int ans = solve(n, m, k);
System.out.println(ans);
}
}
static void output(int[] a) {
if (a == null) {
System.out.println("-1");
return;
}
StringBuilder sb = new StringBuilder();
for (int v : a) {
sb.append(v);
sb.append(' ');
if (sb.length() > 500) {
System.out.print(sb.toString());
sb.setLength(0);
}
}
System.out.println(sb.toString());
}
static void myAssert(boolean cond) {
if (!cond) {
throw new RuntimeException("Unexpected");
}
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
try {
final String USERDIR = System.getProperty("user.dir");
String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(".MyScanner", "");
cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname;
final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in");
br = new BufferedReader(new InputStreamReader(fin.exists()
? new FileInputStream(fin) : System.in));
} catch (Exception e) {
br = new BufferedReader(new InputStreamReader(System.in));
}
}
public String next() {
try {
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["5\n\n2 3 8\n\n1 1 1\n\n1 5 10\n\n3 7 2000\n\n1337666 42424242 2000"] | 3 seconds | ["1028\n1\n3\n729229716\n652219904"] | null | Java 11 | standard input | [
"combinatorics",
"dp",
"math",
"number theory"
] | fc8381e8c97190749b356f10cf80209e | The first line contains one integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of test cases. Each test case consists of one line containing three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n, m \le 998244352$$$; $$$1 \le k \le 2000$$$). | 2,500 | For each test case, print one integer — the sum of $$$F^k$$$ over all possible ways to take $$$n$$$ balls, one from each bag. Since it can be huge, print it modulo $$$998244353$$$. | standard output | |
PASSED | 941824e45d7bde7492ca16784734fe0a | train_109.jsonl | 1659623700 | There are $$$n$$$ bags, each bag contains $$$m$$$ balls with numbers from $$$1$$$ to $$$m$$$. For every $$$i \in [1, m]$$$, there is exactly one ball with number $$$i$$$ in each bag.You have to take exactly one ball from each bag (all bags are different, so, for example, taking the ball $$$1$$$ from the first bag and the ball $$$2$$$ from the second bag is not the same as taking the ball $$$2$$$ from the first bag and the ball $$$1$$$ from the second bag). After that, you calculate the number of balls with odd numbers among the ones you have taken. Let the number of these balls be $$$F$$$.Your task is to calculate the sum of $$$F^k$$$ over all possible ways to take $$$n$$$ balls, one from each bag. | 512 megabytes | // package c1716;
//
// Educational Codeforces Round 133 (Rated for Div. 2) 2022-08-04 07:35
// F. Bags with Balls
// https://codeforces.com/contest/1716/problem/F
// time limit per test 3 seconds; memory limit per test 512 megabytes
// public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*'
//
// There are n bags, each bag contains m balls with numbers from 1 to m. For every i \in [1, m],
// there is exactly one ball with number i in each bag.
//
// You have to take exactly one ball from each bag (all bags are different, so, for example, taking
// the ball 1 from the first bag and the ball 2 from the second bag is not the same as taking the
// ball 2 from the first bag and the ball 1 from the second bag). After that, you calculate the
// number of balls with numbers among the ones you have taken. Let the number of these balls be F.
//
// Your task is to calculate the sum of F^k over all possible ways to take n balls, one from each
// bag.
//
// Input
//
// The first line contains one integer t (1 <= t <= 5000)-- the number of test cases.
//
// Each test case consists of one line containing three integers n, m and k (1 <= n, m <= 998244352;
// 1 <= k <= 2000).
//
// Output
//
// For each test case, print one integer-- the sum of F^k over all possible ways to take n balls,
// one from each bag. Since it can be huge, print it modulo 998244353.
//
// Example
/*
input:
5
2 3 8
1 1 1
1 5 10
3 7 2000
1337666 42424242 2000
output:
1028
1
3
729229716
652219904
*/
//
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.invoke.MethodHandles;
import java.util.Random;
import java.util.StringTokenizer;
public class C1716F {
static final int MOD = 998244353;
static final Random RAND = new Random();
final static int[][] CO = computeCoeff();
static final int LOW = 2000;
static final Combination COMB = new Combination(LOW);
static final long[] F = new long[2001];
static int solveA(int n, int m, int k) {
// Take exactly one ball from each of n bags.
// Let F be number of odd balls with odd numbers among the ones taken
// we like to calculate sum(F^k) over all ways
if (m == 1) {
return power(n, k);
}
// In the example of (3,7,2000)
// we have (4x+3)^3 = 64x^3 + 144x^2 + 108x + 27
// -> 64*3^2000 + 144*2^2000 + 108*1^2000 + 27 * 0^2000
int a = (m + 1) / 2;
int b = m / 2;
long ans = 0;
if (n <= LOW) {
long v0 = (long)a * inverse(b) % MOD;
long v1 = power(b, n);
long v2 = v1;
for (int e = 0; e <= n; e++) {
long v = COMB.choose(n, e) * v2 % MOD;
v2 = v2 * v0 % MOD;
ans = (ans + v * power(e, k)) % MOD;
}
return (int) ans;
}
// consider all (n+1) terms of (ax+b)^n: C(n,e)*a^e*b^(n-e)*x^e for e in [0,n]
// Denote c(e) as C(n,e)*a^e*b^(n-e), we have f_n(x) = (ax+b)^n = sum(c(e)*x^e)
// Denote s(k) as sum(F^k) = sum(c(e)*e^k)
// we have s(0) = sum(c(e)) = (a+b)^n
// f[j] is value of f's j-th derivative at 1 where f = (ax+b)^n, that is,
// f[0] = f(1) = m^n
// f[1] = f'(1) = na(ax+b)^(n-1) = na(a+b)^(n-1) = nam^(n-1)
// f[2] = f''(1) = n(n-1)a^2(ax+b)^(n-2) = n(n-1)a^2(a+b)^n-2 = n(n-1)a^2m^(n-2)
// ...
// f[j] = f(j)(1) = n(n-1)...(n-j+1) a^j m^(n-j)
F[0] = power(m, n);
long mul = 1;
for (int j = 1; j <= k; j++) {
mul = (mul * (n - j + 1) % MOD) * a % MOD;
F[j] = mul * power(m, n-j) % MOD;
}
// s(k) = \sum_{1,n}c(e)*e^k
// s(0) = \sum_{1,n}c(e) =
// s(1) = \sum_{1,n}c(e)*e = f(1)
// s(2) = \sum_{1,n}c(e)*e^2 = f(2) + s(1)
// s(3) = \sum_{1,n}c(e)*e^3 = f(3) + 3s(2) - 2s(1)
// f = \sum_{0,n}c(e)x^e
// f' = \sum_{1,n}c(e)*e*x^(e-1) -> f(1)=\sum_{1,n}c(e)*e
// f'' = \sum_{2,n}c(e)*e*(e-1)x^(e-2) ->
// f(2) = \sum_{2,n}c(e)*(e^2-e)
// = \sum_{1,n}c(e)*(e^2-e) - \sum_{1,1}c(e)*(e^2-e)
// = \sum_{1,n}c(e)*(e^2-e)
// = s(2) - s(1)
// f'''= \sum_{3,n}c(e)*e*(e-1)*(e-2)x^(e-3) ->
// f(3) = \sum_{3,n}c(e)*e*(e-1)*(e-2)
// = \sum_{1,n}c(e)*e*(e-1)*(e-2) - \sum_{1,2}c(e)*e*(e-1)*(e-2)
// = \sum_{1,n}c(e)*e*(e-1)*(e-2)
// = \sum_{1,n}c(e)*(e^3-3e^2+2e)
// = s(3) - 3s(2) + 2s(1)
int[] co = CO[k];
for (int i = 0; i < co.length; i++) {
ans = (ans + co[i] * F[i]) % MOD;
}
return (int) ans;
}
// compute coefficient of s[j] = e(e-1)(e-2)...(e-j+1) in terms of f[]
static int[][] computeCoeff() {
// Use a1 to refer to f[1] etc, we have
// s0 don't really care
// s1 = a1
// s2 = a2 + a1
// s3 = a1 + 3*a2 + a3
// s4 = a1 + 7a2 + 6a3 + a4
//
// 1 1
// 2 1 1
// 3 1 3 1
// 4 1 7 6 1
// 5 1 15 25 10 1
// 6 1 31 90 65 15 1
// 7 1 63 301 350 140 21 1
// 8 1 127 966 1701 1050 266 28 1
// ...
int[][] arr = new int[2001][];
for (int i = 0; i < 2001; i++) {
arr[i] = new int[i+1];
}
arr[0][0] = 1;
for (int i = 1; i < 2001; i++) {
for(int j = 1; j < i; j++) {
arr[i][j] = (int) ((1L * arr[i-1][j] * j % MOD + arr[i-1][j-1]) % MOD);
}
arr[i][i] = 1;
if (i < 20) {
// System.out.format(" i:%2d %s\n", i, Arrays.toString(arr[i]));
}
}
return arr;
}
// compute x such that x * a == 1 % MOD
public static int inverse(long a) {
return power(a, MOD - 2);
}
// To compute x^y % MOD
public static int power(long x, int y) {
if (y == 0) {
return 1;
}
long w = power(x, y / 2);
w = (w * w) % MOD;
return (int) (y % 2 == 0 ? w : (w * x) % MOD);
}
static int solve(int n, int m, int k) {
long a = (m + 1)/2;
long q = a * inverse(m) % MOD;
long ans = 0;
long mul = 1;
for (int i = 1; i <= k; i++) {
mul = mul * q % MOD * (n-i+1) % MOD;
ans = (ans + CO[k][i] * mul % MOD) % MOD;
}
return (int) (ans * power(m,n) % MOD);
}
static class Combination {
final int n;
int[] fact;
int[] finv;
public Combination(int n) {
this.n = n;
this.fact = new int[n+1];
this.finv = new int[n+1];
fact[0] = 1;
finv[0] = 1;
for (int i = 1; i <= n; i++) {
fact[i] = (int) (((long) fact[i-1] * i) % MOD);
finv[i] = (int) (((long) finv[i-1] * inverse(i)) % MOD);
}
}
// Compute (m choose k) % MOD.
public int choose(int m, int k) {
return (int) ((((long)fact[m] * finv[k] % MOD) * finv[m-k]) % MOD);
}
}
private static long[][] computeTailCoeffs(int N) {
// 1 -> 1
// e -> 0 1
// e*(e-1) -> 0 -1 1
// e*(e-1)*(e-2) -> 0 2 -3 1
// ...
//
long[][] ta = new long[N][];
for (int i = 0; i < N; i++) {
ta[i] = new long[i+1];
if (i == 0) {
ta[i][0] = 1;
} else {
// multiple ta[i-1] by (e-(i-1))
System.arraycopy(ta[i-1], 0, ta[i], 1, ta[i-1].length);
for (int h = 0; h < i; h++) {
ta[i][h] = (ta[i][h] + MOD - (i-1) * ta[i-1][h] % MOD) % MOD;
}
}
if (i < 10) {
// System.out.format(" tail %d %s\n", i, Arrays.toString(ta[i]));
}
}
return ta;
}
static void test(int exp, int n, int m, int k) {
int ans = solve(n, m, k);
System.out.format("%9d %9d %9d => %d %s\n", n, m, k, ans, ans == exp ? "" : "Expected " + exp);
myAssert(ans == exp);
}
static boolean test = false;
static void doTest() {
if (!test) {
return;
}
long t0 = System.currentTimeMillis();
// test(652219904, 1337666, 42424242, 2000);
test(485812953, 3825, 476, 2000);
test(75131880, 1317, 8974, 2000);
test(515879741, 9550, 4026, 2000);
test(34049613, 8133, 129, 2000);
test(631767740, 6429, 5211, 2000);
test(330122212, 2715, 5907, 2000);
test(31026911, 6815, 2681, 2000);
test(772513405, 3674, 4043, 2000);
test(546776189, 1614, 1664, 2000);
test(273860898, 4845, 4622, 2000);
test(987134517, 4568, 508, 2000);
test(585535066, 6740, 4691, 2000);
test(303481469, 8401, 2520, 2000);
test(942774678, 5518, 1225, 2000);
test(611130133, 5818, 6963, 2000);
test(884718389, 409, 1798, 2000);
test(61887968, 5932, 597, 2000);
test(391461706, 2489, 8196, 2000);
test(655612215, 9961, 4627, 2000);
test(413770298, 2245, 6151, 2000);
test(960818414, 2549, 2543, 2000);
test(359085754, 743, 3202, 2000);
test(298890537, 6032, 67, 2000);
test(313703051, 5605, 7867, 2000);
test(82535400, 8935, 7951, 2000);
test(379388626, 2411, 123, 2000);
test(351929892, 7627, 4689, 2000);
test(636574771, 5579, 2554, 2000);
test(812449761, 7330, 340, 2000);
test(742447387, 5176, 4410, 2000);
test(762551061, 6781, 7020, 2000);
test(591374949, 2447, 7826, 2000);
System.out.format("%d msec\n", System.currentTimeMillis() - t0);
System.exit(0);
}
public static void main(String[] args) {
doTest();
MyScanner in = new MyScanner();
int T = in.nextInt();
for (int t = 1; t <= T; t++) {
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
int ans = solve(n, m, k);
System.out.println(ans);
}
}
static void output(int[] a) {
if (a == null) {
System.out.println("-1");
return;
}
StringBuilder sb = new StringBuilder();
for (int v : a) {
sb.append(v);
sb.append(' ');
if (sb.length() > 500) {
System.out.print(sb.toString());
sb.setLength(0);
}
}
System.out.println(sb.toString());
}
static void myAssert(boolean cond) {
if (!cond) {
throw new RuntimeException("Unexpected");
}
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
try {
final String USERDIR = System.getProperty("user.dir");
String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(".MyScanner", "");
cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname;
final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in");
br = new BufferedReader(new InputStreamReader(fin.exists()
? new FileInputStream(fin) : System.in));
} catch (Exception e) {
br = new BufferedReader(new InputStreamReader(System.in));
}
}
public String next() {
try {
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["5\n\n2 3 8\n\n1 1 1\n\n1 5 10\n\n3 7 2000\n\n1337666 42424242 2000"] | 3 seconds | ["1028\n1\n3\n729229716\n652219904"] | null | Java 8 | standard input | [
"combinatorics",
"dp",
"math",
"number theory"
] | fc8381e8c97190749b356f10cf80209e | The first line contains one integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of test cases. Each test case consists of one line containing three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n, m \le 998244352$$$; $$$1 \le k \le 2000$$$). | 2,500 | For each test case, print one integer — the sum of $$$F^k$$$ over all possible ways to take $$$n$$$ balls, one from each bag. Since it can be huge, print it modulo $$$998244353$$$. | standard output | |
PASSED | ca7eedf7cd81a68d1aa5dcad95b31794 | train_109.jsonl | 1659623700 | There are $$$n$$$ bags, each bag contains $$$m$$$ balls with numbers from $$$1$$$ to $$$m$$$. For every $$$i \in [1, m]$$$, there is exactly one ball with number $$$i$$$ in each bag.You have to take exactly one ball from each bag (all bags are different, so, for example, taking the ball $$$1$$$ from the first bag and the ball $$$2$$$ from the second bag is not the same as taking the ball $$$2$$$ from the first bag and the ball $$$1$$$ from the second bag). After that, you calculate the number of balls with odd numbers among the ones you have taken. Let the number of these balls be $$$F$$$.Your task is to calculate the sum of $$$F^k$$$ over all possible ways to take $$$n$$$ balls, one from each bag. | 512 megabytes | // package c1716;
//
// Educational Codeforces Round 133 (Rated for Div. 2) 2022-08-04 07:35
// F. Bags with Balls
// https://codeforces.com/contest/1716/problem/F
// time limit per test 3 seconds; memory limit per test 512 megabytes
// public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*'
//
// There are n bags, each bag contains m balls with numbers from 1 to m. For every i \in [1, m],
// there is exactly one ball with number i in each bag.
//
// You have to take exactly one ball from each bag (all bags are different, so, for example, taking
// the ball 1 from the first bag and the ball 2 from the second bag is not the same as taking the
// ball 2 from the first bag and the ball 1 from the second bag). After that, you calculate the
// number of balls with numbers among the ones you have taken. Let the number of these balls be F.
//
// Your task is to calculate the sum of F^k over all possible ways to take n balls, one from each
// bag.
//
// Input
//
// The first line contains one integer t (1 <= t <= 5000)-- the number of test cases.
//
// Each test case consists of one line containing three integers n, m and k (1 <= n, m <= 998244352;
// 1 <= k <= 2000).
//
// Output
//
// For each test case, print one integer-- the sum of F^k over all possible ways to take n balls,
// one from each bag. Since it can be huge, print it modulo 998244353.
//
// Example
/*
input:
5
2 3 8
1 1 1
1 5 10
3 7 2000
1337666 42424242 2000
output:
1028
1
3
729229716
652219904
*/
//
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.invoke.MethodHandles;
import java.util.Random;
import java.util.StringTokenizer;
public class C1716F {
static final int MOD = 998244353;
static final Random RAND = new Random();
final static int[][] CO = computeCoeff();
static final int LOW = 2000;
static final Combination COMB = new Combination(LOW);
static final long[] F = new long[2001];
static int solveA(int n, int m, int k) {
// Take exactly one ball from each of n bags.
// Let F be number of odd balls with odd numbers among the ones taken
// we like to calculate sum(F^k) over all ways
if (m == 1) {
return power(n, k);
}
// In the example of (3,7,2000)
// we have (4x+3)^3 = 64x^3 + 144x^2 + 108x + 27
// -> 64*3^2000 + 144*2^2000 + 108*1^2000 + 27 * 0^2000
int a = (m + 1) / 2;
int b = m / 2;
long ans = 0;
if (n <= LOW) {
long v0 = (long)a * inverse(b) % MOD;
long v1 = power(b, n);
long v2 = v1;
for (int e = 0; e <= n; e++) {
long v = COMB.choose(n, e) * v2 % MOD;
v2 = v2 * v0 % MOD;
ans = (ans + v * power(e, k)) % MOD;
}
return (int) ans;
}
// consider all (n+1) terms of (ax+b)^n: C(n,e)*a^e*b^(n-e)*x^e for e in [0,n]
// Denote c(e) as C(n,e)*a^e*b^(n-e), we have f_n(x) = (ax+b)^n = sum(c(e)*x^e)
// Denote s(k) as sum(F^k) = sum(c(e)*e^k)
// we have s(0) = sum(c(e)) = (a+b)^n
// f[j] is value of f's j-th derivative at 1 where f = (ax+b)^n, that is,
// f[0] = f(1) = m^n
// f[1] = f'(1) = na(ax+b)^(n-1) = na(a+b)^(n-1) = nam^(n-1)
// f[2] = f''(1) = n(n-1)a^2(ax+b)^(n-2) = n(n-1)a^2(a+b)^n-2 = n(n-1)a^2m^(n-2)
// ...
// f[j] = f(j)(1) = n(n-1)...(n-j+1) a^j m^(n-j)
F[0] = power(m, n);
long mul = 1;
for (int j = 1; j <= k; j++) {
mul = (mul * (n - j + 1) % MOD) * a % MOD;
F[j] = mul * power(m, n-j) % MOD;
}
// s(k) = \sum_{1,n}c(e)*e^k
// s(0) = \sum_{1,n}c(e) =
// s(1) = \sum_{1,n}c(e)*e = f(1)
// s(2) = \sum_{1,n}c(e)*e^2 = f(2) + s(1)
// s(3) = \sum_{1,n}c(e)*e^3 = f(3) + 3s(2) - 2s(1)
// f = \sum_{0,n}c(e)x^e
// f' = \sum_{1,n}c(e)*e*x^(e-1) -> f(1)=\sum_{1,n}c(e)*e
// f'' = \sum_{2,n}c(e)*e*(e-1)x^(e-2) ->
// f(2) = \sum_{2,n}c(e)*(e^2-e)
// = \sum_{1,n}c(e)*(e^2-e) - \sum_{1,1}c(e)*(e^2-e)
// = \sum_{1,n}c(e)*(e^2-e)
// = s(2) - s(1)
// f'''= \sum_{3,n}c(e)*e*(e-1)*(e-2)x^(e-3) ->
// f(3) = \sum_{3,n}c(e)*e*(e-1)*(e-2)
// = \sum_{1,n}c(e)*e*(e-1)*(e-2) - \sum_{1,2}c(e)*e*(e-1)*(e-2)
// = \sum_{1,n}c(e)*e*(e-1)*(e-2)
// = \sum_{1,n}c(e)*(e^3-3e^2+2e)
// = s(3) - 3s(2) + 2s(1)
int[] co = CO[k];
for (int i = 0; i < co.length; i++) {
ans = (ans + co[i] * F[i]) % MOD;
}
return (int) ans;
}
// compute coefficient of s[j] = e(e-1)(e-2)...(e-j+1) in terms of f[]
static int[][] computeCoeff() {
// Use a1 to refer to f[1] etc, we have
// s0 don't really care
// s1 = a1
// s2 = a2 + a1
// s3 = a1 + 3*a2 + a3
// s4 = a1 + 7a2 + 6a3 + a4
//
// 1 1
// 2 1 1
// 3 1 3 1
// 4 1 7 6 1
// 5 1 15 25 10 1
// 6 1 31 90 65 15 1
// 7 1 63 301 350 140 21 1
// 8 1 127 966 1701 1050 266 28 1
// ...
int[][] arr = new int[2001][];
for (int i = 0; i < 2001; i++) {
arr[i] = new int[i+1];
}
arr[0][0] = 1;
for (int i = 1; i < 2001; i++) {
for(int j = 1; j < i; j++) {
arr[i][j] = (int) ((1L * arr[i-1][j] * j % MOD + arr[i-1][j-1]) % MOD);
}
arr[i][i] = 1;
if (i < 20) {
// System.out.format(" i:%2d %s\n", i, Arrays.toString(arr[i]));
}
}
return arr;
}
// compute x such that x * a == 1 % MOD
public static int inverse(long a) {
return power(a, MOD - 2);
}
// To compute x^y % MOD
public static int power(long x, int y) {
if (y == 0) {
return 1;
}
long w = power(x, y / 2);
w = (w * w) % MOD;
return (int) (y % 2 == 0 ? w : (w * x) % MOD);
}
static int solve(int n, int m, int k) {
long a = (m + 1)/2;
long q = a * inverse(m) % MOD;
long ans = 0;
long mul = 1;
for (int i = 1; i <= k; i++) {
mul = mul * q % MOD * (n-i+1) % MOD;
ans = (ans + CO[k][i] * mul % MOD) % MOD;
}
return (int) (ans * power(m,n) % MOD);
}
static class Combination {
final int n;
int[] fact;
int[] finv;
public Combination(int n) {
this.n = n;
this.fact = new int[n+1];
this.finv = new int[n+1];
fact[0] = 1;
finv[0] = 1;
for (int i = 1; i <= n; i++) {
fact[i] = (int) (((long) fact[i-1] * i) % MOD);
finv[i] = (int) (((long) finv[i-1] * inverse(i)) % MOD);
}
}
// Compute (m choose k) % MOD.
public int choose(int m, int k) {
return (int) ((((long)fact[m] * finv[k] % MOD) * finv[m-k]) % MOD);
}
}
private static long[][] computeTailCoeffs(int N) {
// 1 -> 1
// e -> 0 1
// e*(e-1) -> 0 -1 1
// e*(e-1)*(e-2) -> 0 2 -3 1
// ...
//
long[][] ta = new long[N][];
for (int i = 0; i < N; i++) {
ta[i] = new long[i+1];
if (i == 0) {
ta[i][0] = 1;
} else {
// multiple ta[i-1] by (e-(i-1))
System.arraycopy(ta[i-1], 0, ta[i], 1, ta[i-1].length);
for (int h = 0; h < i; h++) {
ta[i][h] = (ta[i][h] + MOD - (i-1) * ta[i-1][h] % MOD) % MOD;
}
}
if (i < 10) {
// System.out.format(" tail %d %s\n", i, Arrays.toString(ta[i]));
}
}
return ta;
}
static void test(int exp, int n, int m, int k) {
int ans = solve(n, m, k);
System.out.format("%9d %9d %9d => %d %s\n", n, m, k, ans, ans == exp ? "" : "Expected " + exp);
myAssert(ans == exp);
}
static boolean test = false;
static void doTest() {
if (!test) {
return;
}
long t0 = System.currentTimeMillis();
// test(652219904, 1337666, 42424242, 2000);
test(485812953, 3825, 476, 2000);
test(75131880, 1317, 8974, 2000);
test(515879741, 9550, 4026, 2000);
test(34049613, 8133, 129, 2000);
test(631767740, 6429, 5211, 2000);
test(330122212, 2715, 5907, 2000);
test(31026911, 6815, 2681, 2000);
test(772513405, 3674, 4043, 2000);
test(546776189, 1614, 1664, 2000);
test(273860898, 4845, 4622, 2000);
test(987134517, 4568, 508, 2000);
test(585535066, 6740, 4691, 2000);
test(303481469, 8401, 2520, 2000);
test(942774678, 5518, 1225, 2000);
test(611130133, 5818, 6963, 2000);
test(884718389, 409, 1798, 2000);
test(61887968, 5932, 597, 2000);
test(391461706, 2489, 8196, 2000);
test(655612215, 9961, 4627, 2000);
test(413770298, 2245, 6151, 2000);
test(960818414, 2549, 2543, 2000);
test(359085754, 743, 3202, 2000);
test(298890537, 6032, 67, 2000);
test(313703051, 5605, 7867, 2000);
test(82535400, 8935, 7951, 2000);
test(379388626, 2411, 123, 2000);
test(351929892, 7627, 4689, 2000);
test(636574771, 5579, 2554, 2000);
test(812449761, 7330, 340, 2000);
test(742447387, 5176, 4410, 2000);
test(762551061, 6781, 7020, 2000);
test(591374949, 2447, 7826, 2000);
System.out.format("%d msec\n", System.currentTimeMillis() - t0);
System.exit(0);
}
public static void main(String[] args) {
doTest();
MyScanner in = new MyScanner();
int T = in.nextInt();
for (int t = 1; t <= T; t++) {
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
int ans = solve(n, m, k);
System.out.println(ans);
}
}
static void output(int[] a) {
if (a == null) {
System.out.println("-1");
return;
}
StringBuilder sb = new StringBuilder();
for (int v : a) {
sb.append(v);
sb.append(' ');
if (sb.length() > 500) {
System.out.print(sb.toString());
sb.setLength(0);
}
}
System.out.println(sb.toString());
}
static void myAssert(boolean cond) {
if (!cond) {
throw new RuntimeException("Unexpected");
}
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
try {
final String USERDIR = System.getProperty("user.dir");
String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(".MyScanner", "");
cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname;
final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in");
br = new BufferedReader(new InputStreamReader(fin.exists()
? new FileInputStream(fin) : System.in));
} catch (Exception e) {
br = new BufferedReader(new InputStreamReader(System.in));
}
}
public String next() {
try {
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["5\n\n2 3 8\n\n1 1 1\n\n1 5 10\n\n3 7 2000\n\n1337666 42424242 2000"] | 3 seconds | ["1028\n1\n3\n729229716\n652219904"] | null | Java 8 | standard input | [
"combinatorics",
"dp",
"math",
"number theory"
] | fc8381e8c97190749b356f10cf80209e | The first line contains one integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of test cases. Each test case consists of one line containing three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n, m \le 998244352$$$; $$$1 \le k \le 2000$$$). | 2,500 | For each test case, print one integer — the sum of $$$F^k$$$ over all possible ways to take $$$n$$$ balls, one from each bag. Since it can be huge, print it modulo $$$998244353$$$. | standard output | |
PASSED | 972f5c03473cf3f8317db0f7858a525e | train_109.jsonl | 1659623700 | You are given an array of length $$$2^n$$$. The elements of the array are numbered from $$$1$$$ to $$$2^n$$$.You have to process $$$q$$$ queries to this array. In the $$$i$$$-th query, you will be given an integer $$$k$$$ ($$$0 \le k \le n-1$$$). To process the query, you should do the following: for every $$$i \in [1, 2^n-2^k]$$$ in ascending order, do the following: if the $$$i$$$-th element was already swapped with some other element during this query, skip it; otherwise, swap $$$a_i$$$ and $$$a_{i+2^k}$$$; after that, print the maximum sum over all contiguous subsegments of the array (including the empty subsegment). For example, if the array $$$a$$$ is $$$[-3, 5, -3, 2, 8, -20, 6, -1]$$$, and $$$k = 1$$$, the query is processed as follows: the $$$1$$$-st element wasn't swapped yet, so we swap it with the $$$3$$$-rd element; the $$$2$$$-nd element wasn't swapped yet, so we swap it with the $$$4$$$-th element; the $$$3$$$-rd element was swapped already; the $$$4$$$-th element was swapped already; the $$$5$$$-th element wasn't swapped yet, so we swap it with the $$$7$$$-th element; the $$$6$$$-th element wasn't swapped yet, so we swap it with the $$$8$$$-th element. So, the array becomes $$$[-3, 2, -3, 5, 6, -1, 8, -20]$$$. The subsegment with the maximum sum is $$$[5, 6, -1, 8]$$$, and the answer to the query is $$$18$$$.Note that the queries actually change the array, i. e. after a query is performed, the array does not return to its original state, and the next query will be applied to the modified array. | 512 megabytes | import java.io.*;
import java.util.*;
public class Div21716E {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int n = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
long[] ar = new long[(1<<n)];
for(int i = 0; i < (1<<n); i++)
ar[i] = Integer.parseInt(st.nextToken());
//use combination of merge and pivot operations to get a full range for each mask
long[][][] dp = new long[(1<<n)][][];
dp[0] = new long[(1<<n)][4];
for(int i = 0; i < Math.pow(2, n); i++) {
dp[0][i][0] = ar[i];
dp[0][i][1] = dp[0][i][2] = dp[0][i][3] = Math.max(0, ar[i]);
}
int piv = 1;
for(int i = 1; i <= (1<<n); i++) {
if((i & (i - 1)) == 0 && i > 1) {
for(int j = 0; j < i; j++) {
long[][] nar = new long[dp[j].length/2][4];
for(int k = 0; k < dp[j].length; k += 2) {
nar[k/2][0] = dp[j][k][0] + dp[j][k+1][0];
nar[k/2][1] = Math.max(dp[j][k][1], dp[j][k][0] + dp[j][k+1][1]);
nar[k/2][2] = Math.max(dp[j][k+1][2], dp[j][k+1][0] + dp[j][k][2]);
nar[k/2][3] = Math.max(Math.max(dp[j][k][3], dp[j][k+1][3]), dp[j][k][2] + dp[j][k+1][1]);
}
dp[j] = nar;
}
piv = i;
}
if(i < (1<<n)) {
dp[i] = new long[dp[i^piv].length][4];
for(int j = 0; j < dp[i^piv].length; j += 2) {
dp[i][j] = dp[i^piv][j+1];
dp[i][j+1] = dp[i^piv][j];
}
}
}
int q = Integer.parseInt(br.readLine());
int cm = 0;
while(q --> 0) {
cm ^= (1<<Integer.parseInt(br.readLine()));
pw.println(Math.max(dp[cm][0][1], Math.max(dp[cm][0][2], dp[cm][0][3])));
}
pw.close();
}
}
| Java | ["3\n-3 5 -3 2 8 -20 6 -1\n3\n1\n0\n1"] | 4 seconds | ["18\n8\n13"] | NoteTransformation of the array in the example: $$$[-3, 5, -3, 2, 8, -20, 6, -1] \rightarrow [-3, 2, -3, 5, 6, -1, 8, -20] \rightarrow [2, -3, 5, -3, -1, 6, -20, 8] \rightarrow [5, -3, 2, -3, -20, 8, -1, 6]$$$. | Java 11 | standard input | [
"bitmasks",
"data structures",
"dfs and similar",
"divide and conquer",
"dp"
] | 376b293013562d5e004411f42082ce5c | The first line contains one integer $$$n$$$ ($$$1 \le n \le 18$$$). The second line contains $$$2^n$$$ integers $$$a_1, a_2, \dots, a_{2^n}$$$ ($$$-10^9 \le a_i \le 10^9$$$). The third line contains one integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$). Then $$$q$$$ lines follow, the $$$i$$$-th of them contains one integer $$$k$$$ ($$$0 \le k \le n-1$$$) describing the $$$i$$$-th query. | 2,500 | For each query, print one integer — the maximum sum over all contiguous subsegments of the array (including the empty subsegment) after processing the query. | standard output | |
PASSED | ff81f042521c6a51123fcabae6589052 | train_109.jsonl | 1659623700 | You are given an array of length $$$2^n$$$. The elements of the array are numbered from $$$1$$$ to $$$2^n$$$.You have to process $$$q$$$ queries to this array. In the $$$i$$$-th query, you will be given an integer $$$k$$$ ($$$0 \le k \le n-1$$$). To process the query, you should do the following: for every $$$i \in [1, 2^n-2^k]$$$ in ascending order, do the following: if the $$$i$$$-th element was already swapped with some other element during this query, skip it; otherwise, swap $$$a_i$$$ and $$$a_{i+2^k}$$$; after that, print the maximum sum over all contiguous subsegments of the array (including the empty subsegment). For example, if the array $$$a$$$ is $$$[-3, 5, -3, 2, 8, -20, 6, -1]$$$, and $$$k = 1$$$, the query is processed as follows: the $$$1$$$-st element wasn't swapped yet, so we swap it with the $$$3$$$-rd element; the $$$2$$$-nd element wasn't swapped yet, so we swap it with the $$$4$$$-th element; the $$$3$$$-rd element was swapped already; the $$$4$$$-th element was swapped already; the $$$5$$$-th element wasn't swapped yet, so we swap it with the $$$7$$$-th element; the $$$6$$$-th element wasn't swapped yet, so we swap it with the $$$8$$$-th element. So, the array becomes $$$[-3, 2, -3, 5, 6, -1, 8, -20]$$$. The subsegment with the maximum sum is $$$[5, 6, -1, 8]$$$, and the answer to the query is $$$18$$$.Note that the queries actually change the array, i. e. after a query is performed, the array does not return to its original state, and the next query will be applied to the modified array. | 512 megabytes | import java.io.*;
import java.util.*;
public class Div21716E {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int n = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
long[] ar = new long[(1<<n)];
for(int i = 0; i < (1<<n); i++)
ar[i] = Integer.parseInt(st.nextToken());
//use combination of merge and pivot operations to get a full range for each mask
long[][][] dp = new long[(1<<n)][][];
dp[0] = new long[(1<<n)][4];
for(int i = 0; i < Math.pow(2, n); i++) {
dp[0][i][0] = ar[i];
dp[0][i][1] = dp[0][i][2] = dp[0][i][3] = Math.max(0, ar[i]);
}
int piv = 1;
for(int i = 1; i <= (1<<n); i++) {
if((i & (i - 1)) == 0 && i > 1) {
for(int j = 0; j < i; j++) {
long[][] nar = new long[dp[j].length/2][4];
for(int k = 0; k < dp[j].length; k += 2) {
nar[k/2][0] = dp[j][k][0] + dp[j][k+1][0];
nar[k/2][1] = Math.max(dp[j][k][1], dp[j][k][0] + dp[j][k+1][1]);
nar[k/2][2] = Math.max(dp[j][k+1][2], dp[j][k+1][0] + dp[j][k][2]);
nar[k/2][3] = Math.max(Math.max(dp[j][k][3], dp[j][k+1][3]), dp[j][k][2] + dp[j][k+1][1]);
}
dp[j] = nar;
}
piv = i;
}
if(i < (1<<n)) {
dp[i] = new long[dp[i^piv].length][4];
for(int j = 0; j < dp[i^piv].length; j += 2) {
dp[i][j] = dp[i^piv][j+1];
dp[i][j+1] = dp[i^piv][j];
}
}
}
int q = Integer.parseInt(br.readLine());
int cm = 0;
while(q --> 0) {
cm ^= (1<<Integer.parseInt(br.readLine()));
pw.println(Math.max(dp[cm][0][1], Math.max(dp[cm][0][2], dp[cm][0][3])));
}
pw.close();
}
} | Java | ["3\n-3 5 -3 2 8 -20 6 -1\n3\n1\n0\n1"] | 4 seconds | ["18\n8\n13"] | NoteTransformation of the array in the example: $$$[-3, 5, -3, 2, 8, -20, 6, -1] \rightarrow [-3, 2, -3, 5, 6, -1, 8, -20] \rightarrow [2, -3, 5, -3, -1, 6, -20, 8] \rightarrow [5, -3, 2, -3, -20, 8, -1, 6]$$$. | Java 11 | standard input | [
"bitmasks",
"data structures",
"dfs and similar",
"divide and conquer",
"dp"
] | 376b293013562d5e004411f42082ce5c | The first line contains one integer $$$n$$$ ($$$1 \le n \le 18$$$). The second line contains $$$2^n$$$ integers $$$a_1, a_2, \dots, a_{2^n}$$$ ($$$-10^9 \le a_i \le 10^9$$$). The third line contains one integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$). Then $$$q$$$ lines follow, the $$$i$$$-th of them contains one integer $$$k$$$ ($$$0 \le k \le n-1$$$) describing the $$$i$$$-th query. | 2,500 | For each query, print one integer — the maximum sum over all contiguous subsegments of the array (including the empty subsegment) after processing the query. | standard output | |
PASSED | d3f72abf3cc4f0037276b7df2ccac802 | train_109.jsonl | 1659623700 | You are given an array of length $$$2^n$$$. The elements of the array are numbered from $$$1$$$ to $$$2^n$$$.You have to process $$$q$$$ queries to this array. In the $$$i$$$-th query, you will be given an integer $$$k$$$ ($$$0 \le k \le n-1$$$). To process the query, you should do the following: for every $$$i \in [1, 2^n-2^k]$$$ in ascending order, do the following: if the $$$i$$$-th element was already swapped with some other element during this query, skip it; otherwise, swap $$$a_i$$$ and $$$a_{i+2^k}$$$; after that, print the maximum sum over all contiguous subsegments of the array (including the empty subsegment). For example, if the array $$$a$$$ is $$$[-3, 5, -3, 2, 8, -20, 6, -1]$$$, and $$$k = 1$$$, the query is processed as follows: the $$$1$$$-st element wasn't swapped yet, so we swap it with the $$$3$$$-rd element; the $$$2$$$-nd element wasn't swapped yet, so we swap it with the $$$4$$$-th element; the $$$3$$$-rd element was swapped already; the $$$4$$$-th element was swapped already; the $$$5$$$-th element wasn't swapped yet, so we swap it with the $$$7$$$-th element; the $$$6$$$-th element wasn't swapped yet, so we swap it with the $$$8$$$-th element. So, the array becomes $$$[-3, 2, -3, 5, 6, -1, 8, -20]$$$. The subsegment with the maximum sum is $$$[5, 6, -1, 8]$$$, and the answer to the query is $$$18$$$.Note that the queries actually change the array, i. e. after a query is performed, the array does not return to its original state, and the next query will be applied to the modified array. | 512 megabytes | import java.util.*;
import java.io.*;
import java.util.Arrays;
import java.util.Random;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
/*
Solution Created: 16:30:25 09/08/2022
Custom Competitive programming helper.
*/
public class Main {
static class Node{
long pref, suf, whole, ans;
public Node() {
pref = suf = whole = ans = 0;
}
public Node(long val) {
pref = suf = whole = val;
ans = Math.max(0, val);
}
public Node(Node l, Node r) {
whole = l.whole + r.whole;
pref = Math.max(l.pref, l.whole + r.pref);
suf = Math.max(r.suf, l.suf + r.whole);
ans = Math.max(l.suf + r.pref, Math.max(l.ans, r.ans));
}
}
public static void solve() {
int n = in.nextInt();
long[] D = in.nl(1<<n);
Node[][] a = new Node[20][1<<n];
for(int i = 0; i<(1<<n); i++) a[0][i] = new Node(D[i]);
for(int bit = 1; bit<=n; bit++) {
for(int i = 0; i<1<<n; i++) {
a[bit][i] = new Node(a[bit-1][i], a[bit-1][i^(1<<(bit-1))]);
}
}
int cur = 0, q = in.nextInt();
while(q-->0) {
cur ^= (1<<in.nextInt());
out.println(a[n][cur].ans);
}
}
public static void main(String[] args) {
in = new Reader();
out = new Writer();
int t = 1;
while(t-->0) solve();
out.exit();
}
static Reader in; static Writer out;
static class Reader {
static BufferedReader br;
static StringTokenizer st;
public Reader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public Reader(String f){
try {
br = new BufferedReader(new FileReader(f));
} catch (IOException e) {
e.printStackTrace();
}
}
public int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
public double[] nd(int n) {
double[] a = new double[n];
for (int i = 0; i < n; i++) a[i] = nextDouble();
return a;
}
public long[] nl(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
public char[] nca() {
return next().toCharArray();
}
public String[] ns(int n) {
String[] a = new String[n];
for (int i = 0; i < n; i++) a[i] = next();
return a;
}
public int nextInt() {
ensureNext();
return Integer.parseInt(st.nextToken());
}
public double nextDouble() {
ensureNext();
return Double.parseDouble(st.nextToken());
}
public Long nextLong() {
ensureNext();
return Long.parseLong(st.nextToken());
}
public String next() {
ensureNext();
return st.nextToken();
}
public String nextLine() {
try {
return br.readLine();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private void ensureNext() {
if (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
static class Util {
private static Random random = new Random();
private static long MOD;
static long[] fact, inv, invFact;
public static void initCombinatorics(int n, long mod, boolean inversesToo, boolean inverseFactorialsToo) {
MOD = mod;
fact = new long[n + 1];
fact[0] = 1;
for (int i = 1; i < n + 1; i++) fact[i] = (fact[i - 1] * i) % mod;
if (inversesToo) {
inv = new long[n + 1];
inv[1] = 1;
for (int i = 2; i <= n; ++i) inv[i] = (mod - (mod / i) * inv[(int) (mod % i)] % mod) % mod;
}
if (inverseFactorialsToo) {
invFact = new long[n + 1];
invFact[n] = Util.modInverse(fact[n], mod);
for (int i = n - 1; i >= 0; i--) {
if (invFact[i + 1] == -1) {
invFact[i] = Util.modInverse(fact[i], mod);
continue;
}
invFact[i] = (invFact[i + 1] * (i + 1)) % mod;
}
}
}
public static long modInverse(long a, long mod) {
long[] gcdE = gcdExtended(a, mod);
if (gcdE[0] != 1) return -1; // Inverse doesn't exist
long x = gcdE[1];
return (x % mod + mod) % mod;
}
public static long[] gcdExtended(long p, long q) {
if (q == 0) return new long[] { p, 1, 0 };
long[] vals = gcdExtended(q, p % q);
long tmp = vals[2];
vals[2] = vals[1] - (p / q) * vals[2];
vals[1] = tmp;
return vals;
}
public static long nCr(int n, int r) {
if (r > n) return 0;
return (((fact[n] * invFact[r]) % MOD) * invFact[n - r]) % MOD;
}
public static long nPr(int n, int r) {
if (r > n) return 0;
return (fact[n] * invFact[n - r]) % MOD;
}
public static boolean isPrime(int n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
public static boolean[] getSieve(int n) {
boolean[] isPrime = new boolean[n + 1];
for (int i = 2; i <= n; i++) isPrime[i] = true;
for (int i = 2; i * i <= n; i++)
if (isPrime[i])
for (int j = i; i * j <= n; j++)
isPrime[i * j] = false;
return isPrime;
}
static long pow(long x, long pow, long mod) {
long res = 1;
x = x % mod;
if (x == 0) return 0;
while (pow > 0) {
if ((pow & 1) != 0) res = (res * x) % mod;
pow >>= 1;
x = (x * x) % mod;
}
return res;
}
public static int gcd(int a, int b) {
int tmp = 0;
while (b != 0) {
tmp = b;
b = a % b;
a = tmp;
}
return a;
}
public static long gcd(long a, long b) {
long tmp = 0;
while (b != 0) {
tmp = b;
b = a % b;
a = tmp;
}
return a;
}
public static int random(int min, int max) {
return random.nextInt(max - min + 1) + min;
}
public static void dbg(Object... o) {
System.out.println(Arrays.deepToString(o));
}
public static void reverse(int[] s, int l, int r) {
for (int i = l; i <= (l + r) / 2; i++) {
int tmp = s[i];
s[i] = s[r + l - i];
s[r + l - i] = tmp;
}
}
public static void reverse(int[] s) {
reverse(s, 0, s.length - 1);
}
public static void reverse(long[] s, int l, int r) {
for (int i = l; i <= (l + r) / 2; i++) {
long tmp = s[i];
s[i] = s[r + l - i];
s[r + l - i] = tmp;
}
}
public static void reverse(long[] s) {
reverse(s, 0, s.length - 1);
}
public static void reverse(float[] s, int l, int r) {
for (int i = l; i <= (l + r) / 2; i++) {
float tmp = s[i];
s[i] = s[r + l - i];
s[r + l - i] = tmp;
}
}
public static void reverse(float[] s) {
reverse(s, 0, s.length - 1);
}
public static void reverse(double[] s, int l, int r) {
for (int i = l; i <= (l + r) / 2; i++) {
double tmp = s[i];
s[i] = s[r + l - i];
s[r + l - i] = tmp;
}
}
public static void reverse(double[] s) {
reverse(s, 0, s.length - 1);
}
public static void reverse(char[] s, int l, int r) {
for (int i = l; i <= (l + r) / 2; i++) {
char tmp = s[i];
s[i] = s[r + l - i];
s[r + l - i] = tmp;
}
}
public static void reverse(char[] s) {
reverse(s, 0, s.length - 1);
}
public static <T> void reverse(T[] s, int l, int r) {
for (int i = l; i <= (l + r) / 2; i++) {
T tmp = s[i];
s[i] = s[r + l - i];
s[r + l - i] = tmp;
}
}
public static <T> void reverse(T[] s) {
reverse(s, 0, s.length - 1);
}
public static void shuffle(int[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
int t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(long[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
long t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(float[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
float t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(double[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
double t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(char[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
char t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static <T> void shuffle(T[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
T t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void sortArray(int[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(long[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(float[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(double[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(char[] a) {
shuffle(a);
Arrays.sort(a);
}
public static <T extends Comparable<T>> void sortArray(T[] a) {
Arrays.sort(a);
}
public static int[][] rotate90(int[][] a) {
int n = a.length, m = a[0].length;
int[][] ans = new int[m][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
ans[m - j - 1][i] = a[i][j];
return ans;
}
public static char[][] rotate90(char[][] a) {
int n = a.length, m = a[0].length;
char[][] ans = new char[m][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
ans[m - j - 1][i] = a[i][j];
return ans;
}
}
static class Writer {
private PrintWriter pw;
public Writer(){
pw = new PrintWriter(System.out);
}
public Writer(String f){
try {
pw = new PrintWriter(new FileWriter(f));
} catch (IOException e) {
e.printStackTrace();
}
}
public void yesNo(boolean condition) {
println(condition?"YES":"NO");
}
public void printArray(int[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
}
public void printlnArray(int[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
pw.println();
}
public void printArray(long[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
}
public void printlnArray(long[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
pw.println();
}
public void print(Object o) {
pw.print(o.toString());
}
public void println(Object o) {
pw.println(o.toString());
}
public void println() {
pw.println();
}
public void flush() {
pw.flush();
}
public void exit() {
pw.close();
}
}
}
| Java | ["3\n-3 5 -3 2 8 -20 6 -1\n3\n1\n0\n1"] | 4 seconds | ["18\n8\n13"] | NoteTransformation of the array in the example: $$$[-3, 5, -3, 2, 8, -20, 6, -1] \rightarrow [-3, 2, -3, 5, 6, -1, 8, -20] \rightarrow [2, -3, 5, -3, -1, 6, -20, 8] \rightarrow [5, -3, 2, -3, -20, 8, -1, 6]$$$. | Java 8 | standard input | [
"bitmasks",
"data structures",
"dfs and similar",
"divide and conquer",
"dp"
] | 376b293013562d5e004411f42082ce5c | The first line contains one integer $$$n$$$ ($$$1 \le n \le 18$$$). The second line contains $$$2^n$$$ integers $$$a_1, a_2, \dots, a_{2^n}$$$ ($$$-10^9 \le a_i \le 10^9$$$). The third line contains one integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$). Then $$$q$$$ lines follow, the $$$i$$$-th of them contains one integer $$$k$$$ ($$$0 \le k \le n-1$$$) describing the $$$i$$$-th query. | 2,500 | For each query, print one integer — the maximum sum over all contiguous subsegments of the array (including the empty subsegment) after processing the query. | standard output | |
PASSED | 8f74859d923f067357ef083548c18f33 | train_109.jsonl | 1659623700 | You are given an array of length $$$2^n$$$. The elements of the array are numbered from $$$1$$$ to $$$2^n$$$.You have to process $$$q$$$ queries to this array. In the $$$i$$$-th query, you will be given an integer $$$k$$$ ($$$0 \le k \le n-1$$$). To process the query, you should do the following: for every $$$i \in [1, 2^n-2^k]$$$ in ascending order, do the following: if the $$$i$$$-th element was already swapped with some other element during this query, skip it; otherwise, swap $$$a_i$$$ and $$$a_{i+2^k}$$$; after that, print the maximum sum over all contiguous subsegments of the array (including the empty subsegment). For example, if the array $$$a$$$ is $$$[-3, 5, -3, 2, 8, -20, 6, -1]$$$, and $$$k = 1$$$, the query is processed as follows: the $$$1$$$-st element wasn't swapped yet, so we swap it with the $$$3$$$-rd element; the $$$2$$$-nd element wasn't swapped yet, so we swap it with the $$$4$$$-th element; the $$$3$$$-rd element was swapped already; the $$$4$$$-th element was swapped already; the $$$5$$$-th element wasn't swapped yet, so we swap it with the $$$7$$$-th element; the $$$6$$$-th element wasn't swapped yet, so we swap it with the $$$8$$$-th element. So, the array becomes $$$[-3, 2, -3, 5, 6, -1, 8, -20]$$$. The subsegment with the maximum sum is $$$[5, 6, -1, 8]$$$, and the answer to the query is $$$18$$$.Note that the queries actually change the array, i. e. after a query is performed, the array does not return to its original state, and the next query will be applied to the modified array. | 512 megabytes | import java.util.*;
import java.io.*;
import java.util.Arrays;
import java.util.Random;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
/*
Solution Created: 16:30:25 09/08/2022
Custom Competitive programming helper.
*/
public class Main {
static class Node{
long pref, suf, whole, ans;
public Node() {
pref = suf = whole = ans = 0;
}
public Node(long val) {
pref = suf = whole = val;
ans = Math.max(0, val);
}
public Node(Node l, Node r) {
whole = l.whole + r.whole;
pref = Math.max(l.pref, l.whole + r.pref);
suf = Math.max(r.suf, l.suf + r.whole);
ans = Math.max(l.suf + r.pref, Math.max(l.ans, r.ans));
}
}
public static void solve() {
int n = in.nextInt();
long[] D = in.nl(1<<n);
Node[][] a = new Node[20][1<<n];
for(int i = 0; i<(1<<n); i++) a[0][i] = new Node(D[i]);
for(int bit = 1; bit<=n; bit++) {
for(int i = 0; i<1<<n; i++) {
a[bit][i] = new Node(a[bit-1][i], a[bit-1][i^(1<<(bit-1))]);
}
}
int cur = 0, q = in.nextInt();
while(q-->0) {
cur ^= (1<<in.nextInt());
out.println(a[n][cur].ans);
}
}
public static void main(String[] args) {
in = new Reader();
out = new Writer();
int t = 1;
while(t-->0) solve();
out.exit();
}
static Reader in; static Writer out;
static class Reader {
static BufferedReader br;
static StringTokenizer st;
public Reader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public Reader(String f){
try {
br = new BufferedReader(new FileReader(f));
} catch (IOException e) {
e.printStackTrace();
}
}
public int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
public double[] nd(int n) {
double[] a = new double[n];
for (int i = 0; i < n; i++) a[i] = nextDouble();
return a;
}
public long[] nl(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
public char[] nca() {
return next().toCharArray();
}
public String[] ns(int n) {
String[] a = new String[n];
for (int i = 0; i < n; i++) a[i] = next();
return a;
}
public int nextInt() {
ensureNext();
return Integer.parseInt(st.nextToken());
}
public double nextDouble() {
ensureNext();
return Double.parseDouble(st.nextToken());
}
public Long nextLong() {
ensureNext();
return Long.parseLong(st.nextToken());
}
public String next() {
ensureNext();
return st.nextToken();
}
public String nextLine() {
try {
return br.readLine();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private void ensureNext() {
if (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
static class Util {
private static Random random = new Random();
private static long MOD;
static long[] fact, inv, invFact;
public static void initCombinatorics(int n, long mod, boolean inversesToo, boolean inverseFactorialsToo) {
MOD = mod;
fact = new long[n + 1];
fact[0] = 1;
for (int i = 1; i < n + 1; i++) fact[i] = (fact[i - 1] * i) % mod;
if (inversesToo) {
inv = new long[n + 1];
inv[1] = 1;
for (int i = 2; i <= n; ++i) inv[i] = (mod - (mod / i) * inv[(int) (mod % i)] % mod) % mod;
}
if (inverseFactorialsToo) {
invFact = new long[n + 1];
invFact[n] = Util.modInverse(fact[n], mod);
for (int i = n - 1; i >= 0; i--) {
if (invFact[i + 1] == -1) {
invFact[i] = Util.modInverse(fact[i], mod);
continue;
}
invFact[i] = (invFact[i + 1] * (i + 1)) % mod;
}
}
}
public static long modInverse(long a, long mod) {
long[] gcdE = gcdExtended(a, mod);
if (gcdE[0] != 1) return -1; // Inverse doesn't exist
long x = gcdE[1];
return (x % mod + mod) % mod;
}
public static long[] gcdExtended(long p, long q) {
if (q == 0) return new long[] { p, 1, 0 };
long[] vals = gcdExtended(q, p % q);
long tmp = vals[2];
vals[2] = vals[1] - (p / q) * vals[2];
vals[1] = tmp;
return vals;
}
public static long nCr(int n, int r) {
if (r > n) return 0;
return (((fact[n] * invFact[r]) % MOD) * invFact[n - r]) % MOD;
}
public static long nPr(int n, int r) {
if (r > n) return 0;
return (fact[n] * invFact[n - r]) % MOD;
}
public static boolean isPrime(int n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
public static boolean[] getSieve(int n) {
boolean[] isPrime = new boolean[n + 1];
for (int i = 2; i <= n; i++) isPrime[i] = true;
for (int i = 2; i * i <= n; i++)
if (isPrime[i])
for (int j = i; i * j <= n; j++)
isPrime[i * j] = false;
return isPrime;
}
static long pow(long x, long pow, long mod) {
long res = 1;
x = x % mod;
if (x == 0) return 0;
while (pow > 0) {
if ((pow & 1) != 0) res = (res * x) % mod;
pow >>= 1;
x = (x * x) % mod;
}
return res;
}
public static int gcd(int a, int b) {
int tmp = 0;
while (b != 0) {
tmp = b;
b = a % b;
a = tmp;
}
return a;
}
public static long gcd(long a, long b) {
long tmp = 0;
while (b != 0) {
tmp = b;
b = a % b;
a = tmp;
}
return a;
}
public static int random(int min, int max) {
return random.nextInt(max - min + 1) + min;
}
public static void dbg(Object... o) {
System.out.println(Arrays.deepToString(o));
}
public static void reverse(int[] s, int l, int r) {
for (int i = l; i <= (l + r) / 2; i++) {
int tmp = s[i];
s[i] = s[r + l - i];
s[r + l - i] = tmp;
}
}
public static void reverse(int[] s) {
reverse(s, 0, s.length - 1);
}
public static void reverse(long[] s, int l, int r) {
for (int i = l; i <= (l + r) / 2; i++) {
long tmp = s[i];
s[i] = s[r + l - i];
s[r + l - i] = tmp;
}
}
public static void reverse(long[] s) {
reverse(s, 0, s.length - 1);
}
public static void reverse(float[] s, int l, int r) {
for (int i = l; i <= (l + r) / 2; i++) {
float tmp = s[i];
s[i] = s[r + l - i];
s[r + l - i] = tmp;
}
}
public static void reverse(float[] s) {
reverse(s, 0, s.length - 1);
}
public static void reverse(double[] s, int l, int r) {
for (int i = l; i <= (l + r) / 2; i++) {
double tmp = s[i];
s[i] = s[r + l - i];
s[r + l - i] = tmp;
}
}
public static void reverse(double[] s) {
reverse(s, 0, s.length - 1);
}
public static void reverse(char[] s, int l, int r) {
for (int i = l; i <= (l + r) / 2; i++) {
char tmp = s[i];
s[i] = s[r + l - i];
s[r + l - i] = tmp;
}
}
public static void reverse(char[] s) {
reverse(s, 0, s.length - 1);
}
public static <T> void reverse(T[] s, int l, int r) {
for (int i = l; i <= (l + r) / 2; i++) {
T tmp = s[i];
s[i] = s[r + l - i];
s[r + l - i] = tmp;
}
}
public static <T> void reverse(T[] s) {
reverse(s, 0, s.length - 1);
}
public static void shuffle(int[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
int t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(long[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
long t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(float[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
float t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(double[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
double t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(char[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
char t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static <T> void shuffle(T[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
T t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void sortArray(int[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(long[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(float[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(double[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(char[] a) {
shuffle(a);
Arrays.sort(a);
}
public static <T extends Comparable<T>> void sortArray(T[] a) {
Arrays.sort(a);
}
public static int[][] rotate90(int[][] a) {
int n = a.length, m = a[0].length;
int[][] ans = new int[m][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
ans[m - j - 1][i] = a[i][j];
return ans;
}
public static char[][] rotate90(char[][] a) {
int n = a.length, m = a[0].length;
char[][] ans = new char[m][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
ans[m - j - 1][i] = a[i][j];
return ans;
}
}
static class Writer {
private PrintWriter pw;
public Writer(){
pw = new PrintWriter(System.out);
}
public Writer(String f){
try {
pw = new PrintWriter(new FileWriter(f));
} catch (IOException e) {
e.printStackTrace();
}
}
public void yesNo(boolean condition) {
println(condition?"YES":"NO");
}
public void printArray(int[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
}
public void printlnArray(int[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
pw.println();
}
public void printArray(long[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
}
public void printlnArray(long[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
pw.println();
}
public void print(Object o) {
pw.print(o.toString());
}
public void println(Object o) {
pw.println(o.toString());
}
public void println() {
pw.println();
}
public void flush() {
pw.flush();
}
public void exit() {
pw.close();
}
}
}
| Java | ["3\n-3 5 -3 2 8 -20 6 -1\n3\n1\n0\n1"] | 4 seconds | ["18\n8\n13"] | NoteTransformation of the array in the example: $$$[-3, 5, -3, 2, 8, -20, 6, -1] \rightarrow [-3, 2, -3, 5, 6, -1, 8, -20] \rightarrow [2, -3, 5, -3, -1, 6, -20, 8] \rightarrow [5, -3, 2, -3, -20, 8, -1, 6]$$$. | Java 8 | standard input | [
"bitmasks",
"data structures",
"dfs and similar",
"divide and conquer",
"dp"
] | 376b293013562d5e004411f42082ce5c | The first line contains one integer $$$n$$$ ($$$1 \le n \le 18$$$). The second line contains $$$2^n$$$ integers $$$a_1, a_2, \dots, a_{2^n}$$$ ($$$-10^9 \le a_i \le 10^9$$$). The third line contains one integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$). Then $$$q$$$ lines follow, the $$$i$$$-th of them contains one integer $$$k$$$ ($$$0 \le k \le n-1$$$) describing the $$$i$$$-th query. | 2,500 | For each query, print one integer — the maximum sum over all contiguous subsegments of the array (including the empty subsegment) after processing the query. | standard output | |
PASSED | 6f129fc3a40a9db7574d783cdd9474c5 | train_109.jsonl | 1659623700 | You are given an array of length $$$2^n$$$. The elements of the array are numbered from $$$1$$$ to $$$2^n$$$.You have to process $$$q$$$ queries to this array. In the $$$i$$$-th query, you will be given an integer $$$k$$$ ($$$0 \le k \le n-1$$$). To process the query, you should do the following: for every $$$i \in [1, 2^n-2^k]$$$ in ascending order, do the following: if the $$$i$$$-th element was already swapped with some other element during this query, skip it; otherwise, swap $$$a_i$$$ and $$$a_{i+2^k}$$$; after that, print the maximum sum over all contiguous subsegments of the array (including the empty subsegment). For example, if the array $$$a$$$ is $$$[-3, 5, -3, 2, 8, -20, 6, -1]$$$, and $$$k = 1$$$, the query is processed as follows: the $$$1$$$-st element wasn't swapped yet, so we swap it with the $$$3$$$-rd element; the $$$2$$$-nd element wasn't swapped yet, so we swap it with the $$$4$$$-th element; the $$$3$$$-rd element was swapped already; the $$$4$$$-th element was swapped already; the $$$5$$$-th element wasn't swapped yet, so we swap it with the $$$7$$$-th element; the $$$6$$$-th element wasn't swapped yet, so we swap it with the $$$8$$$-th element. So, the array becomes $$$[-3, 2, -3, 5, 6, -1, 8, -20]$$$. The subsegment with the maximum sum is $$$[5, 6, -1, 8]$$$, and the answer to the query is $$$18$$$.Note that the queries actually change the array, i. e. after a query is performed, the array does not return to its original state, and the next query will be applied to the modified array. | 512 megabytes | import java.util.*;
import java.io.*;
import java.util.Arrays;
import java.util.Random;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
/*
Solution Created: 16:30:25 09/08/2022
Custom Competitive programming helper.
*/
public class Main {
static class Node{
long pref, suf, whole, ans;
public Node() {
pref = suf = whole = ans = 0;
}
public Node(long val) {
pref = suf = whole = val;
ans = Math.max(0, val);
}
public Node(Node l, Node r) {
whole = l.whole + r.whole;
pref = Math.max(l.pref, l.whole + r.pref);
suf = Math.max(r.suf, l.suf + r.whole);
ans = Math.max(l.suf + r.pref, Math.max(l.ans, r.ans));
}
}
public static void solve() {
int n = in.nextInt();
long[] D = in.nl(1<<n);
Node[][] a = new Node[20][1<<n];
for(int i = 0; i<(1<<n); i++) a[0][i] = new Node(D[i]);
for(int bit = 1; bit<=n; bit++) {
for(int i = 0; i<1<<n; i++) {
a[bit][i] = new Node(a[bit-1][i], a[bit-1][i^(1<<(bit-1))]);
}
}
int cur = 0, q = in.nextInt();
while(q-->0) {
cur ^= (1<<in.nextInt());
out.println(a[n][cur].ans);
}
}
public static void main(String[] args) {
in = new Reader();
out = new Writer();
int t = 1;
while(t-->0) solve();
out.exit();
}
static Reader in; static Writer out;
static class Reader {
static BufferedReader br;
static StringTokenizer st;
public Reader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public Reader(String f){
try {
br = new BufferedReader(new FileReader(f));
} catch (IOException e) {
e.printStackTrace();
}
}
public int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
public double[] nd(int n) {
double[] a = new double[n];
for (int i = 0; i < n; i++) a[i] = nextDouble();
return a;
}
public long[] nl(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
public char[] nca() {
return next().toCharArray();
}
public String[] ns(int n) {
String[] a = new String[n];
for (int i = 0; i < n; i++) a[i] = next();
return a;
}
public int nextInt() {
ensureNext();
return Integer.parseInt(st.nextToken());
}
public double nextDouble() {
ensureNext();
return Double.parseDouble(st.nextToken());
}
public Long nextLong() {
ensureNext();
return Long.parseLong(st.nextToken());
}
public String next() {
ensureNext();
return st.nextToken();
}
public String nextLine() {
try {
return br.readLine();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private void ensureNext() {
if (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
static class Util {
private static Random random = new Random();
private static long MOD;
static long[] fact, inv, invFact;
public static void initCombinatorics(int n, long mod, boolean inversesToo, boolean inverseFactorialsToo) {
MOD = mod;
fact = new long[n + 1];
fact[0] = 1;
for (int i = 1; i < n + 1; i++) fact[i] = (fact[i - 1] * i) % mod;
if (inversesToo) {
inv = new long[n + 1];
inv[1] = 1;
for (int i = 2; i <= n; ++i) inv[i] = (mod - (mod / i) * inv[(int) (mod % i)] % mod) % mod;
}
if (inverseFactorialsToo) {
invFact = new long[n + 1];
invFact[n] = Util.modInverse(fact[n], mod);
for (int i = n - 1; i >= 0; i--) {
if (invFact[i + 1] == -1) {
invFact[i] = Util.modInverse(fact[i], mod);
continue;
}
invFact[i] = (invFact[i + 1] * (i + 1)) % mod;
}
}
}
public static long modInverse(long a, long mod) {
long[] gcdE = gcdExtended(a, mod);
if (gcdE[0] != 1) return -1; // Inverse doesn't exist
long x = gcdE[1];
return (x % mod + mod) % mod;
}
public static long[] gcdExtended(long p, long q) {
if (q == 0) return new long[] { p, 1, 0 };
long[] vals = gcdExtended(q, p % q);
long tmp = vals[2];
vals[2] = vals[1] - (p / q) * vals[2];
vals[1] = tmp;
return vals;
}
public static long nCr(int n, int r) {
if (r > n) return 0;
return (((fact[n] * invFact[r]) % MOD) * invFact[n - r]) % MOD;
}
public static long nPr(int n, int r) {
if (r > n) return 0;
return (fact[n] * invFact[n - r]) % MOD;
}
public static boolean isPrime(int n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
public static boolean[] getSieve(int n) {
boolean[] isPrime = new boolean[n + 1];
for (int i = 2; i <= n; i++) isPrime[i] = true;
for (int i = 2; i * i <= n; i++)
if (isPrime[i])
for (int j = i; i * j <= n; j++)
isPrime[i * j] = false;
return isPrime;
}
static long pow(long x, long pow, long mod) {
long res = 1;
x = x % mod;
if (x == 0) return 0;
while (pow > 0) {
if ((pow & 1) != 0) res = (res * x) % mod;
pow >>= 1;
x = (x * x) % mod;
}
return res;
}
public static int gcd(int a, int b) {
int tmp = 0;
while (b != 0) {
tmp = b;
b = a % b;
a = tmp;
}
return a;
}
public static long gcd(long a, long b) {
long tmp = 0;
while (b != 0) {
tmp = b;
b = a % b;
a = tmp;
}
return a;
}
public static int random(int min, int max) {
return random.nextInt(max - min + 1) + min;
}
public static void dbg(Object... o) {
System.out.println(Arrays.deepToString(o));
}
public static void reverse(int[] s, int l, int r) {
for (int i = l; i <= (l + r) / 2; i++) {
int tmp = s[i];
s[i] = s[r + l - i];
s[r + l - i] = tmp;
}
}
public static void reverse(int[] s) {
reverse(s, 0, s.length - 1);
}
public static void reverse(long[] s, int l, int r) {
for (int i = l; i <= (l + r) / 2; i++) {
long tmp = s[i];
s[i] = s[r + l - i];
s[r + l - i] = tmp;
}
}
public static void reverse(long[] s) {
reverse(s, 0, s.length - 1);
}
public static void reverse(float[] s, int l, int r) {
for (int i = l; i <= (l + r) / 2; i++) {
float tmp = s[i];
s[i] = s[r + l - i];
s[r + l - i] = tmp;
}
}
public static void reverse(float[] s) {
reverse(s, 0, s.length - 1);
}
public static void reverse(double[] s, int l, int r) {
for (int i = l; i <= (l + r) / 2; i++) {
double tmp = s[i];
s[i] = s[r + l - i];
s[r + l - i] = tmp;
}
}
public static void reverse(double[] s) {
reverse(s, 0, s.length - 1);
}
public static void reverse(char[] s, int l, int r) {
for (int i = l; i <= (l + r) / 2; i++) {
char tmp = s[i];
s[i] = s[r + l - i];
s[r + l - i] = tmp;
}
}
public static void reverse(char[] s) {
reverse(s, 0, s.length - 1);
}
public static <T> void reverse(T[] s, int l, int r) {
for (int i = l; i <= (l + r) / 2; i++) {
T tmp = s[i];
s[i] = s[r + l - i];
s[r + l - i] = tmp;
}
}
public static <T> void reverse(T[] s) {
reverse(s, 0, s.length - 1);
}
public static void shuffle(int[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
int t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(long[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
long t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(float[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
float t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(double[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
double t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(char[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
char t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static <T> void shuffle(T[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
T t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void sortArray(int[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(long[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(float[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(double[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(char[] a) {
shuffle(a);
Arrays.sort(a);
}
public static <T extends Comparable<T>> void sortArray(T[] a) {
Arrays.sort(a);
}
public static int[][] rotate90(int[][] a) {
int n = a.length, m = a[0].length;
int[][] ans = new int[m][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
ans[m - j - 1][i] = a[i][j];
return ans;
}
public static char[][] rotate90(char[][] a) {
int n = a.length, m = a[0].length;
char[][] ans = new char[m][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
ans[m - j - 1][i] = a[i][j];
return ans;
}
}
static class Writer {
private PrintWriter pw;
public Writer(){
pw = new PrintWriter(System.out);
}
public Writer(String f){
try {
pw = new PrintWriter(new FileWriter(f));
} catch (IOException e) {
e.printStackTrace();
}
}
public void yesNo(boolean condition) {
println(condition?"YES":"NO");
}
public void printArray(int[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
}
public void printlnArray(int[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
pw.println();
}
public void printArray(long[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
}
public void printlnArray(long[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
pw.println();
}
public void print(Object o) {
pw.print(o.toString());
}
public void println(Object o) {
pw.println(o.toString());
}
public void println() {
pw.println();
}
public void flush() {
pw.flush();
}
public void exit() {
pw.close();
}
}
}
| Java | ["3\n-3 5 -3 2 8 -20 6 -1\n3\n1\n0\n1"] | 4 seconds | ["18\n8\n13"] | NoteTransformation of the array in the example: $$$[-3, 5, -3, 2, 8, -20, 6, -1] \rightarrow [-3, 2, -3, 5, 6, -1, 8, -20] \rightarrow [2, -3, 5, -3, -1, 6, -20, 8] \rightarrow [5, -3, 2, -3, -20, 8, -1, 6]$$$. | Java 8 | standard input | [
"bitmasks",
"data structures",
"dfs and similar",
"divide and conquer",
"dp"
] | 376b293013562d5e004411f42082ce5c | The first line contains one integer $$$n$$$ ($$$1 \le n \le 18$$$). The second line contains $$$2^n$$$ integers $$$a_1, a_2, \dots, a_{2^n}$$$ ($$$-10^9 \le a_i \le 10^9$$$). The third line contains one integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$). Then $$$q$$$ lines follow, the $$$i$$$-th of them contains one integer $$$k$$$ ($$$0 \le k \le n-1$$$) describing the $$$i$$$-th query. | 2,500 | For each query, print one integer — the maximum sum over all contiguous subsegments of the array (including the empty subsegment) after processing the query. | standard output | |
PASSED | 2bed998344118f8154a0e4f4c2814046 | train_109.jsonl | 1659623700 | You are given an array of length $$$2^n$$$. The elements of the array are numbered from $$$1$$$ to $$$2^n$$$.You have to process $$$q$$$ queries to this array. In the $$$i$$$-th query, you will be given an integer $$$k$$$ ($$$0 \le k \le n-1$$$). To process the query, you should do the following: for every $$$i \in [1, 2^n-2^k]$$$ in ascending order, do the following: if the $$$i$$$-th element was already swapped with some other element during this query, skip it; otherwise, swap $$$a_i$$$ and $$$a_{i+2^k}$$$; after that, print the maximum sum over all contiguous subsegments of the array (including the empty subsegment). For example, if the array $$$a$$$ is $$$[-3, 5, -3, 2, 8, -20, 6, -1]$$$, and $$$k = 1$$$, the query is processed as follows: the $$$1$$$-st element wasn't swapped yet, so we swap it with the $$$3$$$-rd element; the $$$2$$$-nd element wasn't swapped yet, so we swap it with the $$$4$$$-th element; the $$$3$$$-rd element was swapped already; the $$$4$$$-th element was swapped already; the $$$5$$$-th element wasn't swapped yet, so we swap it with the $$$7$$$-th element; the $$$6$$$-th element wasn't swapped yet, so we swap it with the $$$8$$$-th element. So, the array becomes $$$[-3, 2, -3, 5, 6, -1, 8, -20]$$$. The subsegment with the maximum sum is $$$[5, 6, -1, 8]$$$, and the answer to the query is $$$18$$$.Note that the queries actually change the array, i. e. after a query is performed, the array does not return to its original state, and the next query will be applied to the modified array. | 512 megabytes | import java.util.*;
import java.io.*;
public class Template {
FastScanner in;
PrintWriter out;
long[] prefSums;
public long sumSeg(int l, int r) {
if (l == 0)
return prefSums[r];
else
return prefSums[r] - prefSums[l - 1];
}
public void solve() throws IOException {
int n = in.nextInt();
int totalN = 1<<n;
int[] a = new int[totalN];
for (int i = 0; i < totalN; i++)
a[i] = in.nextInt();
int segSize = (n + 1) / 2;
int groupsSize = n - segSize;
int maxXor = 1<<segSize;
int totGroups = 1<<groupsSize;
long[] maxSum = new long[totGroups];
long[] maxPref = new long[totGroups];
long[] maxSuf = new long[totGroups];
long[] sums = new long[totGroups];
prefSums = new long[totalN];
prefSums[0] = a[0];
for (int i = 1; i < totalN; i++)
prefSums[i] = prefSums[i - 1] + a[i];
long[] ans = new long[totalN];
int prevSmallP = -1;
for (int xr = 0; xr < totalN; xr++) {
int smallP = xr >> groupsSize;
if (prevSmallP != smallP) {
prevSmallP = smallP;
for (int gr = 0; gr < totGroups; gr++) {
int grShift = gr * maxXor;
long prefSum = 0;
long minPref = 0;
long totSum = sumSeg(grShift, grShift + maxXor - 1);
maxSum[gr] = 0;
maxPref[gr] = 0;
maxSuf[gr] = totSum;
sums[gr] = totSum;
for (int i = 0; i < maxXor; i++) {
int cur = a[i ^ smallP + grShift];
prefSum += cur;
maxSum[gr] = Math.max(maxSum[gr], prefSum - minPref);
maxPref[gr] = Math.max(maxPref[gr], prefSum);
maxSuf[gr] = Math.max(maxSuf[gr], totSum - prefSum);
minPref = Math.min(minPref, prefSum);
}
}
}
int bigP = xr & (totGroups - 1);
long mPref = maxPref[bigP];
long mSuf = maxSuf[bigP];
long mSum = maxSum[bigP];
long sm = sums[bigP];
for (int grXored = 1; grXored < totGroups; grXored++) {
int gr = grXored ^ bigP;
mSum = Math.max(Math.max(mSum, maxSum[gr]), mSuf + maxPref[gr]);
mPref = Math.max(mPref, sm + maxPref[gr]);
mSuf = Math.max(mSuf + sums[gr], maxSuf[gr]);
sm += sums[gr];
}
ans[xr] = mSum;
}
int xr = 0;
int q = in.nextInt();
for (int i = 0; i < q; i++) {
int b = in.nextInt();
xr ^= 1<<b;
int nxr = (xr >> segSize) + (xr & (maxXor - 1)) * totGroups;
out.println(ans[nxr]);
}
}
public void run() {
try {
in = new FastScanner(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(Reader f) {
br = new BufferedReader(f);
}
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) {
new Template().run();
}
}
| Java | ["3\n-3 5 -3 2 8 -20 6 -1\n3\n1\n0\n1"] | 4 seconds | ["18\n8\n13"] | NoteTransformation of the array in the example: $$$[-3, 5, -3, 2, 8, -20, 6, -1] \rightarrow [-3, 2, -3, 5, 6, -1, 8, -20] \rightarrow [2, -3, 5, -3, -1, 6, -20, 8] \rightarrow [5, -3, 2, -3, -20, 8, -1, 6]$$$. | Java 17 | standard input | [
"bitmasks",
"data structures",
"dfs and similar",
"divide and conquer",
"dp"
] | 376b293013562d5e004411f42082ce5c | The first line contains one integer $$$n$$$ ($$$1 \le n \le 18$$$). The second line contains $$$2^n$$$ integers $$$a_1, a_2, \dots, a_{2^n}$$$ ($$$-10^9 \le a_i \le 10^9$$$). The third line contains one integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$). Then $$$q$$$ lines follow, the $$$i$$$-th of them contains one integer $$$k$$$ ($$$0 \le k \le n-1$$$) describing the $$$i$$$-th query. | 2,500 | For each query, print one integer — the maximum sum over all contiguous subsegments of the array (including the empty subsegment) after processing the query. | standard output | |
PASSED | 3a29fabef29a65108ada92316f84fcb7 | train_109.jsonl | 1659623700 | You are given an array of length $$$2^n$$$. The elements of the array are numbered from $$$1$$$ to $$$2^n$$$.You have to process $$$q$$$ queries to this array. In the $$$i$$$-th query, you will be given an integer $$$k$$$ ($$$0 \le k \le n-1$$$). To process the query, you should do the following: for every $$$i \in [1, 2^n-2^k]$$$ in ascending order, do the following: if the $$$i$$$-th element was already swapped with some other element during this query, skip it; otherwise, swap $$$a_i$$$ and $$$a_{i+2^k}$$$; after that, print the maximum sum over all contiguous subsegments of the array (including the empty subsegment). For example, if the array $$$a$$$ is $$$[-3, 5, -3, 2, 8, -20, 6, -1]$$$, and $$$k = 1$$$, the query is processed as follows: the $$$1$$$-st element wasn't swapped yet, so we swap it with the $$$3$$$-rd element; the $$$2$$$-nd element wasn't swapped yet, so we swap it with the $$$4$$$-th element; the $$$3$$$-rd element was swapped already; the $$$4$$$-th element was swapped already; the $$$5$$$-th element wasn't swapped yet, so we swap it with the $$$7$$$-th element; the $$$6$$$-th element wasn't swapped yet, so we swap it with the $$$8$$$-th element. So, the array becomes $$$[-3, 2, -3, 5, 6, -1, 8, -20]$$$. The subsegment with the maximum sum is $$$[5, 6, -1, 8]$$$, and the answer to the query is $$$18$$$.Note that the queries actually change the array, i. e. after a query is performed, the array does not return to its original state, and the next query will be applied to the modified array. | 512 megabytes | import java.util.*;
import java.util.function.*;
import java.io.*;
// you can compare with output.txt and expected out
public class RoundEdu133E {
MyPrintWriter out;
MyScanner in;
// final static long FIXED_RANDOM;
// static {
// FIXED_RANDOM = System.currentTimeMillis();
// }
final static String IMPOSSIBLE = "IMPOSSIBLE";
final static String POSSIBLE = "POSSIBLE";
final static String YES = "YES";
final static String NO = "NO";
private void initIO(boolean isFileIO) {
if (System.getProperty("ONLINE_JUDGE") == null && isFileIO) {
try{
in = new MyScanner(new FileInputStream("input.txt"));
out = new MyPrintWriter(new FileOutputStream("output.txt"));
}
catch(FileNotFoundException e){
e.printStackTrace();
}
}
else{
in = new MyScanner(System.in);
out = new MyPrintWriter(new BufferedOutputStream(System.out));
}
}
public static void main(String[] args){
// Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
RoundEdu133E sol = new RoundEdu133E();
sol.run();
}
private void run() {
boolean isDebug = false;
boolean isFileIO = true;
boolean hasMultipleTests = false;
initIO(isFileIO);
int t = hasMultipleTests? in.nextInt() : 1;
for (int i = 1; i <= t; ++i) {
if(isDebug){
out.printf("Test %d\n", i);
}
getInput();
solve();
printOutput();
}
in.close();
out.close();
}
// use suitable one between matrix(2, n) or matrix(n, 2) for graph edges, pairs, ...
int n, q;
int[] a, k;
void getInput() {
n = in.nextInt();
a = in.nextIntArray(1<<n);
q = in.nextInt();
k = in.nextIntArray(q);
}
void printOutput() {
out.printlnAns(ans);
}
long[] ans;
void solve(){
ans = new long[q];
// swap a_i and a_(i^(1<<k)) for each i
// this means, for each bit, we have flip or not
// so that a'_i = a_i' where i' is obtained by flipping bits of i
// moreover, flipping k-th bits doesn't change the range sum of 2^k' elements where k' > k
// how to find the maximum subsegment?
// consider a segment tree
// s00
// s10 s11
// s20 s21 s22 s23
// for each interval
// need to maintain
// 1) maximum sum
// 2) maximum sum that can be extended to the right side
// 3) maximum sum that can be extended to the left side
// (1) can be determined by 2+3 of children or 1 of either child
// (2) can be determined by 2 of right children or whole of right children + 2 of left children
SegmentTree segTree = new SegmentTree(n, a);
int xor = 0;
for(int i=0; i<q; i++) {
xor ^= 1<<k[i];
ans[i] = segTree.query(xor);
}
}
class SegmentTree {
int n;
long[] sum;
long[][] maxSum;
long[][] rightAlignedSum;
long[][] leftAlignedSum;
boolean[][] visited;
public SegmentTree(int n, int[] arr){
this.n = arr.length;
int N = 1<<n;
int m = N<=1? 8: Integer.highestOneBit(N-1)*4;
maxSum = new long[m][];
rightAlignedSum = new long[m][];
leftAlignedSum = new long[m][];
visited = new boolean[m][];
// allocate memory
sum = new long[m];
init(arr, 1, 0, N-1, n);
// O(n*2^n)
for(int i=0; i<N; i++)
build(arr, i, 1, 0, N-1, n);
}
private void init(int[] arr, int treeIdx, int left, int right, int height) {
maxSum[treeIdx] = new long[1<<height];
rightAlignedSum[treeIdx] = new long[1<<height];
leftAlignedSum[treeIdx] = new long[1<<height];
visited[treeIdx] = new boolean[1<<height];
if(left == right) {
sum[treeIdx] = arr[left];
}
if(right > left) {
int mid = (left+right)/2;
init(arr, treeIdx*2, left, mid, height-1);
init(arr, treeIdx*2+1, mid+1, right, height-1);
sum[treeIdx] = sum[treeIdx*2] + sum[treeIdx*2+1];
}
}
private void build(int[] arr, int xor, int treeIdx, int left, int right, int height) {
int lowerBit = xor & ((1<<height) -1);
if(visited[treeIdx][lowerBit])
return;
visited[treeIdx][lowerBit] = true;
if(left == right) {
maxSum[treeIdx][lowerBit] = arr[left^xor];
rightAlignedSum[treeIdx][lowerBit] = arr[left^xor];
leftAlignedSum[treeIdx][lowerBit] = arr[left^xor];
return;
}
int mid = (left+right)/2;
int treeIdxLeftMid = treeIdx<<1;
int treeIdxMidRight = (treeIdx<<1)+1;
build(arr, xor, treeIdxLeftMid, left, mid, height-1);
build(arr, xor, treeIdxMidRight, mid+1, right, height-1);
int lowerBitChild = lowerBit - (xor & (1<<height-1));
if( (xor & (1<<height-1)) > 0) {
// flipped
maxSum[treeIdx][lowerBit] = Math.max(maxSum[treeIdxLeftMid][lowerBitChild], maxSum[treeIdxMidRight][lowerBitChild]);
maxSum[treeIdx][lowerBit] = Math.max(maxSum[treeIdx][lowerBit], leftAlignedSum[treeIdxLeftMid][lowerBitChild] + rightAlignedSum[treeIdxMidRight][lowerBitChild]);
leftAlignedSum[treeIdx][lowerBit] = Math.max(leftAlignedSum[treeIdxMidRight][lowerBitChild],
sum[treeIdxMidRight] + leftAlignedSum[treeIdxLeftMid][lowerBitChild]);
rightAlignedSum[treeIdx][lowerBit] = Math.max(rightAlignedSum[treeIdxLeftMid][lowerBitChild],
sum[treeIdxLeftMid] + rightAlignedSum[treeIdxMidRight][lowerBitChild]);
}
else {
// not flipped
maxSum[treeIdx][lowerBit] = Math.max(maxSum[treeIdxLeftMid][lowerBitChild], maxSum[treeIdxMidRight][lowerBitChild]);
maxSum[treeIdx][lowerBit] = Math.max(maxSum[treeIdx][lowerBit], rightAlignedSum[treeIdxLeftMid][lowerBitChild] + leftAlignedSum[treeIdxMidRight][lowerBitChild]);
leftAlignedSum[treeIdx][lowerBit] = Math.max(leftAlignedSum[treeIdxLeftMid][lowerBitChild],
sum[treeIdxLeftMid] + leftAlignedSum[treeIdxMidRight][lowerBitChild]);
rightAlignedSum[treeIdx][lowerBit] = Math.max(rightAlignedSum[treeIdxMidRight][lowerBitChild],
sum[treeIdxMidRight] + rightAlignedSum[treeIdxLeftMid][lowerBitChild]);
}
}
public long query(int xor) {
return Math.max(0, maxSum[1][xor]);
}
}
// Optional<T> solve()
// return Optional.empty();
static class Pair implements Comparable<Pair>{
final static long FIXED_RANDOM = System.currentTimeMillis();
int first, second;
public Pair(int first, int second) {
this.first = first;
this.second = second;
}
@Override
public int hashCode() {
// http://xorshift.di.unimi.it/splitmix64.c
long x = first;
x <<= 32;
x += second;
x += FIXED_RANDOM;
x += 0x9e3779b97f4a7c15l;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9l;
x = (x ^ (x >> 27)) * 0x94d049bb133111ebl;
return (int)(x ^ (x >> 31));
}
@Override
public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
Pair other = (Pair) obj;
return first == other.first && second == other.second;
}
@Override
public String toString() {
return "[" + first + "," + second + "]";
}
@Override
public int compareTo(Pair o) {
int cmp = Integer.compare(first, o.first);
return cmp != 0? cmp: Integer.compare(second, o.second);
}
}
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
// 32768?
public MyScanner(InputStream is, int bufferSize) {
br = new BufferedReader(new InputStreamReader(is), bufferSize);
}
public MyScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
// br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));
}
public void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[][] nextMatrix(int n, int m) {
return nextMatrix(n, m, 0);
}
int[][] nextMatrix(int n, int m, int offset) {
int[][] mat = new int[n][m];
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
mat[i][j] = nextInt()+offset;
}
}
return mat;
}
int[][] nextTransposedMatrix(int n, int m){
return nextTransposedMatrix(n, m, 0);
}
int[][] nextTransposedMatrix(int n, int m, int offset){
int[][] mat = new int[m][n];
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
mat[j][i] = nextInt()+offset;
}
}
return mat;
}
int[] nextIntArray(int len) {
return nextIntArray(len, 0);
}
int[] nextIntArray(int len, int offset){
int[] a = new int[len];
for(int j=0; j<len; j++)
a[j] = nextInt()+offset;
return a;
}
long[] nextLongArray(int len) {
return nextLongArray(len, 0);
}
long[] nextLongArray(int len, int offset){
long[] a = new long[len];
for(int j=0; j<len; j++)
a[j] = nextLong()+offset;
return a;
}
String[] nextStringArray(int len) {
String[] s = new String[len];
for(int i=0; i<len; i++)
s[i] = next();
return s;
}
}
public static class MyPrintWriter extends PrintWriter{
public MyPrintWriter(OutputStream os) {
super(os);
}
// public <T> void printlnAns(Optional<T> ans) {
// if(ans.isEmpty())
// println(-1);
// else
// printlnAns(ans.get());
// }
public void printlnAns(OptionalInt ans) {
println(ans.orElse(-1));
}
public void printlnAns(long ans) {
println(ans);
}
public void printlnAns(int ans) {
println(ans);
}
public void printlnAns(boolean ans) {
if(ans)
println(YES);
else
println(NO);
}
public void printAns(long[] arr){
if(arr != null && arr.length > 0){
print(arr[0]);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]);
}
}
}
public void printlnAns(long[] arr){
printAns(arr);
println();
}
public void printAns(int[] arr){
if(arr != null && arr.length > 0){
print(arr[0]);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]);
}
}
}
public void printlnAns(int[] arr){
printAns(arr);
println();
}
public <T> void printAns(ArrayList<T> arr){
if(arr != null && arr.size() > 0){
print(arr.get(0));
for(int i=1; i<arr.size(); i++){
print(" ");
print(arr.get(i));
}
}
}
public <T> void printlnAns(ArrayList<T> arr){
printAns(arr);
println();
}
public void printAns(int[] arr, int add){
if(arr != null && arr.length > 0){
print(arr[0]+add);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]+add);
}
}
}
public void printlnAns(int[] arr, int add){
printAns(arr, add);
println();
}
public void printAns(ArrayList<Integer> arr, int add) {
if(arr != null && arr.size() > 0){
print(arr.get(0)+add);
for(int i=1; i<arr.size(); i++){
print(" ");
print(arr.get(i)+add);
}
}
}
public void printlnAns(ArrayList<Integer> arr, int add){
printAns(arr, add);
println();
}
public void printlnAnsSplit(long[] arr, int split){
if(arr != null){
for(int i=0; i<arr.length; i+=split){
print(arr[i]);
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr[j]);
}
println();
}
}
}
public void printlnAnsSplit(int[] arr, int split){
if(arr != null){
for(int i=0; i<arr.length; i+=split){
print(arr[i]);
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr[j]);
}
println();
}
}
}
public <T> void printlnAnsSplit(ArrayList<T> arr, int split){
if(arr != null && !arr.isEmpty()){
for(int i=0; i<arr.size(); i+=split){
print(arr.get(i));
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr.get(j));
}
println();
}
}
}
}
static private void permutateAndSort(long[] a) {
int n = a.length;
Random R = new Random(System.currentTimeMillis());
for(int i=0; i<n; i++) {
int t = R.nextInt(n-i);
long temp = a[n-1-i];
a[n-1-i] = a[t];
a[t] = temp;
}
Arrays.sort(a);
}
static private void permutateAndSort(int[] a) {
int n = a.length;
Random R = new Random(System.currentTimeMillis());
for(int i=0; i<n; i++) {
int t = R.nextInt(n-i);
int temp = a[n-1-i];
a[n-1-i] = a[t];
a[t] = temp;
}
Arrays.sort(a);
}
static private int[][] constructChildren(int n, int[] parent, int parentRoot){
int[][] childrens = new int[n][];
int[] numChildren = new int[n];
for(int i=0; i<parent.length; i++) {
if(parent[i] != parentRoot)
numChildren[parent[i]]++;
}
for(int i=0; i<n; i++) {
childrens[i] = new int[numChildren[i]];
}
int[] idx = new int[n];
for(int i=0; i<parent.length; i++) {
if(parent[i] != parentRoot)
childrens[parent[i]][idx[parent[i]]++] = i;
}
return childrens;
}
static private int[][][] constructDirectedNeighborhood(int n, int[][] e){
int[] inDegree = new int[n];
int[] outDegree = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
outDegree[u]++;
inDegree[v]++;
}
int[][] inNeighbors = new int[n][];
int[][] outNeighbors = new int[n][];
for(int i=0; i<n; i++) {
inNeighbors[i] = new int[inDegree[i]];
outNeighbors[i] = new int[outDegree[i]];
}
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
outNeighbors[u][--outDegree[u]] = v;
inNeighbors[v][--inDegree[v]] = u;
}
return new int[][][] {inNeighbors, outNeighbors};
}
static private int[][] constructNeighborhood(int n, int[][] e) {
int[] degree = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
degree[u]++;
degree[v]++;
}
int[][] neighbors = new int[n][];
for(int i=0; i<n; i++)
neighbors[i] = new int[degree[i]];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
neighbors[u][--degree[u]] = v;
neighbors[v][--degree[v]] = u;
}
return neighbors;
}
static private void drawGraph(int[][] e) {
makeDotUndirected(e);
try {
final Process process = new ProcessBuilder("dot", "-Tpng", "graph.dot")
.redirectOutput(new File("graph.png"))
.start();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
static private void makeDotUndirected(int[][] e) {
MyPrintWriter out2 = null;
try {
out2 = new MyPrintWriter(new FileOutputStream("graph.dot"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
out2.println("strict graph {");
for(int i=0; i<e.length; i++){
out2.println(e[i][0] + "--" + e[i][1] + ";");
}
out2.println("}");
out2.close();
}
static private void makeDotDirected(int[][] e) {
MyPrintWriter out2 = null;
try {
out2 = new MyPrintWriter(new FileOutputStream("graph.dot"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
out2.println("strict digraph {");
for(int i=0; i<e.length; i++){
out2.println(e[i][0] + "->" + e[i][1] + ";");
}
out2.println("}");
out2.close();
}
}
| Java | ["3\n-3 5 -3 2 8 -20 6 -1\n3\n1\n0\n1"] | 4 seconds | ["18\n8\n13"] | NoteTransformation of the array in the example: $$$[-3, 5, -3, 2, 8, -20, 6, -1] \rightarrow [-3, 2, -3, 5, 6, -1, 8, -20] \rightarrow [2, -3, 5, -3, -1, 6, -20, 8] \rightarrow [5, -3, 2, -3, -20, 8, -1, 6]$$$. | Java 17 | standard input | [
"bitmasks",
"data structures",
"dfs and similar",
"divide and conquer",
"dp"
] | 376b293013562d5e004411f42082ce5c | The first line contains one integer $$$n$$$ ($$$1 \le n \le 18$$$). The second line contains $$$2^n$$$ integers $$$a_1, a_2, \dots, a_{2^n}$$$ ($$$-10^9 \le a_i \le 10^9$$$). The third line contains one integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$). Then $$$q$$$ lines follow, the $$$i$$$-th of them contains one integer $$$k$$$ ($$$0 \le k \le n-1$$$) describing the $$$i$$$-th query. | 2,500 | For each query, print one integer — the maximum sum over all contiguous subsegments of the array (including the empty subsegment) after processing the query. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.