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 | f1cd302cc94eb78e358ccadc1d349ab5 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 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)
{// cf
int n=Integer.parseInt(bu.readLine());
int i,a[]=new int[n],b,c[]=new int[n+1];
String s[]=bu.readLine().split(" ");
TreeSet<Integer> ts[]=new TreeSet[n+1],tm=new TreeSet<>();
for(i=0;i<=n;i++) ts[i]=new TreeSet<>();
for(i=0;i<n;i++)
{
a[i]=Integer.parseInt(s[i]);
c[i]++;
ts[a[i]].add(i);
tm.add(i);
}
s=bu.readLine().split(" ");
boolean ans=true;
for(i=0;i<n && ans;i++)
{
b=Integer.parseInt(s[i]);
int cur=tm.higher(-1),low=ts[b].higher(-1),val=a[cur];
while(val!=b)
{
//low is smallest index of b next to this
if(ts[val].higher(low)==null) break; //no larger value possible for val
int small=ts[val].higher(low); //smallest value larger than in_b
c[cur]--; c[small]++;
if(c[cur]==0)
{
tm.remove(cur);
ts[val].remove(cur);
}
cur=tm.higher(-1); val=a[cur];
}
if(val!=b) {ans=false; continue;}
c[cur]--;
if(c[cur]==0)
{
tm.remove(cur);
ts[val].remove(cur);
}
}
if(ans) sb.append("YES\n");
else sb.append("NO\n");
}
System.out.print(sb);
}
} | Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 661896d6e45b41cb559178ccec907992 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 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 i,a[]=new int[n],b,c[]=new int[n+1];
String s[]=bu.readLine().split(" ");
TreeSet<Integer> ts[]=new TreeSet[n+1],tm=new TreeSet<>();
for(i=0;i<=n;i++) ts[i]=new TreeSet<>();
for(i=0;i<n;i++)
{
a[i]=Integer.parseInt(s[i]);
c[i]++;
ts[a[i]].add(i);
tm.add(i);
}
s=bu.readLine().split(" ");
boolean ans=true;
for(i=0;i<n && ans;i++)
{
b=Integer.parseInt(s[i]);
int cur=tm.higher(-1),low=ts[b].higher(-1),val=a[cur];
while(val!=b)
{
//low is smallest index of b next to this
if(ts[val].higher(low)==null) break; //no larger value possible for val
int small=ts[val].higher(low); //smallest value larger than in_b
c[cur]--; c[small]++;
if(c[cur]==0)
{
tm.remove(cur);
ts[val].remove(cur);
}
cur=tm.higher(-1); val=a[cur];
}
if(val!=b) {ans=false; continue;}
c[cur]--;
if(c[cur]==0)
{
tm.remove(cur);
ts[val].remove(cur);
}
}
if(ans) sb.append("YES\n");
else sb.append("NO\n");
}
System.out.print(sb);
}
} | Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 12ee862dbcd7f1959e540c638075d57a | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class Solution{
public static void main(String[] args) {
TaskA solver = new TaskA();
int t = in.nextInt();
for (int i = 1; i <= t ; i++) {
solver.solve(i, in, out);
}
// solver.solve(1, in, out);
out.flush();
out.close();
}
static class TaskA {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n= in.nextInt();
int[]arr1=new int[n];
int[]arr2=new int[n];
for(int i=0;i<n;i++) {
arr1[i]=in.nextInt();
}
for(int i=0;i<n;i++) {
arr2[i]=in.nextInt();
}
HashMap<Integer,Integer>hm=new HashMap<>();
int i=n-1;
int j=n-1;
if(arr1[n-1]!=arr2[n-1]) {
println("NO");return;
}
while(i>=0&&j>=0) {
if(i==n-1&&j==n-1) {
if(arr2[j]!=arr1[i]) {
println("NO");return;
}
i--;j--;
}
else {
if(arr2[j]!=arr1[i]) {
if(arr2[j]==arr2[j+1]) {
hm.put(arr2[j],hm.getOrDefault(arr2[j], 0)+1);
j--;
}
else if(hm.containsKey(arr1[i])&&hm.get(arr1[i])>0) {
hm.put(arr1[i],hm.getOrDefault(arr1[i], 0)-1);
i--;
}
else {
println("NO");return;
}
}
else {
i--;j--;
}
}
}
println("YES");
}
}
static int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static int len(long x) {
String s=String.valueOf(x);
return s.length();
}
static void sort(int[] a) {
ArrayList<Integer> q = new ArrayList<>();
for (int i : a) q.add(i);
Collections.sort(q);
for (int i = 0; i < a.length; i++) a[i] = q.get(i);
}
static void sort(long[] a) {
ArrayList<Long> q = new ArrayList<>();
for (long i : a) q.add(i);
Collections.sort(q);
for (int i = 0; i < a.length; i++) a[i] = q.get(i);
}
static void printArr(int[]arr){
for(int i=0;i<arr.length;i++) {
print(arr[i]+" ");
}
print("\n");
}
static void printArr(long[]arr){
for(int i=0;i<arr.length;i++) {
print(arr[i]+" ");
}
print("\n");
}
static int[]input(int n){
int[]arr=new int[n];
for(int i=0;i<n;i++) {
arr[i]=in.nextInt();
}
return arr;
}
static int[]input(){
int n= in.nextInt();
int[]arr=new int[n];
for(int i=0;i<n;i++) {
arr[i]=in.nextInt();
}
return arr;
}
////////////////////////////////////////////////////////
static class Pair {
int first;
int second;
Pair(int x, int y)
{
this.first = x;
this.second = y;
}
}
static void sortS(Pair arr[])
{
Arrays.sort(arr, new Comparator<Pair>() {
@Override public int compare(Pair p1, Pair p2)
{
return p1.second - p2.second;
}
});
}
static void sortF(Pair arr[])
{
Arrays.sort(arr, new Comparator<Pair>() {
@Override public int compare(Pair p1, Pair p2)
{
return p1.first - p2.first;
}
});
}
/////////////////////////////////////////////////////////////
static InputStream inputStream = System.in;
static OutputStream outputStream = System.out;
static InputReader in = new InputReader(inputStream);
static PrintWriter out = new PrintWriter(outputStream);
static void println(long c) {
out.println(c);
}
static void print(long c) {
out.print(c);
}
static void print(int c) {
out.print(c);
}
static void println(int x) {
out.println(x);
}
static void print(String s) {
out.print(s);
}
static void println(String s) {
out.println(s);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
} | Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 36933dbb294de1db998d2f6531e275d1 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 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.00000");
final static int mod = (int) (1e9 + 7);
final static int MAX = Integer.MAX_VALUE;
final static int MIN = Integer.MIN_VALUE;
final static long INF = Long.MAX_VALUE;
final static long NEG_INF = Long.MIN_VALUE;
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(), idx = n - 1;
int[] a = readIntArray(n), b = readIntArray(n);
Map<Integer, Integer> map = new HashMap<>();
if (a[n - 1] != b[n - 1]) {
out.println("NO");
return;
}
for (int i = n - 1; i >= 0; i--) {
if (a[idx] == b[i]) {
idx--;
} else {
if (b[i] == b[i + 1])
map.put(b[i], map.getOrDefault(b[i], 0) + 1);
else if (map.containsKey(a[idx])) {
if (map.get(a[idx]) == 1)
map.remove(a[idx]);
else
map.put(a[idx], map.get(a[idx]) - 1);
i++;
idx--;
} else {
out.println("NO");
return;
}
}
}
out.println("YES");
}
private static void preprocess() throws IOException {
}
// cd C:\Users\Eshan Bhatt\Visual Studio Code\Competitive Programming\CodeForces
// javac CodeForces.java
// java CodeForces
// javac CodeForces.java && java CodeForces
// ==================== CUSTOM CLASSES ================================
static class 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(int n) 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(m);
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]);
}
// ====================== 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(int a, int 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 int multiply(int a, int b) {
return (int) ((((1L * a) % mod) * ((1L * b) % mod)) % mod);
}
private static int divide(int a, int 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;
}
// ================== 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;
}
}
// ==================== TRIE ================================
static class Trie {
class Node {
Node[] children;
boolean isEnd;
Node() {
children = new Node[26];
}
}
Node root;
Trie() {
root = new Node();
}
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;
}
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;
}
}
// ==================== FENWICK TREE ================================
static class FT {
long[] tree;
int n;
FT(int[] arr, int n) {
this.n = n;
this.tree = new long[n + 1];
for (int i = 1; i <= n; i++) {
update(i, arr[i - 1]);
}
}
void update(int idx, int val) {
while (idx <= n) {
tree[idx] += val;
idx += idx & -idx;
}
}
long query(int l, int r) {
return getSum(r) - getSum(l - 1);
}
long getSum(int idx) {
long ans = 0L;
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 | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 732bb7a1627efb0c78db5826ce30fe38 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | //some updates in import stuff
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.*;
//key points learned
//max space ever that could be alloted in a program to pass in cf
//int[][] prefixSum = new int[201][200_005]; -> not a single array more!!!
//never allocate memory again again to such bigg array, it will give memory exceeded for sure
//believe in your fucking solution and keep improving it!!! (sometimes)
//few things to figure around
//getting better and faster at taking input/output with normal method (buffered reader and printwriter)
//memorise all the key algos! a
public class D{
static int mod = (int) (Math.pow(10, 9)+7);
static final int dx[] = { -1, 0, 1, 0 }, dy[] = { 0, -1, 0, 1 };
static final int[] dx8 = { -1, -1, -1, 0, 0, 1, 1, 1 }, dy8 = { -1, 0, 1, -1, 1, -1, 0, 1 };
static final int[] dx9 = { -1, -1, -1, 0, 0, 0, 1, 1, 1 }, dy9 = { -1, 0, 1, -1, 0, 1, -1, 0, 1 };
static final double eps = 1e-10;
static List<Integer> primeNumbers = new ArrayList<>();
public static void main(String[] args) {
MyScanner sc = new MyScanner(); //pretty important for sure -
out = new PrintWriter(new BufferedOutputStream(System.out)); //dope shit output for sure
//code here
int test = sc.nextInt();
while(test --> 0){
int n = sc.nextInt();
int[] a = new int[n];
int[] b = new int[n];
int[] dead = new int[n + 1];
for(int i= 0; i < n; i++){
a[i] = sc.nextInt();
}
for(int i= 0; i < n; i++){
b[i] = sc.nextInt();
}
int up = n-1;
int down = n-1;
boolean flag = true;
while(up >= 0 && down >= 0){
// out.println(up + " " + down);
if(a[up] == b[down]){
up--;
down--;
}else{
//if not equal
if(down == n-1){
flag = false;
break;
}
if(b[down] == b[down + 1]){
dead[b[down]]++;
down--;
}else{
if(dead[a[up]] > 0){
dead[a[up]]--;
up--; //also loweing
}else{
flag = false;
break;
}
}
}
}
out.println(flag ? "YES" : "NO");
}
out.close();
}
//new stuff to learn (whenever this is need for them, then only)
//Lazy Segment Trees
//Persistent Segment Trees
//Square Root Decomposition
//Geometry & Convex Hull
//High Level DP -- yk yk
//String Matching Algorithms
//Heavy light Decomposition
//Updation Required
//Fenwick Tree - both are done (sum)
//Segment Tree - both are done (min, max, sum)
//-----CURRENTLY PRESENT-------//
//Graph
//DSU
//powerMODe
//power
//Segment Tree (work on this one)
//Prime Sieve
//Count Divisors
//Next Permutation
//Get NCR
//isVowel
//Sort (int)
//Sort (long)
//Binomial Coefficient
//Pair
//Triplet
//lcm (int & long)
//gcd (int & long)
//gcd (for binomial coefficient)
//swap (int & char)
//reverse
//primeExponentCounts
//Fast input and output
//-------------------------------------------------------------------
//-------------------------------------------------------------------
//-------------------------------------------------------------------
//-------------------------------------------------------------------
//-------------------------------------------------------------------
//GRAPH (basic structure)
public static class Graph{
public int V;
public ArrayList<ArrayList<Integer>> edges;
//2 -> [0,1,2] (current)
Graph(int V){
this.V = V;
edges = new ArrayList<>(V+1);
for(int i= 0; i <= V; i++){
edges.add(new ArrayList<>());
}
}
public void addEdge(int from , int to){
edges.get(from).add(to);
edges.get(to).add(from);
}
}
//DSU (path and rank optimised)
public static class DisjointUnionSets {
int[] rank, parent;
int n;
public DisjointUnionSets(int n)
{
rank = new int[n];
parent = new int[n];
Arrays.fill(rank, 1);
Arrays.fill(parent,-1);
this.n = n;
}
public int find(int curr){
if(parent[curr] == -1)
return curr;
//path compression optimisation
return parent[curr] = find(parent[curr]);
}
public void union(int a, int b){
int s1 = find(a);
int s2 = find(b);
if(s1 != s2){
//union by size
if(rank[s1] < rank[s2]){
parent[s1] = s2;
rank[s2] += rank[s1];
}else{
parent[s2] = s1;
rank[s1] += rank[s2];
}
}
}
}
//with mod
public static long powerMOD(long x, long y)
{
long res = 1L;
while (y > 0)
{
// If y is odd, multiply x with result
if ((y & 1) != 0){
x %= mod;
res %= mod;
res = (res * x)%mod;
}
// y must be even now
y = y >> 1; // y = y/2
x%= mod;
x = (x * x)%mod; // Change x to x^2
}
return res%mod;
}
//without mod
public static long power(long x, long y)
{
long res = 1L;
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/
x = (x * x);
}
return res;
}
public static class segmentTree{
//so let's make a constructor function for this bad boi for sure!!!
public long[] arr;
public long[] tree;
//COMPLEXITY (normal segment tree, stuff)
//build -> O(n)
//query -> O(logn)
//update -> O(logn)
//update-range -> O(n) (worst case)
//simple iteration and stuff for sure
public segmentTree(long[] arr){
int n = arr.length;
this.arr = new long[n];
for(int i= 0; i < n; i++){
this.arr[i] = arr[i];
}
tree = new long[4*n + 1];
}
//pretty basic idea if you read the code once
//first make child node once
//then form the parent node using them
public void buildTree(int s, int e, int index){
if(s == e){
tree[index] = arr[s];
return;
}
//recursive case
int mid = (s + e)/2;
buildTree(s, mid, 2 * index);
buildTree(mid + 1, e, 2*index + 1);
//the condition we want from children be like this
tree[index] = min(tree[2 * index], tree[2 * index + 1]);
return;
}
//definitely index based 0 query!!!
//only int index = 1!!
//baaki everything is simple as fuck
public long query(int s, int e, int qs , int qe, int index){
//complete overlap
if(s >= qs && e <= qe){
return tree[index];
}
//no overlap
if(qe < s || qs > e){
return Long.MAX_VALUE;
}
//partial overlap
int mid = (s + e)/2;
long left = query( s, mid , qs, qe, 2*index);
long right = query( mid + 1, e, qs, qe, 2*index + 1);
return min(left, right);
}
//gonna do range updates for sure now!!
//let's do this bois!!! (solve this problem for sure)
public void updateRange(int s, int e, int l, int r, long increment, int index){
//out of bounds
if(l > e || r < s){
return;
}
//leaf node
if(s == e){
tree[index] += increment;
return; //behnchoda return tera baap krvayege?
}
//recursive case
int mid = (s + e)/2;
updateRange(s, mid, l, r, increment, 2 * index);
updateRange(mid + 1, e, l, r, increment, 2 * index + 1);
tree[index] = min(tree[2 * index], tree[2 * index + 1]);
}
}
public static class segmentTreeLazy{
//so let's make a constructor function for this bad boi for sure!!!
public long[] arr;
public long[] tree;
public long[] lazy;
//COMPLEXITY (normal segment tree, stuff)
//build -> O(n)
//query-range -> O(logn)
//lazy update-range -> O(logn) (imp)
//simple iteration and stuff for sure
public segmentTreeLazy(long[] arr){
int n = arr.length;
this.arr = new long[n];
for(int i= 0; i < n; i++){
this.arr[i] = arr[i];
}
tree = new long[4*n + 1];
lazy = new long[1000000]; //pretty big for no inconvenience (no?) NONONONOONON! NO fucker NO!
}
//pretty basic idea if you read the code once
//first make child node once
//then form the parent node using them
public void buildTree(int s, int e, int index){
if(s == e){
tree[index] = arr[s];
return;
}
//recursive case
int mid = (s + e)/2;
buildTree(s, mid, 2 * index);
buildTree(mid + 1, e, 2*index + 1);
//the condition we want from children be like this
tree[index] = min(tree[2 * index], tree[2 * index + 1]);
return;
}
//definitely index based 0 query!!!
//only int index = 1!!
//baaki everything is simple as fuck
public long queryLazy(int s, int e, int qs, int qe, int index){
//before going down resolve if it exist
if(lazy[index] != 0){
tree[index] += lazy[index];
//non leaf node
if(s != e){
lazy[2*index] += lazy[index];
lazy[2*index + 1] += lazy[index];
}
lazy[index] = 0; //clear the lazy value at current node for sure
}
//no overlap
if(s > qe || e < qs){
return Long.MAX_VALUE;
}
//complete overlap
if(s >= qs && e <= qe){
return tree[index];
}
//partial overlap
int mid = (s + e)/2;
long left = queryLazy(s, mid, qs, qe, 2 * index);
long right = queryLazy(mid + 1, e, qs, qe, 2 * index + 1);
return Math.min(left, right);
}
//update range in O(logn) -- using lazy array
public void updateRangeLazy(int s, int e, int l, int r, int inc, int index){
//before going down resolve if it exist
if(lazy[index] != 0){
tree[index] += lazy[index];
//non leaf node
if(s != e){
lazy[2*index] += lazy[index];
lazy[2*index + 1] += lazy[index];
}
lazy[index] = 0; //clear the lazy value at current node for sure
}
//no overlap
if(s > r || l > e){
return;
}
//another case
if(l <= s && e <= r){
tree[index] += inc;
//create a new lazy value for children node
if(s != e){
lazy[2*index] += inc;
lazy[2*index + 1] += inc;
}
return;
}
//recursive case
int mid = (s + e)/2;
updateRangeLazy(s, mid, l, r, inc, 2*index);
updateRangeLazy(mid + 1, e, l, r, inc, 2*index + 1);
//update the tree index
tree[index] = Math.min(tree[2*index], tree[2*index + 1]);
return;
}
}
//prime sieve
public static void primeSieve(int n){
BitSet bitset = new BitSet(n+1);
for(long i = 0; i < n ; i++){
if (i == 0 || i == 1) {
bitset.set((int) i);
continue;
}
if(bitset.get((int) i)) continue;
primeNumbers.add((int)i);
for(long j = i; j <= n ; j+= i)
bitset.set((int)j);
}
}
//number of divisors
public static int countDivisors(long number){
if(number == 1) return 1;
List<Integer> primeFactors = new ArrayList<>();
int index = 0;
long curr = primeNumbers.get(index);
while(curr * curr <= number){
while(number % curr == 0){
number = number/curr;
primeFactors.add((int) curr);
}
index++;
curr = primeNumbers.get(index);
}
if(number != 1) primeFactors.add((int) number);
int current = primeFactors.get(0);
int totalDivisors = 1;
int currentCount = 2;
for (int i = 1; i < primeFactors.size(); i++) {
if (primeFactors.get(i) == current) {
currentCount++;
} else {
totalDivisors *= currentCount;
currentCount = 2;
current = primeFactors.get(i);
}
}
totalDivisors *= currentCount;
return totalDivisors;
}
//primeExponentCounts
public static int primeExponentsCount(int n) {
if (n <= 1)
return 0;
int sqrt = (int) Math.sqrt(n);
int remainingNumber = n;
int result = 0;
for (int i = 2; i <= sqrt; i++) {
while (remainingNumber % i == 0) {
result++;
remainingNumber /= i;
}
}
//in case of prime numbers this would happen
if (remainingNumber > 1) {
result++;
}
return result;
}
//now adding next permutation function to java hehe
public static boolean next_permutation(int[] p) {
for (int a = p.length - 2; a >= 0; --a)
if (p[a] < p[a + 1])
for (int b = p.length - 1;; --b)
if (p[b] > p[a]) {
int t = p[a];
p[a] = p[b];
p[b] = t;
for (++a, b = p.length - 1; a < b; ++a, --b) {
t = p[a];
p[a] = p[b];
p[b] = t;
}
return true;
}
return false;
}
//finding the value of NCR in O(RlogN) time and O(1) space
public static long getNcR(int n, int r)
{
long p = 1, k = 1;
if (n - r < r) r = n - r;
if (r != 0) {
while (r > 0) {
p *= n;
k *= r;
long m = __gcd(p, k);
p /= m;
k /= m;
n--;
r--;
}
}
else {
p = 1;
}
return p;
}
//is vowel function
public static boolean isVowel(char c)
{
return (c=='a' || c=='A' || c=='e' || c=='E' || c=='i' || c=='I' || c=='o' || c=='O' || c=='u' || c=='U');
}
//to sort the array with better method
public 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);
}
//sort long
public static void sort(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);
}
//for calculating binomialCoeff
public static int binomialCoeff(int n, int k)
{
int C[] = new int[k + 1];
// nC0 is 1
C[0] = 1;
for (int i = 1; i <= n; i++) {
// Compute next row of pascal
// triangle using the previous row
for (int j = Math.min(i, k); j > 0; j--)
C[j] = C[j] + C[j - 1];
}
return C[k];
}
//Pair with int int
public static class Pair{
public int a;
public int b;
public int hashCode;
Pair(int a , int b){
this.a = a;
this.b = b;
this.hashCode = Objects.hash(a, b);
}
@Override
public String toString(){
return a + " -> " + b;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Pair that = (Pair) o;
return a == that.a && b == that.b;
}
@Override
public int hashCode() {
return this.hashCode;
}
}
//Triplet with int int int
public static class Triplet{
public int a;
public int b;
public int c;
Triplet(int a , int b, int c){
this.a = a;
this.b = b;
this.c = c;
}
@Override
public String toString(){
return a + " -> " + b;
}
}
//Shortcut function
public static long lcm(long a , long b){
return a * (b/gcd(a,b));
}
//let's make one for calculating lcm basically
public static int lcm(int a , int b){
return (a * b)/gcd(a,b);
}
//int version for gcd
public static int gcd(int a, int b){
if(b == 0)
return a;
return gcd(b , a%b);
}
//long version for gcd
public static long gcd(long a, long b){
if(b == 0)
return a;
return gcd(b , a%b);
}
//for ncr calculator(ignore this code)
public static long __gcd(long n1, long n2)
{
long gcd = 1;
for (int i = 1; i <= n1 && i <= n2; ++i) {
// Checks if i is factor of both integers
if (n1 % i == 0 && n2 % i == 0) {
gcd = i;
}
}
return gcd;
}
//swapping two elements in an array
public static void swap(int[] arr, int left , int right){
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
}
//for char array
public static void swap(char[] arr, int left , int right){
char temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
}
//reversing an array
public static void reverse(int[] arr){
int left = 0;
int right = arr.length-1;
while(left <= right){
swap(arr, left,right);
left++;
right--;
}
}
public static long expo(long a, long b, long mod) {
long res = 1;
while (b > 0) {
if ((b & 1) == 1L) res = (res * a) % mod; //think about this one for a second
a = (a * a) % mod;
b = b >> 1;
}
return res;
}
//SOME EXTRA DOPE FUNCTIONS
public static long mminvprime(long a, long b) {
return expo(a, b - 2, b);
}
public static long mod_add(long a, long b, long m) {
a = a % m;
b = b % m;
return (((a + b) % m) + m) % m;
}
public static long mod_sub(long a, long b, long m) {
a = a % m;
b = b % m;
return (((a - b) % m) + m) % m;
}
public static long mod_mul(long a, long b, long m) {
a = a % m;
b = b % m;
return (((a * b) % m) + m) % m;
}
public static long mod_div(long a, long b, long m) {
a = a % m;
b = b % m;
return (mod_mul(a, mminvprime(b, m), m) + m) % m;
}
//O(n) every single time remember that
public static long nCr(long N, long K , long mod){
long upper = 1L;
long lower = 1L;
long lowerr = 1L;
for(long i = 1; i <= N; i++){
upper = mod_mul(upper, i, mod);
}
for(long i = 1; i <= K; i++){
lower = mod_mul(lower, i, mod);
}
for(long i = 1; i <= (N - K); i++){
lowerr = mod_mul(lowerr, i, mod);
}
// out.println(upper + " " + lower + " " + lowerr);
long answer = mod_mul(lower, lowerr, mod);
answer = mod_div(upper, answer, mod);
return answer;
}
// long[] fact = new long[2 * n + 1];
// long[] ifact = new long[2 * n + 1];
// fact[0] = 1;
// ifact[0] = 1;
// for (long i = 1; i <= 2 * n; i++)
// {
// fact[(int)i] = mod_mul(fact[(int)i - 1], i, mod);
// ifact[(int)i] = mminvprime(fact[(int)i], mod);
// }
//ifact is basically inverse factorial in here!!!!!(imp)
public static long combination(long n, long r, long m, long[] fact, long[] ifact) {
long val1 = fact[(int)n];
long val2 = ifact[(int)(n - r)];
long val3 = ifact[(int)r];
return (((val1 * val2) % m) * val3) % m;
}
//-----------PrintWriter for faster output---------------------------------
public static PrintWriter out;
//-----------MyScanner class for faster input----------
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
//--------------------------------------------------------
} | Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | b8953c0e97e6eb3ea1e1522e777fdb28 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 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 n = sc.nextInt();
for(int i= 0; i < n; i++) solve();
pw.flush();
}
public static void solve() {
int N = sc.nextInt();
int[] A = sc.nextIntArray(N);
int[] B = sc.nextIntArray(N);
Deque<int[]> st = new ArrayDeque<>();
Deque<int[]> st2 = new ArrayDeque<>();
//HashSet<Integer> opened = new HashSet<>();
for(int i = N-1; i >= 0; i--){
int now = A[i];
int cnt = 0;
while(i >= 0 && now == A[i]){
cnt++;
i--;
}
st.add(new int[]{now,cnt});
i++;
}
//HashSet<Integer> opened2 = new HashSet<>();
for(int i = N-1; i >= 0; i--){
int now = B[i];
int cnt = 0;
while(i >= 0 && now == B[i]){
cnt++;
i--;
}
st2.add(new int[]{now,cnt});
i++;
}
HashMap<Integer,Integer> map = new HashMap<>();
HashMap<Integer,Integer> map2 = new HashMap<>();
while(st.size() > 0 && st2.size() > 0){
int[] now = st.poll();
int[] now2 = st2.poll();
//pw.println(now[0] + " " + now[1]);
//pw.println(now2[0] + " " + now2[1]);
map2.put(now2[0],map2.getOrDefault(now2[0],0)+now2[1]);
while(now[0] != now2[0]){
if(map.containsKey(now[0])){
map.put(now[0],map.getOrDefault(now[0],0)+now[1]);
}else{
pw.println("NO");
return;
}
if(map.getOrDefault(now[0],0) > map2.getOrDefault(now[0],0)){
pw.println("NO");
return;
}
if(st.size() == 0){
break;
}
now = st.poll();
}
map.put(now[0],map.getOrDefault(now[0],0)+now[1]);
if(now[0] != now2[0] || map.get(now[0]) > map2.get(now2[0])){
pw.println("NO");
return;
}
}
pw.println("YES");
}
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 | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 6ed230ccb013ede8d7ff25b6c8f4cf6f | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.*;
import java.lang.*;
import java.util.*;
public class ComdeFormces {
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
// Reader.init(System.in);
FastReader sc=new FastReader();
BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
// OutputStream out = new BufferedOutputStream ( System.out );
int t=sc.nextInt();
int tc=1;
while(t--!=0) {
int n=sc.nextInt();
int a[]=new int[n];
int b[]=new int[n];
int mn[]=new int[n+1];
int mx[]=new int[n+1];
Arrays.fill(mn, -1);
for(int i=0;i<n;i++) {
a[i]=sc.nextInt();
if(mn[a[i]]==-1)mn[a[i]]=i;
mx[a[i]]=Math.max(mx[a[i]], i);
}
for(int i=0;i<n;i++) {
b[i]=sc.nextInt();
}
boolean ans=true;
int k=0;
HashMap<Integer,Integer> hm=new HashMap<>();
int ptr=0;
int i=0;
for( i=0;i<n;i++) {
if(a[i]!=b[ptr]) {
if(i-1>=0 && a[i-1]==b[ptr] && hm.getOrDefault(a[i-1],0)>0) {
while(ptr<n && a[i-1]==b[ptr] && hm.getOrDefault(a[i-1],0)>0) {
ptr++;
hm.put(a[i-1],hm.get(a[i-1])-1);
}
if(ptr==n)break;
if(a[i]==b[ptr])ptr++;
else hm.put(a[i],hm.getOrDefault(a[i], 0)+1);
}
else hm.put(a[i],hm.getOrDefault(a[i], 0)+1);
}
else ptr++;
}
if(ptr<=n-1) {
if(i-1>=0 && a[i-1]==b[ptr] && hm.getOrDefault(a[i-1],0)>0) {
while(ptr<n && a[i-1]==b[ptr] && hm.getOrDefault(a[i-1],0)>0) {
ptr++;
hm.put(a[i-1],hm.get(a[i-1])-1);
}
}
}
log.write((ptr==n?"YES":"NO")+"\n");
log.flush();
}
}
static void update(long f[],long upd,int ind) {
int vl=ind;
while(vl<f.length) {
f[vl]+=upd;
int tp=~vl;tp++;tp&=vl;
vl+=tp;
}
}
static long ser(long f[],int ind) {
int vl=ind;
long sm=0;
while(vl!=0) {
sm+=f[vl];
int tp=~vl;tp++;tp&=vl;
vl-=tp;
}
return sm;
}
static int bsfd(ArrayList<Integer> ar,int el) {
int s=0;
int e=ar.size()-1;
while(s<=e) {
int m=s+(e-s)/2;
if(ar.get(m)<=el)s=m+1;
else e=m-1;
}
return e>=0?e+1:0;
}
static int find(int el,int p[]) {
if(p[el]<0)return el;
return p[el]=find(p[el],p);
}
static boolean find(int a,int b,int p[]) {
int p1=find(a,p);
int p2=find(b,p);
if(p1>=0 && p1==p2)return false;
else {
if(p[p1]<p[p2]) {
p[p1]+=p[p2];
p[p2]=p1;
}
else {
p[p2]+=p[p1];
p[p1]=p2;
}
return true;
}
}
public static void radixSort(int a[]) {
int n=a.length;
int res[]=new int[n];
int p=1;
for(int i=0;i<=8;i++) {
int cnt[]=new int[10];
for(int j=0;j<n;j++) {
a[j]=res[j];
cnt[(a[j]/p)%10]++;
}
for(int j=1;j<=9;j++) {
cnt[j]+=cnt[j-1];
}
for(int j=n-1;j>=0;j--) {
res[cnt[(a[j]/p)%10]-1]=a[j];
cnt[(a[j]/p)%10]--;
}
p*=10;
}
}
static int bits(long n) {
int ans=0;
while(n!=0) {
if((n&1)==1)ans++;
n>>=1;
}
return ans;
}
static long flor(ArrayList<Long> ar,long el) {
int s=0;
int e=ar.size()-1;
while(s<=e) {
int m=s+(e-s)/2;
if(ar.get(m)==el)return ar.get(m);
else if(ar.get(m)<el)s=m+1;
else e=m-1;
}
return e>=0?e:-1;
}
public static int kadane(int a[]) {
int sum=0,mx=Integer.MIN_VALUE;
for(int i=0;i<a.length;i++) {
sum+=a[i];
mx=Math.max(mx, sum);
if(sum<0) sum=0;
}
return mx;
}
public static int m=(int)(1e9+7);
public static int mul(int a, int b) {
return ((a%m)*(b%m))%m;
}
public static long mul(long a, long b) {
return ((a%m)*(b%m))%m;
}
public static int add(int a, int b) {
return ((a%m)+(b%m))%m;
}
public static long add(long a, long b) {
return ((a%m)+(b%m))%m;
}
//debug
public static <E> void p(E[][] a,String s) {
System.out.println(s);
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 static void p(int[] a,String s) {
System.out.print(s+"=");
for(int i=0;i<a.length;i++)System.out.print(a[i]+" ");
System.out.println();
}
public static void p(long[] a,String s) {
System.out.print(s+"=");
for(int i=0;i<a.length;i++)System.out.print(a[i]+" ");
System.out.println();
}
public static <E> void p(E a,String s){
System.out.println(s+"="+a);
}
public static <E> void p(ArrayList<E> a,String s){
System.out.println(s+"="+a);
}
public static <E> void p(LinkedList<E> a,String s){
System.out.println(s+"="+a);
}
public static <E> void p(HashSet<E> a,String s){
System.out.println(s+"="+a);
}
public static <E> void p(Stack<E> a,String s){
System.out.println(s+"="+a);
}
public static <E> void p(Queue<E> a,String s){
System.out.println(s+"="+a);
}
//utils
static ArrayList<Integer> divisors(int n){
ArrayList<Integer> ar=new ArrayList<>();
for (int i=2; i<=Math.sqrt(n); i++){
if (n%i == 0){
if (n/i == i) {
ar.add(i);
}
else {
ar.add(i);
ar.add(n/i);
}
}
}
return ar;
}
static ArrayList<Integer> prime(int n){
ArrayList<Integer> ar=new ArrayList<>();
int cnt=0;
boolean pr=false;
while(n%2==0) {
ar.add(2);
n/=2;
}
for(int i=3;i*i<=n;i+=2) {
pr=false;
while(n%i==0) {
n/=i;
ar.add(i);
pr=true;
}
}
if(n>2) ar.add(n);
return ar;
}
static long gcd(long a,long b) {
if(b==0)return a;
else return gcd(b,a%b);
}
static int gcd(int a,int b) {
if(b==0)return a;
else return gcd(b,a%b);
}
static long factmod(long n,long mod,long img) {
if(n==0)return 1;
long ans=1;
long temp=1;
while(n--!=0) {
if(temp!=img) {
ans=((ans%mod)*((temp)%mod))%mod;
}
temp++;
}
return ans%mod;
}
static int ncr(int n, int r){
if(r>n-r)r=n-r;
int ans=1;
for(int i=0;i<r;i++){
ans*=(n-i);
ans/=(i+1);
}
return ans;
}
public static class trip{
int a,b;
int c;
public trip(int a,int b,int c) {
this.a=a;
this.b=b;
this.c=c;
}
public int compareTo(trip q) {
return this.b-q.b;
}
}
static void mergesort(int[] a,int start,int end) {
if(start>=end)return ;
int mid=start+(end-start)/2;
mergesort(a,start,mid);
mergesort(a,mid+1,end);
merge(a,start,mid,end);
}
static void merge(int[] a, int start,int mid,int end) {
int ptr1=start;
int ptr2=mid+1;
int b[]=new int[end-start+1];
int i=0;
while(ptr1<=mid && ptr2<=end) {
if(a[ptr1]<a[ptr2]) {
b[i]=a[ptr1];
ptr1++;
// swp2+;
i++;
}
else {
b[i]=a[ptr2];
// swp+=mid+1-ptr1;
// System.out.println("ch="+b[i]+" "+(ptr2-ptr1));
ptr2++;
i++;
}
}
while(ptr1<=mid) {
b[i]=a[ptr1];
ptr1++;
i++;
}
while(ptr2<=end) {
b[i]=a[ptr2];
ptr2++;
i++;
}
for(int j=start;j<=end;j++) {
a[j]=b[j-start];
}
}
public static class FastReader {
BufferedReader b;
StringTokenizer s;
public FastReader() {
b=new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while(s==null ||!s.hasMoreElements()) {
try {
s=new StringTokenizer(b.readLine());
}
catch(IOException e) {
e.printStackTrace();
}
}
return s.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str="";
try {
str=b.readLine();
}
catch(IOException e) {
e.printStackTrace();
}
return str;
}
boolean hasNext() {
if (s != null && s.hasMoreTokens()) {
return true;
}
String tmp;
try {
b.mark(1000);
tmp = b.readLine();
if (tmp == null) {
return false;
}
b.reset();
} catch (IOException e) {
return false;
}
return true;
}
}
public static class pair{
int a;
int b;
public pair(int a,int b) {
this.a=a;
this.b=b;
}
public int compareTo(pair b) {
return this.a-b.a;
}
// public int compareToo(pair b) {
// return this.b-b.b;
// }
@Override
public String toString() {
return "{"+this.a+" "+this.b+"}";
}
}
static long pow(long a, long pw) {
long temp;
if(pw==0)return 1;
temp=pow(a,pw/2);
if(pw%2==0)return temp*temp;
return a*temp*temp;
}
static int pow(int a, int pw) {
int temp;
if(pw==0)return 1;
temp=pow(a,pw/2);
if(pw%2==0)return temp*temp;
return a*temp*temp;
}
} | Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | f66f06dc639e056a2a0f6dee78d7535b | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.*;
import java.lang.Math;
import java.lang.reflect.Array;
import java.util.*;
import javax.swing.text.DefaultStyledDocument.ElementSpec;
public final class Solution {
static BufferedReader br = new BufferedReader(
new InputStreamReader(System.in)
);
static BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(System.out)
);
static StringTokenizer st;
/*write your constructor and global variables here*/
static class sortCond implements Comparator<Pair<Integer, Integer>> {
@Override
public int compare(Pair<Integer, Integer> p1, Pair<Integer, Integer> p2) {
if (p1.a <= p2.a) {
return -1;
} else {
return 1;
}
}
}
static class Pair<f, s> {
f a;
s b;
Pair(f a, s b) {
this.a = a;
this.b = b;
}
}
interface modOperations {
int mod(int a, int b, int mod);
}
static int findBinaryExponentian(int a, int pow, int mod) {
if (pow == 1) {
return a;
} else if (pow == 0) {
return 1;
} else {
int retVal = findBinaryExponentian(a, (int) pow / 2, mod);
return modMul.mod(
modMul.mod(retVal, retVal, mod),
(pow % 2 == 0) ? 1 : a,
mod
);
}
}
static int findPow(int a, int b, int mod) {
if (b == 1) {
return a % mod;
} else if (b == 0) {
return 1;
} else {
int res = findPow(a, (int) b / 2, mod);
return modMul.mod(res, modMul.mod(res, (b % 2 == 1 ? a : 1), mod), mod);
}
}
static int bleft(long ele, ArrayList<Long> sortedArr) {
int l = 0;
int h = sortedArr.size() - 1;
int ans = -1;
while (l <= h) {
int mid = l + (int) (h - l) / 2;
if (sortedArr.get(mid) < ele) {
l = mid + 1;
} else if (sortedArr.get(mid) >= ele) {
ans = mid;
h = mid - 1;
}
}
return ans;
}
static long gcd(long a, long b) {
long div = b;
long rem = a % b;
while (rem != 0) {
long temp = rem;
rem = div % rem;
div = temp;
}
return div;
}
static int log(int no) {
int i = 0;
while ((1 << i) <= no) {
i++;
}
if ((1 << (i - 1)) == no) {
return i - 1;
} else {
return i;
}
}
static modOperations modAdd = (int a, int b, int mod) -> {
return (a % mod + b % mod) % mod;
};
static modOperations modSub = (int a, int b, int mod) -> {
return (int) ((1l * a % mod - 1l * b % mod + 1l * mod) % mod);
};
static modOperations modMul = (int a, int b, int mod) -> {
return (int) ((1l * (a % mod) * 1l * (b % mod)) % (1l * mod));
};
static modOperations modDiv = (int a, int b, int mod) -> {
return modMul.mod(a, findBinaryExponentian(b, mod - 1, mod), mod);
};
static HashSet<Integer> primeList(int MAXI) {
int[] prime = new int[MAXI + 1];
HashSet<Integer> obj = new HashSet<>();
for (int i = 2; i <= (int) Math.sqrt(MAXI) + 1; i++) {
if (prime[i] == 0) {
obj.add(i);
for (int j = i * i; j <= MAXI; j += i) {
prime[j] = 1;
}
}
}
for (int i = (int) Math.sqrt(MAXI) + 1; i <= MAXI; i++) {
if (prime[i] == 0) {
obj.add(i);
}
}
return obj;
}
static int[] factorialList(int MAXI, int mod) {
int[] factorial = new int[MAXI + 1];
factorial[2] = 1;
for (int i = 3; i < MAXI + 1; i++) {
factorial[i] = modMul.mod(factorial[i - 1], i, mod);
}
return factorial;
}
static void put(HashMap<Integer, Integer> cnt, int key) {
if (cnt.containsKey(key)) {
cnt.replace(key, cnt.get(key) + 1);
} else {
cnt.put(key, 1);
}
}
static long arrSum(ArrayList<Long> arr) {
long tot = 0;
for (int i = 0; i < arr.size(); i++) {
tot += arr.get(i);
}
return tot;
}
static int ord(char b) {
return (int) b - (int) 'a';
}
static int optimSearch(int[] cnt, int lower_bound, int pow, int n) {
int l = lower_bound + 1;
int h = n;
int ans = 0;
while (l <= h) {
int mid = l + (h - l) / 2;
if (cnt[mid] - cnt[lower_bound] == pow) {
return mid;
} else if (cnt[mid] - cnt[lower_bound] < pow) {
ans = mid;
l = mid + 1;
} else {
h = mid - 1;
}
}
return ans;
}
static Pair<Long, Integer> ret_ans(ArrayList<Integer> ans) {
int size = ans.size();
int mini = 1000000000 + 1;
long tit = 0l;
for (int i = 0; i < size; i++) {
tit += 1l * ans.get(i);
mini = Math.min(mini, ans.get(i));
}
return new Pair<>(tit - mini, mini);
}
static int factorList(
HashMap<Integer, Integer> maps,
int no,
int maxK,
int req
) {
int i = 1;
while (i * i <= no) {
if (no % i == 0) {
if (i != no / i) {
put(maps, no / i);
}
put(maps, i);
if (maps.get(i) == req) {
maxK = Math.max(maxK, i);
}
if (maps.get(no / i) == req) {
maxK = Math.max(maxK, no / i);
}
}
i++;
}
return maxK;
}
static ArrayList<Integer> getKeys(HashMap<Integer, Integer> maps) {
ArrayList<Integer> vals = new ArrayList<>();
for (Map.Entry<Integer, Integer> map : maps.entrySet()) {
vals.add(map.getKey());
}
return vals;
}
static ArrayList<Integer> getValues(HashMap<Integer, Integer> maps) {
ArrayList<Integer> vals = new ArrayList<>();
for (Map.Entry<Integer, Integer> map : maps.entrySet()) {
vals.add(map.getValue());
}
return vals;
}
/*write your methods here*/
static int getMax(ArrayList<Integer> arr) {
int max = arr.get(0);
for (int i = 1; i < arr.size(); i++) {
if (arr.get(i) > max) {
max = arr.get(i);
}
}
return max;
}
static int getMin(ArrayList<Integer> arr) {
int max = arr.get(0);
for (int i = 1; i < arr.size(); i++) {
if (arr.get(i) < max) {
max = arr.get(i);
}
}
return max;
}
public static void main(String[] args) throws IOException {
int cases = Integer.parseInt(br.readLine()), n, i;
while (cases-- != 0) {
n = Integer.parseInt(br.readLine());
int a[] = new int[n];
int b[] = new int[n];
st = new StringTokenizer(br.readLine());
for (i = 0; i < n; i++) {
a[i] = Integer.parseInt(st.nextToken());
}
st = new StringTokenizer(br.readLine());
for (i = 0; i < n; i++) {
b[i] = Integer.parseInt(st.nextToken());
}
int cnt[] = new int[n + 1];
int ind = n;
int p1 = 0;
for (i = 0; i < n; i++) {
//System.out.println(i + " " + p1);
if (p1 >= n) {
ind = i;
break;
} else {
if (a[p1] == b[i]) {
p1++;
} else if (
i != 0 &&
p1 - 1 >= 0 &&
a[p1 - 1] == b[i - 1] &&
b[i] == b[i - 1] &&
cnt[b[i]] > 0
) {
cnt[b[i]]--;
} else {
cnt[a[p1]]++;
i--;
p1++;
}
}
}
for (i = ind; i < n; i++) {
if (b[i] == b[i - 1]) {
cnt[b[i]]--;
} else {
break;
}
}
boolean ok = true;
for (i = 1; i <= n; i++) {
if (cnt[i] != 0) {
ok = false;
break;
}
}
if (ok) {
bw.write("YES\n");
} else {
bw.write("NO\n");
}
}
bw.flush();
}
}
| Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 7741ead913422403e25609b187b626c8 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.*;
import java.lang.Math;
import java.lang.reflect.Array;
import java.util.*;
import javax.swing.text.DefaultStyledDocument.ElementSpec;
public final class Solution {
static BufferedReader br = new BufferedReader(
new InputStreamReader(System.in)
);
static BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(System.out)
);
static StringTokenizer st;
/*write your constructor and global variables here*/
static class sortCond implements Comparator<Pair<Integer, Integer>> {
@Override
public int compare(Pair<Integer, Integer> p1, Pair<Integer, Integer> p2) {
if (p1.a <= p2.a) {
return -1;
} else {
return 1;
}
}
}
static class Pair<f, s> {
f a;
s b;
Pair(f a, s b) {
this.a = a;
this.b = b;
}
}
interface modOperations {
int mod(int a, int b, int mod);
}
static int findBinaryExponentian(int a, int pow, int mod) {
if (pow == 1) {
return a;
} else if (pow == 0) {
return 1;
} else {
int retVal = findBinaryExponentian(a, (int) pow / 2, mod);
return modMul.mod(
modMul.mod(retVal, retVal, mod),
(pow % 2 == 0) ? 1 : a,
mod
);
}
}
static int findPow(int a, int b, int mod) {
if (b == 1) {
return a % mod;
} else if (b == 0) {
return 1;
} else {
int res = findPow(a, (int) b / 2, mod);
return modMul.mod(res, modMul.mod(res, (b % 2 == 1 ? a : 1), mod), mod);
}
}
static int bleft(long ele, ArrayList<Long> sortedArr) {
int l = 0;
int h = sortedArr.size() - 1;
int ans = -1;
while (l <= h) {
int mid = l + (int) (h - l) / 2;
if (sortedArr.get(mid) < ele) {
l = mid + 1;
} else if (sortedArr.get(mid) >= ele) {
ans = mid;
h = mid - 1;
}
}
return ans;
}
static long gcd(long a, long b) {
long div = b;
long rem = a % b;
while (rem != 0) {
long temp = rem;
rem = div % rem;
div = temp;
}
return div;
}
static int log(int no) {
int i = 0;
while ((1 << i) <= no) {
i++;
}
if ((1 << (i - 1)) == no) {
return i - 1;
} else {
return i;
}
}
static modOperations modAdd = (int a, int b, int mod) -> {
return (a % mod + b % mod) % mod;
};
static modOperations modSub = (int a, int b, int mod) -> {
return (int) ((1l * a % mod - 1l * b % mod + 1l * mod) % mod);
};
static modOperations modMul = (int a, int b, int mod) -> {
return (int) ((1l * (a % mod) * 1l * (b % mod)) % (1l * mod));
};
static modOperations modDiv = (int a, int b, int mod) -> {
return modMul.mod(a, findBinaryExponentian(b, mod - 1, mod), mod);
};
static HashSet<Integer> primeList(int MAXI) {
int[] prime = new int[MAXI + 1];
HashSet<Integer> obj = new HashSet<>();
for (int i = 2; i <= (int) Math.sqrt(MAXI) + 1; i++) {
if (prime[i] == 0) {
obj.add(i);
for (int j = i * i; j <= MAXI; j += i) {
prime[j] = 1;
}
}
}
for (int i = (int) Math.sqrt(MAXI) + 1; i <= MAXI; i++) {
if (prime[i] == 0) {
obj.add(i);
}
}
return obj;
}
static int[] factorialList(int MAXI, int mod) {
int[] factorial = new int[MAXI + 1];
factorial[2] = 1;
for (int i = 3; i < MAXI + 1; i++) {
factorial[i] = modMul.mod(factorial[i - 1], i, mod);
}
return factorial;
}
static void put(HashMap<Integer, Integer> cnt, int key) {
if (cnt.containsKey(key)) {
cnt.replace(key, cnt.get(key) + 1);
} else {
cnt.put(key, 1);
}
}
static long arrSum(ArrayList<Long> arr) {
long tot = 0;
for (int i = 0; i < arr.size(); i++) {
tot += arr.get(i);
}
return tot;
}
static int ord(char b) {
return (int) b - (int) 'a';
}
static int optimSearch(int[] cnt, int lower_bound, int pow, int n) {
int l = lower_bound + 1;
int h = n;
int ans = 0;
while (l <= h) {
int mid = l + (h - l) / 2;
if (cnt[mid] - cnt[lower_bound] == pow) {
return mid;
} else if (cnt[mid] - cnt[lower_bound] < pow) {
ans = mid;
l = mid + 1;
} else {
h = mid - 1;
}
}
return ans;
}
static Pair<Long, Integer> ret_ans(ArrayList<Integer> ans) {
int size = ans.size();
int mini = 1000000000 + 1;
long tit = 0l;
for (int i = 0; i < size; i++) {
tit += 1l * ans.get(i);
mini = Math.min(mini, ans.get(i));
}
return new Pair<>(tit - mini, mini);
}
static int factorList(
HashMap<Integer, Integer> maps,
int no,
int maxK,
int req
) {
int i = 1;
while (i * i <= no) {
if (no % i == 0) {
if (i != no / i) {
put(maps, no / i);
}
put(maps, i);
if (maps.get(i) == req) {
maxK = Math.max(maxK, i);
}
if (maps.get(no / i) == req) {
maxK = Math.max(maxK, no / i);
}
}
i++;
}
return maxK;
}
static ArrayList<Integer> getKeys(HashMap<Integer, Integer> maps) {
ArrayList<Integer> vals = new ArrayList<>();
for (Map.Entry<Integer, Integer> map : maps.entrySet()) {
vals.add(map.getKey());
}
return vals;
}
static ArrayList<Integer> getValues(HashMap<Integer, Integer> maps) {
ArrayList<Integer> vals = new ArrayList<>();
for (Map.Entry<Integer, Integer> map : maps.entrySet()) {
vals.add(map.getValue());
}
return vals;
}
/*write your methods here*/
static int getMax(ArrayList<Integer> arr) {
int max = arr.get(0);
for (int i = 1; i < arr.size(); i++) {
if (arr.get(i) > max) {
max = arr.get(i);
}
}
return max;
}
static int getMin(ArrayList<Integer> arr) {
int max = arr.get(0);
for (int i = 1; i < arr.size(); i++) {
if (arr.get(i) < max) {
max = arr.get(i);
}
}
return max;
}
public static void main(String[] args) throws IOException {
int cases = Integer.parseInt(br.readLine()), n, i;
while (cases-- != 0) {
n = Integer.parseInt(br.readLine());
int a[] = new int[n];
int b[] = new int[n];
st = new StringTokenizer(br.readLine());
for (i = 0; i < n; i++) {
a[i] = Integer.parseInt(st.nextToken());
}
st = new StringTokenizer(br.readLine());
for (i = 0; i < n; i++) {
b[i] = Integer.parseInt(st.nextToken());
}
int cnt[] = new int[n + 1];
int ind = n;
int p1 = 0;
for (i = 0; i < n; i++) {
//System.out.println(i + " " + p1);
if (p1 >= n) {
ind = i;
break;
} else {
if (a[p1] == b[i]) {
p1++;
} else if (i != 0 && b[i] == b[i - 1] && cnt[b[i]] > 0) {
cnt[b[i]]--;
} else {
cnt[a[p1]]++;
i--;
p1++;
}
}
}
for (i = ind; i < n; i++) {
if (b[i] == b[i - 1]) {
cnt[b[i]]--;
} else {
break;
}
}
boolean ok = true;
for (i = 1; i <= n; i++) {
if (cnt[i] != 0) {
ok = false;
break;
}
}
if (ok) {
bw.write("YES\n");
} else {
bw.write("NO\n");
}
}
bw.flush();
}
}
| Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | ecb4baca997e36518c5f52fb4c4e39a5 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.util.*;
import java.io.*;
// you can compare with output.txt and expected out
public class RoundGlobal20D {
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)));
RoundGlobal20D sol = new RoundGlobal20D();
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) {
int n = in.nextInt();
int[] a = in.nextIntArray(n);
int[] b = in.nextIntArray(n);
if(isDebug){
out.printf("Test %d\n", i);
}
boolean ans = solve(a, b);
out.printlnAns(ans);
if(isDebug)
out.flush();
}
in.close();
out.close();
}
private boolean solve(int[] a, int[] b) {
int n = a.length;
// a1 a2 ... an
// 2 2 x x x 2
// 2 x x x 2 2
// x x x 2 2 2
// x 3 2 2
// x 2 2 2
int[] borrow = new int[n+1];
// ArrayDeque<Integer> queue = new ArrayDeque<Integer>();
int expect = -1;
int j = n-1;
for(int i=n-1; i>=0; i--) {
if(a[j] != b[i]) {
// b[i] = 5
// x x x x x 6
// x x x 5
if(expect == b[i]) {
borrow[b[i]]++;
// queue.add(b[i]);
}
else if(borrow[a[j]] > 0) {
borrow[a[j]]--;
j--;
i++;
}
else
return false;
}
else {
expect = b[i];
j--;
}
}
for(; j>=0; j--) {
if(borrow[a[j]] > 0)
borrow[a[j]]--;
else
return false;
}
return true;
}
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[][] nextTreeEdges(int n, int offset){
int[][] e = new int[n-1][2];
for(int i=0; i<n-1; i++){
e[i][0] = nextInt()+offset;
e[i][1] = nextInt()+offset;
}
return e;
}
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[][] nextPairs(int n){
return nextPairs(n, 0);
}
int[][] nextPairs(int n, int offset) {
int[][] xy = new int[2][n];
for(int i=0; i<n; i++) {
xy[0][i] = nextInt() + offset;
xy[1][i] = nextInt() + offset;
}
return xy;
}
int[][] nextGraphEdges(){
return nextGraphEdges(0);
}
int[][] nextGraphEdges(int offset) {
int m = nextInt();
int[][] e = new int[m][2];
for(int i=0; i<m; i++){
e[i][0] = nextInt()+offset;
e[i][1] = nextInt()+offset;
}
return e;
}
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;
}
}
public static class MyPrintWriter extends PrintWriter{
public MyPrintWriter(OutputStream os) {
super(os);
}
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(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]];
}
int[] inIdx = new int[n];
int[] outIdx = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
outNeighbors[u][outIdx[u]++] = v;
inNeighbors[v][inIdx[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]];
int[] idx = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
neighbors[u][idx[u]++] = v;
neighbors[v][idx[v]++] = u;
}
return neighbors;
}
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\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 27a452b0fc6e5e7725ceeaa334f94740 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.*;
import java.util.*;
/**
* Provide prove of correctness before implementation. Implementation can cost a lot of time.
* Anti test that prove that it's wrong.
* <p>
* Do not confuse i j k g indexes, upTo and length. Do extra methods!!! Write more informative names to simulation
* <p>
* Will program ever exceed limit?
* Try all approaches with prove of correctness if task is not obvious.
* If you are given formula/rule: Try to play with it.
* Analytic solution/Hardcoded solution/Constructive/Greedy/DP/Math/Brute force/Symmetric data
* Number theory
* Game theory (optimal play) that consider local and global strategy.
* Start writing the hardest code first
*/
public class CF1672D {
private String solveOne(int n, int[] a, int[] b) {
List<Pair> grA = groups(a);
List<Pair> grB = groups(b);
if (grA.size() < grB.size()) {
return ("NO");
}
int pa = grA.size() - 1;
int pb = grB.size() - 1;
MultiSet<Integer> opened = MultiSet.UNORDERED();
while (pb >= 0 && pa >= 0) {
Pair pairB = grB.get(pb);
Pair pairA = grA.get(pa);
if (pairB.val == pairA.val) {
//invariant
boolean invariant = pairB.cnt >= pairA.cnt;// && pairB.indR <= pairA.indR;
if (!invariant) {
// if(opened.contains(pairA.val)){
// long toRemove = Math.min(opened.get(pairA.val), pairA.cnt);
// opened.removeAmount(pairA.val, toRemove);
// pa--;
// } else
try {
opened.removeAmount(pairB.val, pairA.cnt - pairB.cnt);
} catch (RuntimeException e){
return ("NO");
}
//} else if (pairB.cnt == pairA.cnt) {
} else {
opened.add(pairB.val, pairB.cnt - pairA.cnt);
}
pb--;
pa--;
} else {
if (opened.get(pairA.val) < pairA.cnt) {
return ("NO");
} else {
opened.removeAmount(pairA.val, pairA.cnt);
//pb--;
pa--;
}
}
}
if (pb > -1) {
return ("NO");
}
while (pa >= 0) {
Pair pairA = grA.get(pa);
if (opened.get(pairA.val) < pairA.cnt) {
return ("NO");
} else {
opened.removeAmount(pairA.val, pairA.cnt);
//pb--;
pa--;
}
}
return (opened.size() == 0 ? "YES" : "NO");
// System.out.println("YES");
// MultiSet<Integer> msA = MultiSet.UNORDERED();
// MultiSet<Integer> msB = MultiSet.UNORDERED();
// System.out.println(ok ? "YES" : "NO");
}
int[] randomArray(Random r, int n, int from, int upTo){
int[] ans = new int[n];
for(int i = 0; i < n ; i ++) {
ans[i] = from + r.nextInt(upTo - from);
}
return ans;
}
class Segment { int left; int right;
public Segment(int left, int right) {
this.left = left;
this.right = right;
}
@Override
public String toString() {
return "Segment{" +
"left=" + left +
", right=" + right +
'}';
}
}
int[] doRandomShift(Random rand, int[] a, int shift, List<Segment> toFill){
int n = a.length;
int[] b = a.clone();
for (int i = 0; i < shift; i++) {
List<Segment> possible = new ArrayList<>();
for(int l = 0 ; l < n; l ++) {
for(int r = 0; r < n; r++){
if(l < r && b[l] == b[r] && r + 1 - l > 2) {
possible.add(new Segment(l, r));
}
}
}
if(possible.isEmpty()){
break;
} else {
Segment s = possible.get(rand.nextInt(possible.size()));
int temp = b[s.left];
java.lang.System.arraycopy(b, s.left + 1, b, s.left, s.right - s.left);
b[s.right] = temp;
toFill.add(s);
}
}
return b;
}
private void solve() {
boolean CORRECTNESS_TEST = false;
if (!CORRECTNESS_TEST) {
int t = nextInt();
for (int tt = 0; tt < t; tt++) {
int n = nextInt();
int[] a = nextIntArr(n);
int[] b = nextIntArr(n);
String res = solveOne(n, a, b);
System.out.println(res);
}
} else {
Random r = new Random(42);
int t = 1_000_000;
for (int tt = 0; tt < t; tt++) {
int n = 5 + r.nextInt(6);
int[] a = randomArray(r, n, 1, 10);
int shifts = 5 + r.nextInt(6);
List<Segment> segments = new ArrayList<>();
int[] b = doRandomShift(r, a, shifts, segments);
String ans = solveOne(n, a, b);
if(!Objects.equals(ans, "YES")) {
throw new AssertionRuntimeException(tt, "YES", ans, a, b, segments);
}
}
}
}
class AssertionRuntimeException extends RuntimeException {
// AssertionRuntimeException(Object expected,
// Object actual, Object... input) {
// super("expected = " + expected + ",\n actual = " + actual + ",\n " + Arrays.deepToString(input));
// }
AssertionRuntimeException(int testCase,
Object expected,
Object actual, Object... input) {
super("Testcase: " + testCase + "\n expected = " + expected + ",\n actual = " + actual + ",\n " + Arrays.deepToString(input));
}
}
private void assertThat(boolean b) {
if (!b) throw new RuntimeException();
}
private List<Pair> groups(int[] a) {
int n = a.length;
List<Pair> ans = new ArrayList<>();
int curCnt = 0;
for (int i = 0; i < n; i++) {
if ((i == 0 || a[i - 1] != a[i])) {
curCnt = 0;
}
curCnt++;
if ((i == n - 1 || a[i + 1] != a[i])) {
ans.add(new Pair(a[i], curCnt, i));
}
}
return ans;
}
class Pair {
int val;
int cnt;
int indR;
public Pair(int val, int cnt, int indR) {
this.val = val;
this.cnt = cnt;
this.indR = indR;
}
@Override
public String toString() {
return "Pair{" +
"val=" + val +
", cnt=" + cnt +
", indR=" + indR +
'}';
}
}
static class MultiSet<T> implements Iterable<T> {
static <T> MultiSet<T> ORDERED(Comparator<T> comparator) {
MultiSet<T> tMultiSet = new MultiSet<>();
tMultiSet.map = new TreeMap<>(comparator);
return tMultiSet;
}
static <T> MultiSet<T> UNORDERED() {
MultiSet<T> tMultiSet = new MultiSet<>();
tMultiSet.map = new HashMap<>();
return tMultiSet;
}
private MultiSet() {
}
private Map<T, Long> map;
private int size = 0;
boolean contains(T val) {
return map.containsKey(val);
}
void add(T val) {
map.merge(val, 1L, Long::sum);
size++;
}
void add(T val, long cnt) {
if(cnt != 0){
map.merge(val, cnt, Long::sum);
size += cnt;
}
}
void removeOne(T val) {
removeAmount(val, 1);
}
void removeAll(T val) {
long cnt = map.get(val);
size -= cnt;
map.remove(val);
}
void removeAmount(T val, long cnt) {
if(cnt == 0) {
return;
}
Objects.requireNonNull(map.get(val));
if (map.get(val) < cnt) {
throw new RuntimeException(
String.format("Trying to remove the amount %d, while %d only available %d!", cnt, val, map.get(val))
);
}
map.merge(val, -cnt, Long::sum);
if (map.get(val) == 0) {
map.remove(val);
}
size -= cnt;
}
long get(T val) {
return map.getOrDefault(val, 0L);
}
int size() {
return size;
}
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
{
this.iterator = map.keySet().iterator();
if (this.iterator.hasNext()) {
next = this.iterator.next();
cnt = map.get(this.next) - 1;
}
}
long cnt;
Iterator<T> iterator;
T next;
private void prepareNext() {
if (cnt > 0) {
cnt--;
} else {
if (this.iterator.hasNext()) {
next = this.iterator.next();
cnt = map.get(this.next) - 1;
} else {
next = null;
cnt = 0;
}
}
}
@Override
public boolean hasNext() {
return next != null;
}
@Override
public T next() {
T ans = next;
prepareNext();
return ans;
}
};
}
}
private int nextInt() {
return System.in.readInt();
}
private long nextLong() {
return System.in.readLong();
}
private String nextString() {
return System.in.readString();
}
private int[] nextIntArr(int n) {
return System.in.readIntArray(n);
}
private long[] nextLongArr(int n) {
return System.in.readLongArray(n);
}
public static void main(String[] args) {
new CF1672D().run();
}
static class System {
private static FastInputStream in;
private static FastPrintStream out;
}
private void run() {
final boolean ONLINE_JUDGE = java.lang.System.getProperty("ONLINE_JUDGE") != null;
final boolean USE_IO = ONLINE_JUDGE;
if (USE_IO) {
System.in = new FastInputStream(java.lang.System.in);
System.out = new FastPrintStream(java.lang.System.out);
solve();
System.out.flush();
} else {
final String nameIn = "input.txt";
final String nameOut = "output.txt";
try {
System.in = new FastInputStream(new FileInputStream(nameIn));
System.out = new FastPrintStream(new PrintStream(nameOut));
solve();
System.out.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
private static class FastPrintStream {
private static final int BUF_SIZE = 8192;
private final byte[] buf = new byte[BUF_SIZE];
private final OutputStream out;
private int ptr = 0;
private FastPrintStream() {
this(java.lang.System.out);
}
public FastPrintStream(OutputStream os) {
this.out = os;
}
public FastPrintStream(String path) {
try {
this.out = new FileOutputStream(path);
} catch (FileNotFoundException e) {
throw new RuntimeException("FastWriter");
}
}
public FastPrintStream print(byte b) {
buf[ptr++] = b;
if (ptr == BUF_SIZE) innerflush();
return this;
}
public FastPrintStream print(char c) {
return print((byte) c);
}
public FastPrintStream print(char[] s) {
for (char c : s) {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
}
return this;
}
public FastPrintStream print(String s) {
s.chars().forEach(c -> {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
});
return this;
}
//can be optimized
public FastPrintStream print0(char[] s) {
if (ptr + s.length < BUF_SIZE) {
for (char c : s) {
buf[ptr++] = (byte) c;
}
} else {
for (char c : s) {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
}
}
return this;
}
//can be optimized
public FastPrintStream print0(String s) {
if (ptr + s.length() < BUF_SIZE) {
for (int i = 0; i < s.length(); i++) {
buf[ptr++] = (byte) s.charAt(i);
}
} else {
for (int i = 0; i < s.length(); i++) {
buf[ptr++] = (byte) s.charAt(i);
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 FastPrintStream print(int x) {
if (x == Integer.MIN_VALUE) {
return print((long) x);
}
if (ptr + 12 >= BUF_SIZE) innerflush();
if (x < 0) {
print((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 FastPrintStream print(long x) {
if (x == Long.MIN_VALUE) {
return print("" + x);
}
if (ptr + 21 >= BUF_SIZE) innerflush();
if (x < 0) {
print((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 FastPrintStream print(double x, int precision) {
if (x < 0) {
print('-');
x = -x;
}
x += Math.pow(10, -precision) / 2;
// if(x < 0){ x = 0; }
print((long) x).print(".");
x -= (long) x;
for (int i = 0; i < precision; i++) {
x *= 10;
print((char) ('0' + (int) x));
x -= (int) x;
}
return this;
}
public FastPrintStream println(int[] a, int from, int upTo, char separator) {
for (int i = from; i < upTo; i++) {
print(a[i]);
print(separator);
}
print('\n');
return this;
}
public FastPrintStream println(int[] a) {
return println(a, 0, a.length, ' ');
}
public FastPrintStream println(long[] a, int from, int upTo, char separator) {
for (int i = from; i < upTo; i++) {
print(a[i]);
print(separator);
}
print('\n');
return this;
}
public FastPrintStream println(long[] a) {
return println(a, 0, a.length, ' ');
}
public FastPrintStream println(char c) {
return print(c).println();
}
public FastPrintStream println(int x) {
return print(x).println();
}
public FastPrintStream println(long x) {
return print(x).println();
}
public FastPrintStream println(String x) {
return print(x).println();
}
public FastPrintStream println(double x, int precision) {
return print(x, precision).println();
}
public FastPrintStream println() {
return print((byte) '\n');
}
public FastPrintStream printf(String format, Object... args) {
return print(String.format(format, args));
}
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");
}
}
}
private static class FastInputStream {
private boolean finished = false;
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public FastInputStream(InputStream stream) {
this.stream = stream;
}
public double[] readDoubleArray(int size) {
double[] array = new double[size];
for (int i = 0; i < size; i++) {
array[i] = readDouble();
}
return array;
}
public String[] readStringArray(int size) {
String[] array = new String[size];
for (int i = 0; i < size; i++) {
array[i] = readString();
}
return array;
}
public char[] readCharArray(int size) {
char[] array = new char[size];
for (int i = 0; i < size; i++) {
array[i] = readCharacter();
}
return array;
}
public char[][] readTable(int rowCount, int columnCount) {
char[][] table = new char[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = this.readCharArray(columnCount);
}
return table;
}
public int[][] readIntTable(int rowCount, int columnCount) {
int[][] table = new int[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = readIntArray(columnCount);
}
return table;
}
public double[][] readDoubleTable(int rowCount, int columnCount) {
double[][] table = new double[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = this.readDoubleArray(columnCount);
}
return table;
}
public long[][] readLongTable(int rowCount, int columnCount) {
long[][] table = new long[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = readLongArray(columnCount);
}
return table;
}
public String[][] readStringTable(int rowCount, int columnCount) {
String[][] table = new String[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = this.readStringArray(columnCount);
}
return table;
}
public String readText() {
StringBuilder result = new StringBuilder();
while (true) {
int character = read();
if (character == '\r') {
continue;
}
if (character == -1) {
break;
}
result.append((char) character);
}
return result.toString();
}
public void readStringArrays(String[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++) {
arrays[j][i] = readString();
}
}
}
public long[] readLongArray(int size) {
long[] array = new long[size];
for (int i = 0; i < size; i++) {
array[i] = readLong();
}
return array;
}
public int[] readIntArray(int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = readInt();
}
return array;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int peek() {
if (numChars == -1) {
return -1;
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar];
}
public int peekNonWhitespace() {
while (isWhitespace(peek())) {
read();
}
return peek();
}
public int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r') {
buf.appendCodePoint(c);
}
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0) {
s = readLine0();
}
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines) {
return readLine();
} else {
return readLine0();
}
}
public char readCharacter() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
return (char) c;
}
public double readDouble() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, readInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, readInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean isExhausted() {
int value;
while (isSpaceChar(value = peek()) && value != -1) {
read();
}
return value == -1;
}
public String next() {
return readString();
}
public SpaceCharFilter getFilter() {
return filter;
}
public void setFilter(SpaceCharFilter filter) {
this.filter = filter;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
} | Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | c42f99f3c404e2294110e88d12a94b18 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.util.*;
import java.io.*;
public class D {
static class Scan {
private byte[] buf=new byte[1024];
private int index;
private InputStream in;
private int total;
public Scan()
{
in=System.in;
}
public int scan()throws IOException
{
if(total<0)
throw new InputMismatchException();
if(index>=total)
{
index=0;
total=in.read(buf);
if(total<=0)
return -1;
}
return buf[index++];
}
public int scanInt()throws IOException
{
int integer=0;
int n=scan();
while(isWhiteSpace(n))
n=scan();
int neg=1;
if(n=='-')
{
neg=-1;
n=scan();
}
while(!isWhiteSpace(n))
{
if(n>='0'&&n<='9')
{
integer*=10;
integer+=n-'0';
n=scan();
}
else throw new InputMismatchException();
}
return neg*integer;
}
public double scanDouble()throws IOException
{
double doub=0;
int n=scan();
while(isWhiteSpace(n))
n=scan();
int neg=1;
if(n=='-')
{
neg=-1;
n=scan();
}
while(!isWhiteSpace(n)&&n!='.')
{
if(n>='0'&&n<='9')
{
doub*=10;
doub+=n-'0';
n=scan();
}
else throw new InputMismatchException();
}
if(n=='.')
{
n=scan();
double temp=1;
while(!isWhiteSpace(n))
{
if(n>='0'&&n<='9')
{
temp/=10;
doub+=(n-'0')*temp;
n=scan();
}
else throw new InputMismatchException();
}
}
return doub*neg;
}
public String scanString()throws IOException
{
StringBuilder sb=new StringBuilder();
int n=scan();
while(isWhiteSpace(n))
n=scan();
while(!isWhiteSpace(n))
{
sb.append((char)n);
n=scan();
}
return sb.toString();
}
private boolean isWhiteSpace(int n)
{
if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1)
return true;
return false;
}
}
public static void sort(int arr[],int l,int r) { //sort(arr,0,n-1);
if(l==r) {
return;
}
int mid=(l+r)/2;
sort(arr,l,mid);
sort(arr,mid+1,r);
merge(arr,l,mid,mid+1,r);
}
public static void merge(int arr[],int l1,int r1,int l2,int r2) {
int tmp[]=new int[r2-l1+1];
int indx1=l1,indx2=l2;
//sorting the two halves using a tmp array
for(int i=0;i<tmp.length;i++) {
if(indx1>r1) {
tmp[i]=arr[indx2];
indx2++;
continue;
}
if(indx2>r2) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
if(arr[indx1]<arr[indx2]) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
tmp[i]=arr[indx2];
indx2++;
}
//Copying the elements of tmp into the main array
for(int i=0,j=l1;i<tmp.length;i++,j++) {
arr[j]=tmp[i];
}
}
public static void sort(long arr[],int l,int r) { //sort(arr,0,n-1);
if(l==r) {
return;
}
int mid=(l+r)/2;
sort(arr,l,mid);
sort(arr,mid+1,r);
merge(arr,l,mid,mid+1,r);
}
public static void merge(long arr[],int l1,int r1,int l2,int r2) {
long tmp[]=new long[r2-l1+1];
int indx1=l1,indx2=l2;
//sorting the two halves using a tmp array
for(int i=0;i<tmp.length;i++) {
if(indx1>r1) {
tmp[i]=arr[indx2];
indx2++;
continue;
}
if(indx2>r2) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
if(arr[indx1]<arr[indx2]) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
tmp[i]=arr[indx2];
indx2++;
}
//Copying the elements of tmp into the main array
for(int i=0,j=l1;i<tmp.length;i++,j++) {
arr[j]=tmp[i];
}
}
static int target[];
public static void main(String args[]) throws IOException {
Scan input=new Scan();
StringBuilder ans=new StringBuilder("");
int test=input.scanInt();
for(int tt=1;tt<=test;tt++) {
int n=input.scanInt();
// int n=5;
int arr[]=new int[n];
int brr[]=new int[n];
for(int i=0;i<n;i++) {
arr[i]=input.scanInt()-1;
// arr[i]=(int)(Math.random()*n);
}
for(int i=0;i<n;i++) {
brr[i]=input.scanInt()-1;
// brr[i]=arr[i];
}
// for(int i=0;i<n/2;i++) {
// int l=(int)(Math.random()*n);
// int r=(int)(Math.random()*n);
//
// int tmp=arr[l];
// arr[l]=arr[r];
// arr[r]=tmp;
// }
target=brr;
int[] arr_1=solve(n,arr);
int[] arr_2=solve(n,brr);
boolean is_pos=true;
for(int i=0;i<n;i++) {
// System.out.println(i+" "+arr_1[i]+" "+arr_2[i]);
if(arr_1[i]!=arr_2[i]) {
is_pos=false;
break;
}
}
if(is_pos) {
int req[]=new int[n];
int nxt=-1;
for(int i=n-1,j=n-1;i>=0 || j>=0;i--) {
// System.out.println(j+" "+i+" "+nxt);
if(i<0) {
if(req[arr[j]]>0) {
req[arr[j]]--;
}
else {
is_pos=false;
break;
}
j--;
continue;
}
if(arr[j]!=brr[i]) {
if(nxt!=brr[i]) {
if(req[arr[j]]>0) {
req[arr[j]]--;
j--;
i++;
continue;
}
is_pos=false;
break;
}
else {
req[brr[i]]++;
}
}
else {
nxt=arr[j];
j--;
}
}
for(int i=0;i<n;i++) {
// System.out.println(i+" "+req[i]);
if(req[i]!=0) {
is_pos=false;
// break;
}
}
int tog_a[]=new int[n];
int tog_b[]=new int[n];
for(int i=n-1;i>=0;i--) {
if(tog_a[arr[i]]!=0) {
continue;
}
int j=i,cnt=1;
while(j>0 && arr[j-1]==arr[i]) {
cnt++;
j--;
}
tog_a[arr[i]]=cnt;
}
for(int i=n-1;i>=0;i--) {
if(tog_b[brr[i]]!=0) {
continue;
}
int j=i,cnt=1;
while(j>0 && brr[j-1]==brr[i]) {
cnt++;
j--;
}
tog_b[brr[i]]=cnt;
}
// for(int i=0;i<n;i++) {
// System.out.println(i+" "+tog_a[i]+" "+tog_b[i]);
// }
// System.out.println();
// for(int i=0;i<n;i++) {
// if(tog_a[i]>tog_b[i]) {
// is_pos=false;
// break;
// }
// }
}
// for(int i=0;i<n;i++) {
// System.out.print(arr_1[i]+" ");
// }
// System.out.println();
// for(int i=0;i<n;i++) {
// System.out.print(arr_2[i]+" ");
// }
// System.out.println();
// boolean bf=bf(n,arr,0);
// if(is_pos!=bf) {
// System.out.println(is_pos+" "+bf);
// for(int i=0;i<n;i++) {
// System.out.print(arr[i]+" ");
// }
// System.out.println();
// for(int i=0;i<n;i++) {
// System.out.print(brr[i]+" ");
// }
// System.out.println();
// }
if(is_pos) {
ans.append("YES\n");
}
else {
ans.append("NO\n");
}
}
System.out.println(ans);
}
public static int[] solve(int n,int arr[]) {
HashMap<Integer,Integer> map=new HashMap<>();
HashMap<Integer,Integer> cnt=new HashMap<>();
for(int i=n-1;i>=0;i--) {
if(!map.containsKey(arr[i])) {
map.put(arr[i], i);
cnt.put(arr[i], 0);
}
cnt.replace(arr[i], cnt.get(arr[i])+1);
}
int brr[]=new int[n];
for(int i=0,indx=0;i<n;i++) {
if(map.get(arr[i])==i) {
int rep=cnt.get(arr[i]);
for(int j=0;j<rep;j++) {
brr[indx]=arr[i];
indx++;
}
}
}
return brr;
}
public static boolean bf(int n,int arr[],int dep) {
if(check(n,arr)) {
return true;
}
if(dep>10) {
return false;
}
for(int i=0;i<n;i++) {
for(int j=i+1;j<n;j++) {
if(arr[i]==arr[j]) {
swap(arr,i,j);
if(bf(n,arr,dep+1)) {
rev_swap(arr,i,j);
return true;
}
rev_swap(arr,i,j);
}
}
}
return false;
}
public static void swap(int arr[],int l,int r) {
int tmp=arr[l];
for(int i=l;i<r;i++) {
arr[i]=arr[i+1];
}
arr[r]=tmp;
}
public static void rev_swap(int arr[],int l,int r) {
int tmp=arr[r];
for(int i=r;i>l;i--) {
arr[i]=arr[i-1];
}
arr[l]=tmp;
}
public static boolean check(int n,int arr[]) {
for(int i=0;i<n;i++) {
if(arr[i]!=target[i]) {
return false;
}
}
return true;
}
}
| Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | e2b848689f9ac39b107bed196959033b | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.*;
import java.util.*;
public class codeforces_G20_D {
private static void solve(FastIOAdapter in, PrintWriter out) {
int n = in.nextInt();
int[] a = in.readArray(n);
int[] b = in.readArray(n);
var m = new HashMap<Integer, TreeSet<Integer>>();
for (int i = 0; i < n; i++) {
if (m.get(a[i]) == null) {
m.put(a[i], new TreeSet<>());
}
m.get(a[i]).add(i);
}
// 2 1 1 5 1 2 2
// 2 5 1 1 1 2 2
// 5 1 1 1 2 2 2
int ai = n - 1;
var used = new HashMap<Integer, Integer>();
for (int i = n - 1; i >= 0; i--) {
if (a[ai] == b[i]) {
ai--;
} else {
if (i == n - 1 || b[i] != b[i + 1]) {
if (used.getOrDefault(a[ai], 0) == 0) {
out.println("NO");
return;
} else {
used.put(a[ai], used.get(a[ai]) - 1);
ai--;
i++;
continue;
}
}
var si = m.get(b[i]).lower(ai);
if (si == null) {
out.println("NO");
return;
} else {
used.put(b[i], used.getOrDefault(b[i], 0) + 1);
}
}
}
out.println("YES");
}
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 | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 5cf4fcc156337b9679c2d54ad18c5cac | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.util.*;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
int testNum = in.nextInt();
solver.solve(testNum, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, InputReader in, PrintWriter out) {
for (int z = 0; z < testNumber; z++) {
int n = in.nextInt();
int[] a = new int[n];
int[] b = new int[n];
for (int i = 0; i <n ; i++) {
a[i] = in.nextInt();
}
for(int i = 0; i <n ;i++) {
b[i] = in.nextInt();
}
int aPoint = n-1;
int bPoint = n-1;
HashMap<Integer, Integer> credit = new HashMap<Integer, Integer>();
boolean works =true;
while (aPoint >= 0 || bPoint >= 0) {
//out.println(aPoint + " " + bPoint);
if (aPoint >= 0 && bPoint >= 0 && a[aPoint] == b[bPoint]) {
aPoint--;
bPoint--;
} else if (aPoint >= -1 && bPoint >= 0 && aPoint < n-1 && a[aPoint+1] == b[bPoint]) {
bPoint--;
if (credit.containsKey(a[aPoint+1])) {
credit.put(a[aPoint+1], credit.get(a[aPoint+1]) + 1);
} else {
credit.put(a[aPoint+1], 1);
}
} else if(aPoint >= 0 && credit.containsKey(a[aPoint])) {
credit.put(a[aPoint], credit.get(a[aPoint]) - 1);
if (credit.get(a[aPoint]) == 0) {
credit.remove(a[aPoint]);
}
aPoint--;
} else {
works = false;
break;
}
}
if (works) {
out.println("yes");
} else {
out.println("no");
}
}
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 770fb5c303c0cf1caa3421ea91b410f5 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.*;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.math.*;
/**
_ _
( _) ( _)
/ / \\ / /\_\_
/ / \\ / / | \ \
/ / \\ / / |\ \ \
/ / , \ , / / /| \ \
/ / |\_ /| / / / \ \_\
/ / |\/ _ '_| \ / / / \ \\
| / |/ 0 \0\ / | | \ \\
| |\| \_\_ / / | \ \\
| | |/ \.\ o\o) / \ | \\
\ | /\\`v-v / | | \\
| \/ /_| \\_| / | | \ \\
| | /__/_ - / ___ | | \ \\
\| [__] \_/ |_________ \ | \ ()
/ [___] ( \ \ |\ | | //
| [___] |\| \| / |/
/| [____] \ |/\ / / ||
( \ [____ / ) _\ \ \ \| | ||
\ \ [_____| / / __/ \ / / //
| \ [_____/ / / \ | \/ //
| / '----| /=\____ _/ | / //
__ / / | / ___/ _/\ \ | ||
(/-(/-\) / \ (/\/\)/ | / | /
(/\/\) / / //
_________/ / /
\____________/ (
@author NTUDragons-Reborn
*/
public class C{
public static void main(String[] args) throws Exception {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task solver = new Task();
solver.solve(in, out);
out.close();
}
// main solver
static class Task{
double eps= 0.00000001;
static final int MAXN = 100005;
static final int MOD= 1000000007;
// stores smallest prime factor for every number
static int spf[] = new int[MAXN];
static boolean[] prime;
Map<Integer,Set<Integer>> dp= new HashMap<>();
// Calculating SPF (Smallest Prime Factor) for every
// number till MAXN.
// Time Complexity : O(nloglogn)
public void sieve()
{
spf[1] = 1;
for (int i=2; i<MAXN; i++)
// marking smallest prime factor for every
// number to be itself.
spf[i] = i;
// separately marking spf for every even
// number as 2
for (int i=4; i<MAXN; i+=2)
spf[i] = 2;
for (int i=3; i*i<MAXN; i++)
{
// checking if i is prime
if (spf[i] == i)
{
// marking SPF for all numbers divisible by i
for (int j=i*i; j<MAXN; j+=i)
// marking spf[j] if it is not
// previously marked
if (spf[j]==j)
spf[j] = i;
}
}
}
void sieveOfEratosthenes(int n)
{
// Create a boolean array
// "prime[0..n]" and
// initialize all entries
// it as true. A value in
// prime[i] will finally be
// false if i is Not a
// prime, else true.
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;
}
}
}
// A O(log n) function returning primefactorization
// by dividing by smallest prime factor at every step
public Set<Integer> getFactorization(int x)
{
if(dp.containsKey(x)) return dp.get(x);
Set<Integer> ret = new HashSet<>();
while (x != 1)
{
if(spf[x]!=2) ret.add(spf[x]);
x = x / spf[x];
}
dp.put(x,ret);
return ret;
}
public Map<Integer,Integer> getFactorizationPower(int x){
Map<Integer,Integer> map= new HashMap<>();
while(x!=1){
map.put(spf[x], map.getOrDefault(spf[x], 0)+1);
x/= spf[x];
}
return map;
}
// function to find first index >= x
public int lowerIndex(List<Integer> arr, int n, int x)
{
int l = 0, h = n - 1;
while (l <= h)
{
int mid = (l + h) / 2;
if (arr.get(mid) >= x)
h = mid - 1;
else
l = mid + 1;
}
return l;
}
public int lowerIndex(int[] arr, int n, int x)
{
int l = 0, h = n - 1;
while (l <= h)
{
int mid = (l + h) / 2;
if (arr[mid] >= x)
h = mid - 1;
else
l = mid + 1;
}
return l;
}
// function to find last index <= y
public int upperIndex(List<Integer> arr, int n, int y)
{
int l = 0, h = n - 1;
while (l <= h)
{
int mid = (l + h) / 2;
if (arr.get(mid) <= y)
l = mid + 1;
else
h = mid - 1;
}
return h;
}
public int upperIndex(int[] arr, int n, int y)
{
int l = 0, h = n - 1;
while (l <= h)
{
int mid = (l + h) / 2;
if (arr[mid] <= y)
l = mid + 1;
else
h = mid - 1;
}
return h;
}
// function to count elements within given range
public int countInRange(List<Integer> arr, int n, int x, int y)
{
// initialize result
int count = 0;
count = upperIndex(arr, n, y) -
lowerIndex(arr, n, x) + 1;
return count;
}
public int add(int a, int b){
a+=b;
while(a>=MOD) a-=MOD;
while(a<0) a+=MOD;
return a;
}
public int mul(int a, int b){
long res= (long)a*(long)b;
return (int)(res%MOD);
}
public int power(int a, int b) {
int ans=1;
while(b>0){
if((b&1)!=0) ans= mul(ans,a);
b>>=1;
a= mul(a,a);
}
return ans;
}
int[] fact= new int[MAXN];
int[] inv= new int[MAXN];
public int Ckn(int n, int k){
if(k<0 || n<0) return 0;
if(n<k) return 0;
return mul(mul(fact[n],inv[k]),inv[n-k]);
}
public int inverse(int a){
return power(a,MOD-2);
}
public void preprocess() {
fact[0]=1;
for(int i=1;i<MAXN;i++) fact[i]= mul(fact[i-1],i);
inv[MAXN-1]= inverse(fact[MAXN-1]);
for(int i=MAXN-2;i>=0;i--){
inv[i]= mul(inv[i+1],i+1);
}
}
/**
* return VALUE of lower bound for unsorted array
*/
public int lowerBoundNormalArray(int[] arr, int x){
TreeSet<Integer> set= new TreeSet<>();
for(int num: arr) set.add(num);
return set.lower(x);
}
/**
* return VALUE of upper bound for unsorted array
*/
public int upperBoundNormalArray(int[] arr, int x){
TreeSet<Integer> set= new TreeSet<>();
for(int num: arr) set.add(num);
return set.higher(x);
}
public void debugArr(int[] arr){
for(int i: arr) out.print(i+" ");
out.println();
}
public int rand(){
int min=0, max= MAXN;
int random_int = (int)Math.floor(Math.random()*(max-min+1)+min);
return random_int;
}
public void suffleSort(int[] arr){
shuffleArray(arr);
Arrays.sort(arr);
}
public void shuffleArray(int[] ar)
{
// If running on Java 6 or older, use new Random() on RHS here
Random rnd = ThreadLocalRandom.current();
for (int i = ar.length - 1; i > 0; i--)
{
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
InputReader in; PrintWriter out;
Scanner sc= new Scanner(System.in);
CustomFileReader cin;
int[] xor= new int[3*100000+5];
int[] pow2= new int[1000000+1];
public void solve(InputReader in, PrintWriter out) throws Exception {
this.in=in; this.out=out;
// sieve();
// pow2[0]=1;
// for(int i=1;i<pow2.length;i++){
// pow2[i]= mul(pow2[i-1],2);
// }
int t=in.nextInt();
// preprocess();
// int t=in.nextInt();
// int t= cin.nextIntArrLine()[0];
for(int i=1;i<=t;i++) solveD(i);
}
final double pi= Math.acos(-1);
void solveD(int test){
int n= in.nextInt();
int[] a= in.nextIntArr(n);
int[] b= in.nextIntArr(n);
if(a[n-1]!=b[n-1]){out.println("NO"); return;}
int[] cnt= new int[n+1];
int ia=n-1, ib= n-1;
while(ia>=0 && ib>=0){
while(ib-1>=0 && b[ib]==b[ib-1]) cnt[b[ib--]]++;
if(a[ia]==b[ib]){
ia--;ib--;
}
else{
if(cnt[a[ia]]<=0) {out.println("NO"); return;}
cnt[a[ia]]--;
ia--;
}
}
out.println("YES");
}
static class ListNode{
int idx=-1;
ListNode next= null;
public ListNode(int idx){
this.idx= idx;
}
}
public long _gcd(long a, long b)
{
if(b == 0) {
return a;
}
else {
return _gcd(b, a % b);
}
}
public long _lcm(long a, long b){
return (a*b)/_gcd(a,b);
}
}
// static class SEG {
// Pair[] segtree;
// public SEG(int n){
// segtree= new Pair[4*n];
// Arrays.fill(segtree, new Pair(-1,Long.MAX_VALUE));
// }
// // void buildTree(int l, int r, int index) {
// // if (l == r) {
// // segtree[index].y = a[l];
// // return;
// // }
// // int mid = (l + r) / 2;
// // buildTree(l, mid, 2 * index + 1);
// // buildTree(mid + 1, r, 2 * index + 2);
// // segtree[index].y = Math.min(segtree[2 * index + 1].y, segtree[2 * index + 2].y);
// // }
// void update(int l, int r, int index, int pos, Pair val) {
// if (l == r) {
// segtree[index] = val;
// return;
// }
// int mid = (l + r) / 2;
// if (pos <= mid) update(l, mid, 2 * index + 1, pos, val);
// else update(mid + 1, r, 2 * index + 2, pos, val);
// if(segtree[2 * index + 1].y < segtree[2 * index + 2].y){
// segtree[index]= segtree[2 * index + 1];
// }
// else {
// segtree[index]= segtree[2 * index + 2];
// }
// }
// // Pair query(int l, int r, int from, int to, int index) {
// // if (from <= l && r <= to)
// // return segtree[index];
// // if (r < from | to < l)
// // return 0;
// // int mid = (l + r) / 2;
// // Pair left= query(l, mid, from, to, 2 * index + 1);
// // Pair right= query(mid + 1, r, from, to, 2 * index + 2);
// // if(left.y < right.y) return left;
// // else return right;
// // }
// }
static class Venice{
public Map<Long,Long> m= new HashMap<>();
public long base=0;
public long totalValue=0;
private int M= 1000000007;
private long addMod(long a, long b){
a+=b;
if(a>=M) a-=M;
return a;
}
public void reset(){
m= new HashMap<>();
base=0;
totalValue=0;
}
public void update(long add){
base= base+ add;
}
public void add(long key, long val){
long newKey= key-base;
m.put(newKey, addMod(m.getOrDefault(newKey,(long)0),val));
}
}
static class Tuple implements Comparable<Tuple>{
int x, y, z;
public Tuple(int x, int y, int z){
this.x= x;
this.y= y;
this.z=z;
}
@Override
public int compareTo(Tuple o){
return this.z-o.z;
}
}
static class Point implements Comparable<Point>{
public double x;
public long y;
public Point(double x, long y){
this.x= x;
this.y= y;
}
@Override
public int compareTo(Point o) {
if(this.y!=o.y) return (int)(this.y-o.y);
return (int)(this.x-o.x);
}
}
// static class Vector {
// public long x;
// public long y;
// // p1 -> p2
// public Vector(Point p1, Point p2){
// this.x= p2.x-p1.x;
// this.y= p2.y-p1.y;
// }
// }
static class Pair implements Comparable<Pair>{
public int x;
public int y;
public Pair(int x, int y){
this.x= x;
this.y= y;
}
@Override
public int compareTo(Pair o) {
if(this.x!=o.x) return (int)(this.x-o.x);
return (int)(this.y-o.y);
}
}
// public static class compareL implements Comparator<Tuple>{
// @Override
// public int compare(Tuple t1, Tuple t2) {
// return t2.l - t1.l;
// }
// }
// fast input reader class;
static class InputReader {
BufferedReader br;
StringTokenizer st;
public InputReader(InputStream stream) {
br = new BufferedReader(new InputStreamReader(stream));
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
String line = null;
try {
line = br.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
if (line == null) {
return null;
}
st = new StringTokenizer(line);
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public double nextDouble(){
return Double.parseDouble(nextToken());
}
public long nextLong(){
return Long.parseLong(nextToken());
}
public int[] nextIntArr(int n){
int[] arr= new int[n];
for(int i=0;i<n;i++) arr[i]= nextInt();
return arr;
}
public long[] nextLongArr(int n){
long[] arr= new long[n];
for(int i=0;i<n;i++) arr[i]= nextLong();
return arr;
}
public List<Integer> nextIntList(int n){
List<Integer> arr= new ArrayList<>();
for(int i=0;i<n;i++) arr.add(nextInt());
return arr;
}
public int[][] nextIntMatArr(int n, int m){
int[][] mat= new int[n][m];
for(int i=0;i<n;i++) for(int j=0;j<m;j++) mat[i][j]= nextInt();
return mat;
}
public List<List<Integer>> nextIntMatList(int n, int m){
List<List<Integer>> mat= new ArrayList<>();
for(int i=0;i<n;i++){
List<Integer> temp= new ArrayList<>();
for(int j=0;j<m;j++) temp.add(nextInt());
mat.add(temp);
}
return mat;
}
public char[] nextStringCharArr(){
return nextToken().toCharArray();
}
}
static class CustomFileReader{
String path="";
Scanner sc;
public CustomFileReader(String path){
this.path=path;
try{
sc= new Scanner(new File(path));
}
catch(Exception e){}
}
public String nextLine(){
return sc.nextLine();
}
public int[] nextIntArrLine(){
String line= sc.nextLine();
String[] part= line.split("[\\s+]");
int[] res= new int[part.length];
for(int i=0;i<res.length;i++) res[i]= Integer.parseInt(part[i]);
return res;
}
}
} | Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 49bbb2f22abe78bcc7b5dd3f9604c94a | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | /*----------- ---------------*
Author : Ryan Ranaut
__Hope is a big word, never lose it__
------------- --------------*/
import java.io.*;
import java.util.*;
public class Codeforces1 {
static PrintWriter out = new PrintWriter(System.out);
static final int mod = 1_000_000_007;
static long min = (long) (-1e16);
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
//Minimization Maximization - BS..... Connections - Graphs.....
//Greedy not worthy - Try DP
//Think edge cases
public static void main(String[] args)
{
FastReader s = new FastReader();
int t = s.nextInt();
while(t-->0)
{
int n = s.nextInt();
int[] a = s.readIntArray(n);
int[] b = s.readIntArray(n);
out.println(find(n, a, b));
}
out.close();
}
public static String find(int n, int[] a, int[] b)
{
if(a[n-1]!=b[n-1])
return "NO";
int i=n-2, j=n-2;
int[] hmp = new int[n+1];
while(i>=0 && j>=0)
{
if(a[i] == b[j]) {
i--;
j--;
}
else
{
if(b[j] == b[j+1])//Can be brought from front
{
hmp[b[j]]++;
j--;
}
else//This guy was used by someone before
{
if(hmp[a[i]] == 0)
return "NO";
hmp[a[i]]--;
i--;
}
}
}
return "YES";
}
/*----------------------------------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;
}
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;
}
}
} | Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 156e6c6f715315f8ff73a213aa59f702 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.*;
import java.util.*;
public class D {
private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
private static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
public static void main(String[] args) throws IOException {
int t = Integer.parseInt(br.readLine());
while (t-- > 0) {
int n = Integer.parseInt(br.readLine());
String s[] = br.readLine().split(" ");
int a[] = new int[n];
TreeMap<Integer, Integer> f = new TreeMap<>();
for (int i = 0; i < n; i++) {
a[i] = Integer.parseInt(s[i]);
if (f.containsKey(a[i])) {
f.put(a[i], f.get(a[i]) + 1);
} else {
f.put(a[i], 1);
}
}
s = br.readLine().split(" ");
int b[] = new int[n];
for (int i = 0; i < n; i++) {
b[i] = Integer.parseInt(s[i]);
}
TreeMap<Integer, Integer> map = new TreeMap<>();
boolean ans = true;
int ai = 0, bi = 0;
int match = 0;
while (ai < n && bi < n) {
if (a[ai] == b[bi]) {
match++;
f.put(a[ai], f.get(a[ai]) - 1);
ai++;
bi++;
continue;
}
if (map.containsKey(b[bi]) && (map.get(b[bi]) > 0)) {
if (a[ai - 1] == b[bi]) {
match++;
map.put(b[bi], map.get(b[bi]) - 1);
bi++;
continue;
}
}
if (f.get(a[ai]) > 1) {
if (map.containsKey(a[ai])) {
map.put(a[ai], map.get(a[ai]) + 1);
} else {
map.put(a[ai], 1);
}
f.put(a[ai], f.get(a[ai]) - 1);
ai++;
continue;
}
ans = false;
break;
}
if (!ans) {
bw.write("NO\n");
continue;
}
for (; bi < n; bi++) {
if (map.containsKey(b[bi]) && (map.get(b[bi]) > 0)) {
if (a[ai - 1] == b[bi]) {
match++;
map.put(b[bi], map.get(b[bi]) - 1);
} else {
ans = false;
break;
}
} else {
ans = false;
break;
}
}
if (match != n) {
ans = false;
}
if (ans) {
bw.write("YES\n");
} else {
bw.write("NO\n");
}
}
bw.flush();
}
}
| Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 489b3e1f861ea0ae790a559284c8fc24 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.util.*;
import java.io.*;
import java.text.*;
public class CF_1672_D{
//SOLUTION BEGIN
void pre() throws Exception{}
void solve(int TC) throws Exception{
int N = ni();
int[] A = new int[N], B = new int[N];
for(int i = 0; i< N; i++)A[i] = ni();
for(int i = 0; i< N; i++)B[i] = ni();
TreeMap<Integer, Integer> f = new TreeMap<>();
int p = N-1;
int prev = -1;
for(int i = N-1; i>= 0; i--){
while (p >= 0 && B[p] == prev){
f.put(B[p], f.getOrDefault(B[p], 0)+1);
p--;
}
if(p >= 0 && A[i] == B[p]){
prev = A[i];
p--;
}else{
if(f.getOrDefault(A[i], 0) > 0){
prev = A[i];
f.put(A[i], f.get(A[i])-1);
}else {
pn("NO");
return;
}
}
}
int sum = 0;
for(int v:f.values())sum += v;
pn(sum == 0 && p == -1?"YES":"NO");
}
//SOLUTION END
void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");}
void exit(boolean b){if(!b)System.exit(0);}
static void dbg(Object... o){System.err.println(Arrays.deepToString(o));}
DecimalFormat df = new DecimalFormat("0.00000000000");
double PI = 3.141592653589793238462643383279502884197169399;
static boolean multipleTC = true, memory = true, fileIO = false;
FastReader in;PrintWriter out;
void run() throws Exception{
long ct = System.currentTimeMillis();
if (fileIO) {
in = new FastReader("");
out = new PrintWriter("");
} else {
in = new FastReader();
out = new PrintWriter(System.out);
}
//Solution Credits: Taranpreet Singh
int T = multipleTC? ni():1;
pre();
for (int t = 1; t <= T; t++) solve(t);
out.flush();
out.close();
System.err.println("Runtime: "+(System.currentTimeMillis() - ct));
}
public static void main(String[] args) throws Exception{
if(memory)new Thread(null, new Runnable() {public void run(){try{new CF_1672_D().run();}catch(Exception e){e.printStackTrace();System.exit(1);}}}, "1", 1 << 28).start();
else new CF_1672_D().run();
}
int[][] make(int n, int e, int[] from, int[] to, boolean f){
int[][] g = new int[n][];int[]cnt = new int[n];
for(int i = 0; i< e; i++){
cnt[from[i]]++;
if(f)cnt[to[i]]++;
}
for(int i = 0; i< n; i++)g[i] = new int[cnt[i]];
for(int i = 0; i< e; i++){
g[from[i]][--cnt[from[i]]] = to[i];
if(f)g[to[i]][--cnt[to[i]]] = from[i];
}
return g;
}
int[][][] makeS(int n, int e, int[] from, int[] to, boolean f){
int[][][] g = new int[n][][];int[]cnt = new int[n];
for(int i = 0; i< e; i++){
cnt[from[i]]++;
if(f)cnt[to[i]]++;
}
for(int i = 0; i< n; i++)g[i] = new int[cnt[i]][];
for(int i = 0; i< e; i++){
g[from[i]][--cnt[from[i]]] = new int[]{to[i], i, 0};
if(f)g[to[i]][--cnt[to[i]]] = new int[]{from[i], i, 1};
}
return g;
}
int find(int[] set, int u){return set[u] = (set[u] == u?u:find(set, set[u]));}
int digit(long s){int ans = 0;while(s>0){s/=10;ans++;}return ans;}
long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);}
int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);}
int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));}
void p(Object... o){for(Object oo:o)out.print(oo+" ");}
void pn(Object... o){for(int i = 0; i< o.length; i++)out.print(o[i]+(i+1 < o.length?" ":"\n"));}
void pni(Object... o){for(Object oo:o)out.print(oo+" ");out.println();out.flush();}
String n()throws Exception{return in.next();}
String nln()throws Exception{return in.nextLine();}
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());}
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 | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 1a4896f7ba4b1af22f230af83edf804b | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
boolean solve(int n, int[] a, int[] b) {
Map<Integer, Integer> skipsAllowed = new HashMap<>();
int i = n-2;
int j = n-2;
int lastI = 0;
while (j >= 0) {
if (a[i] == b[j]) {
lastI = a[i];
i--;
j--;
continue;
}
if (lastI != b[j]) {
while (a[i] != b[j]) {
int sa = skipsAllowed.getOrDefault(a[i], 0);
if (sa > 0) {
skipsAllowed.put(a[i], sa - 1);
i--;
} else {
return false;
}
}
lastI = a[i];
} else {
int sb = skipsAllowed.getOrDefault(b[j], 0);
skipsAllowed.put(b[j], sb + 1);
j--;
}
}
return true;
}
Object readInputAndSolve(Scanner in) {
int n = in.nextInt();
int[] a = new int[n+1];
int[] b = new int[n+1];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
a[n] = 0;
for (int i = 0; i < n; i++) {
b[i] = in.nextInt();
}
b[n] = 0;
return solve(n+1, a, b) ? "YES" : "NO";
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int nTests = in.nextInt();
for (int iTest = 0; iTest < nTests; iTest++) {
Object result = new Main().readInputAndSolve(in);
if (result != null) {
System.out.println(result);
}
}
}
} | Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 14578278b6246f57f74f4691610a3575 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
FastReader sc = new FastReader();
int t = sc.nextInt();
for(int w = 0; w < t; w++){
int n = sc.nextInt();
int[] a = sc.intArray(n);
int[] b = sc.intArray(n);
int[] arr = new int[n+1];
Stack<Integer> s = new Stack();
Arrays.stream(a).forEach(s::push);
boolean ans = true;
for(int i = n-1; i >=0 ;i--){
if(b[i] == s.peek()){
s.pop();
}else{
if(i == n-1){
ans = false;
break;
}
if(b[i] == b[i+1]){
arr[b[i]]--;
}else{
if(arr[s.peek()] < 0){
arr[s.peek()] ++;
s.pop();
i++;
}else{
ans= false;
break;
}
}
}
}
s.forEach(i -> arr[i]++);
for(int i= 0; i < arr.length; i++){
if(arr[i] != 0){
ans = false;
break;
}
}
System.out.println(ans ? "YES" : "NO");
}
}
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;
}
int[] intArray(int n){
int[] arr = new int[n];
for(int i =0; i < n; i ++){
arr[i] = nextInt();
}
return arr;
}
}
} | Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 5916c8929e1f616761e0bec812b9e909 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
FastReader sc = new FastReader();
int t = sc.nextInt();
for(int w = 0; w < t; w++){
int n = sc.nextInt();
int[] a = sc.intArray(n);
int[] b = sc.intArray(n);
int[] arr = new int[n+1];
Stack<Integer> s = new Stack();
for(int i =0; i < n; i++){
arr[a[i]]++;
arr[b[i]]--;
s.push(a[i]);
}
boolean ans = true;
for(int i = n-1; i >=0 ;i--){
//System.out.println("s.peek() = " + s.peek());
if(b[i] == s.peek()){
s.pop();
}else{
if(i == n-1){
ans = false;
break;
}
if(b[i] == b[i+1]){
arr[b[i]]--;
//System.out.println("arr[b[i]] = " + arr[b[i]]);
}else{
if(arr[s.peek()] < 0){
arr[s.peek()] ++;
s.pop();
i++;
}else{
ans= false;
break;
}
}
}
}
//System.out.println(s.size());
while(!s.empty()){
//System.out.println(arr[s.peek()]);
arr[s.pop()]++;
}
for(int i= 0; i < arr.length; i++){
if(arr[i] != 0){
ans = false;
break;
}
}
System.out.println(ans ? "YES" : "NO");
}
}
private static int max(int a, int b){
return Math.max(a, b);
}
private static int min(int a, int b){
return Math.min(a, 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() { 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[] intArray(int n){
int[] arr = new int[n];
for(int i =0; i < n; i ++){
arr[i] = nextInt();
}
return arr;
}
}
} | Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 9cab90a033262feae9eac896dac6c527 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 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());
}
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 = 300005;
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 int index1 = 1;
static int index2 = 1;
static int count = 1;
static int n;
static List<Integer> ans;
static HashMap<Pair,Integer> hm;
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();
int a[] = new int[n];
int b[] = new int[n];
for(int i=0;i<n;i++){
a[i] = scan.nextInt();
}
for(int i=0;i<n;i++){
b[i] = scan.nextInt();
}
HashMap<Integer,Integer> hm = new HashMap<>();
int i=n-1;
int j=n-1;
int flag = 1;
while(i>=0 && j>=0){
while(j>0 && b[j]==b[j-1]){
if(!hm.containsKey(b[j])){
hm.put(b[j],1);
}
else{
hm.put(b[j],hm.get(b[j])+1);
}
j--;
}
if(a[i]==b[j]){
i--;
j--;
}
else{
if(hm.containsKey(a[i])){
int value = hm.get(a[i])-1;
if(value==0){
hm.remove(a[i]);
}
else
hm.put(a[i],value);
i--;
}
else{
flag = 0;
break;
}
}
}
if(flag==0){
pw.println("NO");
}
else{
pw.println("YES");
}
pw.flush();
}
}
static boolean check(String str){
int len = str.length();
int flag = 0;
for(int i=0;i<len;i++){
if(str.charAt(i)!='0' && str.charAt(i)!='1'){
flag = 1;
}
}
if(flag==0)
return false;
return true;
}
//static long bin_exp_mod(long a,long n){
// long res = 1;
// while(n!=0){
// if(n%2==1){
// res = ((res)*(a));
// }
// n = n/2;
// a = ((a)*(a));
// }
// return res;
//}
//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 Pair{
int x,y;
Pair(int x,int y){
this.x = x;
this.y = 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){
if(p1.x==p2.x)
return 0;
else if(p1.x<p2.x)
return -1;
else
return 1;
}
}
//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 | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 41b7a2d0acbd9aebd1aea15bbccad084 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.BufferedReader;
import java.io.*;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.*;
public class Yoo
{
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args)
{
FastReader sc=new FastReader();
int t = sc.nextInt();
while(t-->0)
{
int n = sc.nextInt();
int a[]=new int[n];
int b[]=new int[n];
for(int i=0;i<n;i++)
a[i]=sc.nextInt();
for(int i=0;i<n;i++)
b[i]=sc.nextInt();
Map<Integer, Integer> skipsAllowed = new HashMap<>();
int i = n-1;
int j = n-1;
int lastI = 0;
boolean f =true;
while (j >= 0) {
if (a[i] == b[j]) {
lastI = a[i];
i--;
j--;
continue;
}
if (lastI != b[j]) {
while (a[i] != b[j]) {
int sa = skipsAllowed.getOrDefault(a[i], 0);
if (sa > 0) {
skipsAllowed.put(a[i], sa - 1);
i--;
} else {
f = false;
break;
}
}
if(f==false)
break;
lastI = a[i];
} else {
int sb = skipsAllowed.getOrDefault(b[j], 0);
skipsAllowed.put(b[j], sb + 1);
j--;
}
}
if(f==true)
System.out.println("Yes");
else
System.out.println("No");
}
}
}
| Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | c4ce62b001dc14bbcad08acbae87e7db | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.util.*;
public class D {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
// TODO Auto-generated method stub
int testCases = sc.nextInt();
for (int i = 1; i <= testCases; ++i) {
solve(i);
}
}
private static void solve(int t) {
int n = sc.nextInt();
int [] arr1 = new int [n];
int [] arr2 = new int [n];
for (int i = 0; i < n; ++i)
arr1[i] = sc.nextInt();
for (int i = 0; i < n; ++i)
arr2[i] = sc.nextInt();
//Map<Integer, Integer> lastIndex = new HashMap<>();
Map<Integer, Integer> currentLeft = new HashMap<>();
//for (int i = 0; i < n; ++i) {
//lastIndex.put(arr1[i], i);
//}
int idx = 0;
int nextVal;
int num;
for (int i = 0; i < arr2.length; ++i) {
num = arr2[i];
//System.out.println(idx + " " + num + " " + i);
if (idx == arr1.length) {
System.out.println("NO");
return;
}
if (arr1[idx] == num) {
if (currentLeft.containsKey(num)) {
nextVal = currentLeft.get(num) - 1;
if (nextVal == 0)
currentLeft.remove(num);
else
currentLeft.put(num, nextVal);
}else {
//System.out.println("Here");
++idx;
}
}else {
currentLeft.put(arr1[idx], currentLeft.getOrDefault(arr1[idx], 0) + 1);
++idx;
--i;
}
}
System.out.println("YES");
}
public static void print(int test, long result) {
System.out.println("Case #" + test + ": " + result);
}
}
| Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 8eb7d80d6d1649c786cff5b368a692fa | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author lucasr
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
MyScanner in = new MyScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
DCyclicRotation solver = new DCyclicRotation();
int testCount = Integer.parseInt(in.next());
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
static class DCyclicRotation {
public static MyScanner sc;
public static PrintWriter out;
public void solve(int testNumber, MyScanner sc, PrintWriter out) {
DCyclicRotation.sc = sc;
DCyclicRotation.out = out;
int n = sc.nextInt();
int[] a = read(n);
int[] b = read(n);
boolean can = can(n, a, b);
out.println(can ? "YES" : "NO");
}
static boolean can(int n, int[] a, int[] b) {
IntArray[] pos = new IntArray[n];
for (int i = 0; i < n; i++) {
if (pos[a[i]] == null) pos[a[i]] = new IntArray();
pos[a[i]].add(i);
}
boolean[] used = new boolean[n];
int aIdx = n - 1;
boolean can = true;
for (int i = n - 1; i >= 0 && can; i--) {
if (i + 1 < n && b[i] == b[i + 1]) {
int me = pos[b[i]].last();
used[me] = true;
pos[b[i]].removeLast();
} else {
while (aIdx >= 0 && a[aIdx] != b[i]) {
if (used[aIdx]) aIdx--;
else break;
}
if (aIdx >= 0 && a[aIdx] == b[i]) {
int me = pos[b[i]].last();
used[me] = true;
pos[b[i]].removeLast();
aIdx--;
} else can = false;
}
}
return can;
}
public int[] read(int n) {
int[] ret = sc.nextIntArray(n);
for (int i = 0; i < n; i++) {
ret[i]--;
}
return ret;
}
}
static class MyScanner {
private BufferedReader br;
private StringTokenizer tokenizer;
public MyScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public int[] nextIntArray(int n) {
int[] ret = new int[n];
for (int i = 0; i < n; i++) {
ret[i] = nextInt();
}
return ret;
}
}
static class IntArray {
int[] arr;
int size;
public IntArray() {
arr = new int[4];
}
public void add(int val) {
if (size == arr.length) {
arr = Arrays.copyOf(arr, 2 * arr.length);
}
arr[size++] = val;
}
public int last() {
return arr[size - 1];
}
public void removeLast() {
size--;
}
public int[] toArray() {
return Arrays.copyOf(arr, size);
}
public String toString() {
return "IntArray " + Arrays.toString(toArray());
}
}
}
| Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 6f1f45d8631ebc5625219f2bf4ab50be | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.BufferedReader;
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.time.Clock;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.function.Supplier;
public class Solution {
private void solve() throws IOException {
int n = nextInt();
int[] a = nextIntArray(n);
int[] b = nextIntArray(n);
for (int i = 0; i < n; i++) {
a[i]--;
b[i]--;
}
if (a[n - 1] != b[n - 1]) {
out.println("NO");
return;
}
int[] c = new int[n];
for (int i = n - 2, j = n - 2; i >= 0; i--) {
while (j >= 0 && b[j] == b[j + 1]) {
c[b[j]]++;
j--;
}
if (j >= 0 && a[i] == b[j]) {
j--;
} else if (c[a[i]] > 0) {
c[a[i]]--;
} else {
out.println("NO");
return;
}
}
out.println("YES");
}
private static final boolean runNTestsInProd = true;
private static final boolean printCaseNumber = false;
private static final boolean assertInProd = false;
private static final boolean logToFile = false;
private static final boolean readFromConsoleInDebug = false;
private static final boolean writeToConsoleInDebug = true;
private static final boolean testTimer = false;
private static Boolean isDebug = null;
private BufferedReader in;
private StringTokenizer line;
private PrintWriter out;
public static void main(String[] args) throws Exception {
isDebug = Arrays.asList(args).contains("DEBUG_MODE");
if (isDebug) {
log = logToFile ? new PrintWriter("logs/j_solution_" + System.currentTimeMillis() + ".log") : new PrintWriter(System.out);
clock = Clock.systemDefaultZone();
}
new Solution().run();
}
private void run() throws Exception {
in = new BufferedReader(new InputStreamReader(!isDebug || readFromConsoleInDebug ? System.in : new FileInputStream("input.txt")));
out = !isDebug || writeToConsoleInDebug ? new PrintWriter(System.out) : new PrintWriter("output.txt");
try (Timer totalTimer = new Timer("total")) {
int t = runNTestsInProd || isDebug ? nextInt() : 1;
for (int i = 0; i < t; i++) {
if (printCaseNumber) {
out.print("Case #" + (i + 1) + ": ");
}
if (testTimer) {
try (Timer testTimer = new Timer("test #" + (i + 1))) {
solve();
}
} else {
solve();
}
if (isDebug) {
out.flush();
}
}
}
in.close();
out.flush();
out.close();
}
private void println(Object... objects) {
boolean isFirst = true;
for (Object o : objects) {
if (!isFirst) {
out.print(" ");
} else {
isFirst = false;
}
out.print(o.toString());
}
out.println();
}
private int[] nextIntArray(int n) throws IOException {
int[] res = new int[n];
for (int i = 0; i < n; i++) {
res[i] = nextInt();
}
return res;
}
private long[] nextLongArray(int n) throws IOException {
long[] res = new long[n];
for (int i = 0; i < n; i++) {
res[i] = nextLong();
}
return res;
}
private int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
private long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
private double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
private char[] nextTokenChars() throws IOException {
return nextToken().toCharArray();
}
private String nextToken() throws IOException {
while (line == null || !line.hasMoreTokens()) {
line = new StringTokenizer(in.readLine());
}
return line.nextToken();
}
private static void assertPredicate(boolean p) {
if ((isDebug || assertInProd) && !p) {
throw new RuntimeException();
}
}
private static void assertPredicate(boolean p, String message) {
if ((isDebug || assertInProd) && !p) {
throw new RuntimeException(message);
}
}
private static <T> void assertNotEqual(T unexpected, T actual) {
if ((isDebug || assertInProd) && Objects.equals(actual, unexpected)) {
throw new RuntimeException("assertNotEqual: " + unexpected + " == " + actual);
}
}
private static <T> void assertEqual(T expected, T actual) {
if ((isDebug || assertInProd) && !Objects.equals(actual, expected)) {
throw new RuntimeException("assertEqual: " + expected + " != " + actual);
}
}
private static PrintWriter log = null;
private static Clock clock = null;
private static void log(Object... objects) {
log(true, objects);
}
private static void logNoDelimiter(Object... objects) {
log(false, objects);
}
private static void log(boolean printDelimiter, Object[] objects) {
if (isDebug) {
StringBuilder sb = new StringBuilder();
sb.append(LocalDateTime.now(clock)).append(" - ");
boolean isFirst = true;
for (Object o : objects) {
if (!isFirst && printDelimiter) {
sb.append(" ");
} else {
isFirst = false;
}
sb.append(o.toString());
}
log.println(sb);
log.flush();
}
}
private static class Timer implements Closeable {
private final String label;
private final long startTime = isDebug ? System.nanoTime() : 0;
public Timer(String label) {
this.label = label;
}
@Override
public void close() throws IOException {
if (isDebug) {
long executionTime = System.nanoTime() - startTime;
String fraction = Long.toString(executionTime / 1000 % 1_000_000);
logNoDelimiter("Timer[", label, "]: ", executionTime / 1_000_000_000, '.', "00000".substring(0, 6 - fraction.length()), fraction, 's');
}
}
}
private static <T> T timer(String label, Supplier<T> f) throws Exception {
if (isDebug) {
try (Timer timer = new Timer(label)) {
return f.get();
}
} else {
return f.get();
}
}
}
| Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | c820d2f2c93a050fb83f494c82877259 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.BufferedReader;
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.time.Clock;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.function.Supplier;
public class Solution {
private void solve() throws IOException {
int n = nextInt();
int[] a = nextIntArray(n);
int[] b = nextIntArray(n);
for (int i = 0; i < n; i++) {
a[i]--;
b[i]--;
}
int[] c = new int[n];
for (int i = n - 1, j = n - 1; i >= 0; i--) {
while (j > 0 && b[j] == b[j - 1]) {
c[b[j]]++;
j--;
}
if (j >= 0 && a[i] == b[j]) {
j--;
} else if (c[a[i]] > 0) {
c[a[i]]--;
} else {
out.println("NO");
return;
}
}
out.println("YES");
}
private static final boolean runNTestsInProd = true;
private static final boolean printCaseNumber = false;
private static final boolean assertInProd = false;
private static final boolean logToFile = false;
private static final boolean readFromConsoleInDebug = false;
private static final boolean writeToConsoleInDebug = true;
private static final boolean testTimer = false;
private static Boolean isDebug = null;
private BufferedReader in;
private StringTokenizer line;
private PrintWriter out;
public static void main(String[] args) throws Exception {
isDebug = Arrays.asList(args).contains("DEBUG_MODE");
if (isDebug) {
log = logToFile ? new PrintWriter("logs/j_solution_" + System.currentTimeMillis() + ".log") : new PrintWriter(System.out);
clock = Clock.systemDefaultZone();
}
new Solution().run();
}
private void run() throws Exception {
in = new BufferedReader(new InputStreamReader(!isDebug || readFromConsoleInDebug ? System.in : new FileInputStream("input.txt")));
out = !isDebug || writeToConsoleInDebug ? new PrintWriter(System.out) : new PrintWriter("output.txt");
try (Timer totalTimer = new Timer("total")) {
int t = runNTestsInProd || isDebug ? nextInt() : 1;
for (int i = 0; i < t; i++) {
if (printCaseNumber) {
out.print("Case #" + (i + 1) + ": ");
}
if (testTimer) {
try (Timer testTimer = new Timer("test #" + (i + 1))) {
solve();
}
} else {
solve();
}
if (isDebug) {
out.flush();
}
}
}
in.close();
out.flush();
out.close();
}
private void println(Object... objects) {
boolean isFirst = true;
for (Object o : objects) {
if (!isFirst) {
out.print(" ");
} else {
isFirst = false;
}
out.print(o.toString());
}
out.println();
}
private int[] nextIntArray(int n) throws IOException {
int[] res = new int[n];
for (int i = 0; i < n; i++) {
res[i] = nextInt();
}
return res;
}
private long[] nextLongArray(int n) throws IOException {
long[] res = new long[n];
for (int i = 0; i < n; i++) {
res[i] = nextLong();
}
return res;
}
private int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
private long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
private double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
private char[] nextTokenChars() throws IOException {
return nextToken().toCharArray();
}
private String nextToken() throws IOException {
while (line == null || !line.hasMoreTokens()) {
line = new StringTokenizer(in.readLine());
}
return line.nextToken();
}
private static void assertPredicate(boolean p) {
if ((isDebug || assertInProd) && !p) {
throw new RuntimeException();
}
}
private static void assertPredicate(boolean p, String message) {
if ((isDebug || assertInProd) && !p) {
throw new RuntimeException(message);
}
}
private static <T> void assertNotEqual(T unexpected, T actual) {
if ((isDebug || assertInProd) && Objects.equals(actual, unexpected)) {
throw new RuntimeException("assertNotEqual: " + unexpected + " == " + actual);
}
}
private static <T> void assertEqual(T expected, T actual) {
if ((isDebug || assertInProd) && !Objects.equals(actual, expected)) {
throw new RuntimeException("assertEqual: " + expected + " != " + actual);
}
}
private static PrintWriter log = null;
private static Clock clock = null;
private static void log(Object... objects) {
log(true, objects);
}
private static void logNoDelimiter(Object... objects) {
log(false, objects);
}
private static void log(boolean printDelimiter, Object[] objects) {
if (isDebug) {
StringBuilder sb = new StringBuilder();
sb.append(LocalDateTime.now(clock)).append(" - ");
boolean isFirst = true;
for (Object o : objects) {
if (!isFirst && printDelimiter) {
sb.append(" ");
} else {
isFirst = false;
}
sb.append(o.toString());
}
log.println(sb);
log.flush();
}
}
private static class Timer implements Closeable {
private final String label;
private final long startTime = isDebug ? System.nanoTime() : 0;
public Timer(String label) {
this.label = label;
}
@Override
public void close() throws IOException {
if (isDebug) {
long executionTime = System.nanoTime() - startTime;
String fraction = Long.toString(executionTime / 1000 % 1_000_000);
logNoDelimiter("Timer[", label, "]: ", executionTime / 1_000_000_000, '.', "00000".substring(0, 6 - fraction.length()), fraction, 's');
}
}
}
private static <T> T timer(String label, Supplier<T> f) throws Exception {
if (isDebug) {
try (Timer timer = new Timer(label)) {
return f.get();
}
} else {
return f.get();
}
}
}
| Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 13514ca52cea7568817af3615294d385 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.math.BigInteger;
import java.io.*;
public class Main implements Runnable {
public static void main(String[] args) {
new Thread(null, new Main(), "whatever", 1 << 26).start();
}
private FastScanner sc;
private PrintWriter pw;
public void run() {
try {
boolean isSumitting = true;
// isSumitting = false;
if (isSumitting) {
pw = new PrintWriter(System.out);
sc = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
} else {
pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
sc = new FastScanner(new BufferedReader(new FileReader("input.txt")));
}
} catch (Exception e) {
throw new RuntimeException();
}
int t = sc.nextInt();
// int t = 1;
while (t-- > 0) {
// sc.nextLine();
// System.out.println("for t=" + t);
solve();
}
pw.close();
}
public long mod = 1_000_000_007;
private class Pair {
int first;
long second;
Pair(int first, long second) {
this.first = first;
this.second = second;
}
}
private int max = 2 * 1_00_000 + 1;
private void solve() {
int n = sc.nextInt();
int[] arr = sc.nextIntArray(n);
int[] target = sc.nextIntArray(n);
HashMap<Integer, Integer> memo = new HashMap<Integer, Integer>();
for (int i = n - 1, j = n - 1; i >= 0 && j >= 0; i--) {
if (arr[i] == target[j]) {
j--;
while (j >= 0) {
if (target[j] == arr[i]) {
memo.put(arr[i], memo.getOrDefault(arr[i], 0) + 1);
j--;
} else break;
}
if (j == -1) {
pw.println("YES");
return;
}
} else {
if (memo.containsKey(arr[i])) {
memo.put(arr[i], memo.get(arr[i]) - 1);
if (memo.get(arr[i]) == 0) {
memo.remove(arr[i]);
}
} else {
pw.println("NO");
return;
}
}
}
}
class FastScanner {
private BufferedReader reader = null;
private StringTokenizer tokenizer = null;
public FastScanner(BufferedReader bf) {
reader = bf;
tokenizer = null;
}
public String next() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public String nextLine() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken("\n");
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public float nextFloat() {
return Float.parseFloat(next());
}
public int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public String[] nextStringArray(int n) {
String[] a = new String[n];
for (int i = 0; i < n; i++) {
a[i] = next();
}
return a;
}
public long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = nextLong();
}
return a;
}
}
private static class Sorter {
public static <T extends Comparable<? super T>> void sort(T[] arr) {
Arrays.sort(arr);
}
public static <T> void sort(T[] arr, Comparator<T> c) {
Arrays.sort(arr, c);
}
public static <T> void sort(T[][] arr, Comparator<T[]> c) {
Arrays.sort(arr, c);
}
public static <T extends Comparable<? super T>> void sort(ArrayList<T> arr) {
Collections.sort(arr);
}
public static <T> void sort(ArrayList<T> arr, Comparator<T> c) {
Collections.sort(arr, c);
}
public static void normalSort(int[] arr) {
Arrays.sort(arr);
}
public static void normalSort(long[] arr) {
Arrays.sort(arr);
}
public static void sort(int[] arr) {
timSort(arr);
}
public static void sort(int[] arr, Comparator<Integer> c) {
timSort(arr, c);
}
public static void sort(int[][] arr, Comparator<Integer[]> c) {
timSort(arr, c);
}
public static void sort(long[] arr) {
timSort(arr);
}
public static void sort(long[] arr, Comparator<Long> c) {
timSort(arr, c);
}
public static void sort(long[][] arr, Comparator<Long[]> c) {
timSort(arr, c);
}
private static void timSort(int[] arr) {
Integer[] temp = new Integer[arr.length];
for (int i = 0; i < arr.length; i++) temp[i] = arr[i];
Arrays.sort(temp);
for (int i = 0; i < arr.length; i++) arr[i] = temp[i];
}
private static void timSort(int[] arr, Comparator<Integer> c) {
Integer[] temp = new Integer[arr.length];
for (int i = 0; i < arr.length; i++) temp[i] = arr[i];
Arrays.sort(temp, c);
for (int i = 0; i < arr.length; i++) arr[i] = temp[i];
}
private static void timSort(int[][] arr, Comparator<Integer[]> c) {
Integer[][] temp = new Integer[arr.length][arr[0].length];
for (int i = 0; i < arr.length; i++)
for (int j = 0; j < arr[0].length; j++)
temp[i][j] = arr[i][j];
Arrays.sort(temp, c);
for (int i = 0; i < arr.length; i++)
for (int j = 0; j < arr[0].length; j++)
temp[i][j] = arr[i][j];
}
private static void timSort(long[] arr) {
Long[] temp = new Long[arr.length];
for (int i = 0; i < arr.length; i++) temp[i] = arr[i];
Arrays.sort(temp);
for (int i = 0; i < arr.length; i++) arr[i] = temp[i];
}
private static void timSort(long[] arr, Comparator<Long> c) {
Long[] temp = new Long[arr.length];
for (int i = 0; i < arr.length; i++) temp[i] = arr[i];
Arrays.sort(temp, c);
for (int i = 0; i < arr.length; i++) arr[i] = temp[i];
}
private static void timSort(long[][] arr, Comparator<Long[]> c) {
Long[][] temp = new Long[arr.length][arr[0].length];
for (int i = 0; i < arr.length; i++)
for (int j = 0; j < arr[0].length; j++)
temp[i][j] = arr[i][j];
Arrays.sort(temp, c);
for (int i = 0; i < arr.length; i++)
for (int j = 0; j < arr[0].length; j++)
temp[i][j] = arr[i][j];
}
}
public long fastPow(long x, long y, long mod) {
if (y == 0) return 1;
if (y == 1) return x % mod;
long temp = fastPow(x, y / 2, mod);
long ans = (temp * temp) % mod;
return (y % 2 == 1) ? (ans * (x % mod)) % mod : ans;
}
public long fastPow(long x, long y) {
if (y == 0) return 1;
if (y == 1) return x;
long temp = fastPow(x, y / 2);
long ans = (temp * temp);
return (y % 2 == 1) ? (ans * x) : ans;
}
}
| Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 2425ba1b6eeb0f56bad7d90eb4188e1d | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeSet;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.*;
import java.text.*;
public class Main {
static class Task {
int MOD = 998244353;
int INF = 2000000000;
long INFINITY = (1L<<63)-1;
class Tuple {
Integer [] ara;
Integer x, y, z, t, w;
public Tuple(Integer... a) {
this.ara = a;
if(ara.length > 0) this.x = ara[0];
if(ara.length > 1) this.y = ara[1];
if(ara.length > 2) this.z = ara[2];
if(ara.length > 3) this.t = ara[3];
if(ara.length > 4) this.w = ara[4];
}
}
static final int NN = 32769;
public void solve(InputReader in, PrintWriter out) throws Exception {
int t = in.nextInt();
while(t-->0) {
int n= in.nextInt();
int []a = new int[n];
int []b = new int[n];
for(int i=0;i<n;++i)a[i]=in.nextInt();
for(int i=0;i<n;++i)b[i]=in.nextInt();
Map<Integer, Integer> mp = new HashMap<>();
int i = a.length - 1;
int j = b.length - 1;
boolean yes = true;
while(i>=0||j>=0) {
while(j>0&&b[j]==b[j-1]) {
int c = 0;
if(mp.containsKey(b[j]))c=mp.get(b[j]);
++c;
mp.put(b[j], c);
--j;
}
if(j>=0&&a[i]==b[j]) {
--i;--j;
}else {
if(!mp.containsKey(a[i])) {
yes = false;break;
}
int c = mp.get(a[i]);
--c;
if(c>0) {
mp.put(a[i], c);
}else {
mp.remove(a[i]);
}
--i;
}
}
out.println(yes?"YES":"NO");
}
}
}
static void prepareIO(boolean isFileIO) throws Exception {
//long t1 = System.currentTimeMillis();
Task solver = new Task();
// Standard IO
if(!isFileIO) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
solver.solve(in, out);
//out.println("time(s): " + (1.0*(System.currentTimeMillis()-t1))/1000.0);
out.close();
}
// File IO
else {
String IPfilePath = System.getProperty("user.home") + "/Downloads/ip.in";
String OPfilePath = System.getProperty("user.home") + "/Downloads/op.out";
InputReader fin = new InputReader(IPfilePath);
PrintWriter fout = null;
try {
fout = new PrintWriter(new File(OPfilePath));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
solver.solve(fin, fout);
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss yyyy-MM-dd");
Date date = new Date();
fout.println("\n\ntime(s): " + dateFormat.format(date));
fout.close();
}
}
public static void main(String[] args) throws Exception {
prepareIO(false/*args[0].equals("true")*/);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public InputReader(String filePath) {
File file = new File(filePath);
try {
reader = new BufferedReader(new FileReader(file));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tokenizer = null;
}
public String nextLine() {
String str = "";
try {
str = reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}
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());
}
}
} | Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | b4fbd2e3e34588e5e04c857cef71b50d | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.lang.*;
import java.io.*;
import java.util.*;
public class codeforces {
static int max = Integer.MAX_VALUE, min = Integer.MIN_VALUE;
long maxl = Long.MAX_VALUE, minl = Long.MIN_VALUE;
static PrintWriter pw = new PrintWriter(System.out);
static StringBuilder sb = new StringBuilder();
static int parent[] = new int[100001];
static int mod = 1000000007;
static boolean b1 = true;
public static void main(String[] args) throws IOException {
FastScanner sc = new FastScanner();
int ttt = sc.nextInt();
for (int tt = 1; tt <= ttt; tt++) {
int n = sc.nextInt();
int ar[] = new int[n];
for (int i = 0; i < n; i++)
ar[i] = sc.nextInt();
int br[] = new int[n];
for (int i = 0; i < n; i++)
br[i] = sc.nextInt();
b1 = true;
int count[] = new int[n + 1];
int j = n - 1, i = n - 1;
while (i >= 0 && j >= 0) {
if (ar[i] == br[j]) {
i--;
j--;
continue;
}
if (j + 1 < n && br[j] == br[j + 1]) {
count[br[j]]++;
j--;
continue;
}
if (count[ar[i]] == 0) {
System.out.println("No");
b1 = false;
break;
}
count[ar[i]]--;
i--;
}
if (b1)
System.out.println("Yes");
}
}
public static boolean checkPalindrome(int n) {
int v = 0;
int n1 = n;
while (n > 0) {
v = v * 10 + n % 10;
n = n / 10;
}
if (n1 == v)
return true;
else
return false;
}
public static int lis(int arr[], int n) {
int lis[] = new int[n];
int i, j, max = 0;
/* Initialize LIS values for all indexes */
for (i = 0; i < n; i++)
lis[i] = 1;
/*
* Compute optimized LIS values in
* bottom up manner
*/
for (i = 1; i < n; i++)
for (j = 0; j < i; j++)
if (arr[i] > arr[j] && lis[i] < lis[j] + 1)
lis[i] = lis[j] + 1;
/* Pick maximum of all LIS values */
for (i = 0; i < n; i++)
if (max < lis[i])
max = lis[i];
return max;
}
public static int binarySearch(int arr[], int x) {
int l = 0, r = arr.length - 1;
int result1 = -1;
while (l <= r) {
int mid = l + (r - l) / 2;
if (arr[mid] == x) {
return mid;
} else if (arr[mid] > x) {
r = mid - 1;
} else {
l = mid + 1;
}
}
return result1;
}
public static class Pair {
public int x;
public int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
public static long gcd(long a, long b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
public 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 | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 9c2d3c601bc67b31ed03d3479d0369ce | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.math.BigInteger;
import static java.lang.System.out;
import static java.lang.Math.*;
import java.util.*;
public class Main {
static public void main(String[] args){
Read in = new Read(System.in);
int t = in.nextInt();
while(t>0){
t--;
solve(in);
}
}
static void solve(Read in){
int n = in.nextInt();
int[] s1 = new int[n];
int[] s2 = new int[n];
for(int i=0;i<n;i++){
s1[i]=in.nextInt();
}
for(int i=0;i<n;i++){
s2[i]=in.nextInt();
}
int[] cot = new int [n+1];
int id = 0;
for(int i=0;i<n;){
if(s1[i]==s2[id]){
id++;
}else{
cot[s1[i]]++;
i++;
continue;
}
cot[s1[i]]--;
if(cot[s1[i]]<0){
cot[s1[i]]=0;
i++;
}
}
if(id==n)
out.println("YES");
else
out.println("NO");
}
static class Read {//自定义快读 Read
public BufferedReader reader;
public StringTokenizer tokenizer;
public Read(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public String nextLine() {
String str = null;
try {
str = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public Double nextDouble() {
return Double.parseDouble(next());
}
public BigInteger nextBigInteger() {
return new BigInteger(next());
}
}
static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
static long gcd(long a, long b) {
return (a % b == 0) ? b : gcd(b, a % b);
}
}
| Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 040ba65fc91c159dcbd0b9221e19475f | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.*;
import java.util.*;
public class D {
public static void main (String[] args) throws IOException {
Kattio io = new Kattio();
int t = io.nextInt();
outer: for (int ii=0; ii<t; ii++) {
int n = io.nextInt();
int[] a = new int[n];
int[] b = new int[n];
for (int i=0; i<n; i++) {
a[i] = io.nextInt();
}
for (int i=0; i<n; i++) {
b[i] = io.nextInt();
}
HashMap<Integer, Integer> map = new HashMap<>();
int lo = 0;
int hi = 0;
while (hi < n) {
//System.out.println(lo + " " + hi);
if (lo < n && a[lo] == b[hi]) {
lo++;
hi++;
} else if (lo > 0 && b[hi] == a[lo-1] && map.getOrDefault(a[lo - 1], 0) >= 1) {
map.put(a[lo - 1], map.get(a[lo - 1]) - 1);
hi++;
} else if (lo < n) {
map.put(a[lo], map.getOrDefault(a[lo], 0) + 1);
lo++;
} else {
System.out.println("NO");
continue outer;
}
}
System.out.println("YES");
}
}
static class Kattio extends PrintWriter {
private BufferedReader r;
private StringTokenizer st;
// standard input
public Kattio() { this(System.in, System.out); }
public Kattio(InputStream i, OutputStream o) {
super(o);
r = new BufferedReader(new InputStreamReader(i));
}
// USACO-style file input
public Kattio(String problemName) throws IOException {
super(new FileWriter(problemName + ".out"));
r = new BufferedReader(new FileReader(problemName + ".in"));
}
// returns null if no more input
public String next() {
try {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(r.readLine());
return st.nextToken();
} catch (Exception e) { }
return null;
}
public int nextInt() { return Integer.parseInt(next()); }
public double nextDouble() { return Double.parseDouble(next()); }
public long nextLong() { return Long.parseLong(next()); }
}
} | Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 4d33531803a97e2ffd57dd30ff489fba | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | // package com.dpz.main;
import java.io.*;
import java.util.*;
public class UWI {
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 char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = ni();
return a;
}
private long[] nal(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nl();
return a;
}
private char[][] nm(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++) map[i] = ns(m);
return map;
}
private int[][] nmi(int n, int m) {
int[][] map = new int[n][];
for (int i = 0; i < n; i++) map[i] = na(m);
return map;
}
private int ni() {
return (int) nl();
}
private long nl() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
public static class FastWriter {
private static final int BUF_SIZE = 1 << 13;
private final byte[] buf = new byte[BUF_SIZE];
private final OutputStream out;
private int ptr = 0;
private FastWriter() {
out = null;
}
public FastWriter(OutputStream os) {
this.out = os;
}
public FastWriter(String path) {
try {
this.out = new FileOutputStream(path);
} catch (FileNotFoundException e) {
throw new RuntimeException("FastWriter");
}
}
public FastWriter write(byte b) {
buf[ptr++] = b;
if (ptr == BUF_SIZE) innerflush();
return this;
}
public FastWriter write(char c) {
return write((byte) c);
}
public FastWriter write(char[] s) {
for (char c : s) {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
}
return this;
}
public FastWriter write(String s) {
s.chars().forEach(c -> {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
});
return this;
}
private static int countDigits(int l) {
if (l >= 1000000000) return 10;
if (l >= 100000000) return 9;
if (l >= 10000000) return 8;
if (l >= 1000000) return 7;
if (l >= 100000) return 6;
if (l >= 10000) return 5;
if (l >= 1000) return 4;
if (l >= 100) return 3;
if (l >= 10) return 2;
return 1;
}
public FastWriter write(int x) {
if (x == Integer.MIN_VALUE) {
return write((long) x);
}
if (ptr + 12 >= BUF_SIZE) innerflush();
if (x < 0) {
write((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
private static int countDigits(long l) {
if (l >= 1000000000000000000L) return 19;
if (l >= 100000000000000000L) return 18;
if (l >= 10000000000000000L) return 17;
if (l >= 1000000000000000L) return 16;
if (l >= 100000000000000L) return 15;
if (l >= 10000000000000L) return 14;
if (l >= 1000000000000L) return 13;
if (l >= 100000000000L) return 12;
if (l >= 10000000000L) return 11;
if (l >= 1000000000L) return 10;
if (l >= 100000000L) return 9;
if (l >= 10000000L) return 8;
if (l >= 1000000L) return 7;
if (l >= 100000L) return 6;
if (l >= 10000L) return 5;
if (l >= 1000L) return 4;
if (l >= 100L) return 3;
if (l >= 10L) return 2;
return 1;
}
public FastWriter write(long x) {
if (x == Long.MIN_VALUE) {
return write("" + x);
}
if (ptr + 21 >= BUF_SIZE) innerflush();
if (x < 0) {
write((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
public FastWriter write(double x, int precision) {
if (x < 0) {
write('-');
x = -x;
}
x += Math.pow(10, -precision) / 2;
// if(x < 0){ x = 0; }
write((long) x).write(".");
x -= (long) x;
for (int i = 0; i < precision; i++) {
x *= 10;
write((char) ('0' + (int) x));
x -= (int) x;
}
return this;
}
public FastWriter writeln(char c) {
return write(c).writeln();
}
public FastWriter writeln(int x) {
return write(x).writeln();
}
public FastWriter writeln(long x) {
return write(x).writeln();
}
public FastWriter writeln(double x, int precision) {
return write(x, precision).writeln();
}
public FastWriter write(int... xs) {
boolean first = true;
for (int x : xs) {
if (!first) write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter write(long... xs) {
boolean first = true;
for (long x : xs) {
if (!first) write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter writeln() {
return write((byte) '\n');
}
public FastWriter writeln(int... xs) {
return write(xs).writeln();
}
public FastWriter writeln(long... xs) {
return write(xs).writeln();
}
public FastWriter writeln(char[] line) {
return write(line).writeln();
}
public FastWriter writeln(char[]... map) {
for (char[] line : map) write(line).writeln();
return this;
}
public FastWriter writeln(String s) {
return write(s).writeln();
}
private void innerflush() {
try {
out.write(buf, 0, ptr);
ptr = 0;
} catch (IOException e) {
throw new RuntimeException("innerflush");
}
}
public void flush() {
innerflush();
try {
out.flush();
} catch (IOException e) {
throw new RuntimeException("flush");
}
}
public FastWriter print(byte b) {
return write(b);
}
public FastWriter print(char c) {
return write(c);
}
public FastWriter print(char[] s) {
return write(s);
}
public FastWriter print(String s) {
return write(s);
}
public FastWriter print(int x) {
return write(x);
}
public FastWriter print(long x) {
return write(x);
}
public FastWriter print(double x, int precision) {
return write(x, precision);
}
public FastWriter println(char c) {
return writeln(c);
}
public FastWriter println(int x) {
return writeln(x);
}
public FastWriter println(long x) {
return writeln(x);
}
public FastWriter println(double x, int precision) {
return writeln(x, precision);
}
public FastWriter print(int... xs) {
return write(xs);
}
public FastWriter print(long... xs) {
return write(xs);
}
public FastWriter println(int... xs) {
return writeln(xs);
}
public FastWriter println(long... xs) {
return writeln(xs);
}
public FastWriter println(char[] line) {
return writeln(line);
}
public FastWriter println(char[]... map) {
return writeln(map);
}
public FastWriter println(String s) {
return writeln(s);
}
public FastWriter println() {
return writeln();
}
}
//打印非零?
public void trnz(int... o) {
for (int i = 0; i < o.length; i++) if (o[i] != 0) System.out.print(i + ":" + o[i] + " ");
System.out.println();
}
// print ids which are 1
public void trt(long... o) {
Queue<Integer> stands = new ArrayDeque<>();
for (int i = 0; i < o.length; i++) {
for (long x = o[i]; x != 0; x &= x - 1) stands.add(i << 6 | Long.numberOfTrailingZeros(x));
}
System.out.println(stands);
}
public void tf(boolean... r) {
for (boolean x : r) System.out.print(x ? '#' : '.');
System.out.println();
}
public void tf(boolean[]... b) {
for (boolean[] r : b) {
for (boolean x : r) System.out.print(x ? '#' : '.');
System.out.println();
}
System.out.println();
}
public void tf(long[]... b) {
if (INPUT.length() != 0) {
for (long[] r : b) {
for (long x : r) {
for (int i = 0; i < 64; i++) {
System.out.print(x << ~i < 0 ? '#' : '.');
}
}
System.out.println();
}
System.out.println();
}
}
public void tf(long... b) {
if (INPUT.length() != 0) {
for (long x : b) {
for (int i = 0; i < 64; i++) {
System.out.print(x << ~i < 0 ? '#' : '.');
}
}
System.out.println();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null || ojFlag;
private void tr(Object... o) {
if (!oj) System.out.println(Arrays.deepToString(o));
}
void run() throws Exception {
//add INPUT from local file todo
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");
}
public static void main(String[] args) throws Exception {
new UWI().run();
}
int mod = (int) 1e9 + 7;
long INF = Long.MAX_VALUE / 3;
static boolean ojFlag = false;
void solve() {
for (int T = ni(); T > 0; T--) go();
}
void go() {
int n = ni();
int[] a = na(n), b = na(n);
int[] count = new int[n];
Arrays.fill(count, 1);
List<Deque<Integer>> nextPos = new ArrayList<>();
for (int i = 0; i <= n; i++) {
nextPos.add(new ArrayDeque<>());
}
for (int i = 0; i < n; i++) {
nextPos.get(a[i]).addLast(i);
}
int i = 0, j = 0;
for (; i < n; ) {
Deque<Integer> deque = nextPos.get(a[i]);
if(!deque.isEmpty()&&deque.peekFirst()==i)deque.pollFirst();
if (a[i] == b[j]) {
count[i]--;
if (count[i] == 0) i++;
j++;
} else {
//把a[i]放到下一个和a[i]相同的位置
if (deque.isEmpty()) {
out.println("NO");
return;
}
int next = deque.peekFirst();
count[next] += count[i];
i++;
}
}
out.println("Yes");
}
}
| Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 06499cda45b512d7fe75d1697e5b3efc | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.Arrays;
import java.util.Random;
import java.io.FileWriter;
import java.io.PrintWriter;
/*
Solution Created: 23:09:44 23/04/2022
Custom Competitive programming helper.
*/
public class Main {
public static void solve() {
int n = in.nextInt();
int[] a = in.na(n), b = in.na(n);
boolean can = a[n-1] == b[n-1];
int[] f = new int[n+1];
outer:
for(int i = n-2, j = n-2; i>=0; i--) {
while(j>=0) {
if(a[i]==b[j]) {
j--;
continue outer;
}
if(b[j]==b[j+1]) {
f[b[j]]++;
j--;
}else break;
}
if(f[a[i]]==0) {
can = false;
break;
}
f[a[i]]--;
}
out.yesNo(can);
}
public static void main(String[] args) {
in = new Reader();
out = new Writer();
int t = in.nextInt();
while(t-->0) solve();
out.exit();
}
static Reader in; static Writer out;
static class Reader {
static BufferedReader br;
static StringTokenizer st;
public Reader() {
this.br = new BufferedReader(new InputStreamReader(System.in));
}
public Reader(String f){
try {
this.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();
static long[] fact;
public static void initFactorial(int n, long mod) {
fact = new long[n+1];
fact[0] = 1;
for (int i = 1; i < n+1; i++) fact[i] = (fact[i - 1] * i) % mod;
}
public static long modInverse(long a, long MOD) {
long[] gcdE = gcdExtended(a, MOD);
if (gcdE[0] != 1) return -1; // Inverted 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, long MOD) {
if (r == 0) return 1;
return (fact[n] * modInverse(fact[r], MOD) % MOD * modInverse(fact[n - r], MOD) % MOD) % MOD;
}
public static long nCr(int n, int r) {
return (fact[n]/fact[r])/fact[n-r];
}
public static long nPr(int n, int r, long MOD) {
if (r == 0) return 1;
return (fact[n] * modInverse(fact[n - r], MOD) % MOD) % MOD;
}
public static long nPr(int n, int r) {
return fact[n]/fact[n-r];
}
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 | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 42633b2b19fcca79308b60f9c512f4e2 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | /* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Codechef
{
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 boolean check(int arr[] , int x)
{
for(int i = 0 ; i < arr.length ; i++)
{
if(Math.abs(x+i-arr[i]) > 1)
return false;
}
return true;
}
public static void main(String []args) throws IOException
{
Reader sc = new Reader();
int t = sc.nextInt();
while(t-- > 0)
{
int n = sc.nextInt();
int a[] = new int[n];
int b[] = new int[n];
int cnt[] = new int[n+1];
for(int i = 0 ; i < n ; i++)
{
a[i] = sc.nextInt();
cnt[a[i]]++;
}
for(int i = 0 ; i < n ; i++)
{
b[i] = sc.nextInt();
}
int pos = 0;
boolean bl = true;
for(int i = 0 ; i < n ; i++)
{
if(cnt[a[i]] > 1)
continue;
while(pos < n && cnt[b[pos]] > 1)
{
pos++;
}
if(pos == n || a[i] != b[pos])
{
bl = false;
break;
}
pos++;
}
if(!bl)
System.out.println("NO");
else
{
int pos1 = 0 , pos2 = 0;
int extra[] = new int[n+1];
bl = true;
while(pos2 < n)
{
if(pos1 == n)
{
if(a[pos1-1] != b[pos2])
{
bl = false;
break;
}
for(int i = pos2 ; i < n ; i++)
{
if(b[i] != b[pos2])
{
bl = false;
break;
}
extra[b[i]]--;
if(extra[b[i]] < 0)
{
bl = false;
break;
}
}
break;
}
else
{
if(cnt[b[pos2]] == 1 && cnt[a[pos1]] == 1)
{
pos2++;
pos1++;
}
else if(cnt[b[pos2]] == 1 && cnt[a[pos1]] > 1)
{
extra[a[pos1]]++;
pos1++;
}
else if(cnt[b[pos2]] > 1 && cnt[a[pos1]] == 1)
{
bl = false;
break;
}
else
{
if(a[pos1] == b[pos2])
{
int tot = 0;
int pp = pos2;
while(pp+1 < n && b[pp] == b[pp+1])
{
pp++;
}
int x = a[pos1];
while(pos1 < n && pp-pos2+1 > extra[x])
{
if(cnt[a[pos1]] == 1)
{
bl = false;
break;
}
extra[a[pos1]]++;
pos1++;
}
if(!bl)
break;
if(extra[x] < pp-pos2+1)
{
bl = false;
break;
}
extra[x] -= (pp-pos2+1);
pos2 = pp+1;
}
else
{
extra[a[pos1]]++;
pos1++;
}
}
}
}
for(int i = 1 ; i <= n ; i++)
{
if(extra[i] > 0)
bl = false;
}
if(bl)
System.out.println("YES");
else
System.out.println("NO");
}
}
}
} | Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 3d15a17f5997c5a70d896238effd1afe | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 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 i,a[]=new int[n],b,c[]=new int[n+1];
String s[]=bu.readLine().split(" ");
TreeSet<Integer> ts[]=new TreeSet[n+1],tm=new TreeSet<>();
for(i=0;i<=n;i++) ts[i]=new TreeSet<>();
for(i=0;i<n;i++)
{
a[i]=Integer.parseInt(s[i]);
c[i]++;
ts[a[i]].add(i);
tm.add(i);
}
s=bu.readLine().split(" ");
boolean ans=true;
for(i=0;i<n && ans;i++)
{
b=Integer.parseInt(s[i]);
int cur=tm.higher(-1),low=ts[b].higher(-1),val=a[cur];
while(val!=b)
{
//low is smallest index of b next to this
if(ts[val].higher(low)==null) break; //no larger value possible for val
int small=ts[val].higher(low); //smallest value larger than in_b
c[cur]--; c[small]++;
if(c[cur]==0)
{
tm.remove(cur);
ts[val].remove(cur);
}
cur=tm.higher(-1); val=a[cur];
}
//System.out.println(val+" "+cur+" "+tm);
if(val!=b) {ans=false; continue;}
c[cur]--;
if(c[cur]==0)
{
tm.remove(cur);
ts[val].remove(cur);
}
}
if(ans) sb.append("YES\n");
else sb.append("NO\n");
}
System.out.print(sb);
}
} | Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 63f4cdda52e6dd291dca4a50c6b15dec | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.util.*;
import java.util.Map.Entry;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.math.*;
import java.sql.Array;
public class Simple{
static final Random random=new Random();
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br=new BufferedReader(new InputStreamReader(System.in));
}
String next(){
while(st==null || !st.hasMoreTokens()){
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt(){
return Integer.parseInt(next());
}
long nextLong(){
return Long.parseLong(next());
}
double nextDouble(){
return Double.parseDouble(next());
}
String nextLine(){
String str="";
try {
str=br.readLine().trim();
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
}
static class FastWriter {
private final BufferedWriter bw;
public FastWriter() {
this.bw = new BufferedWriter(new OutputStreamWriter(System.out));
}
public void print(Object object) throws IOException {
bw.append("" + object);
}
public void println(Object object) throws IOException {
print(object);
bw.append("\n");
}
public void close() throws IOException {
bw.close();
}
}
static void ruffleSort(int[] a) {
int n=a.length;
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static void ruffleSort(long[] a) {
int n=a.length;
for (int i=0; i<n; i++) {
long oi=random.nextInt(n), temp=a[(int)oi];
a[(int)oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
public static class Pair implements Comparable<Pair>{
int x;
int y;
public Pair(int x,int y){
this.x = x;
this.y = y;
}
public int compareTo(Pair other){
return (int) (this.y - other.y);
}
public boolean equals(Pair other){
if(this.x == other.x && this.y == other.y)return true;
return false;
}
public int hashCode(){
return 31*x + y;
}
// @Override
// public int compareTo(Simple.Pair o) {
// // TODO Auto-generated method stub
// return 0;
// }
}
static int power(int x, int y, int p)
{
// Initialize result
int res = 1;
// Update x if it is more than or
// equal to p
x = x % p;
while (y > 0) {
// If y is odd, multiply x
// with result
if (y % 2 == 1)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
// Returns n^(-1) mod p
static int modInverse(int n, int p)
{
return power(n, p - 2, p);
}
// Returns nCr % p using Fermat's
// little theorem.
static int nCrModPFermat(int n, int r,
int p)
{
if (n<r)
return 0;
// Base case
if (r == 0)
return 1;
// Fill factorial array so that we
// can find all factorial of r, n
// and n-r
int[] fac = new int[n + 1];
fac[0] = 1;
for (int i = 1; i <= n; i++)
fac[i] = fac[i - 1] * i % p;
return (fac[n] * modInverse(fac[r], p)
% p * modInverse(fac[n - r], p)
% p)
% p;
}
static int nCrModp(int n, int r, int p)
{
if (r > n - r)
r = n - r;
// The array C is going to store last
// row of pascal triangle at the end.
// And last entry of last row is nCr
int C[] = new int[r + 1];
C[0] = 1; // Top row of Pascal Triangle
// One by constructs remaining rows of Pascal
// Triangle from top to bottom
for (int i = 1; i <= n; i++) {
// Fill entries of current row using previous
// row values
for (int j = Math.min(i, r); j > 0; j--)
// nCj = (n-1)Cj + (n-1)C(j-1);
C[j] = (C[j] + C[j - 1]) % p;
}
return C[r];
}
static int gcd(int a, int b)
{
// Everything divides 0
if (a == 0)
return b;
if (b == 0)
return a;
// base case
if (a == b)
return a;
// a is greater
if (a > b)
return gcd(a-b, b);
return gcd(a, b-a);
}
public static class Node{
int root;
ArrayList<Node> al;
Node par;
public Node(int root,ArrayList<Node> al,Node par){
this.root = root;
this.al = al;
this.par = par;
}
}
// public static int helper(int arr[],int n ,int i,int j,int dp[][]){
// if(i==0 || j==0)return 0;
// if(dp[i][j]!=-1){
// return dp[i][j];
// }
// if(helper(arr, n, i-1, j-1, dp)>=0){
// return dp[i][j]=Math.max(helper(arr, n, i-1, j-1,dp)+arr[i-1], helper(arr, n, i-1, j,dp));
// }
// return dp[i][j] = helper(arr, n, i-1, j,dp);
// }
// public static void dfs(ArrayList<ArrayList<Integer>> al,int levelcount[],int node,int count){
// levelcount[count]++;
// for(Integer x : al.get(node)){
// dfs(al, levelcount, x, count+1);
// }
// }
public static long __gcd(long a, long b)
{
if (b == 0)
return a;
return __gcd(b, a % b);
}
public static class DSU{
int n;
int par[];
int rank[];
public DSU(int n){
this.n = n;
par = new int[n+1];
rank = new int[n+1];
for(int i=1;i<=n;i++){
par[i] = i ;
rank[i] = 0;
}
}
public int findPar(int node){
if(node==par[node]){
return node;
}
return par[node] = findPar(par[node]);//path compression
}
public void union(int u,int v){
u = findPar(u);
v = findPar(v);
if(rank[u]<rank[v]){
par[u] = v;
}
else if(rank[u]>rank[v]){
par[v] = u;
}
else{
par[v] = u;
rank[u]++;
}
}
}
public static int helper(int arr[],int k,int n,int i,int dp[]){
if(i>k)return 1;
if(arr[i]==-1){
return dp[i] = helper(arr, k, n, 2*i, dp) + helper(arr, k, n, 2*i+1, dp);
}
else if(arr[i]==0){
return dp[i] = helper(arr, k, n, 2*i, dp);
}
else{
return dp[i] = helper(arr, k, n, 2*i+1, dp);
}
}
public static void main(String args[]){
try {
FastReader s=new FastReader();
FastWriter out = new FastWriter();
// int testCases=s.nextInt();
int testCases = s.nextInt();
while(testCases-- > 0){
int n = s.nextInt();
int a[]= new int[n];
int b[]= new int[n];
Map<Integer,Integer> map = new HashMap<>();
for(int i=0;i<n;i++){
a[i] = s.nextInt();
map.put(a[i],0);
}
for(int i=0;i<n;i++){
b[i] = s.nextInt();
}
int i =0;
int j=0 ;
int carry = 0;
boolean bool = true;
while( j<n){
// System.out.println(i+" "+j);
// System.out.println(map.toString());
if(i<n &&a[i]==b[j] ){
i++;
j++;
// System.out.println("HE");
}
else{
if(j!=0&&b[j]==b[j-1] && map.get(b[j])>0){
map.put(b[j],map.get(b[j])-1);
carry--;
j++;
}
else if(i!=n){
map.put(a[i], map.get(a[i])+1);
carry++;
i++;
}
else{
bool = false;break;
}
// System.out.println("SHE");
}
}
// System.out.println(i+" "+j);
// System.out.println(map.toString());
// System.out.println(carry);
if( bool){
System.out.println("YES");
}
else{
System.out.println("NO");
}
// String str = s.next();
// int n = str.length();
// int len = 0;
// boolean bool = true;
// int lenb = 0;
// for(int i=0;i<n;i++){
// if(str.charAt(i)=='A'){
// len++;
// }
// else{
// int j = i;
// while(j<n && str.charAt(j)=='B'){
// lenb++;
// j++;
// }
// if(lenb>len){
// bool = false;
// break;
// }
// len =0;
// lenb =0;
// i = j-1;
// }
// }
// if(len!=0)bool = false;
// if(bool){
// System.out.println("YES");
// }
// else{
// System.out.println("NO");
// }
}
out.close();
} catch (Exception e) {
return;
}
// int t = s.nextInt();
// for(int t1 = 1;t1<=t;t1++){
// }
// out.close();
}
}
/*
4 2 2 7
0 2 5
-2 3
5
0*x1 + 1*x2 + 2*x3 + 3*x4
*/ | Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 1dba5cbe2856e9d10247a01ae37a4fd9 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | // package c1672;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.StringTokenizer;
//
// Codeforces Global Round 20 2022-04-23 07:05
// D. Cyclic Rotation
// https://codeforces.com/contest/1672/problem/D
// time limit per test 1 second; memory limit per test 256 megabytes
// public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*'
//
// There is an array a of length n. You may perform the following operation any number of times:
// * Choose two indices l and r where 1 <= l < r <= n and a_l = a_r. Then, set a[l ... r] =
// [a_{l+1}, a_{l+2}, ..., a_r, a_l].
//
// You are also given another array b of length n which is a permutation of a. Determine whether it
// is possible to transform array a into an array b using the above operation some number of times.
//
// Input
//
// Each test contains multiple test cases. The first line contains a single integer t (1 <= t <=
// 10^4) -- the number of test cases. The description of the test cases follows.
//
// The first line of each test case contains an integer n (1 <= n <= 2 * 10 ^ 5) -- the length of
// array a and b.
//
// The second line of each test case contains n integers a_1, a_2, ..., a_n (1 <= a_i <= n) --
// elements of the array a.
//
// The third line of each test case contains n integers b_1, b_2, ..., b_n (1 <= b_i <= n) --
// elements of the array b.
//
// It is guaranteed that b is a permutation of a.
//
// It is guaranteed that the sum of n over all test cases does not exceed 2 * 10 ^ 5
//
// Output
//
// For each test case, print "YES" (without quotes) if it is possible to transform array a to b, and
// "NO" (without quotes) otherwise.
//
// You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be
// recognized as a positive response).
//
// Example
/*
input:
5
5
1 2 3 3 2
1 3 3 2 2
5
1 2 4 2 1
4 2 2 1 1
5
2 4 5 5 2
2 2 4 5 5
3
1 2 3
1 2 3
3
1 1 2
2 1 1
output:
YES
YES
NO
YES
NO
*/
// Note
//
// In the first test case, we can choose l=2 and r=5 to form [1, 3, 3, 2, 2].
//
// In the second test case, we can choose l=2 and r=4 to form [1, 4, 2, 2, 1]. Then, we can choose
// l=1 and r=5 to form [4, 2, 2, 1, 1].
//
// In the third test case, it can be proven that it is not possible to transform array a to b using
// the operation.
//
public class C1672D {
static final int MOD = 998244353;
static final Random RAND = new Random();
static boolean solve(int[] a, int[] b) {
int n = a.length;
Map<Integer, Integer> cm = new HashMap<>();
int i = 0;
int j = 0;
// 1 2 4 2 1
// ^
// i 1:1 2:1
// 4 2 2 1 1
// ^
// j
// 1 2 4 2 1
// ^
// i
// 4 2 2 1 1
// ^
// j 1:1
while (i < n || j < n) {
// System.out.format(" i:%d a:%d j:%d b:%d cm:%s\n", i, i < n ? a[i] : -1, j, b[j], Utils.traceMap(cm));
if (i < n && a[i] == b[j]) {
i++;
j++;
continue;
}
int k = cm.getOrDefault(b[j], 0);
if (k > 0 && j > 0 && b[j] == b[j-1]) {
// assume b[j] is a rotated pair
if (k == 1) {
cm.remove(b[j]);
} else {
cm.put(b[j], k - 1);
}
j++;
continue;
}
if (i == n) {
return false;
}
// assume a[i] rotated to one of its pair location
cm.put(a[i], cm.getOrDefault(a[i], 0) + 1);
i++;
}
return i == n && j == n;
}
static void test(int[] a, int[] b) {
boolean ans = solve(a, b);
System.out.format("%s\n%s => %s\n", Arrays.toString(a), Arrays.toString(b), ans ? "YES" : "NO");
}
static boolean test = false;
static void doTest() {
if (!test) {
return;
}
long t0 = System.currentTimeMillis();
test(new int[] {1,2,4,2,1}, new int[] {4,2,2,1,1});
test(new int[] {1,2,1}, new int[] {2,1,1});
test(new int[] {1,2,3,4,5,3,2,4,1}, new int[] {1,3,4,5,3,2,2,4,1});
test(new int[] {1,2,3,4,5,3,2,4,1}, new int[] {1,4,5,3,3,2,2,4,1});
test(new int[] {1,2,3,4,5,3,2,4,1}, new int[] {1,5,3,3,2,2,4,4,1});
test(new int[] {1,2,3,4,5,3,2,4,1}, new int[] {5,3,3,2,2,4,4,1,1});
for (int t = 0; t < 200; t++) {
int n = 10;
int[] a = new int[n];
List<Integer> aa = new ArrayList<>();
for (int i = 0; i < n; i++) {
a[i] = 1 + RAND.nextInt(10);
aa.add(a[i]);
}
Collections.shuffle(aa);
int[] b = new int[n];
for (int i = 0; i < n; i++) {
b[i] = aa.get(i);
}
test(a, b);
}
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[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
int[] b = new int[n];
for (int i = 0; i < n; i++) {
b[i] = in.nextInt();
}
boolean ans = solve(a, b);
System.out.println(ans? "YES" : "NO");
}
}
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\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | a899b5ae342897321a93eddbf5347abc | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
//BufferedReader f = new BufferedReader(new FileReader("talent.in"));
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int t = Integer.parseInt(f.readLine());
while(t-- > 0) {
int n = Integer.parseInt(f.readLine());
StringTokenizer st = new StringTokenizer(f.readLine());
int[] a = new int[n];
for(int i = 0; i < n; i++) {
a[i] = Integer.parseInt(st.nextToken());
}
st = new StringTokenizer(f.readLine());
int[] b = new int[n];
for(int i = 0; i < n; i++) {
b[i] = Integer.parseInt(st.nextToken());
}
ArrayList<int[]> c = new ArrayList<>();
int prev = 0;
int cnt = 0;
for(int i = n-1; i >= 0; i--) {
if(b[i] != prev) {
if(prev != 0) {
c.add(new int[]{prev, cnt});
}
prev = b[i];
cnt = 0;
} else {
cnt++;
}
}
c.add(new int[]{prev, cnt});
int[] left = new int[n+1];
int idx = 0;
boolean flag = false;
for(int i = n-1; i >= 0; i--) {
if(idx < c.size() && a[i] == c.get(idx)[0]) {
left[a[i]] += c.get(idx)[1];
idx++;
} else if(left[a[i]] == 0) {
flag = true;
break;
} else {
left[a[i]]--;
}
}
out.println(idx < c.size() || flag ? "NO" : "YES");
}
f.close();
out.close();
}
}
| Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 8fa53284d1288076b20e6ed3ac952e28 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
public class Solution {
public static void main(String[] args) throws IOException {
Reader.init(System.in);
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
int te = Reader.nextInt();
// int t = 1;
while(te-->0){
int n = Reader.nextInt();
int[] arr = new int[n];
int[] b = new int[n];
int[] elem = new int[n+1];
for(int i = 0;i<n;i++){
arr[i] = Reader.nextInt();
elem[arr[i]]++;
}
for(int i = 0;i<n;i++){
b[i] = Reader.nextInt();
}
int[] ahead = new int[n+1];
int j = 0, i = 0;
boolean flag = true;
while(i<n && j<n){
if(arr[i]==b[j]){
i++;
j++;
}
else{
if(ahead[b[j]]>0 && i-1>=0 && b[j]==arr[i-1]){
ahead[b[j]]--;
j++;
}
else{
ahead[arr[i]]++;
i++;
}
}
}
while(j<n){
if(b[j]==arr[n-1]){
ahead[b[j]]--;
j++;
}
else break;
}
for(int el : ahead){
if(el>0){
flag = false;
break;
}
}
// while(i>=0 && j>=0){
// if(elem[arr[i]]==0) i--;
// else if(arr[i]==b[j]){
// elem[arr[i]]--;
// j--;
// i--;
//
// }
// else{
// if(i+1<n && b[j]==arr[i+1]){
// if(elem[arr[i+1]]>0){
// elem[arr[i+1]]--;
// j--;
// }
// else{
// flag = false;
// break;
// }
// }
// else{
// flag = false;
// break;
// }
// }
// }
//
if(flag){
System.out.println("YES");
}
else{
System.out.println("NO");
}
}
output.close();
}
public static long[] factorial(int n){
long[] factorials = new long[n+1];
factorials[1] = 1;
for(int i = 2;i<=n;i++){
factorials[i] = (factorials[i-1]*i)%((int)1e9+7);
}
return factorials;
}
public static long numOfBits(long n){
long ans = 0;
while(n>0){
n = n & (n-1);
ans++;
}
return ans;
}
public static long ceilOfFraction(long x, long y){
// ceil using integer division: ceil(x/y) = (x+y-1)/y
// using double may go out of range.
return (x+y-1)/y;
}
public static int power(int x, int y, int p) {
int res = 1;
x = x % p;
while (y > 0) {
if (y % 2 == 1) res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
// Returns n^(-1) mod p
public static int modInverse(int n, int p) {
return power(n, p - 2, p);
}
// Returns nCr % p using Fermat's
// little theorem.
public static int nCrModPFermat(int n, int r, int p) {
if (n<r) return 0;
if (r == 0) return 1;
// Fill factorial array so that we
// can find all factorial of r, n
// and n-r
int[] fac = new int[n + 1];
fac[0] = 1;
for (int i = 1; i <= n; i++)
fac[i] = fac[i - 1] * i % p;
return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p;
}
public static long ncr(long n, long r) {
long p = 1, k = 1;
if (n - r < r) {
r = n - r;
}
if (r != 0) {
while (r > 0) {
p *= n;
k *= r;
long m = gcd(p, k);
p /= m;
k /= m;
n--;
r--;
}
} else {
p = 1;
}
return p;
}
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;
for (int i = 5; (long) i * i <= n; i = i + 6){
if (n % i == 0 || n % (i + 2) == 0) {
return false;
}
}
return true;
}
public static int powOf2JustSmallerThanN(int n) {
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
return n ^ (n >> 1);
}
public static int mergeSortAndCount(int[] arr, int l, int r) {
int count = 0;
if (l < r) {
int m = (l + r) / 2;
count += mergeSortAndCount(arr, l, m);
count += mergeSortAndCount(arr, m + 1, r);
count += mergeAndCount(arr, l, m, r);
}
return count;
}
public static int mergeAndCount(int[] arr, int l, int m, int r) {
int[] left = Arrays.copyOfRange(arr, l, m + 1);
int[] right = Arrays.copyOfRange(arr, m + 1, r + 1);
int i = 0, j = 0, k = l, swaps = 0;
while (i < left.length && j < right.length) {
if (left[i] <= right[j])
arr[k++] = left[i++];
else {
arr[k++] = right[j++];
swaps += (m + 1) - (l + i);
}
}
while (i < left.length)
arr[k++] = left[i++];
while (j < right.length)
arr[k++] = right[j++];
return swaps;
}
public static void reverseArray(int[] arr,int start, int end) {
int temp;
while (start < end) {
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
public static long gcd(long a, long b){
if(a==0){
return b;
}
return gcd(b%a,a);
}
public static long lcm(long a, long b){
if(a>b) return a/gcd(b,a) * b;
return b/gcd(a,b) * a;
}
public static long largeExponentMod(long x,long y,long mod){
// computing (x^y) % mod
x%=mod;
long ans = 1;
while(y>0){
if((y&1)==1){
ans = (ans*x)%mod;
}
x = (x*x)%mod;
y = y >> 1;
}
return ans;
}
public static boolean[] numOfPrimesInRange(long L, long R){
boolean[] isPrime = new boolean[(int) (R-L+1)];
Arrays.fill(isPrime,true);
long lim = (long) Math.sqrt(R);
for (long i = 2; i <= lim; i++){
for (long j = Math.max(i * i, (L + i - 1) / i * i); j <= R; j += i){
isPrime[(int) (j - L)] = false;
}
}
if (L == 1) isPrime[0] = false;
return isPrime;
}
public static ArrayList<Long> primeFactors(long n){
ArrayList<Long> factorization = new ArrayList<>();
if(n%2==0){
factorization.add(2L);
}
while(n%2==0){
n/=2;
}
if(n%3==0){
factorization.add(3L);
}
while(n%3==0){
n/=3;
}
if(n%5==0){
factorization.add(5L);
}
while(n%5==0){
// factorization.add(5L);
n/=5;
}
int[] increments = {4, 2, 4, 2, 4, 6, 2, 6};
int i = 0;
for (long d = 7; d * d <= n; d += increments[i++]) {
if(n%d==0){
factorization.add(d);
}
while (n % d == 0) {
// factorization.add(d);
n /= d;
}
if (i == 8)
i = 0;
}
if (n > 1)
factorization.add(n);
return factorization;
}
}
class DSU {
int[] size, parent;
int n;
public DSU(int n){
this.n = n;
size = new int[n];
parent = new int[n];
for(int i = 0;i<n;i++){
parent[i] = i;
size[i] = 1;
}
}
public int find(int u){
if(parent[u]==u){
return u;
}
return parent[u] = find(parent[u]);
}
public void merge(int u, int v){
u = find(u);
v = find(v);
if(u!=v){
if(size[u]>size[v]){
parent[v] = u;
size[u] += size[v];
}
else{
parent[u] = v;
size[v] += size[u];
}
}
}
}
class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input) );
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static String nextLine() throws IOException {
return reader.readLine();
}
static int nextInt() throws IOException {
return Integer.parseInt( next() );
}
static long nextLong() throws IOException{
return Long.parseLong(next() );
}
static double nextDouble() throws IOException {
return Double.parseDouble( next() );
}
} | Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 6d45be36adfa0aaa6839bcb3a02c9de9 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | //Some of the methods are copied from GeeksforGeeks Website
import java.util.*;
import java.lang.*;
import java.io.*;
@SuppressWarnings("unchecked")
public class D_Cyclic_Rotation
{
//static Scanner sc=new Scanner(System.in);
//static Reader sc=new Reader();
static FastReader sc=new FastReader(System.in);
static long mod = (long)(1e9)+ 7;
static int max_num=(int)1e5+5;
static List<Integer> gr[];
public static void main (String[] args) throws java.lang.Exception
{
try{
/* out.println("Case #"+tt+": "+ans );
gr=new ArrayList[n];
for(int i=0;i<n;i++) gr[i]=new ArrayList<>();
while(l<=r)
{
int m=l+(r-l)/2;
if(val(m))
{
ans=m;
l=m+1;
}
else
r=m-1;
}
Collections.sort(al,Collections.reverseOrder());
StringBuilder sb=new StringBuilder(""); sb.append(cur); sb=sb.reverse(); String rev=sb.toString();
map.put(a[i],map.getOrDefault(a[i],0)+1);
map.putIfAbsent(x,new ArrayList<>());
long n=sc.nextLong();
String s=sc.next();
char a[]=s.toCharArray();
*/
int t = sc.nextInt();
for(int tt=1;tt<=t;tt++)
{
int n=sc.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
int b[]=new int[n];
for(int i=0;i<n;i++)
{
b[i]=sc.nextInt();
}
int i=n-1,j=n-1;
Map<Integer,Integer> map=new HashMap<>();
boolean f=true;
while(i>=0 && j>=0)
{
if(i==n-1 && j==n-1)
{
if(a[i]!=b[j])
{
f=false;
break;
}
else
{
i--;
j--;
}
}
else
{
if(a[i]==b[j])
{
i--;
j--;
}
else
{
if(b[j]==b[j+1])
{
map.put(b[j],map.getOrDefault(b[j],0)+1);
j--;
}
else
{
int need=a[i];
if(map.getOrDefault(need,0)<=0)
{
f=false;
break;
}
else
{
map.put(need,map.getOrDefault(need,0)-1);
i--;
}
}
}
}
}
flag(f);
}
out.flush();
out.close();
}
catch(Exception e)
{}
}
/*
...SOLUTION ENDS HERE...........SOLUTION ENDS HERE...
*/
static void flag(boolean flag)
{
out.println(flag ? "YES" : "NO");
out.flush();
}
/*
Map<Long,Long> map=new HashMap<>();
for(int i=0;i<n;i++)
{
if(!map.containsKey(a[i]))
map.put(a[i],1);
else
map.replace(a[i],map.get(a[i])+1);
}
Set<Map.Entry<Long,Long>> hmap=map.entrySet();
for(Map.Entry<Long,Long> data : hmap)
{
}
Iterator<Integer> itr = set.iterator();
while(itr.hasNext())
{
int val=itr.next();
}
*/
// static class Pair
// {
// int x,y;
// Pair(int x,int y)
// {
// this.x=x;
// this.y=y;
// }
// }
// Arrays.sort(p, new Comparator<Pair>()
// {
// @Override
// public int compare(Pair o1,Pair o2)
// {
// if(o1.x>o2.x) return 1;
// else if(o1.x==o2.x)
// {
// if(o1.y>o2.y) return 1;
// else return -1;
// }
// else return -1;
// }});
static void print(int a[])
{
int n=a.length;
for(int i=0;i<n;i++)
{
out.print(a[i]+" ");
}
out.println();
out.flush();
}
static void print(long a[])
{
int n=a.length;
for(int i=0;i<n;i++)
{
out.print(a[i]+" ");
}
out.println();
out.flush();
}
static void print_int(ArrayList<Integer> al)
{
int si=al.size();
for(int i=0;i<si;i++)
{
out.print(al.get(i)+" ");
}
out.println();
out.flush();
}
static void print_long(ArrayList<Long> al)
{
int si=al.size();
for(int i=0;i<si;i++)
{
out.print(al.get(i)+" ");
}
out.println();
out.flush();
}
static void pn(int x)
{
out.println(x);
out.flush();
}
static void pn(long x)
{
out.println(x);
out.flush();
}
static void pn(String x)
{
out.println(x);
out.flush();
}
static int LowerBound(int a[], int x)
{
int l=-1,r=a.length;
while(l+1<r) {
int m=(l+r)>>>1;
if(a[m]>=x) r=m;
else l=m;
}
return r;
}
static int UpperBound(int a[], int x)
{// x is the key or target value
int l=-1,r=a.length;
while(l+1<r) {
int m=(l+r)>>>1;
if(a[m]<=x) l=m;
else r=m;
}
return l+1;
}
static void DFS(ArrayList<Integer> graph[],boolean[] visited, int u)
{
visited[u]=true;
int v=0;
for(int i=0;i<graph[u].size();i++)
{
v=graph[u].get(i);
if(!visited[v])
DFS(graph,visited,v);
}
}
static boolean[] prime(int num)
{
boolean[] bool = new boolean[num];
for (int i = 0; i< bool.length; i++) {
bool[i] = true;
}
for (int i = 2; i< Math.sqrt(num); i++) {
if(bool[i] == true) {
for(int j = (i*i); j<num; j = j+i) {
bool[j] = false;
}
}
}
if(num >= 0) {
bool[0] = false;
bool[1] = false;
}
return bool;
}
static long nCr(long a,long b,long mod)
{
return (((fact[(int)a] * modInverse(fact[(int)b],mod))%mod * modInverse(fact[(int)(a - b)],mod))%mod + mod)%mod;
}
static long fact[]=new long[max_num];
static void fact_fill()
{
fact[0]=1l;
for(int i=1;i<max_num;i++)
{
fact[i]=(fact[i-1]*(long)i);
if(fact[i]>=mod)
fact[i]%=mod;
}
}
static long modInverse(long a, long m)
{
return power(a, m - 2, m);
}
static long power(long x, long y, long m)
{
if (y == 0)
return 1;
long p = power(x, y / 2, m) % m;
p = (long)((p * (long)p) % m);
if (y % 2 == 0)
return p;
else
return (long)((x * (long)p) % m);
}
static long sum_array(int a[])
{
int n=a.length;
long sum=0;
for(int i=0;i<n;i++)
sum+=a[i];
return sum;
}
static long sum_array(long a[])
{
int n=a.length;
long sum=0;
for(int i=0;i<n;i++)
sum+=a[i];
return sum;
}
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 sort(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 void reverse_array(int a[])
{
int n=a.length;
int i,t;
for (i = 0; i < n / 2; i++) {
t = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = t;
}
}
static void reverse_array(long a[])
{
int n=a.length;
int i; long t;
for (i = 0; i < n / 2; i++) {
t = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = t;
}
}
static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
static class FastReader{
byte[] buf = new byte[2048];
int index, total;
InputStream in;
FastReader(InputStream is) {
in = is;
}
int scan() throws IOException {
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0) {
return -1;
}
}
return buf[index++];
}
String next() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan());
StringBuilder sb = new StringBuilder();
for (; c > 32; c = scan()) {
sb.append((char) c);
}
return sb.toString();
}
int nextInt() throws IOException {
int c, val = 0;
for (c = scan(); c <= 32; c = scan());
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
long nextLong() throws IOException {
int c;
long val = 0;
for (c = scan(); c <= 32; c = scan());
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
}
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
static PrintWriter out=new PrintWriter(System.out);
static int int_max=Integer.MAX_VALUE;
static int int_min=Integer.MIN_VALUE;
static long long_max=Long.MAX_VALUE;
static long long_min=Long.MIN_VALUE;
}
// Thank You ! | Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | e100bf51318c8154a98357b4ce99c64e | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 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 mod = 998244353;
public static void main(String[] args) {
FastReader fastReader = new FastReader();
PrintWriter out = new PrintWriter(System.out);
int t = fastReader.nextInt();
outer: while (t-- > 0) {
int n = fastReader.nextInt();
int a[] = fastReader.ria(n);
int b[] = fastReader.ria(n);
int freq[] = new int[n + 1];
int i = n - 1, j = n - 1;
while (i >= 0 && j >= 0) {
if (a[i] == b[j]) {
i--;
j--;
} else if (j + 1 < n && b[j] == b[j + 1]) {
freq[b[j]]++;
j--;
} else {
if (freq[a[i]] == 0) {
out.println("NO");
continue outer;
} else {
freq[a[i]]--;
i--;
}
}
}
out.println("YES");
}
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 | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 66cce5085fd2a2fb23599863023d8aed | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class Solution
{
public static void main(String[] args)
{
try (Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))))
{
int T = in.nextInt();
for (int t = 1; t <= T; t++)
{
int n = in.nextInt();
int[] as = new int[n];
int[] bs = new int[n];
for (int i = 0; i < n; i++)
{
as[i] = in.nextInt();
}
for (int i = 0; i < n; i++)
{
bs[i] = in.nextInt();
}
System.out.println(getCan(as, bs));
}
}
}
private static String getCan(int[] as, int[] bs)
{
List<Node> aNodes = new ArrayList<>();
List<Node> bNodes = new ArrayList<>();
buildNodes(as, aNodes);
buildNodes(bs, bNodes);
Map<Integer, Integer> map = new HashMap<>();
int aIdx = aNodes.size() - 1;
int bIdx = bNodes.size() - 1;
while (true)
{
if (bIdx == -1)
{
return "YES";
}
if (aIdx == -1)
{
return "NO";
}
Node aNode = aNodes.get(aIdx);
Node bNode = bNodes.get(bIdx);
if (aNode.val != bNode.val)
{
map.put(aNode.val, map.getOrDefault(aNode.val, 0) - aNode.count);
if (map.getOrDefault(aNode.val, 0) < 0)
{
return "NO";
}
aIdx--;
}
else if (aNode.count > bNode.count)
{
map.put(aNode.val, map.getOrDefault(aNode.val, 0) - (aNode.count - bNode.count));
if (map.getOrDefault(aNode.val, 0) < 0)
{
return "NO";
}
aIdx--;
bIdx--;
}
else
{
map.put(aNode.val, map.getOrDefault(aNode.val, 0) + (bNode.count - aNode.count));
aIdx--;
bIdx--;
}
}
}
private static void buildNodes(int[] nums, List<Node> nodes)
{
for (int num : nums)
{
if (!nodes.isEmpty() && nodes.get(nodes.size() - 1).val == num)
{
nodes.get(nodes.size() - 1).count++;
}
else
{
nodes.add(new Node(num));
}
}
}
}
class Node
{
int val;
int count;
public Node(int val)
{
this.val = val;
this.count = 1;
}
}
| Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | f604cfe6e4ac46cfed81d9b74aa167dd | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 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 i,a[]=new int[n],b,c[]=new int[n+1];
String s[]=bu.readLine().split(" ");
TreeSet<Integer> ts[]=new TreeSet[n+1],tm=new TreeSet<>();
for(i=0;i<=n;i++) ts[i]=new TreeSet<>();
for(i=0;i<n;i++)
{
a[i]=Integer.parseInt(s[i]);
c[i]++;
ts[a[i]].add(i);
tm.add(i);
}
s=bu.readLine().split(" ");
boolean ans=true;
for(i=0;i<n && ans;i++)
{
b=Integer.parseInt(s[i]);
int cur=tm.higher(-1),low=ts[b].higher(-1),val=a[cur];
while(val!=b)
{
//low is smallest index of b next to this
if(ts[val].higher(low)==null) break; //no larger value possible for val
int small=ts[val].higher(low); //smallest value larger than in_b
c[cur]--; c[small]++;
if(c[cur]==0)
{
tm.remove(cur);
ts[val].remove(cur);
}
cur=tm.higher(-1); val=a[cur];
}
if(val!=b) {ans=false; continue;}
c[cur]--;
if(c[cur]==0)
{
tm.remove(cur);
ts[val].remove(cur);
}
}
if(ans) sb.append("YES\n");
else sb.append("NO\n");
}
System.out.print(sb);
}
} | Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 407d2423f8ec1b5dfe07b3fd22e1bba9 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numberOfTests = scanner.nextInt();
for (int t = 0; t < numberOfTests; t++) {
int n = scanner.nextInt();
int[] a = new int[n + 1];
int[] b = new int[n + 1];
for (int i = 1; i <= n; i++) a[i] = scanner.nextInt();
for (int i = 1; i <= n; i++) b[i] = scanner.nextInt();
int[] c = new int[n + 1];
int[] num = new int[n + 1];
for (int i = 1; i <= n; i++) {
num[a[i]]++;
c[i] = num[a[i]];
}
Arrays.fill(num, 0);
int idx = 1;
for (int i = 1; i <= n; i++) {
num[b[i]]++;
while (idx <= n && (a[idx] != b[i] || c[idx] < num[b[i]])) idx++;
}
if (idx <= n) System.out.println("YES");
else System.out.println("NO");
}
}
}
| Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | f3f3e30afb70245ef78a7d1b6c9c9d5c | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 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);
DCyclicRotation solver = new DCyclicRotation();
int testCount = Integer.parseInt(in.next());
for (int i = 1; i <= testCount; i++) {
solver.solve(i, in, out);
}
out.close();
}
static class DCyclicRotation {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int[] a = new int[n];
int[] cnt = new int[n + 1];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
int[] b = new int[n];
for (int i = 0; i < n; i++) {
b[i] = in.nextInt();
}
int j = n - 1;
for (int i = n - 1; i >= 0 && j >= 0; ) {
while (j - 1 >= 0 && b[j] == b[j - 1]) {
cnt[b[j]]++;
j--;
}
if (a[i] == b[j]) {
i--;
j--;
} else if (cnt[a[i]] > 0) {
cnt[a[i]]--;
i--;
} else {
out.println("NO");
return;
}
}
out.println("YES");
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String nextString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return nextString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | dcbce02bec97ee608bf6aee864f2732f | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.*;
import java.util.*;
public class D {
public static void main (String[] args) throws IOException {
Kattio io = new Kattio();
int t = io.nextInt();
outer: for (int ii=0; ii<t; ii++) {
int n = io.nextInt();
int[] a = new int[n];
int[] b = new int[n];
for (int i=0; i<n; i++) {
a[i] = io.nextInt();
}
for (int i=0; i<n; i++) {
b[i] = io.nextInt();
}
HashMap<Integer, Integer> map = new HashMap<>();
int lo = 0;
int hi = 0;
while (hi < n) {
//System.out.println(lo + " " + hi);
if (lo < n && a[lo] == b[hi]) {
lo++;
hi++;
} else if (lo > 0 && b[hi] == a[lo-1] && map.getOrDefault(a[lo - 1], 0) >= 1) {
map.put(a[lo - 1], map.get(a[lo - 1]) - 1);
hi++;
} else if (lo < n) {
map.put(a[lo], map.getOrDefault(a[lo], 0) + 1);
lo++;
} else {
System.out.println("NO");
continue outer;
}
}
System.out.println("YES");
}
}
static class Kattio extends PrintWriter {
private BufferedReader r;
private StringTokenizer st;
// standard input
public Kattio() { this(System.in, System.out); }
public Kattio(InputStream i, OutputStream o) {
super(o);
r = new BufferedReader(new InputStreamReader(i));
}
// USACO-style file input
public Kattio(String problemName) throws IOException {
super(new FileWriter(problemName + ".out"));
r = new BufferedReader(new FileReader(problemName + ".in"));
}
// returns null if no more input
public String next() {
try {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(r.readLine());
return st.nextToken();
} catch (Exception e) { }
return null;
}
public int nextInt() { return Integer.parseInt(next()); }
public double nextDouble() { return Double.parseDouble(next()); }
public long nextLong() { return Long.parseLong(next()); }
}
} | Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | ca1855e66f83a49a4c1b52485e05da42 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import com.sun.source.tree.Tree;
import java.io.*;
import java.util.InputMismatchException;
import java.util.TreeMap;
public class E1672D {
public static void main(String[] args) {
FastIO io = new FastIO();
int t = io.nextInt();
while (t-- > 0) {
int n = io.nextInt();
int[] a = new int[n];
int[] b = new int[n];
for (int i = 0; i < n; i++) a[i] = io.nextInt();
for (int i = 0; i < n; i++) b[i] = io.nextInt();
TreeMap<Integer, Integer> multiSet = new TreeMap<>();
int i = 0;
int j = 0;
int last = 0;
while (i < n) {
if (a[i] == b[j]) {
last = a[i];
i++;
j++;
} else if (multiSet.containsKey(b[j]) && last == b[j]) {
remove(multiSet, b[j]);
j++;
} else {
add(multiSet, a[i]);
last = a[i];
i++;
}
}
for (; j < n && multiSet.containsKey(b[j]) && last == b[j]; remove(multiSet, b[j]), j++) ;
io.println(j == n ? "YES" : "NO");
}
io.close();
}
static <T> void add(TreeMap<T, Integer> multiSet, T x) {
multiSet.put(x, multiSet.getOrDefault(x, 0) + 1);
}
static <T> void remove(TreeMap<T, Integer> multiSet, T x) {
multiSet.put(x, multiSet.get(x) - 1);
if (multiSet.get(x) == 0) multiSet.remove(x);
}
private static class FastIO extends PrintWriter {
private final InputStream stream;
private final byte[] buf = new byte[1 << 16];
private int curChar, numChars;
// standard input
public FastIO() {
this(System.in, System.out);
}
public FastIO(InputStream i, OutputStream o) {
super(o);
stream = i;
}
// file input
public FastIO(String i, String o) throws IOException {
super(new FileWriter(o));
stream = new FileInputStream(i);
}
// throws InputMismatchException() if previously detected end of file
private int nextByte() {
if (numChars == -1) throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars == -1) return -1; // end of file
}
return buf[curChar++];
}
// to read in entire lines, replace c <= ' '
// with a function that checks whether c is a line break
public String next() {
int c;
do {
c = nextByte();
} while (c <= ' ');
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = nextByte();
} while (c > ' ');
return res.toString();
}
public int nextInt() { // nextLong() would be implemented similarly
int c;
do {
c = nextByte();
} while (c <= ' ');
int sgn = 1;
if (c == '-') {
sgn = -1;
c = nextByte();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = 10 * res + c - '0';
c = nextByte();
} while (c > ' ');
return res * sgn;
}
public long nextLong() { // nextLong() would be implemented similarly
int c;
do {
c = nextByte();
} while (c <= ' ');
int sgn = 1;
if (c == '-') {
sgn = -1;
c = nextByte();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = 10 * res + c - '0';
c = nextByte();
} while (c > ' ');
return res * sgn;
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
}
| Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | d60023d4048ae15bf36c9e25d8932fc6 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.util.*;
import java.io.*;
public class CodeForces {
public static void main(String[] args) throws FileNotFoundException {
FastScanner fs = new FastScanner();
int tt = fs.nextInt();
while(tt-- > 0) {
int n = fs.nextInt();
int[] a = fs.readArray(n);
int[] b = fs.readArray(n);
boolean flag = true;
Map<Integer, Integer> map = new HashMap<>();
int i = a.length - 1, j = b.length - 1;
while(j >= 0 && i >= 0) {
while(j-1 >= 0 && b[j] == b[j - 1]) {
j--;
map.put(b[j], map.getOrDefault(b[j], 0) + 1);
}
if(a[i] == b[j]) {
i--;
j--;
}else {
if(!map.containsKey(a[i]) || map.get(a[i]) == 0) {
flag = false;
break;
}else {
map.put(a[i], map.get(a[i]) - 1);
i--;
}
}
}
if(flag) {
System.out.println("YES");
}else {
System.out.println("NO");
}
}
}
public static int gcd(int a, int b) {
if(b == 0) return a;
return gcd(b, a%b);
}
static void sort(int[] a) {
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
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());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
} | Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 055af5a0e95b5efeaf31c535850f55b8 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class D {
static class RealScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
public boolean isSorted(List<Long> list) {
for (int i = 0; i < list.size() - 1; i++) {
if (list.get(i) > list.get(i + 1))
return false;
}
return true;
}
}
public static void main(String[] args) {
RealScanner sc = new RealScanner();
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
int[] arr1 = new int[n];
int[] arr2 = new int[n];
for (int i = 0; i < n; i++) {
arr1[i] = sc.nextInt();
}
for (int i = 0; i < n; i++) {
arr2[i] = sc.nextInt();
}
if (arr1[n - 1] != arr2[n - 1]) {
System.out.println("NO");
continue;
}
// Map<Integer, Integer> first = new HashMap<>();
// Map<Integer, Integer> second = new HashMap<>();
Map<Integer, Integer> map = new HashMap<>();
boolean check = true;
int idx = 0;
int j = n - 1;
int i = n - 1;
while (i >= 0 && j >= 0) {
int val = arr1[i];
int count = 0;
while (i >= 0 && val == arr1[i]) {
i--;
count++;
}
while (j >= 0 && val == arr2[j]) {
j--;
map.put(val, map.getOrDefault(val, 0) + 1);
}
// System.out.println(i + " " + j);
map.put(val, map.getOrDefault(val, 0) - count);
if (map.get(val) < 0) {
check = false;
break;
}
// idx = j;
// System.out.println(count);
}
if (check || j <= 0) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
}
| Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 8e2da96515c3d50e01780f1152511efd | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.util.*;
public class Hello {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int T = Integer.parseInt(sc.nextLine());
while (T-- > 0) {
int N = sc.nextInt();
int arr1[] = new int[N + 1];
int arr2[] = new int[N + 1];
int count[] = new int[N + 1];
for (int index = 1; index <= N; index++) {
arr1[index] = sc.nextInt();
}
for (int index = 1; index <= N; index++) {
arr2[index] = sc.nextInt();
}
int index1 = 1, index2 = 1;
while (index1 <= N) {
if (arr1[index1] == arr2[index2]) {
index2++;
while (index2 <= N && arr1[index1] == arr2[index2] && count[arr1[index1]] > 0) {
count[arr1[index1]]--;
index2++;
}
} else {
count[arr1[index1]]++;
}
index1++;
}
System.out.println((index2 == N + 1) ? "YES" : "NO");
}
}
} | Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 500a95026da6f50e2cf127b5a207cac1 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | /**
* @description: 比赛
* @author: dzx
* @date: 2022/4/20
*/
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
FastPrinter out = new FastPrinter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, FastScanner in, FastPrinter out) {
int t = in.nextInt();
while (t-- > 0) {
int n = in.nextInt();
int[]a = new int[n];
int[]b = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
for (int i = 0; i < n; i++) {
b[i] = in.nextInt();
}
String s = check(a, b);
System.out.println(s);
}
}
private String check(int[] a, int[] b) {
Map<Integer, Integer> map = new HashMap<>();
int n = a.length;
int aIdx = n-1;
int i = n - 1;
while(i>=0&&aIdx >= 0) {
if (a[aIdx] == b[i]) {
aIdx--;
i--;
}else{
if (i == n - 1) {
break;
}
if (b[i] == b[i + 1]) {
map.put(b[i], map.getOrDefault(b[i], 0) + 1);
i--;
}else{
int time = map.getOrDefault(a[aIdx],0) - 1;
if (time<0) {
return "NO";
}
map.put(a[aIdx--], time);
}
}
}
while (aIdx >= 0) {
int time = map.getOrDefault(a[aIdx],0) - 1;
if (time<0) {
return "NO";
}
map.put(a[aIdx--], time);
}
return "YES";
}
}
static class ru_ifmo_niyaz_arrayutils_ArrayUtils {
static final long seed = System.nanoTime();
static final Random rand = new Random(seed);
public static void sort(int[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void shuffle(int[] a) {
for (int i = 0; i < a.length; i++) {
int j = rand.nextInt(i + 1);
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
}
static class FastPrinter extends PrintWriter {
public FastPrinter(OutputStream out) {
super(out);
}
public FastPrinter(Writer out) {
super(out);
}
}
static class net_egork_misc_ArrayUtils {
public static long sumArray(int[] array) {
long result = 0;
for (int element : array)
result += element;
return result;
}
}
static class FastScanner extends BufferedReader {
public FastScanner(InputStream is) {
super(new InputStreamReader(is));
}
public int read() {
try {
int ret = super.read();
// if (isEOF && ret < 0) {
// throw new InputMismatchException();
// }
// isEOF = ret == -1;
return ret;
} catch (IOException e) {
throw new InputMismatchException();
}
}
public String next() {
StringBuilder sb = new StringBuilder();
int c = read();
while (isWhiteSpace(c)) {
c = read();
}
if (c < 0) {
return null;
}
while (c >= 0 && !isWhiteSpace(c)) {
sb.appendCodePoint(c);
c = read();
}
return sb.toString();
}
static boolean isWhiteSpace(int c) {
return c >= 0 && c <= 32;
}
public int nextInt() {
int c = read();
while (isWhiteSpace(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int ret = 0;
while (c >= 0 && !isWhiteSpace(c)) {
if (c < '0' || c > '9') {
throw new NumberFormatException("digit expected " + (char) c + " found");
}
ret = ret * 10 + c - '0';
c = read();
}
return ret * sgn;
}
public long nextLong() {
return Long.parseLong(next());
}
public String readLine() {
try {
return super.readLine();
} catch (IOException e) {
return null;
}
}
public int[] readIntArray(int n) {
int[] ret = new int[n];
for (int i = 0; i < n; i++) {
ret[i] = nextInt();
}
return ret;
}
}
} | Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 3fa49eeb52f66ad0afe9786ffad1d309 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.util.*;
import java.io.*;
public class D {
static class Scan {
private byte[] buf=new byte[1024];
private int index;
private InputStream in;
private int total;
public Scan()
{
in=System.in;
}
public int scan()throws IOException
{
if(total<0)
throw new InputMismatchException();
if(index>=total)
{
index=0;
total=in.read(buf);
if(total<=0)
return -1;
}
return buf[index++];
}
public int scanInt()throws IOException
{
int integer=0;
int n=scan();
while(isWhiteSpace(n))
n=scan();
int neg=1;
if(n=='-')
{
neg=-1;
n=scan();
}
while(!isWhiteSpace(n))
{
if(n>='0'&&n<='9')
{
integer*=10;
integer+=n-'0';
n=scan();
}
else throw new InputMismatchException();
}
return neg*integer;
}
public double scanDouble()throws IOException
{
double doub=0;
int n=scan();
while(isWhiteSpace(n))
n=scan();
int neg=1;
if(n=='-')
{
neg=-1;
n=scan();
}
while(!isWhiteSpace(n)&&n!='.')
{
if(n>='0'&&n<='9')
{
doub*=10;
doub+=n-'0';
n=scan();
}
else throw new InputMismatchException();
}
if(n=='.')
{
n=scan();
double temp=1;
while(!isWhiteSpace(n))
{
if(n>='0'&&n<='9')
{
temp/=10;
doub+=(n-'0')*temp;
n=scan();
}
else throw new InputMismatchException();
}
}
return doub*neg;
}
public String scanString()throws IOException
{
StringBuilder sb=new StringBuilder();
int n=scan();
while(isWhiteSpace(n))
n=scan();
while(!isWhiteSpace(n))
{
sb.append((char)n);
n=scan();
}
return sb.toString();
}
private boolean isWhiteSpace(int n)
{
if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1)
return true;
return false;
}
}
public static void sort(int arr[],int l,int r) { //sort(arr,0,n-1);
if(l==r) {
return;
}
int mid=(l+r)/2;
sort(arr,l,mid);
sort(arr,mid+1,r);
merge(arr,l,mid,mid+1,r);
}
public static void merge(int arr[],int l1,int r1,int l2,int r2) {
int tmp[]=new int[r2-l1+1];
int indx1=l1,indx2=l2;
//sorting the two halves using a tmp array
for(int i=0;i<tmp.length;i++) {
if(indx1>r1) {
tmp[i]=arr[indx2];
indx2++;
continue;
}
if(indx2>r2) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
if(arr[indx1]<arr[indx2]) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
tmp[i]=arr[indx2];
indx2++;
}
//Copying the elements of tmp into the main array
for(int i=0,j=l1;i<tmp.length;i++,j++) {
arr[j]=tmp[i];
}
}
public static void sort(long arr[],int l,int r) { //sort(arr,0,n-1);
if(l==r) {
return;
}
int mid=(l+r)/2;
sort(arr,l,mid);
sort(arr,mid+1,r);
merge(arr,l,mid,mid+1,r);
}
public static void merge(long arr[],int l1,int r1,int l2,int r2) {
long tmp[]=new long[r2-l1+1];
int indx1=l1,indx2=l2;
//sorting the two halves using a tmp array
for(int i=0;i<tmp.length;i++) {
if(indx1>r1) {
tmp[i]=arr[indx2];
indx2++;
continue;
}
if(indx2>r2) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
if(arr[indx1]<arr[indx2]) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
tmp[i]=arr[indx2];
indx2++;
}
//Copying the elements of tmp into the main array
for(int i=0,j=l1;i<tmp.length;i++,j++) {
arr[j]=tmp[i];
}
}
static int target[];
public static void main(String args[]) throws IOException {
Scan input=new Scan();
StringBuilder ans=new StringBuilder("");
int test=input.scanInt();
for(int tt=1;tt<=test;tt++) {
int n=input.scanInt();
// int n=5;
int arr[]=new int[n];
int brr[]=new int[n];
for(int i=0;i<n;i++) {
arr[i]=input.scanInt()-1;
// arr[i]=(int)(Math.random()*n);
}
for(int i=0;i<n;i++) {
brr[i]=input.scanInt()-1;
// brr[i]=arr[i];
}
// for(int i=0;i<n/2;i++) {
// int l=(int)(Math.random()*n);
// int r=(int)(Math.random()*n);
//
// int tmp=arr[l];
// arr[l]=arr[r];
// arr[r]=tmp;
// }
target=brr;
int[] arr_1=solve(n,arr);
int[] arr_2=solve(n,brr);
boolean is_pos=true;
for(int i=0;i<n;i++) {
// System.out.println(i+" "+arr_1[i]+" "+arr_2[i]);
if(arr_1[i]!=arr_2[i]) {
is_pos=false;
break;
}
}
if(is_pos) {
int req[]=new int[n];
int nxt=-1;
for(int i=n-1,j=n-1;i>=0 || j>=0;i--) {
// System.out.println(j+" "+i+" "+nxt);
if(i<0) {
if(req[arr[j]]>0) {
req[arr[j]]--;
}
else {
is_pos=false;
break;
}
j--;
continue;
}
if(arr[j]!=brr[i]) {
if(nxt!=brr[i]) {
if(req[arr[j]]>0) {
req[arr[j]]--;
j--;
i++;
continue;
}
is_pos=false;
break;
}
else {
req[brr[i]]++;
}
}
else {
nxt=arr[j];
j--;
}
}
for(int i=0;i<n;i++) {
// System.out.println(i+" "+req[i]);
if(req[i]!=0) {
is_pos=false;
// break;
}
}
int tog_a[]=new int[n];
int tog_b[]=new int[n];
for(int i=n-1;i>=0;i--) {
if(tog_a[arr[i]]!=0) {
continue;
}
int j=i,cnt=1;
while(j>0 && arr[j-1]==arr[i]) {
cnt++;
j--;
}
tog_a[arr[i]]=cnt;
}
for(int i=n-1;i>=0;i--) {
if(tog_b[brr[i]]!=0) {
continue;
}
int j=i,cnt=1;
while(j>0 && brr[j-1]==brr[i]) {
cnt++;
j--;
}
tog_b[brr[i]]=cnt;
}
// for(int i=0;i<n;i++) {
// System.out.println(i+" "+tog_a[i]+" "+tog_b[i]);
// }
// System.out.println();
// for(int i=0;i<n;i++) {
// if(tog_a[i]>tog_b[i]) {
// is_pos=false;
// break;
// }
// }
}
// for(int i=0;i<n;i++) {
// System.out.print(arr_1[i]+" ");
// }
// System.out.println();
// for(int i=0;i<n;i++) {
// System.out.print(arr_2[i]+" ");
// }
// System.out.println();
// boolean bf=bf(n,arr,0);
// if(is_pos!=bf) {
// System.out.println(is_pos+" "+bf);
// for(int i=0;i<n;i++) {
// System.out.print(arr[i]+" ");
// }
// System.out.println();
// for(int i=0;i<n;i++) {
// System.out.print(brr[i]+" ");
// }
// System.out.println();
// }
if(is_pos) {
ans.append("YES\n");
}
else {
ans.append("NO\n");
}
}
System.out.println(ans);
}
public static int[] solve(int n,int arr[]) {
HashMap<Integer,Integer> map=new HashMap<>();
HashMap<Integer,Integer> cnt=new HashMap<>();
for(int i=n-1;i>=0;i--) {
if(!map.containsKey(arr[i])) {
map.put(arr[i], i);
cnt.put(arr[i], 0);
}
cnt.replace(arr[i], cnt.get(arr[i])+1);
}
int brr[]=new int[n];
for(int i=0,indx=0;i<n;i++) {
if(map.get(arr[i])==i) {
int rep=cnt.get(arr[i]);
for(int j=0;j<rep;j++) {
brr[indx]=arr[i];
indx++;
}
}
}
return brr;
}
public static boolean bf(int n,int arr[],int dep) {
if(check(n,arr)) {
return true;
}
if(dep>10) {
return false;
}
for(int i=0;i<n;i++) {
for(int j=i+1;j<n;j++) {
if(arr[i]==arr[j]) {
swap(arr,i,j);
if(bf(n,arr,dep+1)) {
rev_swap(arr,i,j);
return true;
}
rev_swap(arr,i,j);
}
}
}
return false;
}
public static void swap(int arr[],int l,int r) {
int tmp=arr[l];
for(int i=l;i<r;i++) {
arr[i]=arr[i+1];
}
arr[r]=tmp;
}
public static void rev_swap(int arr[],int l,int r) {
int tmp=arr[r];
for(int i=r;i>l;i--) {
arr[i]=arr[i-1];
}
arr[l]=tmp;
}
public static boolean check(int n,int arr[]) {
for(int i=0;i<n;i++) {
if(arr[i]!=target[i]) {
return false;
}
}
return true;
}
}
| Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 3584ce164afb76cbb195d73f5fdb9274 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.*;
import java.util.*;
import java.util.List;
public class Main implements Runnable {
public static final int LIMIT = 100010;
int n, m, k;
static boolean use_n_tests = true;
int[] w;
int l, r;
void solve(FastScanner in, PrintWriter out, int testNumber) {
n = in.nextInt();
int[] a1 = in.nextArray(n);
int[] b1 = in.nextArray(n);
int[] a = new int[n + 1];
int[] b = new int[n + 1];
for (int i = 0; i < n; i++) {
a[i + 1] = a1[i];
b[i + 1] = b1[i];
}
int p1 = n;
int p2 = n;
int pivot = 0;
int res = -1;
Multiset<Integer> ms = new Multiset<>();
while (p1 > -1 || p2 > -1) {
if (a[p1] == b[p2]) {
pivot = a[p1];
p1 -= 1;
p2 -= 1;
} else {
if (pivot == b[p2]) {
ms.add(b[p2]);
p2 -= 1;
} else {
if (ms.contains(a[p1])) {
ms.remove(a[p1]);
p1 -= 1;
} else {
res = 0;
break;
}
}
}
}
if (res == 0) {
out.println("NO");
} else {
out.println("YES");
}
/* k = in.nextInt();
List<int[]> ls = new ArrayList<>();
for (int i = 0; i < n; i++) {
int[] a = in.nextArray(3);
ls.add(a);
}
int[][][] dp = new int[n + 1][300][1 << (n + 1)];
for (int i = 0; i < n + 1; i++) {
for (int j = 0; j < 300; j++) {
Arrays.fill(dp[i][j], 1 << 30);
}
}
dp[1][0][100 + k] = 0;
int ans = 0;
for (int mask = 1; mask < 1 << (n + 1); mask++) {
for (int i = 0; i < n + 1; i++) {
for (int p = 0; p < 300; p++) {
if (dp[i][p][mask] != 1 << 30) {
for (int j = 0; j < g.get(i).size(); j++) {
int to = g.get(i).get(j);
if (((mask >> to) & 1) == 0) {
dp[to][mask | to] = Math.min(dp[i][mask] + 1, dp[to][mask | to]);
ans = Math.max(ans, dp[to][mask | to]);
}
}
}
}
}
}
out.println(ans); */
}
boolean has(int[] a, int[] b) {
int k = a[2];
return k >= b[0] && k <= b[1];
}
class Pair1 {
int d;
public int getD() {
return d;
}
public Pair1(int d, int a, int b) {
this.d = d;
this.a = a;
this.b = b;
}
int a;
int b;
}
// ****************************** template code ***********
public static class DisjointSets {
int[] p;
int[] size;
int sccCount;
DisjointSets(int size) {
p = new int[size];
this.size = new int[size];
for (int i = 0; i < size; i++) {
this.size[i] = 1;
p[i] = i;
}
sccCount = size;
}
public int root(int x) {
return x == p[x] ? x : (p[x] = root(p[x]));
}
public void unite(int a, int b) {
a = root(a);
b = root(b);
if (a == b) {
return;
}
if (size[b] > size[a]) {
int tmp = a;
a = b;
b = tmp;
}
size[a] += size[b];
p[b] = a;
sccCount--;
}
int size(int id) {
return size[root(id)];
}
}
static boolean use_file_insteadof_stdin = false; //System.getProperty("ONLINE_JUDGE") == null;
static String input = "input.txt";
static String output = "output.txt";
List<Integer> getGidits(long n) {
List<Integer> res = new ArrayList<>();
while (n != 0) {
res.add((int) (n % 10L));
n /= 10;
}
return res;
}
List<Integer> generatePrimes(int n) {
List<Integer> res = new ArrayList<>();
boolean[] sieve = new boolean[n + 1];
for (int i = 2; i <= n; i++) {
if (!sieve[i]) {
res.add(i);
}
if ((long) i * i <= n) {
for (int j = i * i; j <= n; j += i) {
sieve[j] = true;
}
}
}
return res;
}
int ask(int l, int r) {
if (l >= r) {
return -1;
}
System.out.printf("? %d %d\n", l + 1, r + 1);
System.out.flush();
return in.nextInt() - 1;
}
static int stack_size = 1 << 27;
class Mod {
long mod;
Mod(long mod) {
this.mod = mod;
}
long add(long a, long b) {
a = mod(a);
b = mod(b);
return (a + b) % mod;
}
long sub(long a, long b) {
a = mod(a);
b = mod(b);
return (a - b + mod) % mod;
}
long mul(long a, long b) {
a = mod(a);
b = mod(b);
return (a * b) % mod;
}
long div(long a, long b) {
a = mod(a);
b = mod(b);
return (a * inv(b)) % mod;
}
public long inv(long r) {
if (r == 1)
return 1;
return ((mod - mod / r) * inv(mod % r)) % mod;
}
private long mod(long a) {
return a % mod;
}
}
static class Coeff {
long mod;
long[][] C;
long[] fact;
boolean cycleWay = false;
Coeff(int n, long mod) {
this.mod = mod;
fact = new long[n + 1];
fact[0] = 1;
for (int i = 1; i <= n; i++) {
fact[i] = i;
fact[i] %= mod;
fact[i] *= fact[i - 1];
fact[i] %= mod;
}
}
Coeff(int n, int m, long mod) {
// n > m
cycleWay = true;
this.mod = mod;
C = new long[n + 1][m + 1];
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= Math.min(i, m); j++) {
if (j == 0 || j == i) {
C[i][j] = 1;
} else {
C[i][j] = C[i - 1][j - 1] + C[i - 1][j];
C[i][j] %= mod;
}
}
}
}
public long C(int n, int m) {
if (cycleWay) {
return C[n][m];
}
return fC(n, m);
}
private long fC(int n, int m) {
return (fact[n] * inv(fact[n - m] * fact[m] % mod)) % mod;
}
private long fact(int n) {
return fact[n];
}
private long inv(long r) {
if (r == 1)
return 1;
return ((mod - mod / r) * inv(mod % r)) % mod;
}
}
class Pair {
int first;
long second;
Pair(int f, long s) {
first = f;
second = s;
}
public int getFirst() {
return first;
}
public long getSecond() {
return second;
}
}
class MultisetTree<T> {
int size = 0;
TreeMap<T, Integer> mp = new TreeMap<>();
void add(T x) {
mp.merge(x, 1, Integer::sum);
size++;
}
List<T> getElems() {
List<T> res = new ArrayList<>();
for (T k : mp.keySet()) {
int c = mp.get(k);
for (int i = 0; i < c; i++) {
res.add(k);
}
}
return res;
}
void remove(T x) {
if (mp.containsKey(x)) {
mp.merge(x, -1, Integer::sum);
if (mp.get(x) == 0) {
mp.remove(x);
}
size--;
}
}
boolean contains(T x) {
return mp.containsKey(x);
}
T greatest() {
return mp.lastKey();
}
T smallest() {
return mp.firstKey();
}
int size() {
return size;
}
int diffSize() {
return mp.size();
}
}
class Multiset<T> {
int size = 0;
Map<T, Integer> mp = new HashMap<>();
void add(T x) {
mp.merge(x, 1, Integer::sum);
size++;
}
boolean contains(T x) {
return mp.containsKey(x);
}
void remove(T x) {
if (mp.containsKey(x)) {
mp.merge(x, -1, Integer::sum);
if (mp.get(x) == 0) {
mp.remove(x);
}
size--;
}
}
int size() {
return size;
}
int diffSize() {
return mp.size();
}
}
static class Range {
int l, r;
int id;
public int getL() {
return l;
}
public int getR() {
return r;
}
public Range(int l, int r, int id) {
this.l = l;
this.r = r;
this.id = id;
}
}
static class Array {
static Range[] readRanges(int n, FastScanner in) {
Range[] result = new Range[n];
for (int i = 0; i < n; i++) {
result[i] = new Range(in.nextInt(), in.nextInt(), i);
}
return result;
}
static List<List<Integer>> intInit2D(int n) {
List<List<Integer>> res = new ArrayList<>();
for (int i = 0; i < n; i++) {
res.add(new ArrayList<>());
}
return res;
}
static boolean isSorted(Integer[] a) {
for (int i = 0; i < a.length - 1; i++) {
if (a[i] > a[i + 1]) {
return false;
}
}
return true;
}
static public long sum(int[] a) {
long sum = 0;
for (int x : a) {
sum += x;
}
return sum;
}
static public long sum(long[] a) {
long sum = 0;
for (long x : a) {
sum += x;
}
return sum;
}
static public long sum(Integer[] a) {
long sum = 0;
for (int x : a) {
sum += x;
}
return sum;
}
static public int min(Integer[] a) {
int mn = Integer.MAX_VALUE;
for (int x : a) {
mn = Math.min(mn, x);
}
return mn;
}
static public int min(int[] a) {
int mn = Integer.MAX_VALUE;
for (int x : a) {
mn = Math.min(mn, x);
}
return mn;
}
static public int max(Integer[] a) {
int mx = Integer.MIN_VALUE;
for (int x : a) {
mx = Math.max(mx, x);
}
return mx;
}
static public int max(int[] a) {
int mx = Integer.MIN_VALUE;
for (int x : a) {
mx = Math.max(mx, x);
}
return mx;
}
static public int[] readint(int n, FastScanner in) {
int[] out = new int[n];
for (int i = 0; i < out.length; i++) {
out[i] = in.nextInt();
}
return out;
}
}
class Graph {
List<List<Integer>> graph;
Graph(int n) {
create(n);
}
private void create(int n) {
List<List<Integer>> graph = new ArrayList<>();
for (int i = 0; i < n; i++) {
graph.add(new ArrayList<>());
}
this.graph = graph;
}
void readBi(int m, FastScanner in) {
for (int i = 0; i < m; i++) {
int v = in.nextInt() - 1;
int u = in.nextInt() - 1;
graph.get(v).add(u);
graph.get(u).add(v);
}
}
void add(int v, int u) {
graph.get(v).add(u);
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream io) {
br = new BufferedReader(new InputStreamReader(io));
}
public String line() {
String result = "";
try {
result = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public char[] nextc() {
return next().toCharArray();
}
public int nextInt() {
return Integer.parseInt(next());
}
public int[] nextArray(int n) {
int[] res = new int[n];
for (int i = 0; i < n; i++) {
res[i] = in.nextInt();
}
return res;
}
public long[] nextArrayL(int n) {
long[] res = new long[n];
for (int i = 0; i < n; i++) {
res[i] = in.nextLong();
}
return res;
}
public Long[] nextArrayL2(int n) {
Long[] res = new Long[n];
for (int i = 0; i < n; i++) {
res[i] = in.nextLong();
}
return res;
}
public Integer[] nextArray2(int n) {
Integer[] res = new Integer[n];
for (int i = 0; i < n; i++) {
res[i] = in.nextInt();
}
return res;
}
public long nextLong() {
return Long.parseLong(next());
}
}
void run_t_tests() {
int t = in.nextInt();
int i = 0;
while (t-- > 0) {
solve(in, out, i++);
}
}
void run_one() {
solve(in, out, -1);
}
@Override
public void run() {
if (use_file_insteadof_stdin) {
try {
in = new FastScanner(new FileInputStream(input));
// out = new PrintWriter(new FileOutputStream(output));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else {
in = new FastScanner(System.in);
}
out = new PrintWriter(System.out);
if (use_n_tests) {
run_t_tests();
} else {
run_one();
}
out.close();
}
static FastScanner in;
static PrintWriter out;
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(null, new Main(), "", stack_size);
thread.start();
thread.join();
}
} | Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 50680bbf52d3864a46cc629d3f74ff8f | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.AbstractSet;
import java.util.InputMismatchException;
import java.util.HashMap;
import java.util.function.ObjIntConsumer;
import java.util.function.Function;
import java.util.logging.Level;
import java.util.AbstractCollection;
import java.util.Map;
import java.io.OutputStreamWriter;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.io.BufferedWriter;
import java.util.Collection;
import java.util.Set;
import java.io.IOException;
import java.util.logging.Logger;
import java.io.Serializable;
import java.util.function.Consumer;
import java.util.List;
import java.io.Writer;
import java.util.Map.Entry;
import java.util.Spliterator;
import java.util.Collections;
import java.util.ConcurrentModificationException;
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);
DCyclicRotation solver = new DCyclicRotation();
solver.solve(1, in, out);
out.close();
}
static class DCyclicRotation {
static InputReader in = null;
static OutputWriter out = null;
public void solve(int testNumber, InputReader in, OutputWriter out) {
this.in = in;
this.out = out;
var tc = in.nextInt();
for (int i = 0; i < tc; i++) {
solution(i);
}
}
void solution(int testNumber) {
int n = in.nextInt();
int[] start = in.nextIntArray(n);
int[] target = in.nextIntArray(n);
Multiset<Integer> removed = HashMultiset.create();
int lastStart = n - 1;
int lastTarget = n - 1;
// compare lastStart and lastTarget
// 1 1 2 1
// 1 2 1 1
while (lastTarget > 0) {
if (start[lastStart] != target[lastTarget]) {
// check if we can remove lastStart.
if (removed.contains(start[lastStart])) {
removed.remove(start[lastStart]);
lastStart--;
} else {
out.println("NO");
return;
}
} else if (start[lastStart - 1] != target[lastTarget - 1]) {
removed.add(target[lastTarget]);
lastTarget--;
} else if (start[lastStart - 1] == target[lastTarget - 1]) {
lastTarget--;
lastStart--;
}
}
// 1 2 3 3 2
// 1 3 3 2
// 1 2 3
// 1
// removed = 2, 3, 1
// 1 3 3
// 1 2 3 3
// there are only one element left in target
removed.add(target[0]);
for (int i = 0; i <= lastStart; i++) {
if (removed.contains(start[i])) {
removed.remove(start[i]);
} else {
out.println("NO");
return;
}
}
out.println("YES");
return;
// removed = 1, 2
// 1 2 4
// 4
}
}
static abstract class AbstractMultiset<E> extends AbstractCollection<E> implements Multiset<E> {
private transient Set<E> elementSet;
private transient Set<Multiset.Entry<E>> entrySet;
public boolean isEmpty() {
return entrySet().isEmpty();
}
public boolean contains(Object element) {
return count(element) > 0;
}
public final boolean add(E element) {
add(element, 1);
return true;
}
public int add(E element, int occurrences) {
throw new UnsupportedOperationException();
}
public final boolean remove(Object element) {
return remove(element, 1) > 0;
}
public int remove(Object element, int occurrences) {
throw new UnsupportedOperationException();
}
public int setCount(E element, int count) {
return Multisets.setCountImpl(this, element, count);
}
public boolean setCount(E element, int oldCount, int newCount) {
return Multisets.setCountImpl(this, element, oldCount, newCount);
}
public final boolean addAll(Collection<? extends E> elementsToAdd) {
return Multisets.addAllImpl(this, elementsToAdd);
}
public final boolean removeAll(Collection<?> elementsToRemove) {
return Multisets.removeAllImpl(this, elementsToRemove);
}
public final boolean retainAll(Collection<?> elementsToRetain) {
return Multisets.retainAllImpl(this, elementsToRetain);
}
public abstract void clear();
public Set<E> elementSet() {
Set<E> result = elementSet;
if (result == null) {
elementSet = result = createElementSet();
}
return result;
}
Set<E> createElementSet() {
return new ElementSet();
}
abstract Iterator<E> elementIterator();
public Set<Multiset.Entry<E>> entrySet() {
Set<Multiset.Entry<E>> result = entrySet;
if (result == null) {
entrySet = result = createEntrySet();
}
return result;
}
Set<Multiset.Entry<E>> createEntrySet() {
return new EntrySet();
}
abstract Iterator<Multiset.Entry<E>> entryIterator();
abstract int distinctElements();
public final boolean equals(Object object) {
return Multisets.equalsImpl(this, object);
}
public final int hashCode() {
return entrySet().hashCode();
}
public final String toString() {
return entrySet().toString();
}
class ElementSet extends Multisets.ElementSet<E> {
Multiset<E> multiset() {
return AbstractMultiset.this;
}
public Iterator<E> iterator() {
return elementIterator();
}
}
class EntrySet extends Multisets.EntrySet<E> {
Multiset<E> multiset() {
return AbstractMultiset.this;
}
public Iterator<Multiset.Entry<E>> iterator() {
return entryIterator();
}
public int size() {
return distinctElements();
}
}
}
static final class Objects extends ExtraObjectsMethodsForWeb {
private Objects() {
}
public static boolean equal(Object a, Object b) {
return a == b || (a != null && a.equals(b));
}
}
static abstract class IntsMethodsForWeb {
}
static interface Multiset<E> extends Collection<E> {
int size();
int count(Object element);
int add(E element, int occurrences);
boolean add(E element);
int remove(Object element, int occurrences);
boolean remove(Object element);
int setCount(E element, int count);
boolean setCount(E element, int oldCount, int newCount);
Set<E> elementSet();
Set<Multiset.Entry<E>> entrySet();
default void forEachEntry(ObjIntConsumer<? super E> action) {
Preconditions.checkNotNull(action);
entrySet().forEach(entry -> action.accept(entry.getElement(), entry.getCount()));
}
boolean equals(Object object);
int hashCode();
String toString();
Iterator<E> iterator();
boolean contains(Object element);
boolean containsAll(Collection<?> elements);
boolean removeAll(Collection<?> c);
boolean retainAll(Collection<?> c);
default void forEach(Consumer<? super E> action) {
Preconditions.checkNotNull(action);
entrySet()
.forEach(
entry -> {
E elem = entry.getElement();
int count = entry.getCount();
for (int i = 0; i < count; i++) {
action.accept(elem);
}
});
}
default Spliterator<E> spliterator() {
return Multisets.spliteratorImpl(this);
}
interface Entry<E> {
E getElement();
int getCount();
boolean equals(Object o);
int hashCode();
String toString();
}
}
static final class CollectPreconditions {
static int checkNonnegative(int value, String name) {
if (value < 0) {
throw new IllegalArgumentException(name + " cannot be negative but was: " + value);
}
return value;
}
static void checkRemove(boolean canRemove) {
Preconditions.checkState(canRemove, "no calls to next() since the last call to remove()");
}
}
static final class Count implements Serializable {
private int value;
Count(int value) {
this.value = value;
}
public int get() {
return value;
}
public void add(int delta) {
value += delta;
}
public int addAndGet(int delta) {
return value += delta;
}
public void set(int newValue) {
value = newValue;
}
public int getAndSet(int newValue) {
int result = value;
value = newValue;
return result;
}
public int hashCode() {
return value;
}
public boolean equals(Object obj) {
return obj instanceof Count && ((Count) obj).value == value;
}
public String toString() {
return Integer.toString(value);
}
}
static final class Preconditions {
private Preconditions() {
}
public static void checkArgument(boolean expression) {
if (!expression) {
throw new IllegalArgumentException();
}
}
public static void checkArgument(boolean expression, Object errorMessage) {
if (!expression) {
throw new IllegalArgumentException(String.valueOf(errorMessage));
}
}
public static void checkArgument(boolean b, String errorMessageTemplate, int p1) {
if (!b) {
throw new IllegalArgumentException(Strings.lenientFormat(errorMessageTemplate, p1));
}
}
public static void checkArgument(boolean b, String errorMessageTemplate, long p1) {
if (!b) {
throw new IllegalArgumentException(Strings.lenientFormat(errorMessageTemplate, p1));
}
}
public static void checkState(boolean expression, Object errorMessage) {
if (!expression) {
throw new IllegalStateException(String.valueOf(errorMessage));
}
}
public static <T extends Object> T checkNotNull(T reference) {
if (reference == null) {
throw new NullPointerException();
}
return reference;
}
}
static abstract class ExtraObjectsMethodsForWeb {
}
static final class Iterators {
private Iterators() {
}
public static boolean removeAll(Iterator<?> removeFrom, Collection<?> elementsToRemove) {
Preconditions.checkNotNull(elementsToRemove);
boolean result = false;
while (removeFrom.hasNext()) {
if (elementsToRemove.contains(removeFrom.next())) {
removeFrom.remove();
result = true;
}
}
return result;
}
public static <T> boolean addAll(Collection<T> addTo, Iterator<? extends T> iterator) {
Preconditions.checkNotNull(addTo);
Preconditions.checkNotNull(iterator);
boolean wasModified = false;
while (iterator.hasNext()) {
wasModified |= addTo.add(iterator.next());
}
return wasModified;
}
}
static final class Sets {
private Sets() {
}
static boolean removeAllImpl(Set<?> set, Iterator<?> iterator) {
boolean changed = false;
while (iterator.hasNext()) {
changed |= set.remove(iterator.next());
}
return changed;
}
static boolean removeAllImpl(Set<?> set, Collection<?> collection) {
Preconditions.checkNotNull(collection); // for GWT
if (collection instanceof Multiset) {
collection = ((Multiset<?>) collection).elementSet();
}
/*
* AbstractSet.removeAll(List) has quadratic behavior if the list size
* is just more than the set's size. We augment the test by
* assuming that sets have fast contains() performance, and other
* collections don't. See
* http://code.google.com/p/guava-libraries/issues/detail?id=1013
*/
if (collection instanceof Set && collection.size() > set.size()) {
return Iterators.removeAll(set.iterator(), collection);
} else {
return removeAllImpl(set, collection.iterator());
}
}
abstract static class ImprovedAbstractSet<E> extends AbstractSet<E> {
public boolean removeAll(Collection<?> c) {
return removeAllImpl(this, c);
}
public boolean retainAll(Collection<?> c) {
return super.retainAll(Preconditions.checkNotNull(c)); // GWT compatibility
}
}
}
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 int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; ++i) array[i] = nextInt();
return array;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static final class CollectSpliterators {
private CollectSpliterators() {
}
static <InElementT, OutElementT> Spliterator<OutElementT> flatMap(
Spliterator<InElementT> fromSpliterator,
Function<? super InElementT, Spliterator<OutElementT>> function,
int topCharacteristics,
long topSize) {
Preconditions.checkArgument(
(topCharacteristics & Spliterator.SUBSIZED) == 0,
"flatMap does not support SUBSIZED characteristic");
Preconditions.checkArgument(
(topCharacteristics & Spliterator.SORTED) == 0,
"flatMap does not support SORTED characteristic");
Preconditions.checkNotNull(fromSpliterator);
Preconditions.checkNotNull(function);
return new CollectSpliterators.FlatMapSpliteratorOfObject<InElementT, OutElementT>(
null, fromSpliterator, function, topCharacteristics, topSize);
}
abstract static class FlatMapSpliterator<
InElementT, OutElementT, OutSpliteratorT extends Spliterator<OutElementT>> implements Spliterator<OutElementT> {
OutSpliteratorT prefix;
final Spliterator<InElementT> from;
final Function<? super InElementT, OutSpliteratorT> function;
final CollectSpliterators.FlatMapSpliterator.Factory<InElementT, OutSpliteratorT> factory;
int characteristics;
long estimatedSize;
FlatMapSpliterator(
OutSpliteratorT prefix,
Spliterator<InElementT> from,
Function<? super InElementT, OutSpliteratorT> function,
CollectSpliterators.FlatMapSpliterator.Factory<InElementT, OutSpliteratorT> factory,
int characteristics,
long estimatedSize) {
this.prefix = prefix;
this.from = from;
this.function = function;
this.factory = factory;
this.characteristics = characteristics;
this.estimatedSize = estimatedSize;
}
public final boolean tryAdvance(Consumer<? super OutElementT> action) {
while (true) {
if (prefix != null && prefix.tryAdvance(action)) {
if (estimatedSize != Long.MAX_VALUE) {
estimatedSize--;
}
return true;
} else {
prefix = null;
}
if (!from.tryAdvance(fromElement -> prefix = function.apply(fromElement))) {
return false;
}
}
}
public final void forEachRemaining(Consumer<? super OutElementT> action) {
if (prefix != null) {
prefix.forEachRemaining(action);
prefix = null;
}
from.forEachRemaining(
fromElement -> {
Spliterator<OutElementT> elements = function.apply(fromElement);
if (elements != null) {
elements.forEachRemaining(action);
}
});
estimatedSize = 0;
}
public final OutSpliteratorT trySplit() {
Spliterator<InElementT> fromSplit = from.trySplit();
if (fromSplit != null) {
int splitCharacteristics = characteristics & ~Spliterator.SIZED;
long estSplitSize = estimateSize();
if (estSplitSize < Long.MAX_VALUE) {
estSplitSize /= 2;
this.estimatedSize -= estSplitSize;
this.characteristics = splitCharacteristics;
}
OutSpliteratorT result =
factory.newFlatMapSpliterator(
this.prefix, fromSplit, function, splitCharacteristics, estSplitSize);
this.prefix = null;
return result;
} else if (prefix != null) {
OutSpliteratorT result = prefix;
this.prefix = null;
return result;
} else {
return null;
}
}
public final long estimateSize() {
if (prefix != null) {
estimatedSize = Math.max(estimatedSize, prefix.estimateSize());
}
return Math.max(estimatedSize, 0);
}
public final int characteristics() {
return characteristics;
}
interface Factory<InElementT, OutSpliteratorT extends Spliterator<?>> {
OutSpliteratorT newFlatMapSpliterator(
OutSpliteratorT prefix,
Spliterator<InElementT> fromSplit,
Function<? super InElementT, OutSpliteratorT> function,
int splitCharacteristics,
long estSplitSize);
}
}
static final class FlatMapSpliteratorOfObject<InElementT, OutElementT> extends CollectSpliterators.FlatMapSpliterator<InElementT, OutElementT, Spliterator<OutElementT>> {
FlatMapSpliteratorOfObject(
Spliterator<OutElementT> prefix,
Spliterator<InElementT> from,
Function<? super InElementT, Spliterator<OutElementT>> function,
int characteristics,
long estimatedSize) {
super(
prefix, from, function, CollectSpliterators.FlatMapSpliteratorOfObject::new, characteristics, estimatedSize);
}
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
static final class Strings {
private Strings() {
}
public static String lenientFormat(
String template, Object... args) {
template = String.valueOf(template); // null -> "null"
if (args == null) {
args = new Object[]{"(Object[])null"};
} else {
for (int i = 0; i < args.length; i++) {
args[i] = lenientToString(args[i]);
}
}
// start substituting the arguments into the '%s' placeholders
StringBuilder builder = new StringBuilder(template.length() + 16 * args.length);
int templateStart = 0;
int i = 0;
while (i < args.length) {
int placeholderStart = template.indexOf("%s", templateStart);
if (placeholderStart == -1) {
break;
}
builder.append(template, templateStart, placeholderStart);
builder.append(args[i++]);
templateStart = placeholderStart + 2;
}
builder.append(template, templateStart, template.length());
// if we run out of placeholders, append the extra args in square braces
if (i < args.length) {
builder.append(" [");
builder.append(args[i++]);
while (i < args.length) {
builder.append(", ");
builder.append(args[i++]);
}
builder.append(']');
}
return builder.toString();
}
private static String lenientToString(Object o) {
if (o == null) {
return "null";
}
try {
return o.toString();
} catch (Exception e) {
// Default toString() behavior - see Object.toString()
String objectToString =
o.getClass().getName() + '@' + Integer.toHexString(System.identityHashCode(o));
// Logger is created inline with fixed name to avoid forcing Proguard to create another class.
Logger.getLogger("com.google.common.base.Strings")
.log(Level.WARNING, "Exception during lenientFormat for " + objectToString, e);
return "<" + objectToString + " threw " + e.getClass().getName() + ">";
}
}
}
static final class Multisets {
private Multisets() {
}
static boolean equalsImpl(Multiset<?> multiset, Object object) {
if (object == multiset) {
return true;
}
if (object instanceof Multiset) {
Multiset<?> that = (Multiset<?>) object;
/*
* We can't simply check whether the entry sets are equal, since that
* approach fails when a TreeMultiset has a comparator that returns 0
* when passed unequal elements.
*/
if (multiset.size() != that.size() || multiset.entrySet().size() != that.entrySet().size()) {
return false;
}
for (Multiset.Entry<?> entry : that.entrySet()) {
if (multiset.count(entry.getElement()) != entry.getCount()) {
return false;
}
}
return true;
}
return false;
}
static <E> boolean addAllImpl(Multiset<E> self, Collection<? extends E> elements) {
Preconditions.checkNotNull(self);
Preconditions.checkNotNull(elements);
if (elements instanceof Multiset) {
return addAllImpl(self, cast(elements));
} else if (elements.isEmpty()) {
return false;
} else {
return Iterators.addAll(self, elements.iterator());
}
}
private static <E> boolean addAllImpl(Multiset<E> self, Multiset<? extends E> elements) {
if (elements.isEmpty()) {
return false;
}
elements.forEachEntry(self::add);
return true;
}
static boolean removeAllImpl(Multiset<?> self, Collection<?> elementsToRemove) {
Collection<?> collection =
(elementsToRemove instanceof Multiset)
? ((Multiset<?>) elementsToRemove).elementSet()
: elementsToRemove;
return self.elementSet().removeAll(collection);
}
static boolean retainAllImpl(Multiset<?> self, Collection<?> elementsToRetain) {
Preconditions.checkNotNull(elementsToRetain);
Collection<?> collection =
(elementsToRetain instanceof Multiset)
? ((Multiset<?>) elementsToRetain).elementSet()
: elementsToRetain;
return self.elementSet().retainAll(collection);
}
static <E> int setCountImpl(Multiset<E> self, E element, int count) {
CollectPreconditions.checkNonnegative(count, "count");
int oldCount = self.count(element);
int delta = count - oldCount;
if (delta > 0) {
self.add(element, delta);
} else if (delta < 0) {
self.remove(element, -delta);
}
return oldCount;
}
static <E> boolean setCountImpl(Multiset<E> self, E element, int oldCount, int newCount) {
CollectPreconditions.checkNonnegative(oldCount, "oldCount");
CollectPreconditions.checkNonnegative(newCount, "newCount");
if (self.count(element) == oldCount) {
self.setCount(element, newCount);
return true;
} else {
return false;
}
}
static <E> Spliterator<E> spliteratorImpl(Multiset<E> multiset) {
Spliterator<Multiset.Entry<E>> entrySpliterator = multiset.entrySet().spliterator();
return CollectSpliterators.flatMap(
entrySpliterator,
entry -> Collections.nCopies(entry.getCount(), entry.getElement()).spliterator(),
Spliterator.SIZED
| (entrySpliterator.characteristics()
& (Spliterator.ORDERED | Spliterator.NONNULL | Spliterator.IMMUTABLE)),
multiset.size());
}
static <T> Multiset<T> cast(Iterable<T> iterable) {
return (Multiset<T>) iterable;
}
abstract static class AbstractEntry<E> implements Multiset.Entry<E> {
public boolean equals(Object object) {
if (object instanceof Multiset.Entry) {
Multiset.Entry<?> that = (Multiset.Entry<?>) object;
return this.getCount() == that.getCount()
&& Objects.equal(this.getElement(), that.getElement());
}
return false;
}
public int hashCode() {
E e = getElement();
return ((e == null) ? 0 : e.hashCode()) ^ getCount();
}
public String toString() {
String text = String.valueOf(getElement());
int n = getCount();
return (n == 1) ? text : (text + " x " + n);
}
}
abstract static class ElementSet<E> extends Sets.ImprovedAbstractSet<E> {
abstract Multiset<E> multiset();
public void clear() {
multiset().clear();
}
public boolean contains(Object o) {
return multiset().contains(o);
}
public boolean containsAll(Collection<?> c) {
return multiset().containsAll(c);
}
public boolean isEmpty() {
return multiset().isEmpty();
}
public abstract Iterator<E> iterator();
public boolean remove(Object o) {
return multiset().remove(o, Integer.MAX_VALUE) > 0;
}
public int size() {
return multiset().entrySet().size();
}
}
abstract static class EntrySet<E> extends Sets.ImprovedAbstractSet<Multiset.Entry<E>> {
abstract Multiset<E> multiset();
public boolean contains(Object o) {
if (o instanceof Multiset.Entry) {
/*
* The GWT compiler wrongly issues a warning here.
*/
Multiset.Entry<?> entry = (Multiset.Entry<?>) o;
if (entry.getCount() <= 0) {
return false;
}
int count = multiset().count(entry.getElement());
return count == entry.getCount();
}
return false;
}
public boolean remove(Object object) {
if (object instanceof Multiset.Entry) {
Multiset.Entry<?> entry = (Multiset.Entry<?>) object;
Object element = entry.getElement();
int entryCount = entry.getCount();
if (entryCount != 0) {
// Safe as long as we never add a new entry, which we won't.
Multiset<Object> multiset = (Multiset<Object>) multiset();
return multiset.setCount(element, entryCount, 0);
}
}
return false;
}
public void clear() {
multiset().clear();
}
}
}
static final class Ints extends IntsMethodsForWeb {
public static final int MAX_POWER_OF_TWO = 1 << (Integer.SIZE - 2);
private Ints() {
}
public static int saturatedCast(long value) {
if (value > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
}
if (value < Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}
return (int) value;
}
}
static final class Maps {
private Maps() {
}
public static <K, V> HashMap<K, V> newHashMapWithExpectedSize(int expectedSize) {
return new HashMap<>(capacity(expectedSize));
}
static int capacity(int expectedSize) {
if (expectedSize < 3) {
CollectPreconditions.checkNonnegative(expectedSize, "expectedSize");
return expectedSize + 1;
}
if (expectedSize < Ints.MAX_POWER_OF_TWO) {
// This is the calculation used in JDK8 to resize when a putAll
// happens; it seems to be the most conservative calculation we
// can make. 0.75 is the default load factor.
return (int) ((float) expectedSize / 0.75F + 1.0F);
}
return Integer.MAX_VALUE; // any large value
}
static <V> V safeGet(Map<?, V> map, Object key) {
Preconditions.checkNotNull(map);
try {
return map.get(key);
} catch (ClassCastException | NullPointerException e) {
return null;
}
}
}
static final class HashMultiset<E> extends AbstractMapBasedMultiset<E> {
public static <E> HashMultiset<E> create() {
return new HashMultiset<E>();
}
private HashMultiset() {
super(new HashMap<E, Count>());
}
private HashMultiset(int distinctElements) {
super(Maps.<E, Count>newHashMapWithExpectedSize(distinctElements));
}
}
static abstract class AbstractMapBasedMultiset<E> extends AbstractMultiset<E> implements Serializable {
private transient Map<E, Count> backingMap;
private transient long size;
protected AbstractMapBasedMultiset(Map<E, Count> backingMap) {
Preconditions.checkArgument(backingMap.isEmpty());
this.backingMap = backingMap;
}
public Set<Multiset.Entry<E>> entrySet() {
return super.entrySet();
}
Iterator<E> elementIterator() {
final Iterator<Map.Entry<E, Count>> backingEntries = backingMap.entrySet().iterator();
return new Iterator<E>() {
Map.Entry<E, Count> toRemove;
public boolean hasNext() {
return backingEntries.hasNext();
}
public E next() {
final Map.Entry<E, Count> mapEntry = backingEntries.next();
toRemove = mapEntry;
return mapEntry.getKey();
}
public void remove() {
CollectPreconditions.checkRemove(toRemove != null);
size -= toRemove.getValue().getAndSet(0);
backingEntries.remove();
toRemove = null;
}
};
}
Iterator<Multiset.Entry<E>> entryIterator() {
final Iterator<Map.Entry<E, Count>> backingEntries = backingMap.entrySet().iterator();
return new Iterator<Multiset.Entry<E>>() {
Map.Entry<E, Count> toRemove;
public boolean hasNext() {
return backingEntries.hasNext();
}
public Multiset.Entry<E> next() {
final Map.Entry<E, Count> mapEntry = backingEntries.next();
toRemove = mapEntry;
return new Multisets.AbstractEntry<E>() {
public E getElement() {
return mapEntry.getKey();
}
public int getCount() {
Count count = mapEntry.getValue();
if (count == null || count.get() == 0) {
Count frequency = backingMap.get(getElement());
if (frequency != null) {
return frequency.get();
}
}
return (count == null) ? 0 : count.get();
}
};
}
public void remove() {
CollectPreconditions.checkRemove(toRemove != null);
size -= toRemove.getValue().getAndSet(0);
backingEntries.remove();
toRemove = null;
}
};
}
public void forEachEntry(ObjIntConsumer<? super E> action) {
Preconditions.checkNotNull(action);
backingMap.forEach((element, count) -> action.accept(element, count.get()));
}
public void clear() {
for (Count frequency : backingMap.values()) {
frequency.set(0);
}
backingMap.clear();
size = 0L;
}
int distinctElements() {
return backingMap.size();
}
public int size() {
return Ints.saturatedCast(size);
}
public Iterator<E> iterator() {
return new MapBasedMultisetIterator();
}
public int count(Object element) {
Count frequency = Maps.safeGet(backingMap, element);
return (frequency == null) ? 0 : frequency.get();
}
public int add(E element, int occurrences) {
if (occurrences == 0) {
return count(element);
}
Preconditions.checkArgument(occurrences > 0, "occurrences cannot be negative: %s", occurrences);
Count frequency = backingMap.get(element);
int oldCount;
if (frequency == null) {
oldCount = 0;
backingMap.put(element, new Count(occurrences));
} else {
oldCount = frequency.get();
long newCount = (long) oldCount + (long) occurrences;
Preconditions.checkArgument(newCount <= Integer.MAX_VALUE, "too many occurrences: %s", newCount);
frequency.add(occurrences);
}
size += occurrences;
return oldCount;
}
public int remove(Object element, int occurrences) {
if (occurrences == 0) {
return count(element);
}
Preconditions.checkArgument(occurrences > 0, "occurrences cannot be negative: %s", occurrences);
Count frequency = backingMap.get(element);
if (frequency == null) {
return 0;
}
int oldCount = frequency.get();
int numberRemoved;
if (oldCount > occurrences) {
numberRemoved = occurrences;
} else {
numberRemoved = oldCount;
backingMap.remove(element);
}
frequency.add(-numberRemoved);
size -= numberRemoved;
return oldCount;
}
public int setCount(E element, int count) {
CollectPreconditions.checkNonnegative(count, "count");
Count existingCounter;
int oldCount;
if (count == 0) {
existingCounter = backingMap.remove(element);
oldCount = getAndSet(existingCounter, count);
} else {
existingCounter = backingMap.get(element);
oldCount = getAndSet(existingCounter, count);
if (existingCounter == null) {
backingMap.put(element, new Count(count));
}
}
size += (count - oldCount);
return oldCount;
}
private static int getAndSet(Count i, int count) {
if (i == null) {
return 0;
}
return i.getAndSet(count);
}
private class MapBasedMultisetIterator implements Iterator<E> {
final Iterator<Map.Entry<E, Count>> entryIterator;
Map.Entry<E, Count> currentEntry;
int occurrencesLeft;
boolean canRemove;
MapBasedMultisetIterator() {
this.entryIterator = backingMap.entrySet().iterator();
}
public boolean hasNext() {
return occurrencesLeft > 0 || entryIterator.hasNext();
}
public E next() {
if (occurrencesLeft == 0) {
currentEntry = entryIterator.next();
occurrencesLeft = currentEntry.getValue().get();
}
occurrencesLeft--;
canRemove = true;
return currentEntry.getKey();
}
public void remove() {
CollectPreconditions.checkRemove(canRemove);
int frequency = currentEntry.getValue().get();
if (frequency <= 0) {
throw new ConcurrentModificationException();
}
if (currentEntry.getValue().addAndGet(-1) == 0) {
entryIterator.remove();
}
size--;
canRemove = false;
}
}
}
}
| Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 9560fcf8e13fd864cb92b97e87f2a8ae | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
// Created by @thesupremeone on 4/23/22
public class D {
void solve() {
int ts = getInt();
for (int t = 0; t < ts; t++) {
int n = getInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = getInt();
}
int[] b = new int[n];
TreeMap<Integer, TreeSet<Integer>> map = new TreeMap<>();
for (int i = 0; i < n; i++) {
b[i] = getInt();
if(i==0) continue;
if(b[i]==b[i-1]){
TreeSet<Integer> set;
if(map.containsKey(b[i])){
set = map.get(b[i]);
}else {
set = new TreeSet<>();
map.put(b[i], set);
}
set.add(i);
}
}
int upper = n-1;
int j = 0;
boolean ans = true;
TreeSet<Integer> skip = new TreeSet<>();
for (int i = 0; i < n; i++) {
while (skip.contains(j)) j++;
if(a[i]==b[j]){
j++;
continue;
}
TreeSet<Integer> set = map.getOrDefault(a[i], null);
Integer next;
if(set==null || (next=set.ceiling(j))==null){
ans = false;
break;
}
set.remove(next);
skip.add(next);
}
println(ans?"YES":"NO");
}
}
public static void main(String[] args) throws Exception {
if (isOnlineJudge()) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new BufferedWriter(new OutputStreamWriter(System.out));
new D().solve();
out.flush();
} else {
localJudge = new Thread();
in = new BufferedReader(new FileReader("input.txt"));
out = new BufferedWriter(new FileWriter("output.txt"));
localJudge.start();
new D().solve();
out.flush();
localJudge.suspend();
}
}
static boolean isOnlineJudge() {
try {
return System.getProperty("ONLINE_JUDGE") != null
|| System.getProperty("LOCAL") == null;
} catch (Exception e) {
return true;
}
}
// Fast Input & Output
static Thread localJudge = null;
static BufferedReader in;
static StringTokenizer st;
static BufferedWriter out;
static String getLine() {
try {
return in.readLine();
} catch (Exception ignored) {
return "";
}
}
static String getToken() {
if (st == null || !st.hasMoreTokens())
st = new StringTokenizer(getLine());
return st.nextToken();
}
static int getInt() {
return Integer.parseInt(getToken());
}
static long getLong() {
return Long.parseLong(getToken());
}
static void print(Object s) {
try {
out.write(String.valueOf(s));
} catch (Exception ignored) {
}
}
static void println(Object s) {
try {
out.write(String.valueOf(s));
out.newLine();
} catch (Exception ignored) {
}
}
} | Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 7475e5676eef407de064d0ae3727d6ef | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | /* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Test
{
final static FastReader fr = new FastReader();
final static PrintWriter out = new PrintWriter(System.out) ;
static long mod = (long)1e9 + 7;
static int[] dp ;
static void solve()
{
int n = fr.nextInt();
int[] arr = new int[n] ;
int[] brr = new int[n] ;
for (int i = 0 ; i < n ; i++) arr[i] = fr.nextInt();
for (int i = 0 ; i < n ; i++) brr[i] = fr.nextInt() ;
HashMap<Integer, Integer> last = new HashMap<>() ;
HashMap<Integer, Integer> freq = new HashMap<>() ;
for (int i = 0 ; i < n ; i++)
{
last.put(arr[i], i) ;
freq.put(arr[i], freq.getOrDefault(arr[i], 0)+1);
}
HashMap<Integer, Integer> visited = new HashMap<>() ;
int j = 0 ;
for (int i = 0 ; j < n; i++)
{
if (i < n && arr[i] == brr[j]) {
j++ ;
continue;
}
if (i > 0 && brr[j] == arr[i-1]){
if (visited.containsKey(brr[j]) && visited.get(brr[j]) > 0) {
visited.put(brr[j], visited.getOrDefault(brr[j], 0)-1) ;
if (visited.get(brr[j]) <= 0) {
visited.remove(brr[j]) ;
}
j++ ;
i-- ;
continue;
}
}
if (i >= n) break;
int curr = arr[i] ;
if (last.get(curr) > i){
visited.put(curr, visited.getOrDefault(curr, 0)+1) ;
}
}
if (visited.isEmpty() && j == n) out.println("YES");
else out.println("NO");
}
public static void main(String[] args)
{
int t = 1 ;
t = fr.nextInt() ;
while (t-- > 0)
{
solve() ;
}
out.close() ;
}
static long getMax(long ... a)
{
long max = Long.MIN_VALUE ;
for (long x : a) max = Math.max(x, max) ;
return max ;
}
static long getMin(long ... a)
{
long max = Long.MAX_VALUE ;
for (long x : a) max = Math.min(x, max) ;
return max ;
}
static long fastPower(double a, long b)
{
double ans = 1 ;
while (b > 0)
{
if ((b & 1) != 0) ans *= a ;
a *= a ;
b >>= 1 ;
}
return (long)(ans + 0.5) ;
}
static long fastPower(long a, long b, long mod)
{
long ans = 1 ;
while (b > 0)
{
if ((b&1) != 0) ans = (ans%mod * a%mod) %mod;
b >>= 1 ;
a = (a%mod * a%mod)%mod ;
}
return ans ;
}
static int lower_bound(List<Integer> arr, int key)
{
int pos = Collections.binarySearch(arr, key) ;
if (pos < 0)
{
pos = - (pos + 1) ;
}
return pos ;
}
static int upper_bound(List<Integer> arr, int key)
{
int pos = Collections.binarySearch(arr, key);
pos++ ;
if (pos < 0)
{
pos = -(pos) ;
}
return pos ;
}
static int upper_bound(int arr[], int key)
{
int start = 0 , end = arr.length ;
while (start < end)
{
int mid = start + ((end - start) >> 1) ;
if (arr[mid] <= key) start = mid + 1 ;
else end = mid ;
}
return start ;
}
static int lower_bound(int[] arr, int key)
{
int start = 0 , end = arr.length -1;
int ans = -1 ;
while (start <= end)
{
int mid = start + ((end - start )>>1) ;
if (arr[mid] == key) {
ans = mid ;
}
if (arr[mid] >= key){
end = mid - 1 ;
}
else start = mid + 1 ;
}
return ans ;
}
static class Pair{
long x;
long y ;
Pair(long x, long y){
this.x = x ;
this.y= y ;
}
}
static long gcd(long a, long b)
{
if (b == 0) return a ;
return gcd(b, a%b) ;
}
static long lcm(long a, long b)
{
long lcm = (a * b)/gcd(a, b) ;
return lcm ;
}
static List<Long> seive(int n)
{
// all are false by default
// false -> prime, true -> composite
boolean[] nums = new boolean[n+1] ;
for (int i = 2 ; i <= Math.sqrt(n); i++)
{
if (!nums[i])
{
for (int j = i*i ; j <= n ; j += i)
{
nums[j] = true ;
}
}
}
ArrayList<Long>primes = new ArrayList<>() ;
for (int i = 2 ; i <=n ; i++)
{
if (!nums[i]) primes.add((long) i) ;
}
return primes ;
}
static boolean isVowel(char ch)
{
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
return true ;
return false ;
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 6928664acb30825028fbd6800936b250 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | // Generated by Code Flattener.
// https://plugins.jetbrains.com/plugin/9979-idea-code-flattener
import java.io.*;
import java.util.StringTokenizer;
public class Main {
public void solve(FastReader in, FastWriter out) {
int n = in.nextInt();
int[] a = in.nextInts(n);
int[] b = in.nextInts(n);
int[] c = new int[n + 1];
int ai = 0;
for (int bi = 0; bi < n; bi++) {
int be = b[bi];
if (bi > 0 && b[bi - 1] == be && c[be] > 0) {
c[be]--;
continue;
}
if (ai == n) {
out.println("NO");
return;
}
while (be != a[ai]) {
c[a[ai++]]++;
if (ai == n) {
out.println("NO");
return;
}
}
ai++;
}
out.println("YES");
}
public static void main(String[] args) {
Main main = new Main();
boolean onlineJudge = System.getProperty("ONLINE_JUDGE") != null;
Problem.Builder builder = Problem
.builder()
.solution(main::solve)
.multiTest(true);
if (onlineJudge) {
builder.io(StreamPair.standard());
} else {
builder.io(StreamPair.debug(main.getClass()));
}
builder.build().execute();
}
private static class Problem {
private final Executable solution;
private final Executable init;
private final boolean multiTest;
private final InputStream inputStream;
private final OutputStream outputStream;
public Problem(Executable solution, Executable init, boolean multiTest,
InputStream inputStream, OutputStream outputStream) {
this.solution = solution;
this.init = init;
this.multiTest = multiTest;
this.inputStream = inputStream;
this.outputStream = outputStream;
}
public void execute() {
if (solution == null) {
throw new RuntimeException("please, set solution");
}
FastReader in = new FastReader(inputStream);
FastWriter out = new FastWriter(outputStream);
if (init != null) {
init.run(in, out);
}
if (!multiTest) {
solution.run(in, out);
} else {
int times = in.nextInt();
for (int i = 0; i < times; i++) {
solution.run(in, out);
}
}
out.close();
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
private Executable solution;
private Executable init;
private boolean multiTest;
private InputStream inputStream;
private OutputStream outputStream;
private Builder() {
}
public Builder solution(Executable solution) {
this.solution = solution;
return Builder.this;
}
public Builder init(Executable init) {
this.init = init;
return Builder.this;
}
public Builder multiTest(boolean multiTest) {
this.multiTest = multiTest;
return Builder.this;
}
public Builder io(StreamPair pair) {
this.inputStream = pair.getInputStream();
this.outputStream = pair.getOutputStream();
return Builder.this;
}
public Problem build() {
return new Problem(solution, init, multiTest, inputStream, outputStream);
}
}
}
private static class FastReader {
private final BufferedReader br;
private StringTokenizer st;
public FastReader(InputStream inputStream) {
br = new BufferedReader(new InputStreamReader(inputStream));
}
public String next() {
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(nextLine());
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public int[] nextInts(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
public String nextLine() {
try {
String line = br.readLine();
if (line == null) {
throw new RuntimeException("empty line");
}
st = null;
return line;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
private static class FastWriter {
final private PrintWriter printWriter;
public FastWriter(OutputStream outputStream) {
printWriter = new PrintWriter(new OutputStreamWriter(outputStream));
}
public void println(String s) {
printWriter.println(s);
}
public void close() {
printWriter.close();
}
}
private static class StreamPair {
private final InputStream inputStream;
private final OutputStream outputStream;
public StreamPair(InputStream inputStream, OutputStream outputStream) {
this.inputStream = inputStream;
this.outputStream = outputStream;
}
public static StreamPair standard() {
return new StreamPair(System.in, System.out);
}
public static StreamPair debug(Class resourceClass) {
try {
File file = new File(resourceClass.getClassLoader().getResource("input.txt").getFile());
return new StreamPair(new FileInputStream(file), System.out);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
public InputStream getInputStream() {
return inputStream;
}
public OutputStream getOutputStream() {
return outputStream;
}
}
private interface Executable {
void run(FastReader in, FastWriter out);
}
} | Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 6ba8888c131fcae3c4f5d2cde30228a0 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.FileNotFoundException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
DTsiklicheskiiSdvig solver = new DTsiklicheskiiSdvig();
int testCount = Integer.parseInt(in.next());
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
static class DTsiklicheskiiSdvig {
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int n = in.nextInt();
int[] a = in.nextIntArray(n);
int[] b = in.nextIntArray(n);
if (a[n - 1] != b[n - 1]) {
out.println("NO");
return;
}
int posA = n - 2;
int posB = n - 2;
int[] needSkip = new int[n + 1];
while (posA >= 0 || posB >= 0) {
if (posA >= 0 && posB >= 0 && a[posA] == b[posB]) {
posA--;
posB--;
continue;
}
if (posB >= 0 && b[posB] == b[posB + 1]) {
needSkip[b[posB]]++;
posB--;
continue;
}
if (posA >= 0 && needSkip[a[posA]] > 0) {
needSkip[a[posA]]--;
posA--;
continue;
}
out.println("NO");
return;
}
out.println("YES");
}
}
static class FastScanner {
public BufferedReader br;
public StringTokenizer st;
public FastScanner(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
}
public FastScanner(String fileName) {
try {
br = new BufferedReader(new FileReader(fileName));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public String next() {
while (st == null || !st.hasMoreElements()) {
String line = null;
try {
line = br.readLine();
} catch (IOException e) {
throw new UnknownError();
}
if (line == null) {
throw new UnknownError();
}
st = new StringTokenizer(line);
}
return st.nextToken();
}
public int[] nextIntArray(int n) {
int[] ret = new int[n];
for (int i = 0; i < n; i++) {
ret[i] = nextInt();
}
return ret;
}
}
}
| Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 90cc14d1f306cac0948425a18883c78d | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.*;
import java.util.*;
public class CF1672D extends PrintWriter {
CF1672D() { super(System.out); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF1672D o = new CF1672D(); o.main(); o.flush();
}
void main() {
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
int[] aa = new int[n];
for (int i = 0; i < n; i++)
aa[i] = sc.nextInt();
int[] bb = new int[n];
for (int i = 0; i < n; i++)
bb[i] = sc.nextInt();
int[] kk = new int[n + 1];
boolean yes = true;
out:
for (int i = n - 1, j = n - 1; j >= 0; ) {
int a = aa[i];
int b = bb[j];
if (a != b) {
if (kk[a] > 0) {
kk[a]--;
i--;
continue;
}
yes = false;
break;
}
// a == b
while (j > 0 && bb[j - 1] == b) {
if (i > 0 && aa[i - 1] == a)
i--;
else
kk[a]++;
j--;
}
i--; j--;
}
println(yes ? "YES" : "NO");
}
}
}
| Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 64520632ce18d72bbf6279ae9da0c0e2 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.System.exit;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class D {
static void solve() throws Exception {
int tests = scanInt();
test: for (int test = 0; test < tests; test++) {
int n = scanInt(), a[] = new int[n], b[] = new int[n], moves[] = new int[n + 1];
for (int i = 0; i < n; i++) {
a[i] = scanInt();
}
for (int i = 0; i < n; i++) {
b[i] = scanInt();
}
int pos = 0;
for (int i = 0; i < n; i++) {
int cur = b[i];
if (i > 0 && cur == b[i - 1] && moves[cur] > 0) {
--moves[cur];
} else {
while (pos < n && a[pos] != cur) {
++moves[a[pos]];
++pos;
}
if (pos == n) {
out.println("NO");
continue test;
}
++pos;
}
}
out.println("YES");
}
}
static int scanInt() throws IOException {
return parseInt(scanString());
}
static long scanLong() throws IOException {
return parseLong(scanString());
}
static String scanString() throws IOException {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
static BufferedReader in;
static PrintWriter out;
static StringTokenizer tok;
public static void main(String[] args) {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
in.close();
out.close();
} catch (Throwable e) {
e.printStackTrace();
exit(1);
}
}
} | Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 28bab3e866c8e73c487232315160c927 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
static FastReader sc=new FastReader();
static PrintWriter out=new PrintWriter(System.out);
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 ArrayList<ArrayList<Integer>> graph;
static long fact[];
static pair seg[];
static int dp[][];
// static long dp[][];
public static void main (String[] args) throws java.lang.Exception
{
// code goes here
int t=I();
int f[]=new int[(int)(2e5)+1];
outer:while(t-->0)
{
int n=I();
int a[]=I(n);
int b[]=I(n);
// for(int i=0;i<n;i++){
// f[a[i]]++;
// }
int in=n-1;
int p=0;
HashSet<Integer> hs=new HashSet<>();
for(int i=n-1;i>=0;){
if(in>=0 && a[in]==b[i]){
// f[b[i]]--;
hs.add(b[i]);
i--;
in--;
}else{
if(i<n-1 && b[i]==b[i+1]){
int j=i;
while(j>=0 && b[j]==b[i]){
f[b[i]]++;
j--;
}
if(i==j)i--;
else i=j;
continue;
}
if(in>=0 && hs.contains(a[in]) && f[a[in]]>0){
f[a[in]]--;
in--;
}else{
p=1;
break;
}
}
}
for(int i=0;i<n;i++){
f[a[i]]=0;
}
if(p==1)out.println("NO");
else out.println("YES");
}
out.close();
}
public static class pair
{
long a;
long b;
public pair(long aa,long 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.a==p2.a)
// return 0;
// else if(p1.a<p2.a)
// return 1;
// else
// return -1;
// }
}
public static void DFS(int s,boolean visited[])
{
visited[s]=true;
for(int i:graph[s]){
if(!visited[i]){
DFS(i,visited);
}
}
}
public static void setGraph(int n,int m)
{
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(long arr[],long X,int start, int end) //start=0,end=n-1
{
if(start>end)return -1;
if(arr[arr.length-1]<X)return end;
if(arr[0]>X)return -1;
int left=start,right=end;
while(left<right){
int mid=(left+right)/2;
// if(arr[mid]==X){ //Returns last index of lower bound value.
// if(mid<end && arr[mid+1]==X){
// left=mid+1;
// }else{
// return mid;
// }
// }
if(arr[mid]==X){ //Returns first index of lower bound value.
if(mid>start && arr[mid-1]==X){
right=mid-1;
}else{
return mid;
}
}
else if(arr[mid]>X){
if(mid>start && arr[mid-1]<X){
return mid-1;
}else{
right=mid-1;
}
}else{
if(mid<end && arr[mid+1]>X){
return mid;
}else{
left=mid+1;
}
}
}
return left;
}
//It returns answer according to zero based indexing.
public static int upper_bound(long arr[],long X,int start,int end) //start=0,end=n-1
{
if(arr[0]>=X)return start;
if(arr[arr.length-1]<X)return -1;
int left=start,right=end;
while(left<right){
int mid=(left+right)/2;
if(arr[mid]==X){ //returns first index of upper bound value.
if(mid>start && arr[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[mid]>X){
if(mid>start && arr[mid-1]<X){
return mid;
}else{
right=mid-1;
}
}else{
if(mid<end && arr[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=a[ss];
seg[si].b=1;
return;
}
int mid=(ss+se)/2;
buildTree(a,2*si+1,ss,mid);
buildTree(a,2*si+2,mid+1,se);
long p=seg[2*si+1].a,q=seg[2*si+2].a;
seg[si].a=min(p,q);
if(p==q){
seg[si].b=seg[2*si+1].b+seg[2*si+2].b;
}else{
if(p>q){
seg[si].b=seg[2*si+2].b;
}else{
seg[si].b=seg[2*si+1].b;
}
}
// seg[si]=(seg[2*si+1]&seg[2*si+2]);
}
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++;
}
}
public static void update(int si,int ss,int se,int pos,long val)
{
if(ss==se){
seg[si].a=val;
seg[si].b=1;
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);
}
long p=seg[2*si+1].a;
long q=seg[2*si+2].a;
seg[si].a=min(p,q);
if(p==q){
seg[si].b=seg[2*si+1].b+seg[2*si+2].b;
}else{
if(p>q){
seg[si].b=seg[2*si+2].b;
}else{
seg[si].b=seg[2*si+1].b;
}
}
}
public static pair m(pair a, pair b){
if(a.a>b.a)return b;
if(a.a<b.a)return a;
return new pair(a.a,a.b+b.b);
}
public static pair query1(int si,int ss,int se,int qs,int qe)
{
if(qs>se || qe<ss)return new pair(MAXL,0);
if(ss>=qs && se<=qe)return seg[si];
int mid=(ss+se)/2;
return m(query1(2*si+1,ss,mid,qs,qe),query1(2*si+2,mid+1,se,qs,qe));
}
// public static long query2(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;
// return query2(2*si+1,ss,mid,qs,qe)+query2(2*si+2,mid+1,se,qs,qe);
// }
//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 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(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();
}
}
//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 | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 0a782e75d14f88757345a5d18e063db4 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.*;
import java.util.*;
public class D {
public static PrintWriter out;
public static void main(String[] args)throws IOException{
Scanner sc=new Scanner();
out=new PrintWriter(System.out);
int t=sc.nextInt();
while(t-->0) {
int n=sc.nextInt();
int a[]=new int[n];
int b[]=new int[n];
for(int i=0;i<n;i++) {
a[i]=sc.nextInt();
}
for(int i=0;i<n;i++) {
b[i]=sc.nextInt();
}
int temp[]=new int[n+1];
int j=n-1;
boolean ans=true;
for(int i=n-1;i>=0;i--) {
if (a[j]==b[i]) {
j--;
continue;
}
if (i+1<n && b[i]==b[i+1]) {
temp[b[i]]++;
continue;
}
if (temp[a[j]]==0) {
ans=false;
break;
}
temp[a[j]]--;
j--;
i++;
}
out.println(ans?"YES":"NO");
}
out.close();
}
public static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | c4dfea9aa0eef22e2bfbc24cc1097ec9 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.*;
import java.util.*;
public class A {
static int n,k;
static long ans;
static ArrayList<Integer>[] g;
static boolean[] vis;
static int[][] binLift;
static int[] depth;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
// Scanner sc = new Scanner(new File("consistency_chapter_1_input.txt"));
// PrintWriter pw = new PrintWriter("A_out.txt");
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
int[] a =new int[n];
int[] b =new int[n];
for (int i = 0; i < n; i++) {
a[i]=sc.nextInt();
}
for (int i = 0; i < n; i++) {
b[i]=sc.nextInt();
}
int[] cnt = new int[n+1];
boolean f = true;
int j = 0;
for (int i = 0; i < n; i++) {
while(j< n && a[j] != b[i]){
cnt[a[j]]++;
j++;
}
if(j==n){
f=false;
break;
}
if(cnt[b[i]] == 0){
j++;
}
else{
cnt[b[i]]--;
}
// System.out.println(f);
}
for (int i = 0; i < cnt.length; i++) {
f&= cnt[i]==0;
}
pw.println(f?"YES":"NO");
}
pw.flush();
}
static int mod = 998244353;
static int modPow(int a, int e, int mod) // O(log e)
{
a %= mod;
int res = 1;
while (e > 0) {
if ((e & 1) == 1)
res = (res * a) % mod;
a = (a * a) % mod;
e >>= 1;
}
return res;
}
static class pair implements Comparable<pair> {
int x, y;
public pair(int u, int s) {
x = u;
y = s;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return x + " " + y;
}
@Override
public int compareTo(pair o) {
// TODO Auto-generated method stub
return x - o.x;
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(File 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 | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 25bf2b79400c8feba06bcc275b26f3fc | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.*;
import java.util.*;
public class CyclicRotations{
static long mod = 1000000007L;
static MyScanner sc = new MyScanner();
static void solve() {
int n = sc.nextInt();
int arr[] = sc.readIntArray(n);
int brr[] = sc.readIntArray(n);
int count[] = new int[n+1];
int i = 0;
int j = 0;
while(j<n){
if(i<n && arr[i]==brr[j]){
i++;
j++;
continue;
}
if(count[brr[j]]>0 && brr[j]==brr[j-1]){
count[brr[j]]--;
j++;
}else if(i<n){
count[arr[i]]++;
i++;
}else{
out.println("NO");
return;
}
}
boolean fl = true;
for(int k = 0;k<n+1;k++){
if(count[k]!=0) fl = false;
}
if(fl && i==n){
out.println("YES");
}else{
out.println("NO");
}
}
static long lcm(long a,long b){
return (a*b)/gcd(a,b);
}
static long comb(int n,int k){
return factorial(n) * pow(factorial(k), mod-2) % mod * pow(factorial(n-k), mod-2) % mod;
}
static long factorial(int n){
long ret = 1;
while(n > 0){
ret = ret * n % mod;
n--;
}
return ret;
}
static class Pair implements Comparable<Pair>{
long a;
long b;
Pair(long aa,long bb){
a = aa;
b = bb;
}
public int compareTo(Pair p){
return Long.compare(this.b,p.b);
}
}
static void reverse(int arr[]){
int i = 0;int j = arr.length-1;
while(i<j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
static long pow(long a, long b) {
if (b == 0) return 1;
long res = pow(a, b / 2);
res = (res * res) % 1_000_000_007;
if (b % 2 == 1) {
res = (res * a) % 1_000_000_007;
}
return res;
}
static int lis(int arr[],int n){
int lis[] = new int[n];
lis[0] = 1;
for(int i = 1;i<n;i++){
lis[i] = 1;
for(int j = 0;j<i;j++){
if(arr[i]>arr[j]){
lis[i] = Math.max(lis[i],lis[j]+1);
}
}
}
int max = Integer.MIN_VALUE;
for(int i = 0;i<n;i++){
max = Math.max(lis[i],max);
}
return max;
}
static boolean isPali(String str){
int i = 0;
int j = str.length()-1;
while(i<j){
if(str.charAt(i)!=str.charAt(j)){
return false;
}
i++;
j--;
}
return true;
}
static long gcd(long a,long b){
if(b==0) return a;
return gcd(b,a%b);
}
static String reverse(String str){
char arr[] = str.toCharArray();
int i = 0;
int j = arr.length-1;
while(i<j){
char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
String st = new String(arr);
return st;
}
static boolean isprime(int n){
if(n==1) return false;
if(n==3 || n==2) return true;
if(n%2==0 || n%3==0) return false;
for(int i = 5;i*i<=n;i+= 6){
if(n%i== 0 || n%(i+2)==0){
return false;
}
}
return true;
}
public static void main(String[] args) {
out = new PrintWriter(new BufferedOutputStream(System.out));
int t = sc.nextInt();
// int t= 1;
while(t-- >0){
solve();
// solve2();
// solve3();
}
// Stop writing your solution here. -------------------------------------
out.close();
}
//-----------PrintWriter for faster output---------------------------------
public static PrintWriter out;
//-----------MyScanner class for faster input----------
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int[] readIntArray(int n){
int arr[] = new int[n];
for(int i = 0;i<n;i++){
arr[i] = Integer.parseInt(next());
}
return arr;
}
int[] reverse(int arr[]){
int n= arr.length;
int i = 0;
int j = n-1;
while(i<j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
j--;i++;
}
return arr;
}
long[] readLongArray(int n){
long arr[] = new long[n];
for(int i = 0;i<n;i++){
arr[i] = Long.parseLong(next());
}
return arr;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
private static void sort(int[] arr) {
List<Integer> list = new ArrayList<>();
for (int i=0; i<arr.length; i++){
list.add(arr[i]);
}
Collections.sort(list); // collections.sort uses nlogn in backend
for (int i = 0; i < arr.length; i++){
arr[i] = list.get(i);
}
}
private static void sort(long[] arr) {
List<Long> list = new ArrayList<>();
for (int i=0; i<arr.length; i++){
list.add(arr[i]);
}
Collections.sort(list); // collections.sort uses nlogn in backend
for (int i = 0; i < arr.length; i++){
arr[i] = list.get(i);
}
}
} | Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 29f4cbf98056905b315e518cb3d3f5ba | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.text.DecimalFormat;
import java.util.*;
import java.io.*;
public class CpTemp {
static FastScanner fs = null;
static int rank[];
static int p[];
static int aq[];
static int ans = 1;
public static void main(String[] args) {
fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int t = fs.nextInt();
outer:
while (t-- > 0) {
int n = fs.nextInt();
int a[] = fs.readArray(n);
int b[] = fs.readArray(n);
p = new int[n+1];
// 1 2 3 3 2
// 1 3 3 2 2
boolean f = true;
if(b[n-1]!=a[n-1]){
f = false;
}
if(f) {
int j = n - 2;
int i = n - 2;
while (i >= 0 && j >= 0) {
if (b[j] == a[i]) {
i--;
j--;
} else {
if (b[j] == b[j + 1]) {
p[b[j]]++;
j--;
} else if (p[a[i]]>0) {
p[a[i]]--;
i--;
} else {
f = false;
break;
}
}
}
}
if(f){
out.println("YES");
}else{
out.println("NO");
}
}
out.close();
}
public static int sumu(int x, int count){
if(p[x]==x){
return count+1;
}else{
return sumu(p[x],count + aq[x] );
}
}
public static void union(int a,int b) {
int x = get(a);
int y = get(b);
if(x==y){
return;
}
if(rank[x]==rank[y]){
rank[x]++;
}
if(rank[x]>rank[y]){
p[y] = x;
}else{
p[x] = y;
}
}
public static int get(int a){
if(p[a]==a){
return a;
}else{
return p[a] = get(p[a]);
}
}
static class Pair implements Comparable<Pair> {
int x;
String y;
Pair(int x, String y) {
this.x = x;
this.y = y;
}
public int compareTo(Pair o) {
return this.x-o.x;
}
}
static long power(long x, long y, long p) {
if (y == 0)
return 1;
if (x == 0)
return 0;
long res = 1;
x = x % p;
while (y > 0) {
if (y % 2 == 1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
static long power(long x, long y) {
if (y == 0)
return 1;
if (x == 0)
return 0;
long res = 1;
while (y > 0) {
if (y % 2 == 1)
res = (res * x);
y = y >> 1;
x = (x * x);
}
return res;
}
static void sort(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 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[] 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());
}
}
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;
}
}
}
public static int log2(int x) {
return (int) (Math.log(x) / Math.log(2));
}
public static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
static long nCk(int n, int k) {
long res = 1;
for (int i = n - k + 1; i <= n; ++i)
res *= i;
for (int i = 2; i <= k; ++i)
res /= i;
return res;
}
} | Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 18156d6f182706015074a1ee305b57c3 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
//--------------------------INPUT READER---------------------------------//
static class fs {
public BufferedReader br;
StringTokenizer st = new StringTokenizer("");
public fs() { this(System.in); }
public fs(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
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 nn) {
int n = (int) nn;
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = ni();
return a;
}
long[] nal(long nn) {
int n = (int) nn;
long[] l = new long[n];
for(int i = 0; i < n; i++) l[i] = nl();
return l;
}
}
//-----------------------------------------------------------------------//
//---------------------------PRINTER-------------------------------------//
static class Printer {
static PrintWriter w;
public Printer() {this(System.out);}
public Printer(OutputStream os) {
w = new PrintWriter(os);
}
public void p(int i) {w.println(i);}
public void p(long l) {w.println(l);}
public void p(double d) {w.println(d);}
public void p(String s) { w.println(s);}
public void pr(int i) {w.print(i);}
public void pr(long l) {w.print(l);}
public void pr(double d) {w.print(d);}
public void pr(String s) { w.print(s);}
public void pl() {w.println();}
public void close() {w.close();}
}
//-----------------------------------------------------------------------//
//--------------------------VARIABLES------------------------------------//
static fs sc = new fs();
static OutputStream outputStream = System.out;
static Printer w = new Printer(outputStream);
static long lma = Long.MAX_VALUE, lmi = Long.MIN_VALUE;
static int ima = Integer.MAX_VALUE, imi = Integer.MIN_VALUE;
static long mod = 1000000007;
//-----------------------------------------------------------------------//
//--------------------------ADMIN_MODE-----------------------------------//
private static void ADMIN_MODE() throws IOException {
if (System.getProperty("ONLINE_JUDGE") == null) {
w = new Printer(new FileOutputStream("output.txt"));
sc = new fs(new FileInputStream("input.txt"));
}
}
//-----------------------------------------------------------------------//
//----------------------------START--------------------------------------//
public static void main(String[] args)
throws IOException {
ADMIN_MODE();
int t = sc.ni();while(t-->0)
solve();
w.close();
}
static void solve() throws IOException {
int n = sc.ni();
int[] arr = sc.na(n);
int[] arr2 = sc.na(n);
HashMap<Integer, Integer> hm = new HashMap<>();
int r1 = n-1, r2 = n-1;
while(r2 >= 0) {
if(r2 != n-1 && arr2[r2] == arr2[r2+1]) {
hm.put(arr2[r2], hm.getOrDefault(arr2[r2], 0)+1);
r2--;
continue;
}
if(arr[r1] == arr2[r2]) {
r1--;
r2--;
continue;
}
if(hm.containsKey(arr[r1])) {
hm.replace(arr[r1], hm.get(arr[r1])-1);
if(hm.get(arr[r1]) == 0) hm.remove(arr[r1]);
r1--;
continue;
}
w.p("NO");
return;
}
while(hm.size() > 0) {
if(!hm.containsKey(arr[r1])) {
w.p("NO");
return;
}
hm.replace(arr[r1], hm.get(arr[r1])-1);
if(hm.get(arr[r1]) == 0) hm.remove(arr[r1]);
r1--;
}
w.p("YES");
}
} | Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 9274f2febe36f04966249b744ae34ce2 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
//--------------------------INPUT READER---------------------------------//
static class fs {
public BufferedReader br;
StringTokenizer st = new StringTokenizer("");
public fs() { this(System.in); }
public fs(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
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 nn) {
int n = (int) nn;
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = ni();
return a;
}
long[] nal(long nn) {
int n = (int) nn;
long[] l = new long[n];
for(int i = 0; i < n; i++) l[i] = nl();
return l;
}
}
//-----------------------------------------------------------------------//
//---------------------------PRINTER-------------------------------------//
static class Printer {
static PrintWriter w;
public Printer() {this(System.out);}
public Printer(OutputStream os) {
w = new PrintWriter(os);
}
public void p(int i) {w.println(i);}
public void p(long l) {w.println(l);}
public void p(double d) {w.println(d);}
public void p(String s) { w.println(s);}
public void pr(int i) {w.print(i);}
public void pr(long l) {w.print(l);}
public void pr(double d) {w.print(d);}
public void pr(String s) { w.print(s);}
public void pl() {w.println();}
public void close() {w.close();}
}
//-----------------------------------------------------------------------//
//--------------------------VARIABLES------------------------------------//
static fs sc = new fs();
static OutputStream outputStream = System.out;
static Printer w = new Printer(outputStream);
static long lma = Long.MAX_VALUE, lmi = Long.MIN_VALUE;
static int ima = Integer.MAX_VALUE, imi = Integer.MIN_VALUE;
static long mod = 1000000007;
//-----------------------------------------------------------------------//
//--------------------------ADMIN_MODE-----------------------------------//
private static void ADMIN_MODE() throws IOException {
if (System.getProperty("ONLINE_JUDGE") == null) {
w = new Printer(new FileOutputStream("output.txt"));
sc = new fs(new FileInputStream("input.txt"));
}
}
//-----------------------------------------------------------------------//
//----------------------------START--------------------------------------//
public static void main(String[] args)
throws IOException {
ADMIN_MODE();
int t = sc.ni();while(t-->0)
solve();
w.close();
}
static void solve() throws IOException {
int n = sc.ni();
int[] arr = sc.na(n);
int[] arr2 = sc.na(n);
HashMap<Integer, Integer> hm = new HashMap<>();
int r1 = n-1, r2 = n-1;
while(r2 >= 0) {
if(arr[r1] == arr2[r2]) {
r1--;
r2--;
continue;
}
if(r2 != n-1 && arr2[r2] == arr2[r2+1]) {
hm.put(arr2[r2], hm.getOrDefault(arr2[r2], 0)+1);
r2--;
continue;
}
if(hm.containsKey(arr[r1])) {
hm.replace(arr[r1], hm.get(arr[r1])-1);
if(hm.get(arr[r1]) == 0) hm.remove(arr[r1]);
r1--;
continue;
}
w.p("NO");
return;
}
while(hm.size() > 0) {
if(!hm.containsKey(arr[r1])) {
w.p("NO");
return;
}
hm.replace(arr[r1], hm.get(arr[r1])-1);
if(hm.get(arr[r1]) == 0) hm.remove(arr[r1]);
r1--;
}
w.p("YES");
}
} | Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 173f3ef29ca94e6ec2397d6d05595750 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.*;
import java.util.*;
public class CodeForces {
/*-------------------------------------------EDITING CODE STARTS HERE-------------------------------------------*/
public static void solve(int tCase) throws IOException {
int n = sc.nextInt();
int [] arr = new int[n];
for(int i=0;i<n;i++)arr[i] = sc.nextInt();
int [] brr = new int[n];
for(int i=0;i<n;i++)brr[i] = sc.nextInt();
Map<Integer,Integer> xtra = new HashMap<>();
int j = 0,i = 0;
for(;i<n && j<n;){
// out.println(i+" "+j+xtra);
if(brr[i] == arr[j]){
if(xtra.containsKey(brr[i])) {
int x = xtra.get(brr[i]);
if (x - 1 > 0) xtra.put(brr[i], x - 1);
else xtra.remove(brr[i]);
}else j++;
i++;
}else {
xtra.put(arr[j],xtra.getOrDefault(arr[j],0)+1);
j++;
}
}
if(i==n && j==n )out.println("YES");
else out.println("NO");
}
public static void main(String[] args) throws IOException {
openIO();
int testCase = 1;
testCase = sc.nextInt();
for (int i = 1; i <= testCase; i++) solve(i);
closeIO();
}
/*-------------------------------------------EDITING CODE ENDS HERE-------------------------------------------*/
/*--------------------------------------HELPER FUNCTIONS STARTS HERE-----------------------------------------*/
// public static int mod = (int) 1e9 + 7;
public static int mod = 998244353;
public static int inf_int = (int) 2e9+10;
public static long inf_long = (long) 2e18;
public static void _sort(int[] arr, boolean isAscending) {
int n = arr.length;
List<Integer> list = new ArrayList<>();
for (int ele : arr) list.add(ele);
Collections.sort(list);
if (!isAscending) Collections.reverse(list);
for (int i = 0; i < n; i++) arr[i] = list.get(i);
}
public static void _sort(long[] arr, boolean isAscending) {
int n = arr.length;
List<Long> list = new ArrayList<>();
for (long ele : arr) list.add(ele);
Collections.sort(list);
if (!isAscending) Collections.reverse(list);
for (int i = 0; i < n; i++) arr[i] = list.get(i);
}
// time : O(1), space : O(1)
public static int _digitCount(long num,int base){
// this will give the # of digits needed for a number num in format : base
return (int)(1 + Math.log(num)/Math.log(base));
}
// time : O(n), space: O(n)
public static long _fact(int n){
// simple factorial calculator
long ans = 1;
for(int i=2;i<=n;i++)
ans = ans * i % mod;
return ans;
}
// time for pre-computation of factorial and inverse-factorial table : O(nlog(mod))
public static long[] factorial , inverseFact;
public static void _ncr_precompute(int n){
factorial = new long[n+1];
inverseFact = new long[n+1];
factorial[0] = inverseFact[0] = 1;
for (int i = 1; i <=n; i++) {
factorial[i] = (factorial[i - 1] * i) % mod;
inverseFact[i] = _modExpo(factorial[i], mod - 2);
}
}
// time of factorial calculation after pre-computation is O(1)
public static int _ncr(int n,int r){
if(r > n)return 0;
return (int)(factorial[n] * inverseFact[r] % mod * inverseFact[n - r] % mod);
}
public static int _npr(int n,int r){
if(r > n)return 0;
return (int)(factorial[n] * inverseFact[n - r] % mod);
}
// euclidean algorithm time O(max (loga ,logb))
public static long _gcd(long a, long b) {
while (a>0){
long x = a;
a = b % a;
b = x;
}
return b;
// if (a == 0)
// return b;
// return _gcd(b % a, a);
}
// lcm(a,b) * gcd(a,b) = a * b
public static long _lcm(long a, long b) {
return (a / _gcd(a, b)) * b;
}
// binary exponentiation time O(logn)
public static long _modExpo(long x, long n) {
long ans = 1;
while (n > 0) {
if ((n & 1) == 1) {
ans *= x;
ans %= mod;
n--;
} else {
x *= x;
x %= mod;
n >>= 1;
}
}
return ans;
}
// function to find a/b under modulo mod. time : O(logn)
public static long _modInv(long a,long b){
return (a * _modExpo(b,mod-2)) % mod;
}
//sieve or first divisor time : O(mx * log ( log (mx) ) )
public static int[] _seive(int mx){
int[] firstDivisor = new int[mx+1];
for(int i=0;i<=mx;i++)firstDivisor[i] = i;
for(int i=2;i*i<=mx;i++)
if(firstDivisor[i] == i)
for(int j = i*i;j<=mx;j+=i)
if(firstDivisor[j]==j)firstDivisor[j] = i;
return firstDivisor;
}
// check if x is a prime # of not. time : O( n ^ 1/2 )
private static boolean _isPrime(long x){
for(long i=2;i*i<=x;i++)
if(x%i==0)return false;
return true;
}
static class Pair<K, V>{
K ff;
V ss;
public Pair(K ff, V ss) {
this.ff = ff;
this.ss = ss;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || this.getClass() != o.getClass()) return false;
Pair<?, ?> pair = (Pair<?, ?>) o;
return ff.equals(pair.ff) && ss.equals(pair.ss);
}
@Override
public int hashCode() {
return Objects.hash(ff, ss);
}
@Override
public String toString(){
return ff.toString()+" "+ss.toString();
}
}
/*--------------------------------------HELPER FUNCTIONS ENDS HERE-----------------------------------------*/
/*-------------------------------------------FAST INPUT STARTS HERE---------------------------------------------*/
static FastestReader sc;
static PrintWriter out;
private static void openIO() throws IOException {
sc = new FastestReader();
out = new PrintWriter(System.out);
}
public static void closeIO() throws IOException {
out.flush();
out.close();
sc.close();
}
private static final class FastestReader {
private static final int BUFFER_SIZE = 1 << 16;
private final DataInputStream din;
private final byte[] buffer;
private int bufferPointer, bytesRead;
public FastestReader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public FastestReader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
private static boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() throws IOException {
int b;
//noinspection StatementWithEmptyBody
while ((b = read()) != -1 && isSpaceChar(b)) {}
return b;
}
public String next() throws IOException {
int b = skip();
final StringBuilder sb = new StringBuilder();
while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = read();
}
return sb.toString();
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') c = read();
final boolean neg = c == '-';
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
return neg?-ret:ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ') c = read();
final boolean neg = c == '-';
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
return neg?-ret:ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ') c = read();
final boolean neg = c == '-';
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.')
while ((c = read()) >= '0' && c <= '9')
ret += (c - '0') / (div *= 10);
return neg?-ret:ret;
}
public String nextLine() throws IOException {
final byte[] buf = new byte[(1<<10)]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
break;
}
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
din.close();
}
}
/*---------------------------------------------FAST INPUT ENDS HERE ---------------------------------------------*/
}
/** Some points to keep in mind :
* 1. don't use Arrays.sort(primitive data type array)
* 2. try to make the parameters of a recursive function as less as possible,
* more use static variables.
*
**/ | Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | b64332afebf4c4e550d2856111eb9243 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.*;
import java.util.*;
public class CodeForces {
/*-------------------------------------------EDITING CODE STARTS HERE-------------------------------------------*/
public static void solve(int tCase) throws IOException {
int n = sc.nextInt();
int [] arr = new int[n];
for(int i=0;i<n;i++)arr[i] = sc.nextInt();
int [] brr = new int[n];
for(int i=0;i<n;i++)brr[i] = sc.nextInt();
Map<Integer,Integer> xtra = new HashMap<>();
int j = 0,i = 0;
for(;i<n && j<n;){
// out.println(i+" "+j+xtra);
if(brr[i] == arr[j]){
if(xtra.containsKey(brr[i])) {
int x = xtra.get(brr[i]);
if (x - 1 > 0) xtra.put(brr[i], x - 1);
else xtra.remove(brr[i]);
}else j++;
i++;
}else {
xtra.put(arr[j],xtra.getOrDefault(arr[j],0)+1);
j++;
}
}
// out.println(xtra+" "+i+" "+j);
// for(;i<n;i++){
// if(xtra.containsKey(brr[i]) && arr[n-1] == brr[i]){
// int x = xtra.get(brr[i]);
// if(x-1 >0)xtra.put(brr[i],x-1);
// else xtra.remove(brr[i]);
// }else {
// out.println("NO");
// return;
// }
// }
// out.println(xtra+" "+i+" "+j);
if(i==n && j==n && xtra.isEmpty())out.println("YES");
else out.println("NO");
}
public static void main(String[] args) throws IOException {
openIO();
int testCase = 1;
testCase = sc.nextInt();
for (int i = 1; i <= testCase; i++) solve(i);
closeIO();
}
/*-------------------------------------------EDITING CODE ENDS HERE-------------------------------------------*/
/*--------------------------------------HELPER FUNCTIONS STARTS HERE-----------------------------------------*/
// public static int mod = (int) 1e9 + 7;
public static int mod = 998244353;
public static int inf_int = (int) 2e9+10;
public static long inf_long = (long) 2e18;
public static void _sort(int[] arr, boolean isAscending) {
int n = arr.length;
List<Integer> list = new ArrayList<>();
for (int ele : arr) list.add(ele);
Collections.sort(list);
if (!isAscending) Collections.reverse(list);
for (int i = 0; i < n; i++) arr[i] = list.get(i);
}
public static void _sort(long[] arr, boolean isAscending) {
int n = arr.length;
List<Long> list = new ArrayList<>();
for (long ele : arr) list.add(ele);
Collections.sort(list);
if (!isAscending) Collections.reverse(list);
for (int i = 0; i < n; i++) arr[i] = list.get(i);
}
// time : O(1), space : O(1)
public static int _digitCount(long num,int base){
// this will give the # of digits needed for a number num in format : base
return (int)(1 + Math.log(num)/Math.log(base));
}
// time : O(n), space: O(n)
public static long _fact(int n){
// simple factorial calculator
long ans = 1;
for(int i=2;i<=n;i++)
ans = ans * i % mod;
return ans;
}
// time for pre-computation of factorial and inverse-factorial table : O(nlog(mod))
public static long[] factorial , inverseFact;
public static void _ncr_precompute(int n){
factorial = new long[n+1];
inverseFact = new long[n+1];
factorial[0] = inverseFact[0] = 1;
for (int i = 1; i <=n; i++) {
factorial[i] = (factorial[i - 1] * i) % mod;
inverseFact[i] = _modExpo(factorial[i], mod - 2);
}
}
// time of factorial calculation after pre-computation is O(1)
public static int _ncr(int n,int r){
if(r > n)return 0;
return (int)(factorial[n] * inverseFact[r] % mod * inverseFact[n - r] % mod);
}
public static int _npr(int n,int r){
if(r > n)return 0;
return (int)(factorial[n] * inverseFact[n - r] % mod);
}
// euclidean algorithm time O(max (loga ,logb))
public static long _gcd(long a, long b) {
while (a>0){
long x = a;
a = b % a;
b = x;
}
return b;
// if (a == 0)
// return b;
// return _gcd(b % a, a);
}
// lcm(a,b) * gcd(a,b) = a * b
public static long _lcm(long a, long b) {
return (a / _gcd(a, b)) * b;
}
// binary exponentiation time O(logn)
public static long _modExpo(long x, long n) {
long ans = 1;
while (n > 0) {
if ((n & 1) == 1) {
ans *= x;
ans %= mod;
n--;
} else {
x *= x;
x %= mod;
n >>= 1;
}
}
return ans;
}
// function to find a/b under modulo mod. time : O(logn)
public static long _modInv(long a,long b){
return (a * _modExpo(b,mod-2)) % mod;
}
//sieve or first divisor time : O(mx * log ( log (mx) ) )
public static int[] _seive(int mx){
int[] firstDivisor = new int[mx+1];
for(int i=0;i<=mx;i++)firstDivisor[i] = i;
for(int i=2;i*i<=mx;i++)
if(firstDivisor[i] == i)
for(int j = i*i;j<=mx;j+=i)
if(firstDivisor[j]==j)firstDivisor[j] = i;
return firstDivisor;
}
// check if x is a prime # of not. time : O( n ^ 1/2 )
private static boolean _isPrime(long x){
for(long i=2;i*i<=x;i++)
if(x%i==0)return false;
return true;
}
static class Pair<K, V>{
K ff;
V ss;
public Pair(K ff, V ss) {
this.ff = ff;
this.ss = ss;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || this.getClass() != o.getClass()) return false;
Pair<?, ?> pair = (Pair<?, ?>) o;
return ff.equals(pair.ff) && ss.equals(pair.ss);
}
@Override
public int hashCode() {
return Objects.hash(ff, ss);
}
@Override
public String toString(){
return ff.toString()+" "+ss.toString();
}
}
/*--------------------------------------HELPER FUNCTIONS ENDS HERE-----------------------------------------*/
/*-------------------------------------------FAST INPUT STARTS HERE---------------------------------------------*/
static FastestReader sc;
static PrintWriter out;
private static void openIO() throws IOException {
sc = new FastestReader();
out = new PrintWriter(System.out);
}
public static void closeIO() throws IOException {
out.flush();
out.close();
sc.close();
}
private static final class FastestReader {
private static final int BUFFER_SIZE = 1 << 16;
private final DataInputStream din;
private final byte[] buffer;
private int bufferPointer, bytesRead;
public FastestReader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public FastestReader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
private static boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() throws IOException {
int b;
//noinspection StatementWithEmptyBody
while ((b = read()) != -1 && isSpaceChar(b)) {}
return b;
}
public String next() throws IOException {
int b = skip();
final StringBuilder sb = new StringBuilder();
while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = read();
}
return sb.toString();
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') c = read();
final boolean neg = c == '-';
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
return neg?-ret:ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ') c = read();
final boolean neg = c == '-';
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
return neg?-ret:ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ') c = read();
final boolean neg = c == '-';
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.')
while ((c = read()) >= '0' && c <= '9')
ret += (c - '0') / (div *= 10);
return neg?-ret:ret;
}
public String nextLine() throws IOException {
final byte[] buf = new byte[(1<<10)]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
break;
}
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
din.close();
}
}
/*---------------------------------------------FAST INPUT ENDS HERE ---------------------------------------------*/
}
/** Some points to keep in mind :
* 1. don't use Arrays.sort(primitive data type array)
* 2. try to make the parameters of a recursive function as less as possible,
* more use static variables.
*
**/ | Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 385ff32c7ea2eb12e18904592bf95606 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.*;
import java.util.*;
/*
1
10
1 2 3 1 5 6 1 2 4 1
2 3 5 6 1 1 2 4 1 1
yes
1
6
1 2 3 1 5 1
2 3 1 5 1 1
yes
1
10
1 2 3 1 5 6 1 2 4 1
2 3 1 5 6 1 2 4 1 1
yes
1
6
1 1 1 2 2 1
1 1 2 2 1 1
yes
1
6
1 1 1 2 2 1
2 2 1 1 1 1
yes
1
6
1 3 1 3 4 3
1 1 3 4 3 3
yes
*/
public class CodeForces {
/*-------------------------------------------EDITING CODE STARTS HERE-------------------------------------------*/
public static void solve(int tCase) throws IOException {
int n = sc.nextInt();
int [] arr = new int[n];
for(int i=0;i<n;i++)arr[i] = sc.nextInt();
int [] brr = new int[n];
for(int i=0;i<n;i++)brr[i] = sc.nextInt();
Map<Integer,Integer> xtra = new HashMap<>();
int j = 0,i = 0;
for(;i<n && j<n;){
// out.println(i+" "+j+xtra);
if(brr[i] == arr[j]){
if(xtra.containsKey(brr[i])) {
int x = xtra.get(brr[i]);
if (x - 1 > 0) xtra.put(brr[i], x - 1);
else xtra.remove(brr[i]);
}else j++;
i++;
}else {
xtra.put(arr[j],xtra.getOrDefault(arr[j],0)+1);
j++;
}
}
// out.println(xtra+" "+i+" "+j);
for(;i<n;i++){
if(xtra.containsKey(brr[i]) && arr[n-1] == brr[i]){
int x = xtra.get(brr[i]);
if(x-1 >0)xtra.put(brr[i],x-1);
else xtra.remove(brr[i]);
}else {
out.println("NO");
return;
}
}
// out.println(xtra+" "+i+" "+j);
if(i==n && j==n && xtra.isEmpty())out.println("YES");
else out.println("NO");
}
public static void main(String[] args) throws IOException {
openIO();
int testCase = 1;
testCase = sc.nextInt();
for (int i = 1; i <= testCase; i++) solve(i);
closeIO();
}
/*-------------------------------------------EDITING CODE ENDS HERE-------------------------------------------*/
/*--------------------------------------HELPER FUNCTIONS STARTS HERE-----------------------------------------*/
// public static int mod = (int) 1e9 + 7;
public static int mod = 998244353;
public static int inf_int = (int) 2e9+10;
public static long inf_long = (long) 2e18;
public static void _sort(int[] arr, boolean isAscending) {
int n = arr.length;
List<Integer> list = new ArrayList<>();
for (int ele : arr) list.add(ele);
Collections.sort(list);
if (!isAscending) Collections.reverse(list);
for (int i = 0; i < n; i++) arr[i] = list.get(i);
}
public static void _sort(long[] arr, boolean isAscending) {
int n = arr.length;
List<Long> list = new ArrayList<>();
for (long ele : arr) list.add(ele);
Collections.sort(list);
if (!isAscending) Collections.reverse(list);
for (int i = 0; i < n; i++) arr[i] = list.get(i);
}
// time : O(1), space : O(1)
public static int _digitCount(long num,int base){
// this will give the # of digits needed for a number num in format : base
return (int)(1 + Math.log(num)/Math.log(base));
}
// time : O(n), space: O(n)
public static long _fact(int n){
// simple factorial calculator
long ans = 1;
for(int i=2;i<=n;i++)
ans = ans * i % mod;
return ans;
}
// time for pre-computation of factorial and inverse-factorial table : O(nlog(mod))
public static long[] factorial , inverseFact;
public static void _ncr_precompute(int n){
factorial = new long[n+1];
inverseFact = new long[n+1];
factorial[0] = inverseFact[0] = 1;
for (int i = 1; i <=n; i++) {
factorial[i] = (factorial[i - 1] * i) % mod;
inverseFact[i] = _modExpo(factorial[i], mod - 2);
}
}
// time of factorial calculation after pre-computation is O(1)
public static int _ncr(int n,int r){
if(r > n)return 0;
return (int)(factorial[n] * inverseFact[r] % mod * inverseFact[n - r] % mod);
}
public static int _npr(int n,int r){
if(r > n)return 0;
return (int)(factorial[n] * inverseFact[n - r] % mod);
}
// euclidean algorithm time O(max (loga ,logb))
public static long _gcd(long a, long b) {
while (a>0){
long x = a;
a = b % a;
b = x;
}
return b;
// if (a == 0)
// return b;
// return _gcd(b % a, a);
}
// lcm(a,b) * gcd(a,b) = a * b
public static long _lcm(long a, long b) {
return (a / _gcd(a, b)) * b;
}
// binary exponentiation time O(logn)
public static long _modExpo(long x, long n) {
long ans = 1;
while (n > 0) {
if ((n & 1) == 1) {
ans *= x;
ans %= mod;
n--;
} else {
x *= x;
x %= mod;
n >>= 1;
}
}
return ans;
}
// function to find a/b under modulo mod. time : O(logn)
public static long _modInv(long a,long b){
return (a * _modExpo(b,mod-2)) % mod;
}
//sieve or first divisor time : O(mx * log ( log (mx) ) )
public static int[] _seive(int mx){
int[] firstDivisor = new int[mx+1];
for(int i=0;i<=mx;i++)firstDivisor[i] = i;
for(int i=2;i*i<=mx;i++)
if(firstDivisor[i] == i)
for(int j = i*i;j<=mx;j+=i)
if(firstDivisor[j]==j)firstDivisor[j] = i;
return firstDivisor;
}
// check if x is a prime # of not. time : O( n ^ 1/2 )
private static boolean _isPrime(long x){
for(long i=2;i*i<=x;i++)
if(x%i==0)return false;
return true;
}
static class Pair<K, V>{
K ff;
V ss;
public Pair(K ff, V ss) {
this.ff = ff;
this.ss = ss;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || this.getClass() != o.getClass()) return false;
Pair<?, ?> pair = (Pair<?, ?>) o;
return ff.equals(pair.ff) && ss.equals(pair.ss);
}
@Override
public int hashCode() {
return Objects.hash(ff, ss);
}
@Override
public String toString(){
return ff.toString()+" "+ss.toString();
}
}
/*--------------------------------------HELPER FUNCTIONS ENDS HERE-----------------------------------------*/
/*-------------------------------------------FAST INPUT STARTS HERE---------------------------------------------*/
static FastestReader sc;
static PrintWriter out;
private static void openIO() throws IOException {
sc = new FastestReader();
out = new PrintWriter(System.out);
}
public static void closeIO() throws IOException {
out.flush();
out.close();
sc.close();
}
private static final class FastestReader {
private static final int BUFFER_SIZE = 1 << 16;
private final DataInputStream din;
private final byte[] buffer;
private int bufferPointer, bytesRead;
public FastestReader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public FastestReader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
private static boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() throws IOException {
int b;
//noinspection StatementWithEmptyBody
while ((b = read()) != -1 && isSpaceChar(b)) {}
return b;
}
public String next() throws IOException {
int b = skip();
final StringBuilder sb = new StringBuilder();
while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = read();
}
return sb.toString();
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') c = read();
final boolean neg = c == '-';
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
return neg?-ret:ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ') c = read();
final boolean neg = c == '-';
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
return neg?-ret:ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ') c = read();
final boolean neg = c == '-';
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.')
while ((c = read()) >= '0' && c <= '9')
ret += (c - '0') / (div *= 10);
return neg?-ret:ret;
}
public String nextLine() throws IOException {
final byte[] buf = new byte[(1<<10)]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
break;
}
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
din.close();
}
}
/*---------------------------------------------FAST INPUT ENDS HERE ---------------------------------------------*/
}
/** Some points to keep in mind :
* 1. don't use Arrays.sort(primitive data type array)
* 2. try to make the parameters of a recursive function as less as possible,
* more use static variables.
*
**/ | Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | e183730deeea9c62f5e88346ef3524ec | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes |
//package d;
import java.util.*;
import java.io.*;
public class D {
public static void main(String[] args) throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw=new PrintWriter(System.out);
int cases=Integer.parseInt(br.readLine());
for(int d=0;d<cases;d++){
int length=Integer.parseInt(br.readLine());
Queue<Integer> a=new LinkedList<>();
StringTokenizer st=new StringTokenizer(br.readLine());
int[] map=new int[length+1];
for(int i=0;i<length;i++){
a.add(Integer.parseInt(st.nextToken()));
}
int[] target=new int[length];
st=new StringTokenizer(br.readLine());
for(int i=0;i<length;i++){
target[i]=Integer.parseInt(st.nextToken());
}
int prev=-1;
int leftovers=0;
for(int i=0;i<length;i++){
//System.out.println(a);
if(!a.isEmpty()&&a.peek()==target[i]){
a.remove();
}else{
boolean pass=false;
while(!a.isEmpty()&&a.peek()!=target[i]&&!pass){
if(i>0&&prev==target[i]&&map[target[i]]>0){
pass=true;
map[target[i]]--;
leftovers--;
}else{
map[a.remove()]++;
leftovers++;
}
if(!a.isEmpty()&&a.peek()==target[i]){
a.remove();
pass=true;
}
}
if(!pass&&a.isEmpty()){
if(i>0&&prev==target[i]&&map[target[i]]>0){
map[target[i]]--;
leftovers--;
}else{
break;
}
}
}
prev=target[i];
}
//System.out.println(a);
//System.out.println(leftovers);
if(a.isEmpty()&&leftovers==0){
pw.println("YES");
}else{
pw.println("NO");
}
}
pw.close();
}
}
| Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 9034699996a98a142a2850d2387f8af4 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes |
import java.util.*;
import java.io.*;
public class CyclicRotation {
static MScanner scanner = new MScanner();
public static void main(String[] args) {
int T = scanner.nextInt();
while (T-- > 0) {
int n = scanner.nextInt();
int[] a = new int[n];
for(int i = 0; i < n; i++) {
a[i] = scanner.nextInt();
}
int[] b = new int[n];
for(int i = 0; i < n; i++) {
b[i] = scanner.nextInt();
}
System.out.println(solve(a, b)? "YES" : "NO");
}
}
static boolean solve(int[] a, int[] b) {
int n = a.length;
int l = 0;
int r = 0;
Map<Integer, Integer> cnt = new HashMap<>();
//贪心
while (l < n && r < n) {
// System.out.println(stack);
if (a[l] != b[r]) {
if (!cnt.isEmpty() && cnt.getOrDefault(a[l - 1], 0) > 0 && a[l - 1] == b[r]) {
de(cnt, a[l - 1]);
r ++;
} else {
cnt.put(a[l], cnt.getOrDefault(a[l], 0) + 1);
l ++;
}
} else {
l ++;
r ++;
}
}
while (r < n && a[l - 1] == b[r] && cnt.getOrDefault(a[l - 1], 0) > 0) {
r ++;
de(cnt, a[l - 1]);
}
return cnt.isEmpty();
}
static void de(Map<Integer, Integer> map, int key) {
if (map.getOrDefault(key, 0) == 1) {
map.remove(key);
} else {
map.put(key, map.getOrDefault(key, 0) - 1);
}
}
static class MScanner {
private BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
private StringTokenizer tokenizer = new StringTokenizer("");
private String innerNextLine() {
try {
return reader.readLine();
} catch (IOException ex) {
return null;
}
}
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.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
static void print(int[] nums) {
System.out.println(Arrays.toString(nums));
}
static void print(int[][] nums) {
for (int[] d : nums) {
System.out.println(Arrays.toString(d));
}
}
}
| Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 1abd5b4a2cac70237a5d8fd2223ae32e | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | // "static void main" must be defined in a public class.
import java.io.*;
import java.util.*;
import java.lang.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-->0){
int n = sc.nextInt();
int [] a = new int[n];
HashMap<Integer, Integer> map = new HashMap<>();
for(int i=0;i<n;i++){
a[i] = sc.nextInt();
if(map.get(a[i])==null){
map.put(a[i], 1);
}
else{
map.put(a[i], map.get(a[i])+1);
}
}
String res = "YES";
int [] b = new int[n];
for(int i=0;i<n;i++){
b[i] = sc.nextInt();
}
if(b[n-1]==a[n-1]){
int k = map.get(a[n-1]);
if(k==1){
map.remove(a[n-1]);
}
else{
map.put(a[n-1],k-1);
}
HashMap<Integer, Integer> sk = new HashMap<>();
for(int i=n-2,j=n-2; i>=0; i--){
if(b[i]==a[j]){
k = map.get(a[j]);
if(k==1){
map.remove(a[j]);
}
else{
map.put(a[j],k-1);
}
j--;
}
else if(b[i]==a[j+1] && map.get(a[j+1])!=null){
k = map.get(a[j+1]);
if(k==1){
map.remove(a[j+1]);
}
else{
map.put(a[j+1],k-1);
}
if(sk.get(a[j+1])==null){
sk.put(a[j+1],1);
}
else{
sk.put(a[j+1],sk.get(a[j+1])+1);
}
}
else if(sk.get(a[j])!=null){
k = sk.get(a[j]);
if(k==1){
sk.remove(a[j]);
}
else{
sk.put(a[j],k-1);
}
j--;
i++;
}
else{
res = "NO";
break;
}
}
}
else{
res = "NO";
}
System.out.println(res);
}
}
} | Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 302057828e667d6d641143bbf5aecf21 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.*;
import java.util.*;
public class CyclicRotation {
private static final int START_TEST_CASE = 1;
public static void solveCase(FastIO io, int testCase) {
final int N = io.nextInt();
final int[] A = io.nextIntArray(N);
final int[] B = io.nextIntArray(N);
int[] skips = new int[N + 1];
int ai = N - 1;
for (int bi = N - 1; bi >= 0; --bi) {
if (bi + 1 < N && B[bi] == B[bi + 1]) {
++skips[B[bi]];
} else {
while (A[ai] != B[bi]) {
if (skips[A[ai]] > 0) {
--skips[A[ai]];
--ai;
} else {
io.println("NO");
return;
}
}
--ai;
}
}
io.println("YES");
}
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 | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 95f391be885c6cc813d1491f750454ae | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.*;
import java.util.*;
public class CyclicRotation {
private static final int START_TEST_CASE = 1;
public static void solveCase(FastIO io, int testCase) {
final int N = io.nextInt();
final int[] A = io.nextIntArray(N);
final int[] B = io.nextIntArray(N);
// if (testCase == 79) {
// System.out.println(Arrays.toString(A));
// System.out.println(Arrays.toString(B));
// }
// IntDeque[] idxByVal = new IntDeque[N + 1];
// for (int i = 0; i < N; ++i) {
// IntDeque deq = idxByVal[A[i]];
// if (deq == null) {
// deq = new IntDeque();
// idxByVal[A[i]] = deq;
// }
// deq.push(i);
// }
int[] skips = new int[N + 1];
int ai = N - 1;
boolean[] aUsed = new boolean[N];
for (int bi = N - 1; bi >= 0; --bi) {
// System.out.format("bi = %d, ai = %d, skips = %s\n", bi, ai, Arrays.toString(skips));
// while (A[ai] != B[bi]) {
// if (skips[A[ai]] > 0) {
//
// }
// }
if (bi + 1 < N && B[bi] == B[bi + 1]) {
++skips[B[bi]];
} else {
while (A[ai] != B[bi]) {
if (skips[A[ai]] > 0) {
--skips[A[ai]];
--ai;
} else {
io.println("NO");
return;
}
}
--ai;
}
// if (A[ai] == B[bi]) {
// --ai;
// } else {
// if (bi + 1 < N && B[bi] == B[bi + 1]) {
// } else {
// io.println("NO");
// return;
// }
// }
// while (ai >= 0 && aUsed[ai]) {
// --ai;
// }
}
io.println("YES");
}
/**
* Circular buffer of int values, can be used as:
* - ArrayList: values are added to end.
* - Queue: values are added to end and removed from front.
* - Stack: values are added to and removed from front.
*/
public static class IntDeque {
private int[] arr;
private int off;
private int len;
public IntDeque() {
this(2);
}
public IntDeque(int capacity) {
this.arr = new int[capacity];
}
public void addFirst(int x) {
if (len == arr.length) {
increaseCapacity();
}
if (off == 0) {
off = arr.length;
}
arr[--off] = x;
++len;
}
public void addLast(int x) {
if (len == arr.length) {
increaseCapacity();
}
int idx = index(off + len);
arr[idx] = x;
++len;
}
public int peekFirst() {
return arr[off];
}
public int peekLast() {
int idx = index(off + len - 1);
return arr[idx];
}
public int removeFirst() {
int ans = peekFirst();
off = index(off + 1);
--len;
return ans;
}
public int removeLast() {
int ans = peekLast();
--len;
return ans;
}
public void add(int x) {
addLast(x);
}
public void offer(int x) {
addLast(x);
}
public int poll() {
return removeFirst();
}
public void push(int x) {
addFirst(x);
}
public int pop() {
return removeFirst();
}
public int peek() {
return peekFirst();
}
public int get(int i) {
if (i >= len) {
throw new ArrayIndexOutOfBoundsException(String.format("index %d out of range [0, %d)", i, len));
}
int idx = index(i + off);
return arr[idx];
}
public void set(int i, int x) {
if (i >= len) {
throw new ArrayIndexOutOfBoundsException(String.format("index %d out of range [0, %d)", i, len));
}
int idx = index(i + off);
arr[idx] = x;
}
public int size() {
return len;
}
public boolean isEmpty() {
return size() == 0;
}
public int[] toArray() {
if (len == 0) {
return new int[0];
}
int idx = index(off + len);
if (idx > off) {
return Arrays.copyOfRange(arr, off, idx);
}
int[] A = new int[len];
int endLen = arr.length - off;
int startLen = len - endLen;
System.arraycopy(arr, off, A, 0, endLen);
System.arraycopy(arr, 0, A, endLen, startLen);
return A;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append('[');
printToBuffer(sb, ", ");
sb.append(']');
return sb.toString();
}
private void increaseCapacity() {
int[] next = new int[arr.length << 1];
int endLen = arr.length - off;
System.arraycopy(arr, off, next, 0, endLen);
System.arraycopy(arr, 0, next, endLen, off);
arr = next;
off = 0;
}
private int index(int i) {
if (i >= arr.length) {
i -= arr.length;
} else if (i < 0) {
i += arr.length;
}
return i;
}
private void printToBuffer(StringBuilder sb, CharSequence sep) {
for (int i = 0; i < len; ++i) {
if (i > 0) {
sb.append(sep);
}
sb.append(get(i));
}
}
public static IntDeque of(int... arr) {
IntDeque deq = new IntDeque();
for (int x : arr) {
deq.add(x);
}
return deq;
}
}
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 | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 4c456d9c239e65688615ab9a804d3228 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.util.*;
import java.util.concurrent.TimeUnit;
import java.io.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class D_Cyclic_Rotation{
public static String solve(int a[],int b[],int n){
int count[]=new int[n+1];
int i=n-1,j=n-1;
boolean flag=true;
while(j>=0){
if(j-1>=0&&i>=0&&b[j-1]==b[j]){
count[b[j]]++;
j--;
continue;
}
if(a[i]==b[j]){
i--;j--;
continue;
}
if(count[a[i]]>0){
count[a[i]]--;
i--;
continue;
}
flag=false;
break;
}
if(flag)return "YES";
return "NO";
}
public static void main(String args[])throws IOException, ParseException{
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
StringBuffer res=new StringBuffer();
while(t-->0){
int n=sc.nextInt();
int a[]=new int[n];
int b[]=new int[n];
for(int i=0;i<n;i++)
a[i]=sc.nextInt();
for(int i=0;i<n;i++)
b[i]=sc.nextInt();
res.append(solve(a,b,n));
res.append("\n");
}
System.out.println(res);
}
public static <K,V> Map<K,V> getLimitedSizedCache(int size){
/*Returns an unlimited sized map*/
if(size==0){
return (LinkedHashMap<K, V>) Collections.synchronizedMap(new LinkedHashMap<K, V>());
}
/*Returns the map with the limited size*/
Map<K, V> linkedHashMap = Collections.synchronizedMap(new LinkedHashMap<K, V>() {
protected boolean removeEldestEntry(Map.Entry<K, V> eldest)
{
return size() > size;
}
});
return linkedHashMap;
}
}
class BinarySearch<T extends Comparable<T>> {
T ele[];
int n;
public BinarySearch(T ele[],int n){
this.ele=(T[]) ele;
Arrays.sort(this.ele);
this.n=n;
}
public int lower_bound(T x){
//Return next smallest element greater than ewqual to the current element
int left=0;
int right=n-1;
while(left<=right){
int mid=left+(right-left)/2;
if(x.compareTo(ele[mid])==0)return mid;
if(x.compareTo(ele[mid])>0)left=mid+1;
else right=mid-1;
}
if(left ==n)return -1;
return left;
}
public int upper_bound(T x){
//Returns the highest element lss than equal to the current element
int left=0;
int right=n-1;
while(left<=right){
int mid=left+(right-left)/2;
if(x.compareTo(ele[mid])==0)return mid;
if(x.compareTo(ele[mid])>0)left=mid+1;
else right=mid-1;
}
return right;
}
}
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[1000000]; // 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();
}
}
class Data implements Comparable<Data>{
int num;
public Data(int num){
this.num=num;
}
public int compareTo(Data o){
return -o.num+num;
}
public String toString(){
return num+" ";
}
}
class Binary{
public String convertToBinaryString(long ele){
StringBuffer res=new StringBuffer();
while(ele>0){
if(ele%2==0)res.append(0+"");
else res.append(1+"");
ele=ele/2;
}
return res.reverse().toString();
}
}
class FenwickTree{
int bit[];
int size;
FenwickTree(int n){
this.size=n;
bit=new int[size];
}
public void modify(int index,int value){
while(index<size){
bit[index]+=value;
index=(index|(index+1));
}
}
public int get(int index){
int ans=0;
while(index>=0){
ans+=bit[index];
index=(index&(index+1))-1;
}
return ans;
}
}
class PAndC{
long c[][];
long mod;
public PAndC(int n,long mod){
c=new long[n+1][n+1];
this.mod=mod;
build(n);
}
public void build(int n){
for(int i=0;i<=n;i++){
c[i][0]=1;
c[i][i]=1;
for(int j=1;j<i;j++){
c[i][j]=(c[i-1][j]+c[i-1][j-1])%mod;
}
}
}
}
class Trie{
int trie[][];
int revind[];
int root[];
int tind,n;
int sz[];
int drev[];
public Trie(){
trie=new int[1000000][2];
root=new int[600000];
sz=new int[1000000];
tind=0;
n=0;
revind=new int[1000000];
drev=new int[20];
}
public void add(int ele){
// System.out.println(root[n]+" ");
n++;
tind++;
revind[tind]=n;
root[n]=tind;
addimpl(root[n-1],root[n],ele);
}
public void addimpl(int prev_root,int cur_root,int ele){
for(int i=18;i>=0;i--){
int edge=(ele&(1<<i))>0?1:0;
trie[cur_root][1-edge]=trie[prev_root][1-edge];
sz[cur_root]=sz[trie[cur_root][1-edge]];
tind++;
drev[i]=cur_root;
revind[tind]=n;
trie[cur_root][edge]=tind;
cur_root=tind;
prev_root=trie[prev_root][edge];
}
sz[cur_root]+=sz[prev_root]+1;
for(int i=0;i<=18;i++){
sz[drev[i]]=sz[trie[drev[i]][0]]+sz[trie[drev[i]][1]];
}
}
public void findmaxxor(int l,int r,int x){
int ans=0;
int cur_root=root[r];
for(int i=18;i>=0;i--){
int edge=(x&(1<<i))>0?1:0;
if(revind[trie[cur_root][1-edge]]>=l){
cur_root=trie[cur_root][1-edge];
ans+=(1-edge)*(1<<i);
}else{
cur_root=trie[cur_root][edge];
ans+=(edge)*(1<<i);
}
}
System.out.println(ans);
}
public void findKthStatistic(int l,int r,int k){
//System.out.println("In 3");
int curr=root[r];
int curl=root[l-1];
int ans=0;
for(int i=18;i>=0;i--){
for(int j=0;j<2;j++){
if(sz[trie[curr][j]]-sz[trie[curl][j]]<k)
k-=sz[trie[curr][j]]-sz[trie[curl][j]];
else{
curr=trie[curr][j];
curl=trie[curl][j];
ans+=(j)*(1<<i);
break;
}
}
}
System.out.println(ans);
}
public void findSmallest(int l,int r,int x){
//System.out.println("In 4");
int curr=root[r];
int curl=root[l-1];
int countl=0,countr=0;
// System.out.println(curl+" "+curr);
for(int i=18;i>=0;i--){
int edge=(x&(1<<i))>0?1:0;
// System.out.println(trie[curl][edge]+" "+trie[curr][edge]+" "+sz[curl]+" "+sz[curr]);
if(edge==1){
countr+=sz[trie[curr][0]];
countl+=sz[trie[curl][0]];
}
curr=trie[curr][edge];
curl=trie[curl][edge];
}
countl+=sz[curl];
countr+=sz[curr];
System.out.println(countr-countl);
}
}
class Printer{
public <T> T printArray(T obj[] ,String details){
System.out.println(details);
for(int i=0;i<obj.length;i++)
System.out.print(obj[i]+" ");
System.out.println();
return obj[0];
}
public <T> void print(T obj,String details){
System.out.println(details+" "+obj);
}
}
class Node{
long weight;
int vertex;
public Node(int vertex,long weight){
this.vertex=vertex;
this.weight=weight;
}
public String toString(){
return vertex+" "+weight;
}
}
class Graph{
int nv; //0 indexing i.e vertices starts from 0 input as 1 indexed for add Edge
List<List<Node>> adj;
boolean visited[];
public Graph(int n){
adj=new ArrayList<>();
this.nv=n;
// visited=new boolean[nv];
for(int i=0;i<n;i++)
adj.add(new ArrayList<Node>());
}
public void addEdge(int u,int v,long weight){
u--;v--;
Node first=new Node(v,weight);
Node second=new Node(u,weight);
adj.get(v).add(second);
adj.get(u).add(first);
}
public void dfscheck(int u,long curweight){
visited[u]=true;
for(Node i:adj.get(u)){
if(visited[i.vertex]==false&&(i.weight|curweight)==curweight)
dfscheck(i.vertex,curweight);
}
}
long maxweight;
public void clear(){
this.adj=null;
this.nv=0;
}
public void solve() {
maxweight=(1l<<32)-1;
dfsutil(31);
System.out.println(maxweight);
}
public void dfsutil(int msb){
if(msb<0)return;
maxweight-=(1l<<msb);
visited=new boolean[nv];
dfscheck(0,maxweight);
for(int i=0;i<nv;i++)
{
if(visited[i]==false)
{maxweight+=(1<<msb);
break;}
}
dfsutil(msb-1);
}
// public boolean TopologicalSort() {
// top=new int[nv];
// int cnt=0;
// int indegree[]=new int[nv];
// for(int i=0;i<nv;i++){
// for(int j:adj.get(i)){
// indegree[j]++;
// }
// }
// Deque<Integer> q=new LinkedList<Integer>();
// for(int i=0;i<nv;i++){
// if(indegree[i]==0){
// q.addLast(i);
// }
// }
// while(q.size()>0){
// int tele=q.pop();
// top[tele]=cnt++;
// for(int j:adj.get(tele)){
// indegree[j]--;
// if(indegree[j]==0)
// q.addLast(j);
// }
// }
// return cnt==nv;
// }
// public boolean isBipartiteGraph(){
// col=new Integer[nv];
// visited=new boolean[nv];
// for(int i=0;i<nv;i++){
// if(visited[i]==false){
// col[i]=0;
// dfs(i);
// }
// }
}
class DSU{
int []parent;
int rank[];
int n;
public DSU(int n){
this.n=n;
parent=new int[n];
rank=new int[n];
for(int i=0;i<n;i++)
{ parent[i]=i;
rank[i]=1;
}
}
public int find(int i){
if(parent[i]==i)return i;
return parent[i]=find(parent[i]);
}
public boolean union(int a,int b){
int pa=find(a);
int pb=find(b);
if(pa==pb)return false;
if(rank[pa]>rank[pb]){
parent[pb]=pa;
rank[pa]+=rank[pb];
}
else{
parent[pa]=pb;
rank[pb]+=rank[pa];
}
return true;
}
}
class SegmentTree{
long tree[];
long data[];
int tsize;
int dsize;
public SegmentTree(long data[],int n){
this.tsize=4*n+1;
this.dsize=n;
this.data=data;
this.tree=new long[tsize];
build(0,n-1,0);
}
public SegmentTree(int n,long def){
this.tsize=4*n+1;
this.dsize=n;
this.data=new long[n];
for(int i=0;i<n;i++){
data[i]=def;
}
this.tree=new long[tsize];
build(0,n-1,0);
}
public void build(int l,int r,int treeindex){
if(l==r){
tree[treeindex]=data[l];
return ;
}
int mid=(l+r)/2;
build(l,mid,2*treeindex+1);
build(mid+1,r,2*treeindex+2);
tree[treeindex]=Math.max(tree[2*treeindex+1],tree[2*treeindex+2]);
}
public void updateOneImpl(int l,int r,int tind,int dind){
if(l==r&&l==dind){
tree[tind]=data[dind];
return ;
}
if(dind>=l&&dind<=r){
int mid=(l+r)/2;
updateOneImpl(l,mid,2*tind+1,dind);
updateOneImpl(mid+1,r,2*tind+2,dind);
tree[tind]=Math.max(tree[2*tind+1],tree[2*tind+2]);
}
// System.out.println("In range "+l+" "+r+" "+tree[tind]);
}
public void updateOne(int index,long value){
data[index]=value;
updateOneImpl(0,dsize-1,0,index);
}
public long getRangeValueImpl(int ql,int qr,int tl,int tr,int tind){
if(tr<ql||qr<tl){
return Long.MIN_VALUE;
}
if(qr>=tr&&ql<=tl)return tree[tind];
int mid=(tl+tr)/2;
long l=getRangeValueImpl(ql, qr, tl, mid, 2*tind+1);
long r=getRangeValueImpl(ql, qr, mid+1, tr, 2*tind+2);
//System.out.println("In range "+tl+" "+tr+" "+Math.max(l,r));
return Math.max(l,r);
}
public long getRangeValue(int l,int r){
long temp= getRangeValueImpl(l,r, 0, dsize-1, 0);
// System.out.println(" Max Value in between "+l+" "+r+" = "+temp);
return temp;
}
public void printData(){
System.out.println("The Data After updation");
for(int i=0;i<dsize;i++){
System.out.print(data[i]+" ");
}
System.out.println();
// System.out.println(" The Tree After Updation");
// for(int i=0;i<tsize;i++){
// System.out.print(tree[i]+" ");
// }
// System.out.println();
}
} | Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 12b2b78715d1b58180470ecc827beaa6 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class CyclicRotation {
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 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 double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0,
BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
static Reader in = new Reader();
public static void solve() throws IOException
{
int n = in.nextInt();
int[] a = new int[n];
int[] b = new int[n];
for(int i=0 ; i<n ;i++)
a[i] = in.nextint();
for(int i=0 ; i<n ;i++)
b[i] = in.nextint();
if(a[n-1] != b[n-1])
{
System.out.println("NO");
return;
}
int[] marq = new int[n+1];
int i = n-2 , j = n-2;
while( i >= 0 && j >= 0)
{
if(a[i] == b[j])
{
i--; j--;
}
else
{
if(b[j] == b[j+1])
{
marq[b[j]]++;
j--;
}
else
{
if(marq[a[i]]==0)
{
System.out.println("NO");
return;
}
marq[a[i]]--;
i--;
}
}
}
System.out.println("YES");
return;
}
public static void main(String[] args) throws IOException
{
int t = in.nextInt();
while(t --> 0)
{
solve();
}
}
} | Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | b731ac27a49b25ddffef29bb7c8dd507 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.util.*;
import java.io.*;
public class tr0 {
static PrintWriter out;
static StringBuilder sb;
static long mod = (long) 998244353;
static long inf = (long) 1e16;
static int n, m;
static ArrayList<Integer>[] ad, ad1;
static int[][] remove, add;
static long[][] memo;
static long[] inv, f, ncr[];
static HashMap<Integer, Integer> hm;
static int[] pre, suf, Smax[], Smin[];
static int idmax, idmin;
static ArrayList<Integer> av;
static HashMap<Integer, Integer> mm;
static boolean[] msks;
static int[] lazy[], lazyCount;
static int[] c, w;
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
out = new PrintWriter(System.out);
int t = sc.nextInt();
int c = 1;
while (t-- > 0) {
int n = sc.nextInt();
int[] a = sc.nextArrInt(n);
int[] b = sc.nextArrInt(n);
// if (c == 201) {
// System.out.println(n);
// for (int k : a)
// System.out.print(k + " ");
// System.out.println();
// for (int k : b)
// System.out.print(k + " ");
// return;
// }
c++;
boolean f = true;
boolean[] v = new boolean[n];
int id = 0;
TreeSet<Integer>[] ap = new TreeSet[n + 1];
for (int i = 0; i <= n; i++)
ap[i] = new TreeSet<>();
for (int i = 0; i < n; i++) {
ap[b[i]].add(i);
}
for (int i = 0; i < n; i++) {
// System.out.println(i + " " + id + " " + Arrays.toString(v));
while (v[id])
id++;
if (a[i] == b[id]) {
id++;
} else {
int k = a[i];
int ik = -1;
while (!ap[k].isEmpty()) {
int fi = ap[k].pollFirst();
if (!ap[k].isEmpty() && ap[k].first() == fi + 1 && ap[k].first() > id) {
ik = ap[k].first();
break;
}
}
if (ik == -1) {
f = false;
break;
}
v[ik] = true;
}
}
if (f)
out.println("YES");
else
out.println("NO");
}
out.flush();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public Scanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
public int[] nextArrInt(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public long[] nextArrLong(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public int[] nextArrIntSorted(int n) throws IOException {
int[] a = new int[n];
Integer[] a1 = new Integer[n];
for (int i = 0; i < n; i++)
a1[i] = nextInt();
Arrays.sort(a1);
for (int i = 0; i < n; i++)
a[i] = a1[i].intValue();
return a;
}
public long[] nextArrLongSorted(int n) throws IOException {
long[] a = new long[n];
Long[] a1 = new Long[n];
for (int i = 0; i < n; i++)
a1[i] = nextLong();
Arrays.sort(a1);
for (int i = 0; i < n; i++)
a[i] = a1[i].longValue();
return a;
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
} | Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | edb56c73859d29e0eca1e28212a7d097 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 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();
int T=sc.nextInt();
// int T=1;
for (int tt=1; tt<=T; tt++){
int n = sc.nextInt();
int arr[]=sc.readArray(n);
int b[]=sc.readArray(n);
boolean f=true;
Map<Integer,Integer> xx=new HashMap<>();
int j=n-1;
for (int i=n-1;i>=0; i-- ){
if (arr[i]!=b[j]){
if (i==n-1) f=false;
else if (b[j]==b[j+1]){
// arr[i]=arr[i+1];
if (!xx.containsKey(b[j])) xx.put(b[j],1);
else xx.put(b[j],xx.get(b[j])+1);
i++;
j--;
}
else if (xx.containsKey(arr[i])){
xx.put(arr[i],xx.get(arr[i])-1);
if (xx.get(arr[i])==0) xx.remove(arr[i]);
}
else f=false;
}
else j--;
if (!f || j<0) break;
}
if (f) System.out.println("YES");
else System.out.println("NO");
}
}
static class SegmentTree{
int nodes[];
int arr[];
int lazy[];
public SegmentTree(int n, int arr[]){
nodes = new int [4*n+1];
lazy= new int [4*n+1];
this.arr=arr;
build(1,1,n);
}
private void build (int v, int l , int r){
if (l==r) {
nodes[v]=arr[l-1];}
else {
int m=(l+r)/2;
build(2*v,l,m);
build(2*v+1,m+1,r);
nodes[v]=Math.min(nodes[2*v], nodes[2*v+1]);
}
}
private void push(int v) {
nodes[v*2] += lazy[v];
lazy[v*2] += lazy[v];
nodes[v*2+1] += lazy[v];
lazy[v*2+1] += lazy[v];
lazy[v] = 0;
}
private void update(int v, int l, int r, int x, int y, int add) {
if (l>y || r<x) return;
if (l>=x && y>=r) {
nodes[v]+=add;
lazy[v]+=add;
}
else {
push(v);
int mid =(l+r)/2;
update(2*v,l,mid,x,y,add);
update(2*v+1,mid+1,r,x,y,add);
nodes[v]=Math.min(nodes[v*2], nodes[v*2+1]);
}
}
private int query(int v, int l, int r, int x, int y){
if (l>y || r<x) return Integer.MAX_VALUE;
if (l>=x && r<=y) return nodes[v];
else {
int m = (l+r)/2;
push(v);
return Math.min(query(2*v+1,m+1,r,x,y),query(2*v,l,m,x,y));
}
}
}
static class LPair{
long x,y;
LPair(long x , long y){
this.x=x;
this.y=y;
}
}
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 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 boolean []sieveOfEratosthenes(int n){
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;
}
}
return prime;
}
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);
}
// 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 | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 45b4df7c808b637994b550da427d9ec6 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import static java.lang.System.out;
import java.util.*;
import java.io.*;
import java.math.*;
/*
getOrDefault
valueOf
System.out.println();
*/
public class HelloWorld{
public static void main(String []args) throws Exception
{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int T=Integer.parseInt(st.nextToken());
for(int z=0;z<T;z++){
st = new StringTokenizer(infile.readLine());
int n=Integer.parseInt(st.nextToken());
st = new StringTokenizer(infile.readLine());
//long[] arr=new long[n];
int[] a=new int[n+1];
build(a,n,st,1);
st = new StringTokenizer(infile.readLine());
int[] b=new int[n];
build(b,n,st,0);
//for(int i=0;i<n;i++) System.out.print(b[i]+" ");
//System.out.println();
Map<Integer,Integer> map=new HashMap<>();
int id=1;
boolean exit=false;
for(int i=0;i<n;i++){
if(id==n+1){
if(b[i]!=a[n] || map.getOrDefault(a[n],0)==0){
exit=true;
System.out.println("NO");
break;
}
else map.put(a[n], map.getOrDefault(a[n],0)-1);
}
else{
if(a[id]==b[i]){
id++;
continue;
}
else if(a[id-1]==b[i] && map.getOrDefault(a[id-1],0)>0){
map.put(a[id-1], map.get(a[id-1])-1);
continue;
}
while(id<n && a[id]!=b[i]){
map.put(a[id], map.getOrDefault(a[id],0)+1);
id++;
}
if(id==n){
exit=true;
System.out.println("NO");
break;
}
else id++;
}
}
if(!exit) System.out.println("YES");
}
}
//public static void build(long[] arr, int n, StringTokenizer st){
// for(int i=0;i<n;i++) arr[i]=Long.parseLong(st.nextToken());
//}
public static void build(int[] arr, int n, StringTokenizer st, int lo){
for(int i=lo;i<arr.length;i++) arr[i]=Integer.parseInt(st.nextToken());
}
}
class SEG{
int[] tr;
int[] arr;
public SEG(int size, int[] a){
tr=new int[size];
arr=a;
}
public void update(int id,int ss,int se,int qs, int qe, int val){
if(ss==qs && se==qe){
tr[id]=val;
return;
}
if(qe<ss || qs>se) return;
int tm = (ss + se) / 2;
update(id*2, ss, tm,qs,qe,val);
update(id*2+1, tm+1, se,qs,qe,val);
tr[id] = tr[id*2] + tr[id*2+1];
}
public int query(int id,int ss,int se,int qs, int qe){
if (qs > qe) return 0;
if (qs == ss && qe == se) {
return tr[id];
}
int mid = (ss + se) / 2;
return query(id*2, ss, mid, qs, min(qe, mid))
+ query(id*2+1, mid+1, se, max(qs, mid+1), qe);
}
public void build(int id,int l,int r){
if(l==r){
tr[id]=arr[l];
return;
}
int tm = (l + r) / 2;
build(id*2, l, tm);
build(id*2+1, tm+1, r);
tr[id] = tr[id*2] + tr[id*2+1];
}
}
class DSU{
int[] parent;
int[] size;
public DSU(int n){
this.parent=new int[n];
this.size=new int[n];
for(int i=0;i<n;i++){
parent[i]=i;
size[i]=1;
}
}
public int find(int x){
if(x!=parent[x]){
parent[x]=find(parent[x]);
}
return parent[x];
}
public void union(int x,int y){
int rootx=find(x);
int rooty=find(y);
if(rootx==rooty) return;
if(size[rootx]>size[rooty]){
parent[rooty]=rootx;
size[rootx]+=size[rooty];
}
else{
parent[rootx]=rooty;
size[rooty]+=size[rootx];
}
}
public boolean connect(int x, int y){
return find(x)==find(y);
}
} | Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | a586b22ac1bf844083ead1b5bf441098 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.*;
public class Codeforces {
static long mod= Long.MAX_VALUE;
public static void main(String[] args) throws Exception {
PrintWriter out=new PrintWriter(System.out);
FastScanner fs=new FastScanner();
// DecimalFormat formatter= new DecimalFormat("#0.000000");
int t=fs.nextInt();
// int t=1;
outer:for(int time=1;time<=t;time++) {
int n=fs.nextInt();
int arr[]=fs.readArray(n);
int brr[]=fs.readArray(n);
Map<Integer,Integer> map=new HashMap<>();
int i=n-1,j=n-1;
while(i>=0) {
if(j>0&&brr[j]==brr[j-1]) {
map.put(brr[j], map.getOrDefault(brr[j], 0)+1);
j--;
continue ;
}
if(j>=0&&arr[i]==brr[j]) {
i--;
j--;
continue;
}
if(map.getOrDefault(arr[i], 0)>0) {
map.put(arr[i],map.getOrDefault(arr[i], 0)-1);
i--;
}
else {
out.println("NO");
continue outer;
}
}
out.println("YES");
}
out.close();
}
static long pow(long a,long b) {
if(b<0) return 1;
long res=1;
while(b!=0) {
if((b&1)!=0) {
res*=a;
res%=mod;
}
a*=a;
a%=mod;
b=b>>1;
}
return res;
}
static long gcd(long a,long b) {
if(b==0) return a;
return gcd(b,a%b);
}
static long nck(int n,int k) {
if(k>n) return 0;
long res=1;
res*=fact(n);
res%=mod;
res*=modInv(fact(k));
res%=mod;
res*=modInv(fact(n-k));
res%=mod;
return res;
}
static long fact(long n) {
// return fact[(int)n];
long res=1;
for(int i=2;i<=n;i++) {
res*=i;
res%=mod;
}
return res;
}
static long modInv(long n) {
return pow(n,mod-2);
}
static void sort(int[] a) {
//suffle
int n=a.length;
Random r=new Random();
for (int i=0; i<a.length; i++) {
int oi=r.nextInt(n);
int temp=a[i];
a[i]=a[oi];
a[oi]=temp;
}
//then sort
Arrays.sort(a);
}
static void sort(long[] a) {
//suffle
int n=a.length;
Random r=new Random();
for (int i=0; i<a.length; i++) {
int oi=r.nextInt(n);
long temp=a[i];
a[i]=a[oi];
a[oi]=temp;
}
//then sort
Arrays.sort(a);
}
// Use this to input code since it is faster than a Scanner
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();
}
String nextLine() {
String str="";
try {
str= (br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int nextInt() {
return Integer.parseInt(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
long[] readArrayL(int n) {
long a[]=new long[n];
for(int i=0;i<n;i++) a[i]=nextLong();
return a;
}
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 | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 5ebefd53a262f9627860f429517a5d24 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | /*
I am dead inside
Do you like NCT, sKz, BTS?
5 4 3 2 1 Moonwalk
Imma knock it down like domino
Is this what you want? Is this what you want?
Let's ttalkbocky about that
*/
import static java.lang.Math.*;
import java.util.*;
import java.io.*;
public class CyclicRotation
{
public static void main(String omkar[]) throws Exception
{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int T = Integer.parseInt(st.nextToken());
StringBuilder sb = new StringBuilder();
tc:while(T-->0)
{
st = new StringTokenizer(infile.readLine());
int N = Integer.parseInt(st.nextToken());
int[] arr = readArr(N, infile, st);
int[] brr = readArr(N, infile, st);
if(arr[N-1] != brr[N-1])
{
sb.append("NO\n");
continue tc;
}
int[] moved = new int[N+1];
int pointer = N-2;
for(int i=N-2; i >= 0; i--)
{
while(pointer >= 0 && brr[pointer] == brr[pointer+1] && arr[i] != brr[pointer])
{
moved[brr[pointer]]++;
pointer--;
}
if(pointer == -1 || brr[pointer] != arr[i])
{
moved[arr[i]]--;
if(moved[arr[i]] < 0)
{
sb.append("NO\n");
continue tc;
}
}
else
pointer--;
}
sb.append("YES\n");
}
System.out.print(sb);
}
public static int[] readArr(int N, BufferedReader infile, StringTokenizer st) throws Exception
{
int[] arr = new int[N];
st = new StringTokenizer(infile.readLine());
for(int i=0; i < N; i++)
arr[i] = Integer.parseInt(st.nextToken());
return arr;
}
} | Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 990700920dfa7f5f34add75e67339186 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes |
import javax.swing.*;
import java.lang.reflect.Array;
import java.text.DecimalFormat;
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;
import java.util.stream.Stream;
// Please name your class Main
public class Main {
static FastScanner fs=new FastScanner();
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
public String next() {
while (!st.hasMoreElements())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int Int() {
return Integer.parseInt(next());
}
long Long() {
return Long.parseLong(next());
}
String Str(){
return next();
}
}
public static void main (String[] args) throws java.lang.Exception {
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
//reading /writing file
//Scanner in=new Scanner(System.in);
//Scanner in=new Scanner(new File("input.txt"));
//PrintWriter pr=new PrintWriter("output.txt")
int T=Int();
for(int t=0;t<T;t++){
Solution sol1=new Solution(out,fs);
sol1.solution(T,t);
}
out.flush();
}
public static int[] Arr(int n){
int A[]=new int[n];
for(int i=0;i<n;i++)A[i]=Int();
return A;
}
public static int Int(){
return fs.Int();
}
public static long Long(){
return fs.Long();
}
public static String Str(){
return fs.Str();
}
}
class Solution {
PrintWriter out;
int INF = Integer.MAX_VALUE;
int NINF = Integer.MIN_VALUE;
int MOD = 998244353;
int mod = 998244353;
Main.FastScanner fs;
public Solution(PrintWriter out, Main.FastScanner fs) {
this.out = out;
this.fs = fs;
}
public void add(Map<Integer, Integer> f, int key) {
Integer cnt = f.get(key);
if(cnt == null) {
f.put(key, 1);
} else {
f.put(key, cnt + 1);
}
}
public void del(Map<Integer, Integer> f, int key) {
Integer cnt = f.get(key);
if(cnt == 1) {
f.remove(key);
} else {
f.put(key, cnt - 1);
}
}
public void msg(String s) {
System.out.println(s);
}
public void solution(int all, int testcase) {
int n = fs.Int();
int a[] = new int[n];
int b[] = new int[n];
for(int i = 0; i < n; i++) {
a[i] =fs.Int();
}
for(int i = 0; i < n; i++) {
b[i] =fs.Int();
}
if(b[n - 1] != a[n - 1]) {
out.println("NO");
return;
}
int cnt[] = new int[n + 1];
PriorityQueue<int[]> pq = new PriorityQueue<>((x,y) -> {
return y[1] - x[1];
});
for(int i = 0; i < n - 1; i++) {
pq.add(new int[]{a[i], i});
}
for(int i = n - 2; i >= 0; i--) {
int top[] = pq.peek();
if(top[0] == b[i]) {
pq.poll();
} else {
if(b[i] == b[i + 1]) {
cnt[b[i]]++;
} else {
while(pq.size() > 0) {
int pair[] = pq.peek();
if(pair[0] == b[i]) break;
if(cnt[pair[0]] > 0) {
cnt[pair[0]]--;
pq.poll();
} else {
out.println("NO");
return;
}
}
int pair[] = pq.peek();
if(pair[0] == b[i]) {
pq.poll();
} else {
out.println("NO");
return;
}
}
}
}
out.println("YES");
}
}
| Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 0a9ed45c6164de3f7a6dce791f3b5f9c | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class CyclicRotation {
static class Pair
{
int f;int s; //
Pair(){}
Pair(int f,int s){ this.f=f;this.s=s;}
}
static class sortbyfirst implements Comparator<Pair>
{
public int compare(Pair a, Pair b)
{
return a.f-b.f;
}
}
static class Fast {
BufferedReader br;
StringTokenizer st;
public Fast() {
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
int[] readArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
long[] readArray1(int n) {
long a[] = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
String nextLine() {
String str = "";
try {
str = br.readLine().trim();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
/* static long noOfDivisor(long a)
{
long count=0;
long t=a;
for(long i=1;i<=(int)Math.sqrt(a);i++)
{
if(a%i==0)
count+=2;
}
if(a==((long)Math.sqrt(a)*(long)Math.sqrt(a)))
{
count--;
}
return count;
}*/
static boolean isPrime(long a) {
for (long i = 2; i <= (long) Math.sqrt(a); i++) {
if (a % i == 0)
return false;
}
return true;
}
static void primeFact(int n) {
int temp = n;
HashMap<Integer, Integer> h = new HashMap<>();
for (int i = 2; i * i <= n; i++) {
if (temp % i == 0) {
int c = 0;
while (temp % i == 0) {
c++;
temp /= i;
}
h.put(i, c);
}
}
if (temp != 1)
h.put(temp, 1);
}
static void reverseArray(int a[]) {
int n = a.length;
for (int i = 0; i < n / 2; i++) {
a[i] = a[i] ^ a[n - i - 1];
a[n - i - 1] = a[i] ^ a[n - i - 1];
a[i] = a[i] ^ a[n - i - 1];
}
}
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 sort(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 int max(int a,int b)
{
return a>b?a:b;
}
static int min(int a,int b)
{
return a<b?a:b;
}
public static void main(String args[]) throws IOException {
Fast sc = new Fast();
PrintWriter out = new PrintWriter(System.out);
int t1 = sc.nextInt();
outer: while (t1-- > 0) {
int n=sc.nextInt();int a[]=sc.readArray(n);
int b[]=sc.readArray(n);
int ai=n-1;int i=n-1;
int[] toHandle=new int[n+1];
while(i>0)
{
// if two pointers are equal decrease both by 1
if(a[ai]==b[i])
{
ai--;i--;
}
//we will handle it later
else if(i<n-1&&b[i]==b[i+1])
{
toHandle[b[i]]++;i--;
}
//otherwise they don't match, this a[i] needs to be handled
else if(toHandle[a[ai]]==0)
{
out.println("NO");continue outer;
}
else
{
toHandle[a[ai]]--;
ai--;
}
}
out.println("YES");
}
out.close();
}
}
| Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 5f5b41408d667b9a76b1619f77254c6f | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class CyclicRotation {
static class Pair
{
int f;int s; //
Pair(){}
Pair(int f,int s){ this.f=f;this.s=s;}
}
static class sortbyfirst implements Comparator<Pair>
{
public int compare(Pair a, Pair b)
{
return a.f-b.f;
}
}
static class Fast {
BufferedReader br;
StringTokenizer st;
public Fast() {
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
int[] readArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
long[] readArray1(int n) {
long a[] = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
String nextLine() {
String str = "";
try {
str = br.readLine().trim();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
/* static long noOfDivisor(long a)
{
long count=0;
long t=a;
for(long i=1;i<=(int)Math.sqrt(a);i++)
{
if(a%i==0)
count+=2;
}
if(a==((long)Math.sqrt(a)*(long)Math.sqrt(a)))
{
count--;
}
return count;
}*/
static boolean isPrime(long a) {
for (long i = 2; i <= (long) Math.sqrt(a); i++) {
if (a % i == 0)
return false;
}
return true;
}
static void primeFact(int n) {
int temp = n;
HashMap<Integer, Integer> h = new HashMap<>();
for (int i = 2; i * i <= n; i++) {
if (temp % i == 0) {
int c = 0;
while (temp % i == 0) {
c++;
temp /= i;
}
h.put(i, c);
}
}
if (temp != 1)
h.put(temp, 1);
}
static void reverseArray(int a[]) {
int n = a.length;
for (int i = 0; i < n / 2; i++) {
a[i] = a[i] ^ a[n - i - 1];
a[n - i - 1] = a[i] ^ a[n - i - 1];
a[i] = a[i] ^ a[n - i - 1];
}
}
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 sort(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 int max(int a,int b)
{
return a>b?a:b;
}
static int min(int a,int b)
{
return a<b?a:b;
}
public static void main(String args[]) throws IOException {
Fast sc = new Fast();
PrintWriter out = new PrintWriter(System.out);
int t1 = sc.nextInt();
outer: while (t1-- > 0) {
int n=sc.nextInt();int a[]=sc.readArray(n);
int b[]=sc.readArray(n);
int ai=n-1;int i=n-1;
int[] toHandle=new int[n+1];
while(i>0)
{
if(a[ai]==b[i])
{
ai--;i--;
}
else if(i<n-1&&b[i]==b[i+1])
{
toHandle[b[i]]++;i--;
}
else if(toHandle[a[ai]]==0)
{
out.println("NO");continue outer;
}
else
{
toHandle[a[ai]]--;
ai--;
}
}
out.println("YES");
}
out.close();
}
}
| Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 09a0605bd6fd2a6edc6ea13c6a67739f | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
//--------------------------INPUT READER---------------------------------//
static class fs {
public BufferedReader br;
StringTokenizer st = new StringTokenizer("");
public fs() { this(System.in); }
public fs(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
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 nn) {
int n = (int) nn;
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = ni();
return a;
}
long[] nal(long nn) {
int n = (int) nn;
long[] l = new long[n];
for(int i = 0; i < n; i++) l[i] = nl();
return l;
}
}
//-----------------------------------------------------------------------//
//---------------------------PRINTER-------------------------------------//
static class Printer {
static PrintWriter w;
public Printer() {this(System.out);}
public Printer(OutputStream os) {
w = new PrintWriter(os);
}
public void p(int i) {w.println(i);}
public void p(long l) {w.println(l);}
public void p(double d) {w.println(d);}
public void p(String s) { w.println(s);}
public void pr(int i) {w.print(i);}
public void pr(long l) {w.print(l);}
public void pr(double d) {w.print(d);}
public void pr(String s) { w.print(s);}
public void pl() {w.println();}
public void close() {w.close();}
}
//-----------------------------------------------------------------------//
//--------------------------VARIABLES------------------------------------//
static fs sc = new fs();
static OutputStream outputStream = System.out;
static Printer w = new Printer(outputStream);
static long lma = Long.MAX_VALUE, lmi = Long.MIN_VALUE;
static int ima = Integer.MAX_VALUE, imi = Integer.MIN_VALUE;
static long mod = 1000000007;
//-----------------------------------------------------------------------//
//--------------------------ADMIN_MODE-----------------------------------//
private static void ADMIN_MODE() throws IOException {
if (System.getProperty("ONLINE_JUDGE") == null) {
w = new Printer(new FileOutputStream("output.txt"));
sc = new fs(new FileInputStream("input.txt"));
}
}
//-----------------------------------------------------------------------//
//----------------------------START--------------------------------------//
public static void main(String[] args)
throws IOException {
ADMIN_MODE();
int t = sc.ni();
while(t-->0) {
count++;
solve();
}
w.close();
}
static int count = 0;
static void solve() throws IOException {
int n = sc.ni();
int[] arr = sc.na(n);
int[] arr2 = sc.na(n);
// if(count == 515) {
// for(int i: arr) {
// w.pr(i+":");
// }
// w.pr("_");
// for(int i: arr2) {
// w.pr(i+":");
// }
// }
HashMap<Integer, Integer> hm = new HashMap<>();
int r1 = n-1, r2 = n-1;
while(r2 >= 0) {
if(arr[r1] == arr2[r2]) {
r1--;
r2--;
continue;
}
if(r2 != n-1 && arr2[r2] == arr2[r2+1]) {
hm.put(arr2[r2], hm.getOrDefault(arr2[r2], 0)+1);
r2--;
continue;
}
if(hm.containsKey(arr[r1])) {
hm.replace(arr[r1], hm.get(arr[r1])-1);
if(hm.get(arr[r1]) == 0) hm.remove(arr[r1]);
r1--;
continue;
}
w.p("NO");
return;
}
while(hm.size() > 0) {
if(!hm.containsKey(arr[r1])) {
w.p("NO");
return;
}
hm.replace(arr[r1], hm.get(arr[r1])-1);
if(hm.get(arr[r1]) == 0) hm.remove(arr[r1]);
r1--;
}
w.p("YES");
}
} | Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | d706fa1996e50d2de221cd040ca6532d | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.NoSuchElementException;
import java.util.*;
import static java.util.Arrays.*;
public class CodeforcesTemp {
public static void main(String[] args) throws IOException {
Reader scan = new Reader();
FastPrinter out = new FastPrinter();
int t = scan.nextInt();
for (int tc = 1; tc <= t; tc++) {
int n=scan.nextInt();
int[] a=scan.nextIntArray(n);
int[] b=scan.nextIntArray(n);
int[] taken=new int[(int) (1e5*2+1)];
String ans="YES";
int i=n-1,j=n-1;
while (i>=0 && j>=0){
if(a[i]!=b[j]){
if((i+1)<n && a[i+1]==b[j]){
taken[b[j]]++;
j--;
}
else if(taken[a[i]]>0){
taken[a[i]]--;
i--;
}
else {
ans="NO";
break;
}
}
else {
i--;
j--;
}
}
out.println(ans);
}
out.close();
}
static class Reader {
private final 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 Reader(InputStream in) {
this.in = in;
}
public Reader() {
this(System.in);
}
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;
}
public boolean hasNext() {while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++;
return hasNextByte();}
public String next() {
if (!hasNext())
throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = readByte();
while (isPrintableChar(b)) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public long 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') {
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("not number"));
}
}
} 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("not number"));
}
}
}
}
throw new ArithmeticException(
String.format(" overflows long."));
}
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[][] nextIntArrayMulti(int length, int width) {
int[][] arrays = new int[width][length];
for (int i = 0; i < length; i++) {
for (int j = 0; j < width; j++)
arrays[j][i] = this.nextInt();
}
return arrays;
}
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;
}
}
static class FastPrinter extends PrintWriter {
public FastPrinter(PrintStream stream) {
super(stream);
}
public FastPrinter() {
super(System.out);
}
private static String dtos(double x, int n) {
StringBuilder sb = new StringBuilder();
if (x < 0) {
sb.append('-');
x = -x;
}
x += Math.pow(10, -n) / 2;
sb.append((long) x);
sb.append(".");
x -= (long) x;
for (int i = 0; i < n; i++) {
x *= 10;
sb.append((int) x);
x -= (int) x;
}
return sb.toString();
}
@Override
public void print(float f) {
super.print(dtos(f, 20));
}
@Override
public void println(float f) {
super.println(dtos(f, 20));
}
@Override
public void print(double d) {
super.print(dtos(d, 20));
}
@Override
public void println(double d) {
super.println(dtos(d, 20));
}
public void printArray(int[] array, String separator) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
super.print(array[i]);
super.print(separator);
}
super.println(array[n - 1]);
}
public void printArray(int[] array) {
this.printArray(array, " ");
}
public void printArray(int[] array, String separator, java.util.function.IntUnaryOperator map) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
super.print(map.applyAsInt(array[i]));
super.print(separator);
}
super.println(map.applyAsInt(array[n - 1]));
}
public void printArray(int[] array, java.util.function.IntUnaryOperator map) {
this.printArray(array, " ", map);
}
public void printArray(long[] array, String separator) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
super.print(array[i]);
super.print(separator);
}
super.println(array[n - 1]);
}
public void printArray(long[] array) {
this.printArray(array, " ");
}
public void printArray(long[] array, String separator, java.util.function.LongUnaryOperator map) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
super.print(map.applyAsLong(array[i]));
super.print(separator);
}
super.println(map.applyAsLong(array[n - 1]));
}
public void printArray(long[] array, java.util.function.LongUnaryOperator map) {
this.printArray(array, " ", map);
}
public void printMatrix(int[][] arr) {
for (int i = 0; i < arr.length; i++) {
this.printArray(arr[i]);
}
}
}
static Random __r = new Random();
static int randInt(int min, int max) {return __r.nextInt(max - min + 1) + min;}
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;}
}
| Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 2fff0850b47e92760c30f1771aed1c77 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.NoSuchElementException;
import java.util.*;
import static java.util.Arrays.*;
public class CodeforcesTemp {
public static void main(String[] args) throws IOException {
Reader scan = new Reader();
FastPrinter out = new FastPrinter();
int t = scan.nextInt();
outer:for (int tc = 1; tc <= t; tc++) {
int n=scan.nextInt();
int[] a=scan.nextIntArray(n);
int[] b=scan.nextIntArray(n);
int[] taken=new int[(int) (1e5*2+1)];
int i=n-1,j=n-1;
while (i>=0 && j>=0){
if(a[i]!=b[j]){
if((i+1)<n && a[i+1]==b[j]){
taken[b[j]]++;
j--;
}
else if(taken[a[i]]>0){
taken[a[i]]--;
i--;
}
else {
out.println("NO");
continue outer;
}
}
else {
i--;
j--;
}
}
out.println("YES");
}
out.close();
}
static class Reader {
private final 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 Reader(InputStream in) {
this.in = in;
}
public Reader() {
this(System.in);
}
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;
}
public boolean hasNext() {while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++;
return hasNextByte();}
public String next() {
if (!hasNext())
throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = readByte();
while (isPrintableChar(b)) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public long 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') {
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("not number"));
}
}
} 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("not number"));
}
}
}
}
throw new ArithmeticException(
String.format(" overflows long."));
}
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[][] nextIntArrayMulti(int length, int width) {
int[][] arrays = new int[width][length];
for (int i = 0; i < length; i++) {
for (int j = 0; j < width; j++)
arrays[j][i] = this.nextInt();
}
return arrays;
}
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;
}
}
static class FastPrinter extends PrintWriter {
public FastPrinter(PrintStream stream) {
super(stream);
}
public FastPrinter() {
super(System.out);
}
private static String dtos(double x, int n) {
StringBuilder sb = new StringBuilder();
if (x < 0) {
sb.append('-');
x = -x;
}
x += Math.pow(10, -n) / 2;
sb.append((long) x);
sb.append(".");
x -= (long) x;
for (int i = 0; i < n; i++) {
x *= 10;
sb.append((int) x);
x -= (int) x;
}
return sb.toString();
}
@Override
public void print(float f) {
super.print(dtos(f, 20));
}
@Override
public void println(float f) {
super.println(dtos(f, 20));
}
@Override
public void print(double d) {
super.print(dtos(d, 20));
}
@Override
public void println(double d) {
super.println(dtos(d, 20));
}
public void printArray(int[] array, String separator) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
super.print(array[i]);
super.print(separator);
}
super.println(array[n - 1]);
}
public void printArray(int[] array) {
this.printArray(array, " ");
}
public void printArray(int[] array, String separator, java.util.function.IntUnaryOperator map) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
super.print(map.applyAsInt(array[i]));
super.print(separator);
}
super.println(map.applyAsInt(array[n - 1]));
}
public void printArray(int[] array, java.util.function.IntUnaryOperator map) {
this.printArray(array, " ", map);
}
public void printArray(long[] array, String separator) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
super.print(array[i]);
super.print(separator);
}
super.println(array[n - 1]);
}
public void printArray(long[] array) {
this.printArray(array, " ");
}
public void printArray(long[] array, String separator, java.util.function.LongUnaryOperator map) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
super.print(map.applyAsLong(array[i]));
super.print(separator);
}
super.println(map.applyAsLong(array[n - 1]));
}
public void printArray(long[] array, java.util.function.LongUnaryOperator map) {
this.printArray(array, " ", map);
}
public void printMatrix(int[][] arr) {
for (int i = 0; i < arr.length; i++) {
this.printArray(arr[i]);
}
}
}
static Random __r = new Random();
static int randInt(int min, int max) {return __r.nextInt(max - min + 1) + min;}
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;}
}
| Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | ebff5406cadde1fd1dfbe4901143c1fb | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.*;
import java.util.*;
public class Failed {
static BufferedReader bf;
static PrintWriter out;
public static void main (String[] args)throws IOException {
bf = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
int t = nextInt();
while(t-->0){
solve();
}
}
public static void solve()throws IOException{
int n = nextInt();
int[]arr = nextIntArray(n);
int[]brr = nextIntArray(n);
Map<Integer,Integer>map = new HashMap<>();
int i = n-1;
int j =n-1 ;
while(i>=0 && j>=0){
while(j > 0 && brr[j-1] == brr[j]){
map.put(brr[j],map.getOrDefault(brr[j],0)+1);
j--;
}
if(arr[i] == brr[j]){
i--;
j--;
}
else{
if(map.containsKey(arr[i]) && map.get(arr[i]) > 0){
map.put(arr[i],map.get(arr[i])-1);
i--;
}
else{
println("NO");
return;
}
}
}
while(i >=0){
if(map.containsKey(arr[i]) && map.get(arr[i]) > 0){
map.put(arr[i],map.get(arr[i])-1);
i--;
}
else{
println("NO");
return;
}
}
println("YES");
}
public static long gcd(long a,long b){
if(b == 0)return a;
return gcd(b,a%b);
}
// code for input
public static void print(String s ){
System.out.print(s);
}
public static void sort(long[]arr){
List<Long>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 static void print(int num ){
System.out.print(num);
}
public static void print(long num ){
System.out.print(num);
}
public static void println(String s){
System.out.println(s);
}
public static void println(int num){
System.out.println(num);
}
public static void println(long num){
System.out.println(num);
}
public static void println(){
System.out.println();
}
public static int toInt(String s){
return Integer.parseInt(s);
}
public static long toLong(String s){
return Long.parseLong(s);
}
public static String[] nextStringArray()throws IOException{
return bf.readLine().split(" ");
}
public static int nextInt()throws IOException{
return Integer.parseInt(bf.readLine());
}
public static long nextLong()throws IOException{
return Long.parseLong(bf.readLine());
}
public static String nextString()throws IOException{
return bf.readLine();
}
public static int[] nextIntArray(int n)throws IOException{
String[]str = bf.readLine().split(" ");
int[]arr = new int[n];
for(int i =0;i<n;i++){
arr[i] = Integer.parseInt(str[i]);
}
return arr;
}
public static long[] nextLongArray(int n)throws IOException{
String[]str = bf.readLine().split(" ");
long[]arr = new long[n];
for(int i =0;i<n;i++){
arr[i] = Long.parseLong(str[i]);
}
return arr;
}
public static int[][] newIntMatrix(int r,int c)throws IOException{
int[][]arr = new int[r][c];
for(int i =0;i<r;i++){
String[]str = bf.readLine().split(" ");
for(int j =0;j<c;j++){
arr[i][j] = Integer.parseInt(str[j]);
}
}
return arr;
}
public static long[][] newLongMatrix(int r,int c)throws IOException{
long[][]arr = new long[r][c];
for(int i =0;i<r;i++){
String[]str = bf.readLine().split(" ");
for(int j =0;j<c;j++){
arr[i][j] = Long.parseLong(str[j]);
}
}
return arr;
}
}
// if a problem is related to binary string it could also be related to parenthesis
// try to use binary search in the question it might work
// try sorting
// try to think in opposite direction of question it might work in your way
// if a problem is related to maths try to relate some of the continuous subarray with variables like - > a+b+c+ or a,b,c,d in general
// gcd(1.p1,2.p2,3.p3,4.p4....n.pn) cannot be greater than 2 it has been proveds | Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 87f48bcf14bf3dc48979a741eb6894a9 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 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 D_Cyclic_Rotation{
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 n=s.nextInt();
long array1[]= new long[n];
for(int i=0;i<n;i++){
array1[i]=s.nextLong();
}
long array2[] = new long[n];
for(int i=0;i<n;i++){
array2[i]=s.nextLong();
}
HashMap<Long,Long> map = new HashMap<Long,Long>();
int index1=n-1;
int index2=n-1;
int flag=0;
while(index1>=0 && index2>=0){
if(index2>0){
long num1=array2[index2];
long num2=array2[index2-1];
if(num1==num2){
if(map.containsKey(num1)){
long a=map.get(num1);
a++;
map.remove(num1);
map.put(num1,a);
}
else{
map.put(num1,1L);
}
index2--;
}
else{
long num3=array1[index1];
if(num3==num1){
index1--;
index2--;
}
else{
if(map.containsKey(num3)){
long a=map.get(num3);
a--;
map.remove(num3);
if(a>0){
map.put(num3,a);
}
index1--;
}
else{
flag=1;
break;
}
}
}
}
else{
long num3=array1[index1];
long num1=array2[index2];
if(num3==num1){
index1--;
index2--;
}
else{
if(map.containsKey(num3)){
long a=map.get(num3);
a--;
map.remove(num3);
if(a>0){
map.put(num3,a);
}
index1--;
}
else{
flag=1;
break;
}
}
}
}
while(index1>=0){
long num3=array1[index1];
if(map.containsKey(num3)){
long a=map.get(num3);
a--;
map.remove(num3);
if(a>0){
map.put(num3,a);
}
index1--;
}
else{
flag=1;
break;
}
}
if(index1>=0 || index2>=0){
flag=1;
}
if(flag==0){
res.append("YES \n");
}
else{
res.append("NO \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 | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 7e13ae6d44f90e9fae77d1c3f1521f50 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.*;
import java.util.*;
public class problemD {
public static void main(String[] args)throws IOException {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
int t = Integer.parseInt(br.readLine());
for(int i=0; i<t; i++) {
int n = Integer.parseInt(br.readLine());
int[] arr = new int[n];
int[] comp = new int[n];
int[] next = new int[n];
Map<Integer, Integer> map = new HashMap<>();
StringTokenizer st = new StringTokenizer(br.readLine());
for(int j=0; j<n; j++)
arr[j] = (Integer.parseInt(st.nextToken()));
for(int j=n-1; j>-1; j--) {
if(map.containsKey(arr[j]))
next[j] = map.get(arr[j]);
else
next[j] = -1;
map.put(arr[j], j);
}
int[] count = new int[n];
Arrays.fill(count, 1);
st = new StringTokenizer(br.readLine());
for(int j=0; j<n; j++) comp[j] = Integer.parseInt(st.nextToken());
int joyce = 0;
int qu = 0;
while(joyce<n&&qu<n) {
if(arr[joyce]==comp[qu]) {
if(count[joyce]==1)joyce++;
else count[joyce]--;
qu++;
}
else {
if(next[joyce]==-1)break;
count[next[joyce]] +=count[joyce];
joyce++;
}
}
if(qu==n)out.write("YES\n");
else out.write("NO\n");
}
out.flush();
out.close();
}
}
| Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | e845ad0937589fc02451716f2e35d71b | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class D {
public static void main(String[] args) throws NumberFormatException, IOException {
MyReader reader = new MyReader();
int t = reader.nextInt();
for(int testcase=0; testcase<t; testcase++) {
int n = reader.nextInt();
int[] a = new int[n];
for(int i=0; i<n; i++) {
a[i] = reader.nextInt();
}
int[] b = new int[n];
for(int i=0; i<n; i++) {
b[i] = reader.nextInt();
}
int i = n-1;
int j = n-1;
int[] deletes = new int[n+1];
boolean NO = false;
while(!(i==-1 && j==-1)) {
if(j == -1 || b[j] != a[i]) {
deletes[a[i]]--;
if(deletes[a[i]] < 0) {
NO = true;
break;
}
i--;
}
else if(i>0 && a[i-1] == a[i]) {
i--;
j--;
}
else if(j==0 || b[j-1] != b[j]) {
i--;
j--;
}
else if(j>0 && b[j-1] == b[j]) {
for(; j>0 && b[j-1] == b[j]; j--) {
deletes[a[i]]++;
}
i--;
j--;
}
else {
System.out.println("error");
}
}
if(NO) System.out.println("NO");
else System.out.println("YES");
}
}
static class MyReader {
BufferedReader br;
StringTokenizer st;
public MyReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() throws IOException {
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(next());
}
long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(next());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(next());
}
String nextLine() throws IOException {
return br.readLine();
}
}
}
| Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 7d9d06a520969c8ec908377ed9f761b1 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class D {
FastScanner in;
PrintWriter out;
boolean systemIO = true;
int mod = 998244353;
public int sum(int x, int y) {
if (x + y >= mod) {
return x + y - mod;
}
return x + y;
}
public int diff(int x, int y) {
if (x >= y) {
return x - y;
}
return x - y + mod;
}
public int mult(int x, int y) {
return (int) (x * 1L * y % mod);
}
public int pow(int x, long p) {
int ans = 1;
while (p > 0) {
if ((p & 1) == 1) {
ans = mult(ans, x);
}
x = mult(x, x);
p >>= 1;
}
return ans;
}
public int inv(int x) {
return pow(x, mod - 2);
}
public int div(int x, int y) {
return mult(x, inv(y));
}
public class DSU {
int[] sz;
int[] p;
public DSU(int n) {
sz = new int[n];
p = new int[n];
for (int i = 0; i < p.length; i++) {
p[i] = i;
sz[i] = 1;
}
}
public int get(int x) {
if (x == p[x]) {
return x;
}
int par = get(p[x]);
p[x] = par;
return par;
}
public boolean unite(int a, int b) {
int pa = get(a);
int pb = get(b);
if (pa == pb) {
return false;
}
if (sz[pa] < sz[pb]) {
p[pa] = pb;
sz[pb] += sz[pa];
} else {
p[pb] = pa;
sz[pa] += sz[pb];
}
return true;
}
}
public class SegmentTreeAdd {
int pow;
long[] max;
long[] delta;
boolean[] flag;
public SegmentTreeAdd(long[] a) {
pow = 1;
while (pow < a.length) {
pow *= 2;
}
flag = new boolean[2 * pow];
max = new long[2 * pow];
delta = new long[2 * pow];
for (int i = 0; i < max.length; i++) {
max[i] = Long.MIN_VALUE / 2;
}
for (int i = 0; i < a.length; i++) {
max[pow + i] = a[i];
}
for (int i = pow - 1; i > 0; i--) {
max[i] = f(max[2 * i], max[2 * i + 1]);
}
}
public long get(int v, int tl, int tr, int l, int r) {
push(v, tl, tr);
if (l > r) {
return Long.MIN_VALUE / 2;
}
if (l == tl && r == tr) {
return max[v];
}
int tm = (tl + tr) / 2;
return f(get(2 * v, tl, tm, l, Math.min(r, tm)), get(2 * v + 1, tm + 1, tr, Math.max(l, tm + 1), r));
}
public void set(int v, int tl, int tr, int l, int r, long x) {
push(v, tl, tr);
if (l > tr || r < tl) {
return;
}
if (l <= tl && r >= tr) {
delta[v] += x;
flag[v] = true;
push(v, tl, tr);
return;
}
int tm = (tl + tr) / 2;
set(2 * v, tl, tm, l, r, x);
set(2 * v + 1, tm + 1, tr, l, r, x);
max[v] = f(max[2 * v], max[2 * v + 1]);
}
public void push(int v, int tl, int tr) {
if (flag[v]) {
if (v < pow) {
flag[2 * v] = true;
flag[2 * v + 1] = true;
delta[2 * v] += delta[v];
delta[2 * v + 1] += delta[v];
}
flag[v] = false;
max[v] += delta[v];
delta[v] = 0;
}
}
public long f(long a, long b) {
return Math.max(a, b);
}
}
public class SegmentTreeSet {
int pow;
int[] sum;
int[] delta;
boolean[] flag;
public SegmentTreeSet(int[] a) {
pow = 1;
while (pow < a.length) {
pow *= 2;
}
flag = new boolean[2 * pow];
sum = new int[2 * pow];
delta = new int[2 * pow];
for (int i = 0; i < a.length; i++) {
sum[pow + i] = a[i];
}
for (int i = pow - 1; i > 0; i--) {
sum[i] = f(sum[2 * i], sum[2 * i + 1]);
}
}
public int get(int v, int tl, int tr, int l, int r) {
push(v, tl, tr);
if (l > r) {
return 0;
}
if (l == tl && r == tr) {
return sum[v];
}
int tm = (tl + tr) / 2;
return f(get(2 * v, tl, tm, l, Math.min(r, tm)), get(2 * v + 1, tm + 1, tr, Math.max(l, tm + 1), r));
}
public void set(int v, int tl, int tr, int l, int r, int x) {
push(v, tl, tr);
if (l > tr || r < tl) {
return;
}
if (l <= tl && r >= tr) {
delta[v] = x;
flag[v] = true;
push(v, tl, tr);
return;
}
int tm = (tl + tr) / 2;
set(2 * v, tl, tm, l, r, x);
set(2 * v + 1, tm + 1, tr, l, r, x);
sum[v] = f(sum[2 * v], sum[2 * v + 1]);
}
public void push(int v, int tl, int tr) {
if (flag[v]) {
if (v < pow) {
flag[2 * v] = true;
flag[2 * v + 1] = true;
delta[2 * v] = delta[v];
delta[2 * v + 1] = delta[v];
}
flag[v] = false;
sum[v] = delta[v] * (tr - tl + 1);
}
}
public int f(int a, int b) {
return a + b;
}
}
public class Pair implements Comparable<Pair> {
long x;
int y;
public Pair(long x, int y) {
this.x = x;
this.y = y;
}
public Pair clone() {
return new Pair(x, y);
}
public String toString() {
return x + " " + y;
}
@Override
public int compareTo(Pair o) {
if (x > o.x) {
return 1;
}
if (x < o.x) {
return -1;
}
if (y > o.y) {
return 1;
}
if (y < o.y) {
return -1;
}
return 0;
}
}
Random random = new Random(566);
public void shuffle(Pair[] a) {
for (int i = 0; i < a.length; i++) {
int x = random.nextInt(i + 1);
Pair t = a[x];
a[x] = a[i];
a[i] = t;
}
}
public void sort(int[][] a) {
for (int i = 0; i < a.length; i++) {
Arrays.sort(a[i]);
}
}
public void add(Map<Long, Integer> map, long l) {
if (map.containsKey(l)) {
map.put(l, map.get(l) + 1);
} else {
map.put(l, 1);
}
}
public void remove(Map<Integer, Integer> map, Integer s) {
if (map.get(s) > 1) {
map.put(s, map.get(s) - 1);
} else {
map.remove(s);
}
}
long max = Long.MAX_VALUE / 2;
double eps = 1e-10;
public int signum(double x) {
if (x > eps) {
return 1;
}
if (x < -eps) {
return -1;
}
return 0;
}
public long abs(long x) {
return x < 0 ? -x : x;
}
public long min(long x, long y) {
return x < y ? x : y;
}
public long max(long x, long y) {
return x > y ? x : y;
}
public long gcd(long x, long y) {
while (y > 0) {
long c = y;
y = x % y;
x = c;
}
return x;
}
public final Vector ZERO = new Vector(0, 0);
// public class Vector implements Comparable<Vector> {
// long x;
// long y;
// int type;
// int number;
//
// public Vector() {
// x = 0;
// y = 0;
// }
//
// public Vector(long x, long y, int type, int number) {
// this.x = x;
// this.y = y;
// this.type = type;
// this.number = number;
// }
//
// public Vector(long x, long y) {
//
// }
//
// public Vector(Point begin, Point end) {
// this(end.x - begin.x, end.y - begin.y);
// }
//
// public void orient() {
// if (x < 0) {
// x = -x;
// y = -y;
// }
// if (x == 0 && y < 0) {
// y = -y;
// }
// }
//
// public void normalize() {
// long gcd = gcd(abs(x), abs(y));
// x /= gcd;
// y /= gcd;
// }
//
// public String toString() {
// return x + " " + y;
// }
//
// public boolean equals(Vector v) {
// return x == v.x && y == v.y;
// }
//
// public boolean collinear(Vector v) {
// return cp(this, v) == 0;
// }
//
// public boolean orthogonal(Vector v) {
// return dp(this, v) == 0;
// }
//
// public Vector ort(Vector v) {
// return new Vector(-y, x);
// }
//
// public Vector add(Vector v) {
// return new Vector(x + v.x, y + v.y);
// }
//
// public Vector multiply(long c) {
// return new Vector(c * x, c * y);
// }
//
// public int quater() {
// if (x > 0 && y >= 0) {
// return 1;
// }
// if (x <= 0 && y > 0) {
// return 2;
// }
// if (x < 0) {
// return 3;
// }
// return 0;
// }
//
// public long len2() {
// return x * x + y * y;
// }
//
// @Override
// public int compareTo(Vector o) {
// if (quater() != o.quater()) {
// return quater() - o.quater();
// }
// return signum(cp(o, this));
// }
// }
// public long dp(Vector v1, Vector v2) {
// return v1.x * v2.x + v1.y * v2.y;
// }
//
// public long cp(Vector v1, Vector v2) {
// return v1.x * v2.y - v1.y * v2.x;
// }
// public class Line implements Comparable<Line> {
// Point p;
// Vector v;
//
// public Line(Point p, Vector v) {
// this.p = p;
// this.v = v;
// }
//
// public Line(Point p1, Point p2) {
// if (p1.compareTo(p2) < 0) {
// p = p1;
// v = new Vector(p1, p2);
// } else {
// p = p2;
// v = new Vector();
// }
// }
//
// public boolean collinear(Line l) {
// return v.collinear(l.v);
// }
//
// public boolean inLine(Point p) {
// return hv(p) == 0;
// }
//
// public boolean inSegment(Point p) {
// if (!inLine(p)) {
// return false;
// }
// Point p1 = p;
// Point p2 = p.add(v);
// return p1.x <= p.x && p.x <= p2.x && min(p1.y, p2.y) <= p.y && p.y <=
// max(p1.y, p2.y);
// }
//
// public boolean equalsSegment(Line l) {
// return p.equals(l.p) && v.equals(l.v);
// }
//
// public boolean equalsLine(Line l) {
// return collinear(l) && inLine(l.p);
// }
//
// public long hv(Point p) {
// Vector v1 = new Vector(this.p, p);
// return cp(v, v1);
// }
//
// public double h(Point p) {
// Vector v1 = new Vector(this.p, p);
// return cp(v, v1) / Math.sqrt(v.len2());
// }
//
// public long[] intersectLines(Line l) {
// if (collinear(l)) {
// return null;
// }
// long[] ans = new long[4];
//
// return ans;
// }
//
// public long[] intersectSegment(Line l) {
// long[] ans = intersectLines(l);
// if (ans == null) {
// return null;
// }
// Point p1 = p;
// Point p2 = p.add(v);
// boolean f1 = p1.x * ans[1] <= ans[0] && ans[0] <= p2.x * ans[1] && min(p1.y,
// p2.y) * ans[3] <= ans[2]
// && ans[2] <= max(p1.y, p2.y) * ans[3];
// p1 = l.p;
// p2 = l.p.add(v);
// boolean f2 = p1.x * ans[1] <= ans[0] && ans[0] <= p2.x * ans[1] && min(p1.y,
// p2.y) * ans[3] <= ans[2]
// && ans[2] <= max(p1.y, p2.y) * ans[3];
// if (!f1 || !f2) {
// return null;
// }
// return ans;
// }
//
// @Override
// public int compareTo(Line o) {
// return v.compareTo(o.v);
// }
// }
public class Rect {
long x1;
long x2;
long y1;
long y2;
int number;
public Rect(long x1, long x2, long y1, long y2, int number) {
this.x1 = x1;
this.x2 = x2;
this.y1 = y1;
this.y2 = y2;
this.number = number;
}
}
public static class Fenvik {
int[] t;
public Fenvik(int n) {
t = new int[n];
}
public void add(int x, int delta) {
for (int i = x; i < t.length; i = (i | (i + 1))) {
t[i] += delta;
}
}
private int sum(int r) {
int ans = 0;
int x = r;
while (x >= 0) {
ans += t[x];
x = (x & (x + 1)) - 1;
}
return ans;
}
public int sum(int l, int r) {
return sum(r) - sum(l - 1);
}
}
public class SegmentTreeMaxSum {
int pow;
int[] sum;
int[] maxPrefSum;
int[] maxSufSum;
int[] maxSum;
public SegmentTreeMaxSum(int[] a) {
pow = 1;
while (pow < a.length) {
pow *= 2;
}
sum = new int[2 * pow];
maxPrefSum = new int[2 * pow];
maxSum = new int[2 * pow];
maxSufSum = new int[2 * pow];
for (int i = 0; i < a.length; i++) {
sum[pow + i] = a[i];
maxSum[pow + i] = Math.max(a[i], 0);
maxPrefSum[pow + i] = maxSum[pow + i];
maxSufSum[pow + i] = maxSum[pow + i];
}
for (int i = pow - 1; i > 0; i--) {
update(i);
}
}
public int[] get(int v, int tl, int tr, int l, int r) {
if (r <= tl || l >= tr) {
int[] ans = { 0, 0, 0, 0 };
return ans;
}
if (l <= tl && r >= tr) {
int[] ans = { maxPrefSum[v], maxSum[v], maxSufSum[v], sum[v] };
return ans;
}
int tm = (tl + tr) / 2;
int[] left = get(2 * v, tl, tm, l, r);
int[] right = get(2 * v + 1, tm, tr, l, r);
int[] ans = { Math.max(left[0], right[0] + left[3]),
Math.max(left[1], Math.max(right[1], left[2] + right[0])), Math.max(right[2], left[2] + right[3]),
left[3] + right[3] };
return ans;
}
public void set(int v, int tl, int tr, int x, int value) {
if (v >= pow) {
sum[v] = value;
maxSum[v] = Math.max(value, 0);
maxPrefSum[v] = maxSum[v];
maxSufSum[v] = maxSum[v];
return;
}
int tm = (tl + tr) / 2;
if (x < tm) {
set(2 * v, tl, tm, x, value);
} else {
set(2 * v + 1, tm, tr, x, value);
}
update(v);
}
public void update(int i) {
sum[i] = f(sum[2 * i], sum[2 * i + 1]);
maxSum[i] = Math.max(maxSum[2 * i], Math.max(maxSum[2 * i + 1], maxSufSum[2 * i] + maxPrefSum[2 * i + 1]));
maxPrefSum[i] = Math.max(maxPrefSum[2 * i], maxPrefSum[2 * i + 1] + sum[2 * i]);
maxSufSum[i] = Math.max(maxSufSum[2 * i + 1], maxSufSum[2 * i] + sum[2 * i + 1]);
}
public int f(int a, int b) {
return a + b;
}
}
public class Point implements Comparable<Point> {
double x;
double y;
public Point() {
x = 0;
y = 0;
}
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public String toString() {
return x + " " + y;
}
public boolean equals(Point p) {
return x == p.x && y == p.y;
}
public double dist2() {
return x * x + y * y;
}
public Point add(Point v) {
return new Point(x + v.x, y + v.y);
}
@Override
public int compareTo(Point o) {
int z = signum(x + y - o.x - o.y);
if (z != 0) {
return z;
}
return signum(x - o.x) != 0 ? signum(x - o.x) : signum(y - o.y);
}
}
public class Circle implements Comparable<Circle> {
Point p;
int r;
public Circle(Point p, int r) {
this.p = p;
this.r = r;
}
public Point angle() {
double z = r / sq2;
z -= z % 1e-5;
return new Point(p.x - z, p.y - z);
}
public boolean inside(Point p) {
return hypot2(p.x - this.p.x, p.y - this.p.y) <= sq(r);
}
@Override
public int compareTo(Circle o) {
Point a = angle();
Point oa = o.angle();
int z = signum(a.x + a.y - oa.x - oa.y);
if (z != 0) {
return z;
}
return signum(a.y - oa.y);
}
}
public class Fraction implements Comparable<Fraction> {
long x;
long y;
public Fraction(long x, long y, boolean needNorm) {
this.x = x;
this.y = y;
if (y < 0) {
this.x *= -1;
this.y *= -1;
}
if (needNorm) {
long gcd = gcd(this.x, this.y);
this.x /= gcd;
this.y /= gcd;
}
}
public Fraction clone() {
return new Fraction(x, y, false);
}
public String toString() {
return x + "/" + y;
}
@Override
public int compareTo(Fraction o) {
long res = x * o.y - y * o.x;
if (res > 0) {
return 1;
}
if (res < 0) {
return -1;
}
return 0;
}
}
public double sq(double x) {
return x * x;
}
public long sq(long x) {
return x * x;
}
public double hypot2(double x, double y) {
return sq(x) + sq(y);
}
public long hypot2(long x, long y) {
return sq(x) + sq(y);
}
public boolean kuhn(int v, int[][] edge, boolean[] used, int[] mt) {
used[v] = true;
for (int u : edge[v]) {
if (mt[u] < 0 || (!used[mt[u]] && kuhn(mt[u], edge, used, mt))) {
mt[u] = v;
return true;
}
}
return false;
}
public int matching(int[][] edge) {
int n = edge.length;
int[] mt = new int[n];
Arrays.fill(mt, -1);
boolean[] used = new boolean[n];
int ans = 0;
for (int i = 0; i < n; i++) {
if (!used[i] && kuhn(i, edge, used, mt)) {
Arrays.fill(used, false);
ans++;
}
}
return ans;
}
double sq2 = Math.sqrt(2);
int small = 20;
public class MyStack {
int[] st;
int sz;
public MyStack(int n) {
this.st = new int[n];
sz = 0;
}
public boolean isEmpty() {
return sz == 0;
}
public int peek() {
return st[sz - 1];
}
public int pop() {
sz--;
return st[sz];
}
public void clear() {
sz = 0;
}
public void add(int x) {
st[sz++] = x;
}
public int get(int x) {
return st[x];
}
}
public int[][] readGraph(int n, int m) {
int[][] to = new int[n][];
int[] sz = new int[n];
int[] x = new int[m];
int[] y = new int[m];
for (int i = 0; i < m; i++) {
x[i] = in.nextInt() - 1;
y[i] = in.nextInt() - 1;
sz[x[i]]++;
sz[y[i]]++;
}
for (int i = 0; i < to.length; i++) {
to[i] = new int[sz[i]];
sz[i] = 0;
}
for (int i = 0; i < x.length; i++) {
to[x[i]][sz[x[i]]++] = y[i];
to[y[i]][sz[y[i]]++] = x[i];
}
return to;
}
public class Pol {
double[] coeff;
public Pol(double[] coeff) {
this.coeff = coeff;
}
public Pol mult(Pol p) {
double[] ans = new double[coeff.length + p.coeff.length - 1];
for (int i = 0; i < ans.length; i++) {
for (int j = Math.max(0, i - p.coeff.length + 1); j < coeff.length && j <= i; j++) {
ans[i] += coeff[j] * p.coeff[i - j];
}
}
return new Pol(ans);
}
public String toString() {
String ans = "";
for (int i = 0; i < coeff.length; i++) {
ans += coeff[i] + " ";
}
return ans;
}
public double value(double x) {
double ans = 0;
double p = 1;
for (int i = 0; i < coeff.length; i++) {
ans += coeff[i] * p;
p *= x;
}
return ans;
}
public double integrate(double r) {
Pol p = new Pol(new double[coeff.length + 1]);
for (int i = 0; i < coeff.length; i++) {
p.coeff[i + 1] = coeff[i] / fact[i + 1];
}
return p.value(r);
}
public double integrate(double l, double r) {
return integrate(r) - integrate(l);
}
}
double[] fact = new double[100];
public class SparseTable {
int pow;
int[] lessPow;
int[][] min;
public SparseTable(int[] a) {
pow = 0;
while ((1 << pow) <= a.length) {
pow++;
}
min = new int[pow][a.length];
for (int i = 0; i < a.length; i++) {
min[0][i] = a[i];
}
for (int i = 1; i < pow; i++) {
for (int j = 0; j < a.length; j++) {
min[i][j] = min[i - 1][j];
if (j + (1 << (i - 1)) < a.length) {
min[i][j] = func(min[i][j], min[i - 1][j + (1 << (i - 1))]);
}
}
}
lessPow = new int[a.length + 1];
for (int i = 1; i < lessPow.length; i++) {
if (i < (1 << (lessPow[i - 1]) + 1)) {
lessPow[i] = lessPow[i - 1];
} else {
lessPow[i] = lessPow[i - 1] + 1;
}
}
}
public int get(int l, int r) { // [l, r)
int p = lessPow[r - l];
return func(min[p][l], min[p][r - (1 << p)]);
}
public int func(int a, int b) {
if (a < b) {
return a;
}
return b;
}
}
public double check(int n, ArrayList<Integer> masks) {
int good = 0;
for (int colorMask = 0; colorMask < (1 << n); ++colorMask) {
int best = 2 << n;
int cnt = 0;
for (int curMask : masks) {
int curScore = 0;
for (int i = 0; i < n; ++i) {
if (((curMask >> i) & 1) == 1) {
if (((colorMask >> i) & 1) == 0) {
curScore += 1;
} else {
curScore += 2;
}
}
}
if (curScore < best) {
best = curScore;
cnt = 1;
} else if (curScore == best) {
++cnt;
}
}
if (cnt == 1) {
++good;
}
}
return (double) good / (double) (1 << n);
}
public int builtin_popcount(int x) {
int ans = 0;
for (int i = 0; i < 14; i++) {
if (((x >> i) & 1) > 0) {
ans++;
}
}
return ans;
}
public int number(int[] x) {
int ans = 0;
for (int i = 0; i < x.length; i++) {
ans *= 3;
ans += x[i];
}
return ans;
}
public int[] rotate(int[] x) {
int[] ans = { x[2], x[0], x[3], x[1] };
return ans;
}
int MAX = 200001;
boolean[] b = new boolean[MAX];
int[][] max0 = new int[MAX][2];
int[][] max1 = new int[MAX][2];
int[][] max2 = new int[MAX][2];
int[] index0 = new int[MAX];
int[] index1 = new int[MAX];
int[] p = new int[MAX];
public int place(String s) {
if (s.charAt(s.length() - 1) == '1') {
return 1;
}
int number = 16;
boolean w = true;
boolean a = true;
for (int i = 0; i < s.length(); i++) {
if (number == 1) {
return 2;
}
if (s.charAt(i) == '1') {
if (w) {
number /= 2;
} else {
if (a) {
a = false;
} else {
number /= 2;
a = true;
}
}
} else {
if (w) {
if (number == 16) {
w = false;
number /= 2;
} else {
w = false;
a = false;
}
} else {
if (number == 8) {
if (a) {
return 13;
} else {
return 9;
}
} else if (number == 4) {
if (a) {
return 7;
} else {
return 5;
}
} else if (a) {
return 4;
} else {
return 3;
}
}
}
}
return 0;
}
public class P implements Comparable<P> {
Integer x;
String s;
public P(Integer x, String s) {
this.x = x;
this.s = s;
}
@Override
public String toString() {
return x + " " + s;
}
@Override
public int compareTo(P o) {
if (x != o.x) {
return x - o.x;
}
return s.compareTo(o.s);
}
}
public BigInteger prod(int l, int r) {
if (l + 1 == r) {
return BigInteger.valueOf(l);
}
int m = (l + r) >> 1;
return prod(l, m).multiply(prod(m, r));
}
public class Frac {
BigInteger p;
BigInteger q;
public Frac(BigInteger p, BigInteger q) {
BigInteger gcd = p.gcd(q);
this.p = p.divide(gcd);
this.q = q.divide(gcd);
}
public String toString() {
return p + "\n" + q;
}
public Frac(long p, long q) {
this(BigInteger.valueOf(p), BigInteger.valueOf(q));
}
public Frac mul(Frac o) {
return new Frac(p.multiply(o.p), q.multiply(o.q));
}
public Frac sum(Frac o) {
return new Frac(p.multiply(o.q).add(q.multiply(o.p)), q.multiply(o.q));
}
public Frac diff(Frac o) {
return new Frac(p.multiply(o.q).subtract(q.multiply(o.p)), q.multiply(o.q));
}
}
public int[] transform(int[] x, int k, int step) {
int n = x.length;
int[] a = new int[n];
int[][] prefsum = new int[n][];
int[] elements = new int[n];
int[] start = new int[n];
int[] id = new int[n];
for (int i = 0; i < n; i++) {
if (elements[i] > 0) {
continue;
}
int cur = i;
do {
elements[i]++;
cur += step;
cur %= n;
} while (cur != i);
for (int j = 0; j < elements[i]; j++) {
start[cur] = i;
id[cur] = j;
elements[cur] = elements[i];
cur += step;
cur %= n;
}
prefsum[i] = new int[3 * elements[i] + 1];
for (int j = 0; j < 3 * elements[i]; j++) {
prefsum[i][j + 1] = prefsum[i][j] ^ x[cur];
cur += step;
cur %= n;
}
}
for (int i = 0; i < x.length; i++) {
int curlen = k % (2 * elements[i]);
a[i] = prefsum[start[i]][id[i] + curlen] ^ prefsum[start[i]][id[i]];
}
return a;
}
public boolean rated(String s, int x) {
if (s.toUpperCase().equals("ABC")) {
return x <= 1999;
}
if (s.toUpperCase().equals("ARC")) {
return x <= 2799;
}
if (s.toUpperCase().equals("AGC")) {
return x >= 1200;
}
return false;
}
public long calc(double mult, long n) {
long ans = 0;
long cur = 1;
while (cur < n) {
if (mult * cur > Long.MAX_VALUE / 2) {
ans++;
break;
}
ans++;
cur = Math.round(cur * mult);
}
return ans;
}
public boolean first(int n, int[] a, int[] b) {
Queue<Integer> aq = new ArrayDeque<>();
Queue<Integer> bq = new ArrayDeque<>();
int[] used = new int[n];
int[] unused = new int[n];
for (int i = 0; i < a.length; i++) {
unused[a[i]]++;
aq.add(a[i]);
bq.add(b[i]);
}
while (!bq.isEmpty()) {
if (aq.isEmpty()) {
return false;
}
if (aq.peek() == bq.peek()) {
if (used[aq.peek()] > 0) {
used[bq.poll()]--;
} else {
aq.poll();
unused[bq.poll()]--;
}
} else {
if (unused[aq.peek()] == 1) {
return false;
}
used[aq.peek()]++;
unused[aq.poll()]--;
}
}
return true;
}
public boolean second(int n, int[] a, int[] b) {
int[] used = new int[n];
int i = 0;
int j = 0;
while (i < n && j < n) {
if (a[i] == b[j] && j < n - 1 && b[j] == b[j + 1] && used[a[i]] > 0) {
used[b[j++]]--;
} else if (a[i] == b[j]) {
i++;
j++;
} else {
used[a[i++]]++;
}
}
if (i != n || j != n) {
return false;
}
for (int j2 = 0; j2 < used.length; j2++) {
if (used[j2] > 0) {
return false;
}
}
return true;
}
public void solve() {
// for (int i = 0; i < 100000;) {
// if (i % 100 == 0) {
// System.out.println(i);
// }
// int n = 20;
// ArrayList<Integer> list = new ArrayList<>();
// while (list.size() < n) {
// list.add(random.nextInt(4));
// }
// int[] a = new int[n];
// for (int j = 0; j < a.length; j++) {
// a[j] = list.get(j);
// }
// ArrayList<Integer> list1 = (ArrayList<Integer>) list.clone();
// Collections.shuffle(list1);
// int[] b = new int[n];
// for (int j = 0; j < a.length; j++) {
// b[j] = list1.get(j);
// }
// if (first(n, a, b) != second(n, a, b)) {
// System.out.println(n);
// for (int j = 0; j < a.length; j++) {
// System.out.print(a[j] + " ");
// }
// System.out.println();
// for (int j = 0; j < b.length; j++) {
// System.out.print(b[j] + " ");
// }
// System.out.println();
// System.out.println(first(n, a, b) + " " + second(n, a, b));
// }
// if (first(n, a, b)) {
// i++;
// }
// }
f : for (int qwerty = in.nextInt(); qwerty > 0; --qwerty) {
int n = in.nextInt();
int[] a = new int[n];
int[] b = new int[n];
for (int i = 0; i < b.length; i++) {
a[i] = in.nextInt() - 1;
}
for (int i = 0; i < b.length; i++) {
b[i] = in.nextInt() - 1;
}
if (second(n, a, b)) {
out.println("YES");
} else {
out.println("NO");
}
}
}
public void add(HashMap<Integer, Integer> map, int x) {
if (map.containsKey(x)) {
map.put(x, map.get(x) + 1);
} else {
map.put(x, 1);
}
}
public void run() {
try {
if (systemIO) {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
} else {
in = new FastScanner(new File("input.txt"));
out = new PrintWriter(new File("output.txt"));
}
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f));
}
String nextLine() {
try {
return br.readLine();
} catch (IOException e) {
return null;
}
}
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());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
// AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
public static void main(String[] arg) {
new D().run();
}
} | Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | b0e0b2062d5f4dce40c897dfa69e1b5e | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
static long startTime = System.currentTimeMillis();
// for global initializations and methods starts here
// global initialisations and methods end here
static void run() {
boolean tc = true;
AdityaFastIO r = new AdityaFastIO();
//FastReader r = new FastReader();
try (OutputStream out = new BufferedOutputStream(System.out)) {
//long startTime = System.currentTimeMillis();
int testcases = tc ? r.ni() : 1;
int tcCounter = 1;
// Hold Here Sparky------------------->>>
// Solution Starts Here
start:
while (testcases-- > 0) {
int n = r.ni();
List<Long> a = readLongList(n, r);
List<Long> b = readLongList(n, r);
PriorityQueue<Long> pq = new PriorityQueue<>();
Map<Long, Long> map = new HashMap<>();
long max = -(int) 1e9;
b.set(0, max);
long can = -max;
int there1 = n;
int there2 = n;
boolean ff = true;
if (there1 != 0 || there2 != 0) {
do {
if (!Objects.equals(a.get(there1), b.get(there2))) {
if (can == b.get(there2)) {
//pq.add(b.get(there2));
map.put(b.get(there2), map.getOrDefault(b.get(there2), 0L) + 1);
there2--;
} else {
if (map.getOrDefault(a.get(there1), 0L) != 0) {
//pq.remove(a.get(there1));
map.put(a.get(there1), map.getOrDefault(a.get(there1), 0L) - 1);
there1--;
} else {
ff = false;
break;
}
}
} else {
can = Math.toIntExact(a.get(there1));
there1--;
there2--;
}
} while (there1 != 0 || there2 != 0);
}
if (ff) out.write(("YES" + " ").getBytes());
else out.write(("NO" + " ").getBytes());
out.write(("\n").getBytes());
}
// Solution Ends Here
} catch (IOException e) {
e.printStackTrace();
}
}
static class AdityaFastIO {
final private int BUFFER_SIZE = 1 << 16;
private final DataInputStream din;
private final byte[] buffer;
private int bufferPointer, bytesRead;
public BufferedReader br;
public StringTokenizer st;
public AdityaFastIO() {
br = new BufferedReader(new InputStreamReader(System.in));
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public AdityaFastIO(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String word() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public String line() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public String readLine() throws IOException {
byte[] buf = new byte[100000001]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int ni() 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 nl() 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 nd() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ') c = read();
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.') while ((c = read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10);
if (neg) return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null) return;
din.close();
}
}
public static void main(String[] args) throws Exception {
run();
}
static int[] readIntArr(int n, AdityaFastIO r) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < n; i++) arr[i] = r.ni();
return arr;
}
static long[] readLongArr(int n, AdityaFastIO r) throws IOException {
long[] arr = new long[n];
for (int i = 0; i < n; i++) arr[i] = r.nl();
return arr;
}
static List<Integer> readIntList(int n, AdityaFastIO r) throws IOException {
List<Integer> al = new ArrayList<>();
for (int i = 0; i < n; i++) al.add(r.ni());
return al;
}
static List<Long> readLongList(int n, AdityaFastIO r) throws IOException {
List<Long> al = new ArrayList<>();
al.add(-1L);
for (int i = 0; i < n; i++) al.add(r.nl());
return al;
}
static long mod = 998244353;
static long modInv(long base, long e) {
long result = 1;
base %= mod;
while (e > 0) {
if ((e & 1) > 0) result = result * base % mod;
base = base * base % mod;
e >>= 1;
}
return result;
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String word() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
String line() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int ni() {
return Integer.parseInt(word());
}
long nl() {
return Long.parseLong(word());
}
double nd() {
return Double.parseDouble(word());
}
}
static int MOD = (int) (1e9 + 7);
static long powerLL(long x, long n) {
long result = 1;
while (n > 0) {
if (n % 2 == 1) result = result * x % MOD;
n = n / 2;
x = x * x % MOD;
}
return result;
}
static long powerStrings(int i1, int i2) {
String sa = String.valueOf(i1);
String sb = String.valueOf(i2);
long a = 0, b = 0;
for (int i = 0; i < sa.length(); i++) a = (a * 10 + (sa.charAt(i) - '0')) % MOD;
for (int i = 0; i < sb.length(); i++) b = (b * 10 + (sb.charAt(i) - '0')) % (MOD - 1);
return powerLL(a, b);
}
static long gcd(long a, long b) {
if (a == 0) return b;
else return gcd(b % a, a);
}
static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
static long lower_bound(int[] arr, int x) {
int l = -1, r = arr.length;
while (l + 1 < r) {
int m = (l + r) >>> 1;
if (arr[m] >= x) r = m;
else l = m;
}
return r;
}
static int upper_bound(int[] arr, int x) {
int l = -1, r = arr.length;
while (l + 1 < r) {
int m = (l + r) >>> 1;
if (arr[m] <= x) l = m;
else r = m;
}
return l + 1;
}
static void addEdge(ArrayList<ArrayList<Integer>> graph, int edge1, int edge2) {
graph.get(edge1).add(edge2);
graph.get(edge2).add(edge1);
}
public static class Pair implements Comparable<Pair> {
int first;
int second;
public Pair(int first, int second) {
this.first = first;
this.second = second;
}
public String toString() {
return "(" + first + "," + second + ")";
}
public int compareTo(Pair o) {
// TODO Auto-generated method stub
if (this.first != o.first)
return (int) (this.first - o.first);
else return (int) (this.second - o.second);
}
}
public static class PairC<X, Y> implements Comparable<PairC> {
X first;
Y second;
public PairC(X first, Y second) {
this.first = first;
this.second = second;
}
public String toString() {
return "(" + first + "," + second + ")";
}
public int compareTo(PairC o) {
// TODO Auto-generated method stub
return o.compareTo((PairC) first);
}
}
static boolean isCollectionsSorted(List<Long> list) {
if (list.size() == 0 || list.size() == 1) return true;
for (int i = 1; i < list.size(); i++) if (list.get(i) <= list.get(i - 1)) return false;
return true;
}
static boolean isCollectionsSortedReverseOrder(List<Long> list) {
if (list.size() == 0 || list.size() == 1) return true;
for (int i = 1; i < list.size(); i++) if (list.get(i) >= list.get(i - 1)) return false;
return true;
}
} | Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | 12db3e68c04db69145160925030f0f76 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int numTests = in.nextInt();
for (int test = 0; test < numTests; test++) {
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt() - 1;
}
int[] b = new int[n];
for (int i = 0; i < n; i++) {
b[i] = in.nextInt() - 1;
}
int[] canRemove = new int[n];
boolean ans = true;
int ia = n - 1;
outer:
for (int ib = n - 1; ib >= 0; ) {
int jb = ib;
while (jb >= 0 && b[ib] == b[jb]) {
--jb;
}
int val = b[ib];
int need = ib - jb;
ib = jb;
while (a[ia] != val) {
if (canRemove[a[ia]] > 0) {
--canRemove[a[ia]];
--ia;
} else {
ans = false;
break outer;
}
}
--ia;
canRemove[val] += need - 1;
}
out.println(ans ? "YES" : "NO");
}
}
}
static class FastScanner {
private BufferedReader in;
private StringTokenizer st;
public FastScanner(InputStream stream) {
try {
in = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
} catch (Exception e) {
throw new AssertionError();
}
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
String rl = in.readLine();
if (rl == null) {
return null;
}
st = new StringTokenizer(rl);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | ce3ac0cbb141921a1e96a9f864816b1e | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;
import java.util.StringTokenizer;
/*
1
5
1 2 3 3 2
1 3 3 2 2
*/
public class D2 {
public static void main(String[] args) {
FastScanner fs=new FastScanner();
PrintWriter out=new PrintWriter(System.out);
int T=fs.nextInt();
// int T=1;
outer: for (int tt=0; tt<T; tt++) {
int n=fs.nextInt();
int[] a=fs.readArray(n), b=fs.readArray(n);
int ai=n-1;
int[] toHandle=new int[n+1];
for (int i=n-1; i>=0; i--) {
if (a[ai]==b[i]) {
ai--;
continue;
}
//we will handle it later
if (i+1<n && b[i]==b[i+1]) {
toHandle[b[i]]++;
continue;
}
//otherwise they don't match, this a[i] needs to be handled
if (toHandle[a[ai]]==0) {
System.out.println("NO");
continue outer;
}
toHandle[a[ai]]--;
ai--;
i++;
}
System.out.println("YES");
}
}
static final Random random=new Random();
static final int mod=1_000_000_007;
static void ruffleSort(int[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static long add(long a, long b) {
return (a+b)%mod;
}
static long sub(long a, long b) {
return ((a-b)%mod+mod)%mod;
}
static long mul(long a, long b) {
return (a*b)%mod;
}
static long exp(long base, long exp) {
if (exp==0) return 1;
long half=exp(base, exp/2);
if (exp%2==0) return mul(half, half);
return mul(half, mul(half, base));
}
static long[] factorials=new long[2_000_001];
static long[] invFactorials=new long[2_000_001];
static void precompFacts() {
factorials[0]=invFactorials[0]=1;
for (int i=1; i<factorials.length; i++) factorials[i]=mul(factorials[i-1], i);
invFactorials[factorials.length-1]=exp(factorials[factorials.length-1], mod-2);
for (int i=invFactorials.length-2; i>=0; i--)
invFactorials[i]=mul(invFactorials[i+1], i+1);
}
static long nCk(int n, int k) {
return mul(factorials[n], mul(invFactorials[k], invFactorials[n-k]));
}
static void sort(int[] a) {
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | dd4849d697d925a98eb4b3a952691bb0 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 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 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);
int[] c = new int[n + 1];
int ra = n - 1;
int rb = n - 1;
while (rb >= 0) {
int e = b[rb];
int cnt = 0;
while (rb >= 0) {
if (b[rb] == e) {
rb--;
cnt++;
} else {
break;
}
}
c[e] += cnt;
while (a[ra] != e) {
if (c[a[ra]] > 0) {
c[a[ra]]--;
ra--;
} else {
out.println("NO");
return;
}
}
c[e]--;
ra--;
}
out.println("YES");
}
// (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 | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | ea6b68f9f8044fda2de346ad871f1874 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
//import java.util.Collections;
import java.io.InputStreamReader;
import static java.lang.Math.*;
import static java.lang.System.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class taskA {
public static void main(String[] args) throws IOException {
// try {
// Scanner in = new Scanner(System.in) ;
FastScanner in = new FastScanner();
int t = in.nextInt() ;
outer : while (t-- > 0){
int n = in.nextInt() ;
int a[] = in.readArray(n) ;
int b[] = in.readArray(n) ;
int last[] = new int[n+1] ;
Arrays.fill(last , -1);
int curr[] = new int[n] ;
for (int i = n-1; i >=0 ; i--) {
curr[i] = last[a[i]] ;
last[a[i]] = i ;
}
int freq[] = new int[n] ;
Arrays.fill(freq , 1);
int ptr1 = 0 , ptr2 = 0 ;
while (ptr1 != n){
if (a[ptr1] == b[ptr2]){
ptr2++ ;
freq[ptr1]-- ;
if (freq[ptr1] == 0)ptr1++ ;
}
else {
int ele = a[ptr1] ;
if (curr[ptr1] == -1){
System.out.println("NO");
continue outer;
}
freq[curr[ptr1]] += freq[ptr1] ;
freq[ptr1] = 0 ;
ptr1++ ;
}
}
System.out.println("YES");
}
// } catch (Exception e) {
// System.out.println(e);
// return;
// }
}
static long gcd(long a, long b) {
return (b == 0) ? a : gcd(b, a % b);
}
static int gcd(int a, int b) {
return (b == 0) ? a : gcd(b, a % b);
}
static void sort(int ar[]) {
int n = ar.length;ArrayList<Integer> a = new ArrayList<>();
for (int i = 0; i < n; i++) a.add(ar[i]);
Collections.sort(a);
for (int i = 0; i < n; i++) ar[i] = a.get(i);
}
static void sort1(long ar[]) {
int n = ar.length;ArrayList<Long> a = new ArrayList<>();
for (int i = 0; i < n; i++) a.add(ar[i]);
Collections.sort(a);
for (int i = 0; i < n; i++) ar[i] = a.get(i);
}
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
static PrintWriter out = new PrintWriter(System.out);
}
| Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output | |
PASSED | b35ea664e53573fd235626460e615f84 | train_108.jsonl | 1650722700 | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class Solution
{
public static void main(String[] args)
{
try (Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))))
{
int T = in.nextInt();
for (int t = 1; t <= T; t++)
{
int n = in.nextInt();
int[] as = new int[n];
int[] bs = new int[n];
for (int i = 0; i < n; i++)
{
as[i] = in.nextInt();
}
for (int i = 0; i < n; i++)
{
bs[i] = in.nextInt();
}
System.out.println(getCan(as, bs));
}
}
}
private static String getCan(int[] as, int[] bs)
{
List<Node> aNodes = new ArrayList<>();
List<Node> bNodes = new ArrayList<>();
buildNodes(as, aNodes);
buildNodes(bs, bNodes);
Map<Integer, Integer> map = new HashMap<>();
int aIdx = aNodes.size() - 1;
int bIdx = bNodes.size() - 1;
while (true)
{
if (bIdx == -1)
{
return "YES";
}
if (aIdx == -1)
{
return "NO";
}
Node aNode = aNodes.get(aIdx);
Node bNode = bNodes.get(bIdx);
if (aNode.val != bNode.val)
{
map.put(aNode.val, map.getOrDefault(aNode.val, 0) - aNode.count);
if (map.getOrDefault(aNode.val, 0) < 0)
{
return "NO";
}
aIdx--;
}
else if (aNode.count > bNode.count)
{
map.put(aNode.val, map.getOrDefault(aNode.val, 0) - (aNode.count - bNode.count));
if (map.getOrDefault(aNode.val, 0) < 0)
{
return "NO";
}
aIdx--;
bIdx--;
}
else
{
map.put(aNode.val, map.getOrDefault(aNode.val, 0) + (bNode.count - aNode.count));
aIdx--;
bIdx--;
}
}
}
private static void buildNodes(int[] nums, List<Node> nodes)
{
for (int num : nums)
{
if (!nodes.isEmpty() && nodes.get(nodes.size() - 1).val == num)
{
nodes.get(nodes.size() - 1).count++;
}
else
{
nodes.add(new Node(num));
}
}
}
}
class Node
{
int val;
int count;
public Node(int val)
{
this.val = val;
this.count = 1;
}
}
| Java | ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 158bd0ab8f4319f5fd1e6062caddad4e | Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$ | 1,700 | For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.