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
8cedfdb66d391568ee37f8d0ca1a3184
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 < p_2 < \ldots < p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i < m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class maxWidth { public static void main(String[] args) { // Scanner sc = new Scanner(System.in); // int t = sc.nextInt(); // for(int o= 0 ; o<t;o++) { FastReader sc = new FastReader(); int n = sc.nextInt(); int m = sc.nextInt(); String s = sc.next(); String str = sc.next(); HashMap<Character, TreeSet<Integer>> map = new HashMap<Character, TreeSet<Integer>>(); for(int i = 0; i<n;i++) { if(!map.containsKey(s.charAt(i))) { TreeSet<Integer> set = new TreeSet<Integer>(); set.add(i); map.put(s.charAt(i), set); }else { TreeSet<Integer> set = map.get(s.charAt(i)); set.add(i); map.put(s.charAt(i), set); } } int max = 0; // for(int i = 0 ; i<m-2;i++) { // System.out.println(11111); // char a = str.charAt(i); // char b = str.charAt(i+1); // char c = str.charAt(i+2); // int x = map.get(a).first(); // int k = map.get(c).last(); // int y = map.get(b).floor(k); // System.out.println(y-x); // if(y-x>max) { // max = y-x; // } // // // } // int x = map.get(str.charAt(m-2)).first(); // int y = map.get(str.charAt(m-1)).last(); // if(y-x>max) { // max = y-x; // } pair[] arr = new pair[m]; int q = map.get(str.charAt(m-1)).last(); arr[m-1] = new pair(0,q); for(int i = m-2;i>=0;i--) { int b = map.get(str.charAt(i)).lower(arr[i+1].l); //int a = map.get(str.charAt(i)).first(); arr[i] = new pair(0,b); } int y = arr[0].l; int x = map.get(str.charAt(0)).first(); arr[0] = new pair(x,y); for(int i = 1 ; i<m;i++) { int a = map.get(str.charAt(i)).higher(arr[i-1].f); int b = arr[i].l; arr[i] = new pair(a,b); } int ans = 0; for(int i = 0 ; i<m-1;i++) { if(arr[i+1].l - arr[i].f>ans) { ans = arr[i+1].l - arr[i].f; } } System.out.println(ans); // System.out.println(max); // } } } class pair{ int f , l; public pair(int f , int l) { this.f = f; this.l = l; } } 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 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
af222047fb1c7e477103f76a83b851fc
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.io.*; import java.util.*; public class D{ public static void main(String[] args) throws IOException { // br = new BufferedReader(new FileReader(".in")); // out = new PrintWriter(new FileWriter(".out")); //new Thread(null, new (), "peepee", 1<<28).start(); readInt(); readInt(); String s = read(); String s2 = read(); int[] pre = new int[s2.length()+1]; int[] suf = new int[s2.length()+1]; int[] prep = new int[s2.length()+1]; int[] sufp = new int[s2.length()+1]; prep[0] = 0; sufp[0] = s.length()-1; int max = 0; int prev = -1; int p = 0; for (int i = 0; i < s.length() && p < s2.length(); i++) { if (s.charAt(i) == s2.charAt(p)) { p++; max = Integer.max(max, (i-prev)-1); prep[p] = i; prev = i; pre[p] = max; } } max = 0; prev = s2.length(); p = s2.length()-1; int len = 0; for (int i = s.length()-1; i >= 0 && p >= 0; i--) { if (s.charAt(i) == s2.charAt(p)) { len++; max = Integer.max(max, (prev-i)-1); sufp[len] = i; prev = i; p--; suf[len] = max; } } max = 0; for (int i = 0; i <= s2.length(); i++) { if (i == 0 || s2.length()-i==0) continue; int delta = sufp[s2.length()-i] - prep[i]; //System.out.println("Indices " + i + " " + (s2.length()-i)); //System.out.println("Delta things " + sufp[s2.length()-i] + " " + prep[i]); //System.out.println("Ohters " + pre[i] + " " + suf[s2.length()-i] + " " + delta); max = Integer.max(max, Integer.max(pre[i], suf[s2.length()-i])); max = Integer.max(max, delta); } out.println(max); out.close(); } static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); static StringTokenizer st = new StringTokenizer(""); static String read() throws IOException{return st.hasMoreTokens() ? st.nextToken():(st = new StringTokenizer(br.readLine())).nextToken();} static int readInt() throws IOException{return Integer.parseInt(read());} static long readLong() throws IOException{return Long.parseLong(read());} static double readDouble() throws IOException{return Double.parseDouble(read());} }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
3032f472dcdfc53b2a165af57ac4ad0c
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; public class C70 { static BufferedReader br; static long mod = 1000000000 + 7; static HashSet<Integer> p = new HashSet<>(); public static void main(String[] args) throws Exception { br = new BufferedReader(new InputStreamReader(System.in)); int tc = 1; // tc = cinI(); while (tc-- > 0) { int[] ar =readArray(2,0,0); char[] a = cin().toCharArray(); char[] b = cin().toCharArray(); // x ,y x/y char[][] x = new char[200002][2]; int[][] dp = new int[200002][2]; // System.out.println(a.length+" "+b.length); for(int i=0;i<a.length;i++){ // System.out.println(a[i]); x[i][0]=a[i]; } for(int i=0;i<b.length;i++){ x[i][1]=b[i]; } int prev=0; for(int i=0; i<a.length-1; i++){ if(x[prev][1]==x[i][0]){ dp[prev][0]=i; prev++; } if(prev==b.length) break; } prev=b.length-1; for(int i=a.length-1; i>0; i--){ if(x[prev][1]==x[i][0]){ dp[prev][1]=i; prev--; } if(prev==0) break; } int ans=0; for(int i=0; i<b.length-1; i++){ if(dp[i+1][1]-dp[i][0]>ans) ans=dp[i+1][1]-dp[i][0]; } System.out.println(ans); } } private static int dfs(TreeMap<Integer, HashSet<Integer>> graph, boolean[] vis, Integer key, Stack<Integer> st) { if (st.size() == 0) { return 0; } int par = st.pop(); HashSet<Integer> child = graph.get(par); vis[par] = true; int nodes = 1; for (int c : child) { if (vis[c] == false) { st.add(c); nodes += dfs(graph, vis, c, st); } } return nodes; } public static boolean isSorted(int[] arr) { for (int i = 0; i < arr.length - 1; i++) { if (arr[i] > arr[i + 1]) { return false; } } return true; } private static long gcd(long a, long b) { 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 long min(long a, long b) { return Math.min(a, b); } public static int min(int a, int b) { return Math.min(a, b); } public static void sieve() { int[] pf = new int[100000000 + 1]; //0 prime //1 not prime pf[0] = 1; pf[1] = 1; for (int j = 2; j <= 10000; j++) { if (pf[j] == 0) { p.add(j); for (int k = j * j; k < pf.length; k += j) { pf[k] = 1; } } } } public static int[] readArray(int n, int x, int z) throws Exception { int[] arr = new int[n]; String[] ar = cinA(); for (int i = x; i < n + x; i++) { arr[i] = getI(ar[i - x]); } return arr; } public static long[] readArray(int n, int x) throws Exception { long[] arr = new long[n]; String[] ar = cinA(); for (int i = x; i < n + x; i++) { arr[i] = getL(ar[i - x]); } return arr; } public static void arrinit(String[] a, long[] b) throws Exception { for (int i = 0; i < a.length; i++) { b[i] = Long.parseLong(a[i]); } } public static HashSet<Integer>[] Graph(int n, int edge, int directed) throws Exception { HashSet<Integer>[] tree = new HashSet[n]; for (int j = 0; j < edge; j++) { String[] uv = cinA(); int u = getI(uv[0]); int v = getI(uv[1]); if (directed == 0) { tree[v].add(u); } tree[u].add(v); } return tree; } public static void arrinit(String[] a, int[] b) throws Exception { for (int i = 0; i < a.length; i++) { b[i] = Integer.parseInt(a[i]); } } static double findRoots(int a, int b, int c) { // If a is 0, then equation is not //quadratic, but linear int d = b * b - 4 * a * c; double sqrt_val = Math.sqrt(Math.abs(d)); // System.out.println("Roots are real and different \n"); return Math.max((double) (-b + sqrt_val) / (2 * a), (double) (-b - sqrt_val) / (2 * a)); } public static String cin() throws Exception { return br.readLine(); } public static String[] cinA() throws Exception { return br.readLine().split(" "); } public static String[] cinA(int x) throws Exception { return br.readLine().split(""); } public static String ToString(Long x) { return Long.toBinaryString(x); } public static void cout(String s) { System.out.println(s); } public static Integer cinI() throws Exception { return Integer.parseInt(br.readLine()); } public static int getI(String s) throws Exception { return Integer.parseInt(s); } public static long getL(String s) throws Exception { return Long.parseLong(s); } public static long max(long a, long b) { return Math.max(a, b); } public static int max(int a, int b) { return Math.max(a, b); } public static void coutI(int x) { System.out.println(String.valueOf(x)); } public static void coutI(long x) { System.out.println(String.valueOf(x)); } public static Long cinL() throws Exception { return Long.parseLong(br.readLine()); } public static void arrInit(String[] arr, int[] arr1) throws Exception { for (int i = 0; i < arr.length; i++) { arr1[i] = getI(arr[i]); } } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
bd707edb66d59b4e0a4a0e7f3273c21c
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.io.*; import java.lang.*; import java.util.*; public class longetsdiffincommonsubseq { static class FastScanner { InputStreamReader is; BufferedReader br; StringTokenizer st; public FastScanner() { is = new InputStreamReader(System.in); br = new BufferedReader(is); } String next() throws Exception { while (st == null || !st.hasMoreElements()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws Exception { return Integer.parseInt(next()); } long nextLong() throws Exception { return Long.parseLong(next()); } int[] readArray(int num) throws Exception { int arr[]=new int[num]; for(int i=0;i<num;i++) arr[i]=nextInt(); return arr; } String nextLine() throws Exception { return br.readLine(); } } public static boolean power_of_two(int a) { if((a&(a-1))==0) { return true; } return false; } static boolean PS(double x) { if (x >= 0) { double i= Math.sqrt(x); if(i%1!=0) { return false; } return ((i * i) == x); } return false; } public static int[] ia(int n) { int ar[]=new int[n]; return ar; } public static long[] la(int n) { long ar[]=new long[n]; return ar; } public static void print(int ans,int t) { System.out.println("Case"+" "+"#"+t+":"+" "+ans); } //**** M A I N C O D E **** public static void main(String args[]) throws java.lang.Exception { FastScanner sc=new FastScanner(); int n=sc.nextInt(); int m=sc.nextInt(); String a=sc.next(); String b=sc.next(); int low[]=new int[m]; int high[]=new int[m]; int idx=0; for(int i=0;i<n&&idx<m;i++) { if(a.charAt(i)==b.charAt(idx)) { low[idx]=i; idx++; } } idx=m-1; for(int i=n-1;i>=0&&idx>=0;i--) { if(a.charAt(i)==b.charAt(idx)) { high[idx]=i; idx--; } } long max=Integer.MIN_VALUE; for(int i=1;i<m;i++) { max=Math.max(max,high[i]-low[i-1]); } System.out.println(max); } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
dbace44fcd81b53113fe0fa3def876f1
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Main { public static void main (String[] args) { // Scanner scan = new Scanner(System.in); FastScanner scan = new FastScanner(); int m = scan.nextInt(); int n = scan.nextInt(); char[] s = scan.next().toCharArray(); char[] t = scan.next().toCharArray(); int[] first = new int[n]; int[] last = new int[n]; int id = 0; for(int i = 0; i < n; i++) { while(s[id] != t[i]) id++; first[i] = id; id++; } id = m - 1; for(int i = n - 1; i >= 0; i--) { while(s[id] != t[i]) id--; last[i] = id; id--; } int max = 0; for(int i = 1; i < n; i++) { max = Math.max(max, last[i] - first[i - 1]); } System.out.println(max); } /* int n = scan.nextInt(); int[] arr = scan.readArray(n); int n = scan.nextInt(); int m = scan.nextInt(); int[][] arr = new int[n][m]; for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { arr[i][j] = scan.nextInt(); } } */ 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 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
b3be1f0d470a8deeb8b9974701cc6a91
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.io.*; import java.util.*; import static java.lang.System.out; public class C704 { public static void main(String[] args)throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(in.readLine()); int n = Integer.parseInt(st.nextToken()), k = Integer.parseInt(st.nextToken()); String s = in.readLine(), s2 = in.readLine(); int[] mins = new int[k], maxes = new int[k]; int p = 0; for(int x=0; x<k; x++) { while(p<n-1 && s.charAt(p)!=s2.charAt(x)) p++; mins[x] = p; p++; } p = n-1; for(int x=k-1; x>=0; x--) { while(p>0 && s.charAt(p)!=s2.charAt(x)) p--; maxes[x] = p; p--; } int ans = 0; for(int x=0; x<k-1; x++) { ans = Math.max(ans, maxes[x+1]-mins[x]); } out.println(ans); } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
75815a6c21e37146003793735ac0de1f
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.lang.*; import java.lang.reflect.Array; import java.util.*; import java.io.*; public class Main { static FastScanner in = new FastScanner(); static void solve() { int n = in.nextInt(), m = in.nextInt(); char[] s = in.nextLine().toCharArray(), t = in.nextLine().toCharArray(); int[] left = new int[m], right = new int[m]; int cur = 0; for (int i = 0; i < n; ++i) { if (t[cur] == s[i]) { left[cur] = i + 1; ++cur; if (cur >= m) break; } } cur = m - 1; for (int i = n - 1; i >= 0; --i) { if (t[cur] == s[i]) { right[cur] = i + 1; --cur; if (cur < 0) break; } } int ans = 0; for (int i = 0; i < m - 1; ++i) ans = Math.max(ans, right[i + 1] - left[i]); System.out.println(ans); } public static void main(String[] args) { int T = 1; while (T-- > 0) solve(); } static class Pair<X, Y> { X x; Y y; public Pair(X x, Y y) { this.x = x; this.y = y; } } } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { 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 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
4e0a356c8a10133700cb77d389426d28
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.util.*; public class Prob_one { public static void main(String args[]) { Scanner sc =new Scanner(System.in); int a,b; a=sc.nextInt(); b=sc.nextInt(); String a1,a2; a1=sc.next(); a2=sc.next(); int min[]=new int[b]; int max[]=new int[b]; int l=-1; for(int i=0;i<b;i++) { char c =a2.charAt(i); for(int j=l+1;j<a;j++) { if(c==a1.charAt(j)) { min[i]=j; l=j; break; } } } l=a1.length(); for(int i=b-1;i>=0;i--) { char c =a2.charAt(i); for(int j=l-1;j>=0;j--) { if(c==a1.charAt(j)) { max[i]=j; l=j; break; } } } int ma=-1; for(int i=1;i<b;i++) { ma=Math.max(ma,max[i]-min[i-1]); } System.out.println(ma); } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
e278a693d350d36c2ab5e1dd4bd1af31
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.util.*; import java.io.*; public class Main { 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]; } } public static void main(String args[]) throws IOException { Scan input=new Scan(); int n=input.scanInt(); int m=input.scanInt(); String s=input.scanString(); String t=input.scanString(); int cnt[]=new int[n]; for(int i=s.length()-1,j=t.length()-1,cnt1=0;i>=0;i--) { if(j>=0 && s.charAt(i)==t.charAt(j)) { j--; cnt1++; } cnt[i]=cnt1; } // for(int i=0;i<n;i++) { // System.out.print(cnt[i]+" "); // } // System.out.println(); int max=0,indx=0; for(int i=0,j=0,cnt1=0;i<n;i++) { if(j<m && s.charAt(i)==t.charAt(j)) { j++; cnt1++; } else { continue; } if(cnt1==m) { break; } indx=Math.max(indx,i+1); while(indx<n && cnt[indx]+cnt1!=m) { indx++; } while(indx<n-1 && cnt[indx+1]+cnt1==m) { indx++; } // System.out.println(i+" "+cnt1+" "+indx); if(indx<n && cnt[indx]+cnt1==m) { max=Math.max(max,indx-i); } } System.out.println(max); } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
9b1eb3c10ca790798a00e1992a93d26b
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
//package clipse; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.*; import java.math.*; public class BB { static StringBuffer sb; static boolean A[]; static char a[]; static char b[]; static long k; static ArrayList<Integer>prime; public static void main(String[] args) { int n=i(); int m=i(); char c1[]=s().toCharArray(); char c2[]=s().toCharArray(); HashMap<Character,Integer>first=new HashMap<>(); for(int i=0;i<n;i++) { if(!first.containsKey((char)c1[i])) { first.put(c1[i], i); } } HashMap<Character,Integer>second=new HashMap<>(); int suff[]=new int[m]; ArrayList<Integer>l=new ArrayList<>(); for(int i=n-1,j=m-1;i>=0&&j>=0;i--) { if(c1[i]==c2[j]) { l.add(i); j--; } } for(int i=0;i<m;i++) { suff[i]=l.get(m-i-1); } int pre[]=new int[m]; for(int i=0, j=0;i<n && j<m;i++){ if(c1[i] == c2[j]){ pre[j]=i; j++; } } int min=Integer.MIN_VALUE; for(int i=0;i<m-1;i++) { min=Math.max(suff[i+1]-pre[i],min); } System.out.println(min); } //*******************************************PRIME FACTORIZE *****************************************************************************************************// static TreeMap<Integer,Integer> prime(long n) { TreeMap<Integer,Integer>h=new TreeMap<>(); long num=n; for(int i=2;i<=Math.sqrt(num);i++) { if(n%i==0) { int nt=0; while(n%i==0) { n=n/i; nt++; } h.put(i, nt); } } if(n!=1) h.put((int)n, 1); return h; } //*************CLASS PAIR *********************************************************************************************************************************************** static class pair { int x; int y; pair(int x, int y) { this.x = x; this.y = y; } } //*************CLASS PAIR ***************************************************************************************************************************************************** static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int Int() { 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 String() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return String(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } static InputReader in = new InputReader(System.in); static OutputWriter out = new OutputWriter(System.out); static int modulus = (int) 1e7; public static int[] sort(int[] a) { int n = a.length; ArrayList<Integer> l = new ArrayList<>(); for (int i : a) l.add(i); Collections.sort(l); for (int i = 0; i < l.size(); i++) a[i] = l.get(i); return a; } public static long[] sort(long[] a) { int n = a.length; ArrayList<Long> l = new ArrayList<>(); for (long i : a) l.add(i); Collections.sort(l); for (int i = 0; i < l.size(); i++) a[i] = l.get(i); return a; } public static long pow(long x, long y) { long res = 1; while (y > 0) { if (y % 2 != 0) { res = (res * x) % modulus; y--; } x = (x * x) % modulus; y = y / 2; } return res; } //GCD___+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ public static long gcd(long x, long y) { if (x == 0) return y; else return gcd(y % x, x); } //****************LOWEST COMMON MULTIPLE ************************************************************************************************************************************* public static long lcm(long x, long y) { return (x * (y / gcd(x, y))); } //INPUT PATTERN****************************************************************************************************************************************************************** public static int i() { return in.Int(); } public static long l() { String s = in.String(); return Long.parseLong(s); } public static String s() { return in.String(); } public static int[] readArray(int n) { int A[] = new int[n]; for (int i = 0; i < n; i++) { A[i] = i(); } return A; } public static long[] readArray(long n) { long A[] = new long[(int) n]; for (int i = 0; i < n; i++) { A[i] = l(); } return A; } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
9b92a6a9a6176899b74127c0eab8f41b
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
//package credit; import java.io.*; import java.util.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Main{ static boolean v[]; static int ans[]; int size[]; static int count=0; static int dsu=0; static int c=0; static int e9=1000000007; int min=Integer.MAX_VALUE; int max=Integer.MIN_VALUE; long max1=Long.MIN_VALUE; long min1=Long.MAX_VALUE; boolean aBoolean=true; boolean y=false; long m=0; static boolean t1=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; } } int parent[]; int rank[]; int n=0; ArrayList<ArrayList<Integer>> arrayLists; boolean v1[]; static boolean t2=false; boolean r=false; int fib[]; int fib1[]; int ind[]; int min3=Integer.MAX_VALUE; public static void main(String[] args) throws IOException { Main g = new Main(); g.go(); } public void go() throws IOException { FastReader scanner = new FastReader(); // Scanner scanner = new Scanner(System.in); // BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(System.in)); // String s; PrintWriter printWriter = new PrintWriter(System.out); int t =1; for (int i = 0; i < t; i++) { int n=scanner.nextInt(); int m=scanner.nextInt(); int s[]=new int[m]; int e[]=new int[m]; String a=scanner.next(); String b=scanner.next(); int y=0; for (int j = 0; j < a.length()&&y<m; j++) { if(b.charAt(y)==a.charAt(j)){ s[y]=j+1; y++; } } y=m-1; for (int j =a.length()-1; j>=0&&y>=0; j--) { if(b.charAt(y)==a.charAt(j)){ e[y]=j+1; y--; } } int max=Integer.MIN_VALUE; for (int j = 0; j <m-1; j++) { max=Math.max(max,e[j+1]-s[j]); } printWriter.println(max); } printWriter.flush(); } static final int mod=1_000_000_007; public long mul(long a, long b) { return a*b; } public long fact(int x) { long ans=1; for (int i=2; i<=x; i++) ans=mul(ans, i); return ans; } public 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)); } public long modInv(long x) { return fastPow(x, mod-2); } public long nCk(int n, int k) { return mul(fact(n), mul(modInv(fact(k)), modInv(fact(n-k)))); } // public void sieve(int n){ // fib=new int[n+1]; // fib[1]=-1; // fib[0]=-1; // for (int i =2; i*i<=n; i++) { // if(fib[i]==0) // for (int j =i*i; j <=n; j+=i){ // fib[j]=-1; //// System.out.println("l"); // } // } // } public void parent(int n){ for (int i = 0; i < n; i++) { parent[i]=i; rank[i]=1; size[i]=1; } } public void union(int i,int j){ int root1=find(i); int root2=find(j); // if(root1 != root2) { // parent[root2] = root1; //// sz[a] += sz[b]; // } if(root1==root2){ return; } if(rank[root1]>rank[root2]){ parent[root2]=root1; rank[root1]++; size[root1]+=size[root2]; } else if(rank[root1]<rank[root2]){ parent[root1]=root2; size[root2]+=size[root1]; rank[root2]++; } else{ parent[root2]=root1; rank[root1]+=1; size[root1]+=size[root2]; } } public int find(int p){ if(parent[p]!=p){ if(parent[p]==-1){ return parent[p]; } parent[p]=find(parent[p]); } return parent[p]; // if(parent[p]==-1){ // return -1; // } // else if(parent[p]==p){ // return p; // } // else { // parent[p]=find(parent[p]); // return parent[p]; // } } public double dist(double x1,double y1,double x2,double y2){ double e=(x2-x1)*(x2-x1)+(y2-y1)*(y2-y1); double e1=Math.sqrt(e); return e1; } public void make(int p){ parent[p]=p; rank[p]=1; } Random rand = new Random(); public void sort(int[] a, int n) { for (int i = 0; i < n; i++) { int j = rand.nextInt(i + 1); int tmp = a[i]; a[i] = a[j]; a[j] = tmp; } Arrays.sort(a, 0, n); } public long gcd(long a,long b){ if(b==0){ return a; } return gcd(b,a%b); } public void dfs(ArrayList<Integer> arrayLists1){ for (int i = 0; i < arrayLists1.size(); i++) { if(v1[arrayLists1.get(i)]==false){ System.out.println(arrayLists1.get(i)); v1[arrayLists1.get(i)]=true; count++; dfs(arrayLists.get(arrayLists1.get(i))); } } } private void dfs2(ArrayList<Integer>[]arrayList,int j,int count){ ans[j]=count; for(int i:arrayList[j]){ if(ans[i]==-1){ dfs2(arrayList,i,count); } } } private void dfs3(ArrayList<Integer>[] arrayList, int j) { v[j]=true; count++; for(int i:arrayList[j]){ if(v[i]==false) { dfs3(arrayList, i); } } } public double fact(double h){ double sum=1; while(h>=1){ sum=(sum%e9)*(h%e9); h--; } return sum%e9; } public long primef(double r){ long c=0; long ans=1; while(r%2==0){ c++; r=r/2; } if(c>0){ ans*=2; } c=0; // System.out.println(ans+" "+r); for (int i = 3; i <=Math.sqrt(r) ;i+=2) { while(r%i==0){ // System.out.println(i); c++; r=r/i; } if(c>0){ ans*=i; } c=0; } if(r>2){ ans*=r; } return ans; } public long divisor(double r){ long c=0; for (int i = 1; i <=Math.sqrt(r); i++) { if(r%i==0){ if(r/i==i){ c++; } else{ c+=2; } } } return c; } } class Pair{ int x; int y; double z; public Pair(int x,int y){ this.x=x; this.y=y; } @Override public int hashCode() { int hash =37; return this.x * hash + this.y; } @Override public boolean equals(Object o1){ if(o1==null||o1.getClass()!=this.getClass()){ return false; } Pair o=(Pair)o1; if(o.x==this.x&&o.y==this.y){ return true; } return false; } } class Sorting implements Comparator<Pair> { public int compare(Pair p1,Pair p2){ // if(p1.x==p2.x){ // return -1*Double.compare(p1.y,p2.y); // } // else { return Double.compare(p1.x, p2.x); // } } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
94e5869a00835be83917529f1b143ac5
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.*; public class C_Maximum_width { public static void main(String[] args) { FastScanner fs = new FastScanner(); int n = fs.nextInt(); int m = fs.nextInt(); String s = fs.next(); String t = fs.next(); int[] first = new int[t.length()]; int[] last = new int[t.length()]; int i = 0, j = 0; for (; i < t.length(); i++) { while (t.charAt(i) != s.charAt(j)) { j++; } first[i] = j; j++; } i = t.length() - 1; j = s.length() - 1; for (; i >= 0; i--) { while (t.charAt(i) != s.charAt(j)) { j--; } last[i] = j; j--; } int ans = Integer.MIN_VALUE; for (i = 1; i < t.length(); i++) { ans = Math.max(last[i] - first[i - 1], ans); } System.out.println(ans); } static final int mod = 1_000_000_007; static long mul(long a, long b) { return a * b % mod; } static long fact(int x) { long ans = 1; for (int i = 2; i <= x; 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 long modInv(long x) { return fastPow(x, mod - 2); } static long nCk(int n, int k) { return mul(fact(n), mul(modInv(fact(k)), modInv(fact(n - k)))); } 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()); } } class Cool { int m; int n; Cool(int m, int n) { this.m = m; this.n = n; } } class SortCool implements Comparator<Cool> { @Override public int compare(Cool ob1, Cool ob2) { return ob1.m - ob2.m; } } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
bda32f5b057bca164b878e2d22177015
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.StringTokenizer; import java.util.TreeSet; @SuppressWarnings("ConstantConditions") public final class C { public static void main(String[] args) { final FastScanner fs = new FastScanner(); final int n = fs.nextInt(); final int m = fs.nextInt(); final char[] s = fs.next().toCharArray(); final char[] t = fs.next().toCharArray(); final List<TreeSet<Integer>> g = new ArrayList<>(26); for (int i = 0; i < 26; i++) { g.add(new TreeSet<>()); } for (int i = 0; i < n; i++) { g.get(s[i] - 'a').add(i); } final int[] curr = new int[m]; for (int i = 0; i < m; i++) { if (i == 0) { curr[0] = g.get(t[0] - 'a').first(); } else { curr[i] = g.get(t[i] - 'a').higher(curr[i - 1]); } } int res = 0; for (int i = 0; i < m - 1; i++) { res = Math.max(res, curr[i + 1] - curr[i]); } for (int i = m - 1; i >= 0; i--) { if (i == m - 1) { curr[m - 1] = g.get(t[m - 1] - 'a').last(); } else { res = Math.max(res, curr[i + 1] - curr[i]); curr[i] = g.get(t[i] - 'a').lower(curr[i + 1]); } } System.out.println(res); } static final class Utils { private static class Shuffler { private static void shuffle(int[] x) { final Random r = new Random(); for (int i = 0; i <= x.length - 2; i++) { final int j = i + r.nextInt(x.length - i); swap(x, i, j); } } private static void shuffle(long[] x) { final Random r = new Random(); for (int i = 0; i <= x.length - 2; i++) { final int j = i + r.nextInt(x.length - i); swap(x, i, j); } } private static void swap(int[] x, int i, int j) { final int t = x[i]; x[i] = x[j]; x[j] = t; } private static void swap(long[] x, int i, int j) { final long t = x[i]; x[i] = x[j]; x[j] = t; } } public static void shuffleSort(int[] arr) { Shuffler.shuffle(arr); Arrays.sort(arr); } public static void shuffleSort(long[] arr) { Shuffler.shuffle(arr); Arrays.sort(arr); } private Utils() {} } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); private String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { //noinspection CallToPrintStackTrace e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } int[] nextIntArray(int n) { final int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } long[] nextLongArray(int n) { final long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
9b305fb55f5964f3c49038ef8e0dc74f
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.StringTokenizer; import java.util.TreeSet; public final class C { public static void main(String[] args) { final FastScanner fs = new FastScanner(); final int n = fs.nextInt(); final int m = fs.nextInt(); final char[] s = fs.next().toCharArray(); final char[] t = fs.next().toCharArray(); final List<TreeSet<Integer>> g = new ArrayList<>(26); for (int i = 0; i < 26; i++) { g.add(new TreeSet<>()); } for (int i = 0; i < n; i++) { g.get(s[i] - 'a').add(i); } final int[] curr = new int[m]; for (int i = 0; i < m; i++) { if (i == 0) { curr[0] = g.get(t[0] - 'a').first(); } else { curr[i] = g.get(t[i] - 'a').higher(curr[i - 1]); } } int res = 0; for (int i = 0; i < m - 1; i++) { res = Math.max(res, curr[i + 1] - curr[i]); } for (int i = m - 1; i >= 0; i--) { if (i == m - 1) { curr[m - 1] = g.get(t[m - 1] - 'a').last(); res = Math.max(res, curr[m - 1] - curr[m - 2]); } else { curr[i] = g.get(t[i] - 'a').lower(curr[i + 1]); res = Math.max(res, curr[i + 1] - curr[i]); if (i > 0) { res = Math.max(res, curr[i] - curr[i - 1]); } } } System.out.println(res); } static final class Utils { private static class Shuffler { private static void shuffle(int[] x) { final Random r = new Random(); for (int i = 0; i <= x.length - 2; i++) { final int j = i + r.nextInt(x.length - i); swap(x, i, j); } } private static void shuffle(long[] x) { final Random r = new Random(); for (int i = 0; i <= x.length - 2; i++) { final int j = i + r.nextInt(x.length - i); swap(x, i, j); } } private static void swap(int[] x, int i, int j) { final int t = x[i]; x[i] = x[j]; x[j] = t; } private static void swap(long[] x, int i, int j) { final long t = x[i]; x[i] = x[j]; x[j] = t; } } public static void shuffleSort(int[] arr) { Shuffler.shuffle(arr); Arrays.sort(arr); } public static void shuffleSort(long[] arr) { Shuffler.shuffle(arr); Arrays.sort(arr); } private Utils() {} } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); private String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { //noinspection CallToPrintStackTrace e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } int[] nextIntArray(int n) { final int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } long[] nextLongArray(int n) { final long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
35b06c3aacc27bc92b8a261496aaa4d0
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.util.*; import java.io.*; public class Main{ static int mod=(int)1e9+7; public static void main(String[] args) throws IOException { PrintWriter out=new PrintWriter(System.out); Reader in=new Reader(System.in); int ts=1; // ts=in.nextInt(); while(ts-->0) solve(in, out); out.close(); } static void solve(Reader in, PrintWriter out) { //for two consecutive characters of t, the max width int n=in.nextInt(); int m=in.nextInt(); char s[]=in.next().toCharArray(); char t[]=in.next().toCharArray(); int st[]=new int[m], la[]=new int[m]; int pos=0; for(int i=0; i<m; ++i) { char c=t[i]; for(int j=pos; ; ++j) { if(c==s[j]) { pos=j+1; st[i]=j; break; } } } pos=n-1; for(int i=m-1; i>=0; --i) { char c=t[i]; for(int j=pos; ; --j) { if(c==s[j]) { pos=j-1; la[i]=j; break; } } } int ans=0; for(int i=0; i<m-1; ++i) { ans=Math.max(ans, la[i+1]-st[i]); } out.println(ans); } static void sort(long a[]) { ArrayList<Long> al=new ArrayList<>(); for(long i: a) al.add(i); Collections.sort(al, Comparator.reverseOrder()); for(int i=0; i<a.length; ++i) a[i]=al.get(i); } static class Reader{ BufferedReader br; StringTokenizer to; Reader(InputStream stream){ br=new BufferedReader(new InputStreamReader(stream)); to=new StringTokenizer(""); } String nextLine() { String line=""; try { line=br.readLine(); }catch(IOException e) {}; return line; } String next() { while(!to.hasMoreTokens()) { try { to=new StringTokenizer(br.readLine()); }catch(IOException e) {} } return to.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } int [] readArray(int n) { int a[]=new int[n]; for(int i=0; i<n; i++) a[i]=nextInt(); return a; } long [] readLongArray(int n) { long [] a =new long[n]; for(int i=0; i<n; ++i) a[i]=nextLong(); return a; } } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
e2914283faf762152b81402807962acf
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.TreeSet; import java.util.ArrayList; 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; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); CMaximumWidth solver = new CMaximumWidth(); solver.solve(1, in, out); out.close(); } static class CMaximumWidth { int n; int m; char[] first; char[] second; public void readInput(Scanner sc) { n = sc.nextInt(); m = sc.nextInt(); first = sc.next().toCharArray(); second = sc.next().toCharArray(); } public void solve(int testNumber, Scanner sc, PrintWriter pw) { int q = 1; while (q-- > 0) { readInput(sc); TreeSet<Integer>[] sets = new TreeSet[26]; for (int i = 0; i < 26; i++) sets[i] = new TreeSet<>(); for (int i = 0; i < n; i++) sets[first[i] - 'a'].add(i); int idx = -1; ArrayList<Integer> list = new ArrayList<>(); for (int i = 0; i < m; i++) { idx = sets[second[i] - 'a'].higher(idx); list.add(idx); } ArrayList<Integer> list2 = new ArrayList<>(); idx = n; for (int i = m - 1; i >= 0; i--) { idx = sets[second[i] - 'a'].lower(idx); list2.add(idx); } int ans = 0; for (int i = 0; i < m - 1; i++) ans = Math.max(ans, list2.get(i) - list.get(m - i - 2)); pw.println(ans); } } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() { try { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } catch (Exception e) { throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
63c0fe9329371964fd00c364fc528fac
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
//package random; import java.io.*; import java.util.*; public class Playoff { public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); String s = br.readLine(); String t = br.readLine(); int[] front = new int[m]; int[] back = new int[m]; int cur = 0; for (int i=0; i<m; i++) { while(s.charAt(cur)!=t.charAt(i)) { cur++; } front[i] = cur; cur++; } cur = n-1; for (int i=m-1; i>=0; i--) { while(s.charAt(cur)!=t.charAt(i)) { cur--; } back[i] = cur; cur--; } int ans = 0; for (int i=0; i<m-1; i++) { ans = Math.max(back[i+1]-front[i], ans); } System.out.println(ans); } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
274bf094a0fa8fca1ccf117e4fe61efb
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.io.*; import java.lang.Math; import java.util.*; import javax.management.ValueExp; public final class Codechef { static BufferedReader br = new BufferedReader( new InputStreamReader(System.in) ); static BufferedWriter bw = new BufferedWriter( new OutputStreamWriter(System.out) ); static StringTokenizer st; static int mod = 1000000007; /*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 sortCond1 implements Comparator<Integer> { @Override public int compare(Integer p1, Integer p2) { if (p1 <= p2) { return 1; } else { return -1; } } } static class Rec { int a; int b; long c; Rec(int a, int b, long c) { this.a = a; this.b = b; this.c = c; } } 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); int val = (pow % 2 == 0) ? 1 : a; return modMul.mod(modMul.mod(retVal, retVal, mod), val, 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(int ele, int[] arr) { int l = 0; int h = arr.length - 1; int ans = -1; while (l <= h) { int mid = l + (int) (h - l) / 2; int val = arr[mid]; if (ele > val) { l = mid + 1; } else if (ele < val) { h = mid - 1; } else { ans = mid; h = mid - 1; } } return ans; } static int gcd(int a, int b) { int div = b; int rem = a % b; while (rem != 0) { int temp = rem; rem = div % rem; div = temp; } return div; } static long[] log(long no, long n) { long i = 1; int cnt = 0; long sum = 0l; long arr[] = new long[2]; while (i < no) { sum += i; cnt++; if (sum == n) { arr[0] = 1l * cnt; arr[1] = sum; break; } i *= 2l; } if (arr[0] == 0) { arr[0] = cnt; arr[1] = sum; } return arr; } 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[0] = factorial[1] = 1; factorial[2] = 2; 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; } 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; } static void bitRep(int n, int no) throws IOException { int curr = (int) Math.pow(2, n - 1); for (int i = n - 1; i >= 0; i--) { if ((curr & no) != 0) { bw.write("1"); } else { bw.write("0"); } curr /= 2; } bw.write("\n"); } static ArrayList<Integer> retPow(int MAXI) { long curr = 1l; ArrayList<Integer> arr = new ArrayList<>(); for (int i = 1; i <= MAXI; i++) { curr *= 2l; curr = curr % mod; arr.add((int) curr); } return arr; } static String is(int no) { return Integer.toString(no); } static String ls(long no) { return Long.toString(no); } static int pi(String s) { return Integer.parseInt(s); } static long pl(String s) { return Long.parseLong(s); } /*write your methods and classes here*/ public static void main(String[] args) throws IOException { st = new StringTokenizer(br.readLine()); int n = pi(st.nextToken()), i; int m = pi(st.nextToken()); String a = br.readLine(); String b = br.readLine(); int MAXI = -n - 2; int top = 0; int bottom = n - 1; int topi[] = new int[m]; int boti[] = new int[m]; for (i = 0; i < m - 1; i++) { while (a.charAt(top) != b.charAt(i)) { top++; } topi[i] = top; top++; } for (i = m - 1; i >= 1; i--) { while (a.charAt(bottom) != b.charAt(i)) { bottom--; } boti[i] = bottom; bottom--; } for (i = 1; i < m; i++) { MAXI = Math.max(MAXI, boti[i] - topi[i - 1]); } bw.write(is(MAXI) + "\n"); bw.flush(); } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
5fd6122d9b3344d052cac3a93133305a
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.util.*; import java.util.Map.Entry; import java.math.*; public class Simple{ public static class Pair{ int x; long y; public Pair(int x,long y){ this.x = x; this.y = y; } } 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]; } // public static int helper(int mat[][],int n,int m,int i,int j,int min,int max){ // if(j==m){ // return max- min; // } // if(dp[i][j]){ // return dp[] // } // int ans1 = Integer.MAX_VALUE; // int ans2 = Integer.MAX_VALUE; // //we take that element // for(int k = 0;k<n;k++){ // ans1 = Math.min(ans1,helper(mat, n, m, i+k, j+1, Math.min(min,mat[i+k][j+1]), Math.max(max,mat))); // } // //we do not take that element // return dp[i][j] = Math.min(ans1,ans2); // } public static void main(String args[]){ //System.out.println("Hello Java"); Scanner s = new Scanner(System.in); int t = 1; for(int t1 = 1;t1<=t;t1++){ int n = s.nextInt(); int m = s.nextInt(); String str = s.next(); String ttr = s.next(); int left[] = new int[n]; int right[] = new int[n]; int j =0; for(int i=0;i<n && j<m;i++){ if(str.charAt(i)==ttr.charAt(j)){ left[j] = i; j++; } } j=m-1; for(int i=n-1;i>=0 && j>=0;i--){ if(str.charAt(i)==ttr.charAt(j)){ right[j] = i; j--; } } int ans = 0; for(int i=1;i<m;i++){ ans = Math.max(right[i]-left[i-1],ans); } System.out.println(ans); } } } /* 4 2 2 7 0 2 5 -2 3 5 0*x1 + 1*x2 + 2*x3 + 3*x4 */
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
c6de0b65db2f267a379266dc3a54810a
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.util.*; import java.io.*; public class C_Maximum_width{ 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(); } } public static void solve(int n,int m,String s,String t){ int left[]=new int[m]; int right[]=new int[m]; for(int i=0,j=0;i<n&&j<m;i++){ if(s.charAt(i)==t.charAt(j)){ j++; left[j-1]=i; } } for(int i=n-1,j=m-1;j>=0&&i>=0;i--){ if(s.charAt(i)==t.charAt(j)){j--; right[j+1]=i; } } // print(left,"Left arrya"); // print(right,"Right array"); int res=0; for(int i=0;i<m-1;i++){ res=Math.max(res,right[i+1]-left[i]); } System.out.println(res); } public static void print(int []arr,String text){ System.out.println(text); for(int i=0;i<arr.length;i++) System.out.print(arr[i]+ " "); System.out.println(); } public static void main(String args[])throws IOException{ Scanner sc=new Scanner(System.in); int t=1; while(t-->0){ int n=sc.nextInt(); int m=sc.nextInt(); String s=sc.next(); String tc=sc.next(); solve(n,m,s,tc); } } } class Data implements Comparable<Data>{ int num; public Data(int num){ this.num=num; } public int compareTo(Data o){ return o.num-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 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; } } } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
658cdc7bf9241678f6a0d73eabeb81be
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.util.HashMap; import java.util.Scanner; public class reversestring { private static class pair{ int low,high; pair(int low,int high){ this.low=low;this.high=high; } } public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m=in.nextInt();String s=in.next(); String t=in.next();char sa[]=s.toCharArray();char ta[]=t.toCharArray() ;int min=Integer.MIN_VALUE; int f[]=new int[m];int l[]=new int[m]; int p=0; for(int i=0;i<m;i++) { while(p<n && sa[p]!=ta[i]) { p++; } f[i]=p++; } p=n-1; for(int i=m-1;i>=0;i--) { while(p>=0 && sa[p]!=ta[i]) { p--; } l[i]=p--; } for(int i=0;i<m-1;i++) { min=Math.max(l[i+1]-f[i],min); } System.out.print(min); } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
c37d1006d4424c6fa395eb14dd2dcab6
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.io.*; import java.util.*; public class MaxWidth { public static void main(String[] args)throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); String s = br.readLine(); String t = br.readLine(); int[] pfx = new int[m]; int[] sfx = new int[m]; Arrays.fill(pfx, -1); Arrays.fill(sfx, -1); int count = 0; for(int i =0;i<n;i++){ if(count < m && s.charAt(i)==t.charAt(count)){ pfx[count]=i; count++; } } count = m-1; for(int i = n-1;i>-1;i--){ if(count > -1 && s.charAt(i)==t.charAt(count)){ sfx[count] = i; count--; } } int max = 0; for(int i = 0;i<m-1;i++){ if(pfx[i]!=-1 && sfx[i]!=-1)max = Math.max(max, sfx[i+1] - pfx[i]); } System.out.println(max); } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
e7e930d37b74c20b11eae499ac54a07f
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class MaximumWidth { public static void main(String[] args) throws IOException { BufferedReader read = new BufferedReader(new InputStreamReader(System.in));//new FileReader("cowdance.in") PrintWriter out = new PrintWriter(System.out);//new FileWriter("cowdance.out") StringTokenizer st = new StringTokenizer(read.readLine()); int n = Integer.parseInt(st.nextToken());//Long.parseLong(st.nextToken()); int m = Integer.parseInt(st.nextToken()); String s = read.readLine(); String t = read.readLine(); int [] h = new int [m]; int [] l = new int [m]; int max = 0; int ind = 0; for (int i = 0; i < n; i++) { if (s.charAt(i) == t.charAt(ind)) { l[ind] = i; ind++; } if (ind == m)break; } ind = m-1; for (int i = n-1; i >= 0; i--) { if (s.charAt(i) == t.charAt(ind)) { h[ind] = i; ind--; } if (ind == -1)break; } for (int i = 0; i < m-1; i++) { max = Math.max(h[i+1]-l[i], max); } out.println(max); out.close(); } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
36a4b91eb2da21b6051f0b908f5623aa
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.util.*; import java.lang.*; import java.io.*; public final class Solution{ public static void main (String[] args) throws Exception { BufferedWriter op = new BufferedWriter(new OutputStreamWriter(System.out)); Scanner sc= new Scanner(System.in); int n =sc.nextInt(); int m=sc.nextInt(); String b= sc.next(); String a= sc.next(); HashMap<Character ,ArrayList<Integer>> hm = new HashMap<>(); for(int i = 0; i<n ; i++){ char c=b.charAt(i); if(hm.containsKey(c)){ ArrayList<Integer> list= hm.get(c); list.add(i); hm.put(c,list); }else{ ArrayList<Integer> list= new ArrayList<>(); list.add(i); hm.put(c,list); } } ArrayList<Integer> minlist= new ArrayList<>(); ArrayList<Integer> maxlist= new ArrayList<>(); ArrayList<Integer> max= new ArrayList<>(); int c=0; for(int i=0;i<n;i++){ if(c==m){break;} if(b.charAt(i)==a.charAt(c)){ c++; minlist.add(i); } } c=m-1; for(int i=n-1;i>=0;i--){ if(c==-1) break; if(b.charAt(i)==a.charAt(c)){ max.add(i); c--; } } for(int i=max.size()-1 ;i>=0;i--){ maxlist.add(max.get(i)); } for(int i=0;i<m-1;i++){ if(maxlist.get(i+1)<maxlist.get(i)){ ArrayList<Integer> l= hm.get(i); for(int j=l.size()-1;j>=0;j-- ){ if(l.get(j)<maxlist.get(i+1)){ maxlist.set(i, l.get(j)); break; } } } } int ans= 0; for(int i=0;i<minlist.size()-1;i++){ ans =Math.max(maxlist.get(i+1)-minlist.get(i), ans); } op.write(ans+""); op.write("\n"); op.flush(); } } 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(); } } // BufferedWriter op = new BufferedWriter(new OutputStreamWriter(System.out)); // 1 1 1 0 -1 -1 -1 1 1 1 0 -1 -1 1 1 1 0 -1 1 1 1 0 1 1 1 1 1 1
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
b7655d24bc474ffae405933f87dcb435
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
/* _oo0oo_ o8888888o 88" . "88 (| -_- |) 0\ = /0 ___/`---'\___ .' \\| |// '. / \\||| : |||// \ / _||||| -:- |||||- \ | | \\\ - /// | | | \_| ''\---/'' |_/ | \ .-\__ '-' ___/-. / ___'. .' /--.--\ `. .'___ ."" '< `.___\_<|>_/___.' >' "". | | : `- \`.;`\ _ /`;.`/ - ` : | | \ \ `_. \_ __\ /__ _/ .-` / / =====`-.____`.___ \_____/___.-`___.-'===== `=---=' */ import java.util.function.Consumer; import java.util.*; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.text.DecimalFormat; import java.io.*; import java.lang.Math.*; public class KickStart2020{ 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());} float nextFloat() {return Float.parseFloat(next());} String nextLine() { String str = ""; try {str = br.readLine();} catch (IOException e) { e.printStackTrace();} return str; }} static boolean isBracketSequence(String s, int a, int b) { Stack<Character> ss = new Stack<>(); boolean hachu = true; for(int i = a; i <= b; i++) { if(s.charAt(i) == ')' && ss.isEmpty()) {hachu = false; break;} if(s.charAt(i) == '(') ss.add('('); else ss.pop(); } return ss.empty() && hachu; } static String reverseOfString(String a) { StringBuilder ssd = new StringBuilder(); for(int i = a.length() - 1; i >= 0; i--) { ssd.append(a.charAt(i)); } return ssd.toString(); } static char[] reverseOfChar(char a[]) { char b[] = new char[a.length]; int j = 0; for(int i = a.length - 1; i >= 0; i--) { b[i] = a[j]; j++; } return b; } static boolean isPalindrome(char a[]) { boolean hachu = true; for(int i = 0; i <= a.length / 2; i++) { if(a[i] != a[a.length - 1 - i]) { hachu = false; break; } } return hachu; } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static long powermod(long x, long y, long mod){ long ans = 1; x = x % mod; if (x == 0) return 0; int i = 1; while (y > 0){ if ((y & 1) != 0) ans = (ans * x) % mod; y = y >> 1; x = (x * x) % mod; } return ans; } static long power(long x, long y){ long ans = 1; if (x == 0) return 0; int i = 1; while (y > 0){ if ((y & 1) != 0) ans = (ans * x); y = y >> 1; x = (x * x); } return ans; } static boolean check(String a) { boolean hachu = true; for(int i = 0; i < a.length(); i++) { if(a.charAt(0) != a.charAt(i)) {hachu = false; break;} } return hachu; } public static class Pair implements Comparable<Pair> { public final int index; public final int value; public Pair(int index, int value) { this.index = index; this.value = value; } @Override public int compareTo(Pair other) { //multiplied to -1 as the author need descending sort order return -1 * Integer.valueOf(this.value).compareTo(other.value); } } static boolean equalString(int i, int j, int arr[], String b) { int brr[] = new int[26]; for(int k = i; k <= j; k++) brr[b.charAt(k) - 'a']++; for(int k = 0; k < 26; k++) { if(arr[k] != brr[k]) return false; } return true; } static boolean cequalArray(String a, String b) { int count[] = new int[26]; int count1[] = new int[26]; for(int i = 0; i < a.length(); i++) count[a.charAt(i) - 'a']++; for(int i = 0; i < a.length(); i++) count1[b.charAt(i) - 'a']++; for(int i = 0; i < 26; i++) if(count[i] != count1[i]) return false; return true; } static boolean isPrime(long d) { if(d == 1) return true; for(int i = 2; i <= (long)Math.sqrt(d); i++) { if(d % i == 0) return false; } return true; } public static void main(String[] args) throws Exception{ FastReader sc = new FastReader(); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); int m = sc.nextInt(); String a = sc.next(); String b = sc.next(); int i = 0, j = 0; int arr[] = new int[m]; int brr[] = new int[m]; while(i < n && j < m) { if(a.charAt(i) == b.charAt(j)) { arr[j++] = i; } i++; } i = n - 1; j = m - 1; while(i >= 0 && j >= 0) { if(a.charAt(i) == b.charAt(j)) { brr[j--] = i; } i--; } int max = -1; for(int k = 1; k < m; k++) { max = Math.max(max, brr[k] - arr[k - 1]); } out.println(max); out.close(); } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
387ed6e8cd73c1bc8d76cd65128ded83
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.util.*; import java.io.*; public class Main { static BufferedReader rd = new BufferedReader(new InputStreamReader(System.in)); static BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(System.out)); static StringTokenizer tok; public static void main(String[] args) throws Exception { solution(); } public static void solution() throws Exception { tok = new StringTokenizer(rd.readLine()); int n = Integer.parseInt(tok.nextToken()); int m = Integer.parseInt(tok.nextToken()); String s = rd.readLine(); String t = rd.readLine(); Seq[] pos = new Seq[m]; // 모든 값들의 현재 위치와 각 max값들을 저장할 Seq 배열 int i=0, j=0, k=m-1; // 인덱스 while(s.charAt(j) != t.charAt(i)) j++; // 먼저 첫번째 위치를 찾는다. pos[0] = new Seq(0,j); // 첫번째 문자위치 적용, 첫번째값은 i-1을 뺄수 없으므로 최댓값이 존재하지 않음. for(i=n-1;i>j;i--) { if(k > 0 && s.charAt(i) == t.charAt(k)) { pos[k] = new Seq(0,i); // 최댓값은 배열 완성된 후에 다시 계산함. k--; } } // 첫번째 값을 제외한 나머지 문자들을 오른쪽 끝에서부터 찾아놓는다. for(i=1;i<m;i++) pos[i].setMax(pos[i].cindex - pos[i-1].cindex); // 배열완성된 후 초기 최댓값을 계산하여 적용함. i =1; // i인덱스는 반복문에서 현재 t문자열의 위치를 의미함. j++; // j인덱스는 반복문에서 현재 s문자열의 위치를 의미함. while(i < m-1 && j < n) { if(s.charAt(j) == t.charAt(i)) { pos[i].setIndex(j); pos[i].setMax(pos[i].cindex - pos[i-1].cindex); pos[i+1].setMax(pos[i+1].cindex - pos[i].cindex); // 최댓값을 바뀐값과 현재값중 더 큰값으로 설정한다. i++; } // s문자열에서 이번에는 왼쪽으로 붙이면서 t문자열의 위치를 찾아낸다. j++; } Arrays.sort(pos); System.out.println(pos[0].max); // System.out.println(Arrays.toString(pos)); } static class Seq implements Comparable<Seq> { int max; int cindex; public Seq(int m, int c) { this.max = m; this.cindex=c; } public void setMax(int m) { this.max = Math.max(this.max, m); } public void setIndex(int c) { this.cindex = c; } @Override public String toString() { return "{max=" + max + ", cindex=" + cindex + "}"; } @Override public int compareTo(Seq o) { return o.max - this.max; } } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
5594cc1d37e1805c6c3095da542fbc0a
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.io.*; import java.util.*; public class tank { static final FastScanner fs = new FastScanner(); public static void main(String[] args) { // int t = fs.nextInt(); // while(t-->0){ // run_case(); // } run_case(); } static void run_case() { int n = fs.nextInt(), m = fs.nextInt(), ans = 0, fiel = 0, lael = n-1; String s = fs.next(), t = fs.next(); int[] cache = new int[m]; while(s.charAt(fiel) != t.charAt(0)) fiel++; cache[0] = fiel; fiel++; for (int i = m-1; i > 0; i--) { while(s.charAt(lael) != t.charAt(i)) lael--; cache[i] = lael; lael--; } for (int i = 0; i < m - 1; i++) { ans = Math.max(ans, cache[i + 1] - cache[i]); while(s.charAt(fiel) != t.charAt(i + 1)) fiel++; cache[i + 1] = fiel; fiel++; } System.out.println(ans); } 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()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
8a50d53baa08eacb780f31d3864437e1
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class CodeForces extends Functions { static Scanner sc = new Scanner(); public static void solve() { int n = sc.nextInt(); int m = sc.nextInt(); String s =sc.next(); String t = sc.next(); int[] left = new int[m]; int[] right =new int[m]; int i=0,j=0; while(j<m){ if(s.charAt(i)==t.charAt(j)){ left[j] = i; i++; j++; } else i++; } i=n-1;j=m-1; while(j>=0){ if(s.charAt(i)==t.charAt(j)){ right[j] = i; i--; j--; } else i--; } int max = 0; for(int k=0;k<m-1;k++) max = Math.max(right[k+1]-left[k],max); System.out.println(max); } public static void main(String[] args) { // int testCase= sc.nextInt(); int testCase = 1; while (testCase-->0){ solve(); } long end = System.currentTimeMillis(); // System.out.println("time took in ms : "+(end-start)); } } class Functions { public static int mod = (int)1e9+7; public static void sort(int[] a){ ArrayList<Integer> temp = new ArrayList<>(); for (int j : a) temp.add(j); Collections.sort(temp);; for(int i=0;i<a.length;i++)a[i] = temp.get(i); } public static long factorial(int n){ long fact = 1L; for(int i=2;i<=n;i++)fact= (fact*i)%mod; return fact; } public static void sortRev(int[] a){ sort(a); int left = 0; int right = a.length-1; while (left<right){ int temp =a[left]; a[left] = a[right]; a[right] = temp; left++; right--; } } public static long isPrime(long n){ for(long i=2;i*i<=n;i++) if(n%i==0)return i; return -1; } } class Scanner { private BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); private StringTokenizer st = new StringTokenizer(""); public String next(){ while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); }catch (IOException e){ e.printStackTrace(); } return st.nextToken(); } public int nextInt(){return Integer.parseInt(next());} public long nextLong(){return Long.parseLong(next());} public double nextDouble(){return Double.parseDouble(next());} public int[] setIntArray(int n){ int[] arr =new int[n]; for(int i=0;i<n;i++)arr[i] = nextInt(); return arr; } public Integer[] setIntegerArray(int n){ Integer[] arr =new Integer[n]; for(int i=0;i<n;i++)arr[i] = nextInt(); return arr; } public long[] setlongArray(int n){ long[] arr =new long[n]; for(int i=0;i<n;i++)arr[i] = nextLong(); return arr; } public int[][] set2DIntegerMatrix(int row,int col){ int[][] arr = new int[row][col]; for(int i=0;i<row;i++) for(int j= 0;j<col;j++) arr[i][j] = nextInt(); return arr; } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
b3a175e574e24dbb75dd63b4e43c4bcc
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.util.*; import java.io.*; public class MaxWid { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] snm=br.readLine().split(" "); int n = Integer.parseInt(snm[0]); int m = Integer.parseInt(snm[1]); String s = br.readLine(); String t = br.readLine(); int ans=0; int[] lefts=new int[m]; int left=0; int[] rights=new int[m]; int right=n-1; int i=0; while (true) { //System.out.println(left); if (s.substring(left,left+1).equals(t.substring(i,i+1))==false) left+=1; else { lefts[i]=left; i+=1; left+=1;} if (i==m) break; } while (true) { if (s.substring(right,right+1).equals(t.substring(i-1,i))==false) { right-=1; } else { rights[i-1]=right; right-=1; i-=1; } if (i==0) break; } for (int j=0; j<m-1; j++) { if (rights[j+1]-lefts[j]>ans) ans=rights[j+1]-lefts[j]; } System.out.println(ans); } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
5a65300bd15386168f9205dc71462244
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Solution { public static void main(String[] args) throws IOException { Scanner scanner=new Scanner(System.in); int a=scanner.nextInt(); int b=scanner.nextInt(); String aa=scanner.next(); String bb=scanner.next(); int arr[]=new int[b]; int brr[]=new int[a]; int x=0; for(int i=0;i<a;i++){ if(x<b&&aa.charAt(i)==bb.charAt(x)){ arr[x]=i; x++; } } x=b-1; for(int i=a-1;i>=0;i--){ if(x>=0&&aa.charAt(i)==bb.charAt(x)){ brr[x]=i; x--; } } int mx=0; for(int i=1;i<b;i++){ mx=Math.max(mx,brr[i]-arr[i-1]); } System.out.println(mx); } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
7471807a4a4817222d5b66d5a3f9f330
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
// package feb2021; import java.util.*; import java.lang.*; import java.math.*; import java.io.*; public class cf_subs { static FastReader scn = new FastReader(); static OutputStream out = new BufferedOutputStream(System.out); public static void main(String[] args) throws IOException { // TODO Auto-generated method stub // int tc = scn.nextInt(); int tc =1; while(tc-->0) { int n= scn.nextInt(),m=scn.nextInt(),MAX=(int)2e5+5; char[] s =scn.next().toCharArray(), t = scn.next().toCharArray(); int[] l = new int[MAX],r = new int[MAX]; int idx =0; for(int i=0;i<s.length;i++) { if(idx<t.length&&s[i]==t[idx]) { l[idx]=i;idx++; } } idx=t.length-1; for(int i=s.length-1;i>=0;i--) { if(idx>=0&&s[i]==t[idx]) { r[idx]=i;idx--; } } int ans=0; for(int i=0;i<t.length-1;i++) { ans = Math.max(ans, r[i+1]-l[i]); } out.write((ans+"\n").getBytes()); } out.close(); } static long gcd(long a, long b) { if(a==0) return b; return gcd(b%a,a); } static class Edge implements Comparable<Edge>{ int u,v,w; public Edge(int u, int v, int w) { this.u=u;this.v =v;this.w =w; } public int compareTo(Edge o) { return this.w-o.w; } public String toString() { return "["+u+','+v+','+w+']'; } } // static class Pair implements Comparable<Pair>{ // int first; // int second; // int idx; // public Pair() { // this.first=-1; // this.second =-1; // this.idx=-1; // } // public Pair(int first) { // this.first = first; // this.second =-1; // this.idx=-1; // } // public Pair(int first, int second,int idx) { // this.first = first; // this.second = second; // this.idx=idx; // } // public int compareTo(Pair o) { // return this.first+this.second-o.first-o.second; // } // public String toString() { // return "{"+this.first+","+this.second+"}"; // } // } static class Pair<S extends Comparable<S>,T extends Comparable<T>> implements Comparable<Pair<S,T>>{ S first; T second; // int idx; public Pair() { this.first=null; this.second =null; // this.idx=-1; } public Pair(S first) { this.first = first; this.second =null; // this.idx=-1; } public Pair(S first, T second) { this.first = first; this.second = second; // this.idx=idx; } public int compareTo(Pair<S,T> o) { if(this.first.compareTo(o.first)==0) { return this.second.compareTo(o.second); } return this.first.compareTo(o.first); } public String toString() { return "{"+this.first.toString()+","+this.second.toString()+"}"; } } static int log(long N) { // TODO Auto-generated method stub return 63- Long.numberOfLeadingZeros(N); } static int lowerBound(int[] a, int x,int lf,int rg) { int l = lf-1, r = rg+1; while (r - l > 1) { int c = (l + r) / 2; if (a[c] < x) { //if (a[c] > x) { l = c; } else { r = c; } } return r; } static int upperBound(int[] a, int x,int lf,int rg) { int l = lf-1, r = rg+1; while (r - l > 1) { int c = (l + r) / 2; if (a[c] <= x) { l = c; } else { r = c; } } return r; } static int lowerBound(long[] a, long x) { int l = -1, r = a.length; while (r - l > 1) { int c = (l + r) / 2; if (a[c] < x) { l = c; } else { r = c; } } return r; } static int upperBound(long[] a, long x) { int l = -1, r = a.length; while (r - l > 1) { int c = (l + r) / 2; if (a[c] <= x) { l = c; } else { r = c; } } return r; } static int lowerBound(double[] a, double x) { int l = -1, r = a.length; while (r - l > 1) { int c = (l + r) / 2; if (a[c] < x) { l = c; } else { r = c; } } return r; } static int upperBound(double[] a, double x) { int l = -1, r = a.length; while (r - l > 1) { int c = (l + r) / 2; if (a[c] <= x) { l = c; } else { r = c; } } return r; } @SuppressWarnings("unchecked") static <T> int lowerBound(List<T> ls, T x) throws RuntimeException { if (ls.size() == 0) return -1; if (ls.get(0) instanceof Integer) { return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Integer) t1).compareTo((Integer) t2) >= 0 ? 1 : -1); } else if (ls.get(0) instanceof Long) { return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Long) t1).compareTo((Long) t2) >= 0 ? 1 : -1); } else if (ls.get(0) instanceof Double) { return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Double) t1).compareTo((Double) t2) >= 0 ? 1 : -1); } else if(ls.get(0) instanceof Pair){ return ~Collections.binarySearch(ls, x,(t1,t2)->(((Pair<Integer,Integer>) t1).compareTo((Pair<Integer,Integer>)t2)>=0?1:-1)); }else{ System.err.println( String.format("%s:Arey Maa chudi padi hai", Thread.currentThread().getStackTrace()[1].getMethodName())); throw new RuntimeException(); } } static <T> int upperBound(List<T> ls, T x) throws RuntimeException { if (ls.size() == 0) return -1; if (ls.get(0) instanceof Integer) { return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Integer) t1).compareTo((Integer) t2) > 0 ? 1 : -1); } else if (ls.get(0) instanceof Long) { return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Long) t1).compareTo((Long) t2) > 0 ? 1 : -1); } else if (ls.get(0) instanceof Double) { return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Double) t1).compareTo((Double) t2) > 0 ? 1 : -1); } else { System.err.println( String.format("%s:Arey Maa chudi padi hai", Thread.currentThread().getStackTrace()[1].getMethodName())); throw new RuntimeException(); } } static <T> int rupperBound(List<T> ls, T x) throws RuntimeException { if (ls.size() == 0) return -1; if (ls.get(0) instanceof Integer) { return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Integer) t1).compareTo((Integer) t2) < 0 ? 1 : -1); } else if (ls.get(0) instanceof Long) { return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Long) t1).compareTo((Long) t2) < 0 ? 1 : -1); } else if (ls.get(0) instanceof Double) { return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Double) t1).compareTo((Double) t2) < 0 ? 1 : -1); } else { System.err.println( String.format("%s:Arey maa chudi padi hai", Thread.currentThread().getStackTrace()[1].getMethodName())); throw new RuntimeException(); } } static <T> int rlowerBound(List<T> ls, T x) { if (ls.size() == 0) return -1; if (ls.get(0) instanceof Integer) { return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Integer) t1).compareTo((Integer) t2) <= 0 ? 1 : -1); } else if (ls.get(0) instanceof Long) { return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Long) t1).compareTo((Long) t2) <= 0 ? 1 : -1); } else if (ls.get(0) instanceof Double) { return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Double) t1).compareTo((Double) t2) <= 0 ? 1 : -1); } else { System.err.println( String.format("%s:Arey maa chudi padi hai", Thread.currentThread().getStackTrace()[1].getMethodName())); throw new RuntimeException(); } } public static int[] merge(int[] one,int[] two){ int[] res = new int[one.length+two.length]; int i = 0; int j = 0; int k = 0; while(i<one.length&&j<two.length){ if(one[i]<two[j]){ res[k] = one[i]; i++; k++; } else{ res[k] = two[j]; j++; k++; } } if(i==one.length){ while(j<two.length){ res[k] = two[j]; j++; k++; } } else{ while(i<one.length){ res[k] = one[i]; k++; i++; } } return res; } public static int[] mergesort(int[] arr, int l, int r){ if(l==r){ int[] br = new int[1]; br[0] = arr[l]; return br; } int mid = (l+r)/2; int[] fh = mergesort(arr,l,mid); int[] sh = mergesort(arr,mid+1,r); return merge(fh,sh); } 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 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
1e64cc1afbfecc7517e6262facd7d01d
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.util.*; import java.io.*; import java.lang.*; public class ProblemD { public static void main(String[] args) { MyScanner sc = new MyScanner(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int n=sc.nextInt(); int m=sc.nextInt(); char s[]=sc.next().toCharArray(); char t[]=sc.next().toCharArray(); int min[]=new int[n]; int max[]=new int[m]; int j=0; for(int i=0;i<m;i++){ while(j<n){ if(s[j] == t[i]){ min[i]=j; j++; break; } j++; } } j=n-1; for(int i=m-1;i>=0;i--){ while(j>=0){ if(s[j] == t[i]){ max[i]=j; j--; break; } j--; } } int width=Integer.MIN_VALUE; for(int i=0;i<m-1;i++){ width=Math.max(width,max[i+1]-min[i]); } System.out.println(width); out.close(); } } 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 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
f430a73f5bb34460da97b1009ae9dd05
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.util.*; public class Solve{ public static void main(String[] args){ Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int m=sc.nextInt(); char[] s=sc.next().toCharArray(); char[] t=sc.next().toCharArray(); ArrayList<Integer>[] al=new ArrayList[26]; for(int i=0;i<26;i++){ al[i]=new ArrayList<>(); } int[] dmin=new int[m]; int[] dmax=new int[m]; for(int i=0;i<26;i++){ for(int j=0;j<s.length;j++){ if(s[j]-'a'==i){ al[i].add(j); } } } int mm=-1; for(int i=0;i<t.length;i++){ for(int j=0;j<26;j++){ if(t[i]-'a'==j){ int x=upper(al[j],mm); dmin[i]=al[j].get(x); mm=al[j].get(x); } } } for(int i=0;i<26;i++){ for(int j=0;j<al[i].size();j++){ al[i].set(j,-al[i].get(j)); } Collections.sort(al[i]); } mm=-n-1; for(int i=t.length-1;i>=0;i--){ for(int j=0;j<26;j++){ if(t[i]-'a'==j){ int x=upper(al[j],mm); dmax[i]=-al[j].get(Math.abs(x)); mm=al[j].get(Math.abs(x)); } } } int ans=0; for(int i=0;i<m;i++){ // System.out.println(dmin[i]+" "+dmax[i]); } for(int i=0;i<m-1;i++){ ans=Math.max(dmax[i+1]-dmin[i],ans); } System.out.println(ans); } static int upper(ArrayList<Integer> ar,int x){ int l=-1; int r=ar.size(); while(l+1<r){ int m=(l+r)>>>1; if(ar.get(m)<=x) l=m; else r=m; } return l+1; } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
b9c32ace4a06f2bebcca7fa230e5b75c
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.io.*; import java.util.*; import java.util.function.*; import static java.lang.Math.*; public class C{ public static void main(String[] args) throws Exception { InputStream inputStream; OutputStream outputStream; if(args.length > 0 && System.getProperty("ONLINE_JUDGE") == null) { File input = new File("test.inp"); inputStream = new FileInputStream(input); } else { inputStream = System.in; } outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); int nTest = 1; while(nTest-- > 0){ Task solver = new Task(); solver.solve(in, out); } out.close(); } static class Task { int n,m; String s,t; int[] l,r; public void solve(InputReader in, PrintWriter out) { n = in.nextInt(); m = in.nextInt(); s = in.nextLine(); t = in.nextLine(); l = new int[m + 2]; r = new int[m + 2]; Arrays.fill(l,0); Arrays.fill(r,0); int cur = 0; for(int i = 0;i < m;++i){ while(cur < n && s.charAt(cur) != t.charAt(i)){ ++cur; } l[i] = cur++; } cur = n - 1; for(int i = m - 1;i >= 0;--i){ while(cur >= 0 && s.charAt(cur) != t.charAt(i)){ --cur; } r[i] = cur--; } int ans = 0; for(int i = 0;i < m - 1;++i){ ans = Math.max(ans,r[i + 1] - l[i]); } out.println(ans); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = reader.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
8a118fed56c4fc1495949f2b2e0eb446
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import javax.swing.plaf.FontUIResource; import java.lang.reflect.Array; import java.util.*; import java.lang.*; import java.io.*; public class Codechef { public static void main(String[] args) throws java.lang.Exception { out = new PrintWriter(new BufferedOutputStream(System.out)); sc = new FastReader(); int test = 1; for (int t = 0; t < test; t++) { int n = sc.nextInt(); int m = sc.nextInt(); char[] S = sc.next().toCharArray(); char[] T = sc.next().toCharArray(); int res = 0; int[] prefixes = new int[n + 5]; int[] suffixes = new int[n + 5]; int j = 0; for (int i = 0; i < n; i++) { if (j == m) { break; } if (S[i] == T[j]) { prefixes[j + 1] = i + 1; j++; } } j = m - 1; for (int i = n - 1; i >= 0; i--) { if (j < 0) { break; } if (S[i] == T[j]) { suffixes[j + 1] = i + 1; j--; } } for (int i = 1; i <= m; i++) { res = Math.max(res, suffixes[i + 1] - prefixes[i]); } out.println(res); } out.close(); } public static FastReader sc; public static PrintWriter out; 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 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
2004a8e71186f35dfc05be7d90c52728
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.lang.*; public class Main implements Runnable { static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static void main(String args[]) throws Exception { new Thread(null, new Main(), "Main", 1 << 27).start(); } static class Pair { int f; int s; int p; PrintWriter w; // int t; Pair(int f, int s) { // Pair(int f,int s, PrintWriter w){ this.f = f; this.s = s; // this.p = p; // this.w = w; // this.t = t; } public static Comparator<Pair> wc = new Comparator<Pair>() { public int compare(Pair e1, Pair e2) { // 1 for swap if (Math.abs(e1.f) - Math.abs(e2.f) != 0) { // e1.w.println("**"+e1.f+" "+e2.f); return (Math.abs(e1.f) - Math.abs(e2.f)); } else { // e1.w.println("##"+e1.f+" "+e2.f); return (Math.abs(e1.s) - Math.abs(e2.s)); } } }; } public static ArrayList<Integer> sieve(int N) { int i, j, flag; ArrayList<Integer> p = new ArrayList<Integer>(); for (i = 1; i < N; i++) { if (i == 1 || i == 0) continue; flag = 1; for (j = 2; j <= i / 2; ++j) { if (i % j == 0) { flag = 0; break; } } if (flag == 1) { p.add(i); } } return p; } public static long gcd(long a, long b) { if (b == 0) return a; else return gcd(b, a % b); } //// recursive dfs public static int dfs(int s, ArrayList<Integer>[] g, long[] dist, boolean[] v, PrintWriter w, int p) { v[s] = true; int ans = 1; // int n = dist.length - 1; int t = g[s].size(); // int max = 1; for (int i = 0; i < t; i++) { int x = g[s].get(i); if (!v[x]) { // dist[x] = dist[s] + 1; ans = Math.min(ans, dfs(x, g, dist, v, w, s)); } else if (x != p) { // w.println("* " + s + " " + x + " " + p); ans = 0; } } // max = Math.max(max,(n-p)); return ans; } //// iterative BFS public static int bfs(int s, ArrayList<Integer>[] g, long[] dist, boolean[] b, PrintWriter w, int p) { b[s] = true; int siz = 1; // dist--; Queue<Integer> q = new LinkedList<>(); q.add(s); while (q.size() != 0) { int i = q.poll(); Iterator<Integer> it = g[i].listIterator(); int z = 0; while (it.hasNext()) { z = it.next(); if (!b[z]) { b[z] = true; // dist--; dist[z] = dist[i] + 1; // siz++; q.add(z); } else if (z != p) { siz = 0; } } } return siz; } public static int lower(int key, int[] a) { int l = 0; int r = a.length - 1; int res = 0; while (l <= r) { int mid = (l + r) / 2; if (a[mid] <= key) { l = mid + 1; res = mid + 1; } else { r = mid - 1; } } return res; } public static long power(long x, long y, long m) { if (y == 0) return 1; long p = power(x, y / 2, m) % m; p = (p * p) % m; if (y % 2 == 0) return p; else return (x * p) % m; } ////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////// // code here int[] parent; int[] dist; int[] height; boolean[] vis; HashSet<Integer>[] g; int[] c; int L[]; int l[]; public void run() { InputReader sc = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int defaultValue = 0; int mod = 1000000007; int oo = (int) 1e9; int test = 1; // test = sc.nextInt(); while (test-- > 0) { int n = sc.nextInt(); int m = sc.nextInt(); char[] a = sc.next().toCharArray(); char[] b = sc.next().toCharArray(); L = new int[m + 1]; l = new int[m + 1]; sol(b, a, m, n); sol2(b, a, m, n); int ans = 0; for (int i = 2; i <= m; i++) { ans = Math.max(L[i] - L[i - 1], ans); ans = Math.max(l[i] - L[i - 1], ans); } w.println(ans); } w.flush(); w.close(); } public void sol(char[] X, char[] Y, int m, int n) { int x = 1; for (int i = 1; i <= m; i++) { for (int j = x; j <= n; j++, x++) { if (i == 0 || j == 0) L[i] = 0; else if (X[i - 1] == Y[j - 1]) { L[i] = j; x++; break; } } } } public void sol2(char[] X, char[] Y, int m, int n) { int x = n; for (int i = m; i > 0; i--) { for (int j = x; j > -1; j--, x--) { if (i == 0 || j == 0) l[i] = 0; else if (X[i - 1] == Y[j - 1]) { l[i] = j; x--; break; } } } } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
1e23e0e33a5cefb8d92daa4a27971d86
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.io.PrintWriter; import java.util.*; public class TP { public static PrintWriter out = new PrintWriter(System.out); public static Scanner in = new Scanner(System.in); public static void main(String[] args) { long s = System.currentTimeMillis(); int t = 1; // t = ni(); while (t-- > 0) solve(); out.flush(); tr(System.currentTimeMillis() - s + "ms"); } private static void solve() { int n = ni(), m = ni(); char[] s = in.next().toCharArray(); char[] t = in.next().toCharArray(); int[] first = new int[m]; { int p = 0; for (int i = 0; i < m; i++) { while (p < n && s[p] != t[i]) p++; first[i] = p++; } } int[] last = new int[m]; { int p = n - 1; for (int i = m - 1; i >= 0; i--) { while (p >= 0 && s[p] != t[i]) p--; last[i] = p--; } } int ans = 0; for (int i = 0; i < m - 1; i++) { ans = Math.max(ans, last[i + 1] - first[i]); } out.println(ans); } private static int ni() { return in.nextInt(); } private static int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } private static long[] nal(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nl(); return a; } private static long nl() { return in.nextLong(); } private float nf() { return in.nextFloat(); } private static double nd() { return in.nextDouble(); } public static int[] facs(int n, int[] primes) { int[] ret = new int[9]; int rp = 0; for (int p : primes) { if (p * p > n) break; int i; i = 0; while (n % p == 0) { n /= p; i++; } if (i > 0) ret[rp++] = p; } if (n != 1) ret[rp++] = n; return Arrays.copyOf(ret, rp); } public static int[] sieveEratosthenes(int n) { if (n <= 32) { int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31}; for (int i = 0; i < primes.length; i++) { if (n < primes[i]) { return Arrays.copyOf(primes, i); } } return primes; } int u = n + 32; double lu = Math.log(u); int[] ret = new int[(int) (u / lu + u / lu / lu * 1.5)]; ret[0] = 2; int pos = 1; int[] isnp = new int[(n + 1) / 32 / 2 + 1]; int sup = (n + 1) / 32 / 2 + 1; int[] tprimes = {3, 5, 7, 11, 13, 17, 19, 23, 29, 31}; for (int tp : tprimes) { ret[pos++] = tp; int[] ptn = new int[tp]; for (int i = (tp - 3) / 2; i < tp << 5; i += tp) ptn[i >> 5] |= 1 << (i & 31); for (int j = 0; j < sup; j += tp) { for (int i = 0; i < tp && i + j < sup; i++) { isnp[j + i] |= ptn[i]; } } } // 3,5,7 // 2x+3=n int[] magic = { 0, 1, 23, 2, 29, 24, 19, 3, 30, 27, 25, 11, 20, 8, 4, 13, 31, 22, 28, 18, 26, 10, 7, 12, 21, 17, 9, 6, 16, 5, 15, 14 }; int h = n / 2; for (int i = 0; i < sup; i++) { for (int j = ~isnp[i]; j != 0; j &= j - 1) { int pp = i << 5 | magic[(j & -j) * 0x076be629 >>> 27]; int p = 2 * pp + 3; if (p > n) break; ret[pos++] = p; if ((long) p * p > n) continue; for (int q = (p * p - 3) / 2; q <= h; q += p) isnp[q >> 5] |= 1 << q; } } return Arrays.copyOf(ret, pos); } private static boolean oj = System.getProperty("ONLINE_JUDGE") != null; private static void tr(Object... o) { if (!oj) System.out.println(Arrays.deepToString(o)); } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
ff13b05330ee52073a36e190bcac4746
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.io.*; import java.util.*; public class A { public static void main(String[] args) { FastScanner sc = new FastScanner(); int n = sc.nextInt(); int m = sc.nextInt(); String s = sc.next(), t = sc.next(); Map<Character,List<Integer>> map = new HashMap<>(); for(int i = 0; i < s.length(); i++) { map.computeIfAbsent(s.charAt(i), x -> new ArrayList<>()); map.get(s.charAt(i)).add(i); } // for min int[] min = new int[m]; min[0] = map.get(t.charAt(0)).get(0); for(int i = 1; i < m; i++) { List<Integer> list = map.get(t.charAt(i)); int start = 0; int end = list.size()-1; int ans = list.size()-1; while(start <= end) { int mid = start + (end-start)/2; if(list.get(mid) > min[i-1]) { ans = mid; end = mid-1; } else { start = mid+1; } } min[i] = list.get(ans); } // for max int[] max = new int[m]; List<Integer> ll = map.get(t.charAt(m-1)); max[m-1] = ll.get(ll.size()-1); for(int i = m-2; i >= 0; i--) { List<Integer> list = map.get(t.charAt(i)); int start = 0; int end = list.size()-1; int ans = list.size()-1; while(start <= end) { int mid = start + (end-start)/2; if(list.get(mid) < max[i+1]) { ans = mid; start = mid+1; } else { end = mid-1; } } max[i] = list.get(ans); } int ans = Integer.MIN_VALUE; for(int i = 1; i < m; i++) { ans = Math.max(ans, max[i]-min[i-1]); } System.out.println(ans); } static class Pair { int x; int y; public Pair(int x, int y) { this.x = x; this.y = y; } } static void ruffleSort(int[] a) { int n = a.length; Random r = new Random(); for (int i = 0; i < a.length; i++) { int oi = r.nextInt(n), temp = a[i]; a[i] = a[oi]; a[oi] = temp; } Arrays.sort(a); } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static boolean[] sieve(int n) { boolean isPrime[] = new boolean[n + 1]; for (int i = 2; i <= n; i++) { if (isPrime[i]) continue; for (int j = 2 * i; j <= n; j += i) { isPrime[j] = true; } } return isPrime; } static int mod = 1000000007; static long pow(int a, long b) { if (b == 0) { return 1; } if (b == 1) { return a; } if (b % 2 == 0) { long ans = pow(a, b / 2); return ans * ans; } else { long ans = pow(a, (b - 1) / 2); return a * ans * ans; } } 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()); } } // For Input.txt and Output.txt // FileInputStream in = new FileInputStream("input.txt"); // FileOutputStream out = new FileOutputStream("output.txt"); // PrintWriter pw = new PrintWriter(out); // Scanner sc = new Scanner(in); }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
aedf038653048aa8fb089a4d05bcc97f
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
//@author->.....future_me......// //..............Learning.........// /*Compete against yourself*/ import java.util.*; import java.io.*; import java.lang.*; import java.math.BigInteger; public class C { // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Code Starts <<<<<<<<<<<<<<<<<<<<<<<<<<<<< // static FastReader sc = new FastReader(); static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) throws Exception { // try { // int t = sc.nextInt(); // while (t-- > 0) C.go(); out.flush(); // } catch (Exception e) { // return; // } } static void go() { int n=sc.nextInt(); int m=sc.nextInt(); char s[]=sc.next().toCharArray(); char t[]=sc.next().toCharArray(); int id=n-1; idd aa[]=new idd[m+1]; idd bb[]=new idd[m+1]; for(int i=m-1;i>=0;i--) { for(int j=id;j>=0;j--) { if(s[j]==t[i]) { aa[i]=new idd(t[i],j); id=j-1; break; } } } id=0; for(int i=0;i<m;i++) { for(int j=id;j<n;j++) { if(s[j]==t[i]) { bb[i]=new idd(t[i],j); id=j+1; break; } } } // for(idd i:aa) { // out.print(i.a+"-"+i.id+" "); // } // out.println(); // for(int i=0;i<m;i++) { // out.print(bb[i].a+"-"+bb[i].id+" "); // } int max=Integer.MIN_VALUE; for(int i=0;i<m-1;i++) { char a=t[i]; char b=t[i+1]; int id1=bb[i].id; int id2=aa[i+1].id; max=Math.max(id2-id1, max); } out.println(max); } // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Code Ends <<<<<<<<<<<<<<<<<<<<<<<<<<<<< // static int mod = (int) 1e9 + 7; // Returns nCr % p using Fermat's // little theorem. static long fac[]; static long ncr(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 return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p; } private static long modInverse(long l, int p) { return pow(l,p-2); } static void sort(long[] a) { ArrayList<Long> aa = new ArrayList<>(); for (long i : a) { aa.add(i); } Collections.sort(aa); for (int i = 0; i < a.length; i++) a[i] = aa.get(i); } static long pow(long x, long y) { long res = 1l; while (y != 0) { if (y % 2 == 1) { res = x * res % mod; } y /= 2; x = (x * x) % mod; } return res; } //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Fast IO <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } } class idd{ char a;int id; idd(char a,int id){ this.a=a; this.id=id; } } //use this for double quotes inside string // " \"asdf\""
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
1f18028ad9cb5e37bf7aaf3e8eb3f095
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class C2 { BufferedReader input; BufferedWriter output; StringTokenizer st; private static float binarySearch(ArrayList<Integer> arr, int start, int end, int x) { if (end >= start) { int mid = start + (end - start) / 2; if (arr.get(mid) == x) return mid; if (arr.get(mid) > x) return binarySearch(arr, start, mid - 1, x); return binarySearch(arr, mid + 1, end, x); } return end+0.5f; } // My Solution void solve() throws IOException { int n = getInt(); int m = getInt(); String s = input.readLine(); String t = input.readLine(); HashMap<Character, ArrayList<Integer>> map = new HashMap<>(); for (int i = 0; i < n; i++) { char c = s.charAt(i); ArrayList<Integer> occurrences; if(map.containsKey(c)){ occurrences = map.get(c); }else { occurrences = new ArrayList<>(); map.put(c, occurrences); } occurrences.add(i+1); } int[] maxValues = new int[m]; int[] minValues = new int[m]; for (int i = m-1; i >= 0; i--) { ArrayList<Integer> occurrences = map.get(t.charAt(i)); int index = occurrences.size()-1; int max = occurrences.get(index); if (i!=m-1) { index = (int) Math.floor(binarySearch(occurrences, 0, occurrences.size()-1, maxValues[i+1]-1)); max = occurrences.get(index); } maxValues[i] = max; } for (int i = 0; i < m; i++) { ArrayList<Integer> occurrences = map.get(t.charAt(i)); int index = 0; int min = occurrences.get(index); if (i!=0) { index = (int) Math.ceil(binarySearch(occurrences, 0, occurrences.size()-1, minValues[i-1]+1)); min = occurrences.get(index); } minValues[i] = min; } int ans = -1; for (int i = 0; i < m-1; i++) { int a = maxValues[i+1]-minValues[i]; ans = Math.max(ans, a); } print(ans+"\n"); } // Some basic functions int min(int...i){ int min = Integer.MAX_VALUE; for (int value : i) min = Math.min(min, value); return min; } int max(int...i){ int max = Integer.MIN_VALUE; for (int value : i) max = Math.max(max, value); return max; } // Printing stuff void print(int... i) throws IOException { for (int value : i) output.write(value + " "); } void print(long... l) throws IOException { for (long value : l) output.write(value + " "); } void print(String... s) throws IOException { for (String value : s) output.write(value); } void nextLine() throws IOException { output.write("\n"); } // Taking Inputs int[][] getIntMat(int n, int m) throws IOException { int[][] mat = new int[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) mat[i][j] = getInt(); return mat; } char[][] getCharMat(int n, int m) throws IOException { char[][] mat = new char[n][m]; for (int i = 0; i < n; i++) { String s = input.readLine(); for (int j = 0; j < m; j++) mat[i][j] = s.charAt(j); } return mat; } int getInt() throws IOException { if(st ==null || !st.hasMoreTokens()) st = new StringTokenizer(input.readLine()); return Integer.parseInt(st.nextToken()); } int[] getInts(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = getInt(); return a; } long getLong() throws IOException { if(st==null || !st.hasMoreTokens()) st = new StringTokenizer(input.readLine()); return Long.parseLong(st.nextToken()); } long[] getLongs(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = getLong(); return a; } // Checks whether the code is running on OnlineJudge or LocalSystem boolean isOnlineJudge() { if (System.getProperty("ONLINE_JUDGE") != null) return true; try { return System.getProperty("LOCAL")==null; } catch (Exception e) { return true; } } // Handling CodeExecution public static void main(String[] args) throws Exception { new C2().run(); } void run() throws IOException { // Defining Input Streams if (isOnlineJudge()) { input = new BufferedReader(new InputStreamReader(System.in)); output = new BufferedWriter(new OutputStreamWriter(System.out)); } else { input = new BufferedReader(new FileReader("input.txt")); output = new BufferedWriter(new FileWriter("output.txt")); } // Running Logic solve(); output.flush(); // Run example test cases if (!isOnlineJudge()) { BufferedReader output = new BufferedReader(new FileReader("output.txt")); BufferedReader answer = new BufferedReader(new FileReader("answer.txt")); StringBuilder outFile = new StringBuilder(); StringBuilder ansFile = new StringBuilder(); String temp; while ((temp = output.readLine()) != null) outFile.append(temp.trim()); while ((temp = answer.readLine()) != null) ansFile.append(temp.trim()); if (outFile.toString().equals(ansFile.toString())) System.out.println("Test Cases Passed!!!"); else System.out.println("Failed..."); } } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
9190b3b2dde97412291b174aae2a8e5a
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.io.*; import java.util.*; public class P1492C { static InputReader in = new InputReader(System.in); static PrintWriter pw = new PrintWriter(System.out); static long mod = (long) (Math.pow(10, 9)) + 7; static HashMap<Integer, List<Integer>> adjList = new HashMap<>(); static boolean[] visited; public static void main(String[] args) { int test = 1; while(test-->0) { solve(); } pw.close(); } static void solve() { int m = in.nextInt(), n = in.nextInt(); String s = in.nextLine(), t = in.nextLine(); int[][] dp = generate(s, t, m ,n); int[][] reverse = generateReverse(s, t, m, n); int[][] finalDP = new int[n][2]; for (int i = 0; i < n; i++) { finalDP[i][0] = Math.min(dp[i][0], reverse[i][0]); finalDP[i][1] = Math.max(dp[i][1], reverse[i][1]); } int ans = 0; for (int i = 0; i < n - 1; i++) { ans = Math.max(finalDP[i + 1][1] - finalDP[i][0], ans); } pw.println(ans); } static int[][] generateReverse(String s, String t, int m, int n) { int[][] dp = new int[n][2]; int index = m - 1; for (int i = n - 1; i >= 0; i--) { while (index > 0 && s.charAt(index) != t.charAt(i)) { index--; } dp[i][1] = index; if (i - 1 >= 0 && t.charAt(i - 1) == t.charAt(i)) { dp[i][0] = index; index--; continue; } while (index >= 0 && s.charAt(index) == t.charAt(i)) { index--; } dp[i][0] = index + 1; } return dp; } static int[][] generate(String s, String t, int m, int n) { int[][] dp = new int[n][2]; int index = 0; for (int i = 0; i < n; i++) { while (index < m && s.charAt(index) != t.charAt(i)) { index++; } dp[i][0] = index; if (i + 1 < n && t.charAt(i + 1) == t.charAt(i)) { dp[i][1] = index; index++; continue; } while (index < m && s.charAt(index) == t.charAt(i)) { index++; } dp[i][1] = index - 1; } return dp; } static void ruffleSort(int[] a) { int n=a.length; Random r=new Random(); for (int i=0; i<a.length; i++) { int oi=r.nextInt(n), temp=a[i]; a[i]=a[oi]; a[oi]=temp; } Arrays.sort(a); } public static List<Long> getFactors(long num) { List<Long> res = new ArrayList(); res.add(num); for (long d = 2; d <= (long)Math.sqrt(num); d++) { if (num % d == 0) { res.add(d); if ((num / d) != d) { res.add(num / d); } } } return res; } static long fast_pow(long a, long b) { if(b == 0) return 1L; long val = fast_pow(a, b / 2); if(b % 2 == 0) return val * val % mod; else return val * val % mod * a % mod; } static void sort(long[] a) //check for long { 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 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 addEdge(int u, int v) { adjList.putIfAbsent(u, new ArrayList<>()); adjList.get(u).add(v); } 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 boolean[] sieve(int n) { boolean[] isPrime = new boolean[n + 1]; isPrime[0] = false; isPrime[1] = false; for (int i = 2; i <= n; i++) { if (isPrime[i] && i * i <= n) { for (int j = i * i; j <= n; j += i) { isPrime[i] = false; } } } return isPrime; } static boolean isPrime(int n) { for (int d = 2; d * d <= n; d++) { if (n % d == 0) { return false; } } return true; } //ternary search on a graph that is concave down static int high(int[] a) { int lo = 0, hi = a.length - 1; int error = 3; while (hi - lo > error) { int right = hi - (hi - lo) / 3; int left = lo + (hi - lo) / 3; if (a[left] < a[right]) { lo = left; } else { hi = right; } } //check for the lowest from a[l, h] int ans = lo; for (int i = lo; i <= hi; i++) { if (a[ans] < a[i]) { ans = i; } } return ans; } //ternary search on a concave up graph static int low(int[] a) { int lo = 0, hi = a.length - 1; int error = 3; while (hi - lo > error) { int right = hi - (hi - lo) / 3; int left = lo + (hi - lo) / 3; if (a[left] < a[right]) { hi = right; } else { lo = left; } } //check for the lowerst from a[l, h] int ans = lo; for (int i = lo; i <= hi; i++) { if (a[ans] > a[i]) { ans = i; } } return ans; } static boolean contains(int[] a, int key) { int ans = 0; int low = 0, high = a.length - 1; while (low <= high) { int mid = low + (high - low) / 2; int midVal = a[mid]; if (midVal < key) { low = mid + 1; } else if (midVal > key) { high = mid - 1; } else if (midVal == key) { ans = 1; break; } } return ans == 1; } static int first(int[] a, int key) { int ans = -1; int low = 0, high = a.length - 1; while (low <= high) { int mid = low + (high - low + 1) / 2; int midVal = a[mid]; if (midVal < key) { low = mid + 1; } else if (midVal > key) { high = mid - 1; } else if (midVal == key) { ans = mid; high = mid - 1; } } return ans; } static int last(int[] a, int key) { int ans = -1; int low = 0, high = a.length - 1; while (low <= high) { int mid = low + (high - low + 1) / 2; int midVal = a[mid]; if (midVal < key) { low = mid + 1; } else if (midVal > key) { high = mid - 1; } else if (midVal == key) { ans = mid; low = mid + 1; } } return ans; } static int greaterOrEqual(int[] a, int key) { int ans = -1; int low = 0, high = a.length - 1; while (low <= high) { int mid = low + (high - low + 1) / 2; int midVal = a[mid]; if (midVal < key) { low = mid + 1; } else if (midVal > key) { ans = mid; high = mid - 1; } else if (midVal == key) { return mid; } } return ans; } static int lesserOrEqual(int[] a, int key) { int ans = -1; int low = 0, high = a.length - 1; while (low <= high) { int mid = low + (high - low + 1) / 2; int midVal = a[mid]; if (midVal < key) { ans = mid; low = mid + 1; } else if (midVal > key) { high = mid - 1; } else if (midVal == key) { return mid; } } return ans; } static class SegTree { long st[]; public SegTree(long[] arr, int n) { int x = (int) (Math.ceil(Math.log(n) / Math.log(2))); int max_size = 2 * (int) Math.pow(2, x) - 1; st = new long[max_size]; constructSTUtil(arr, 0, n - 1, 0); } int getMid(int s, int e) { return s + (e - s) / 2; } long getSumUtil(int ss, int se, int qs, int qe, int si) { if (qs <= ss && qe >= se) return st[si]; if (se < qs || ss > qe) return 0; int mid = getMid(ss, se); return getSumUtil(ss, mid, qs, qe, 2 * si + 1) + getSumUtil(mid + 1, se, qs, qe, 2 * si + 2); } void updateValueUtil(int ss, int se, int i, long diff, int si) { if (i < ss || i > se) return; st[si] = st[si] + diff; if (se != ss) { int mid = getMid(ss, se); updateValueUtil(ss, mid, i, diff, 2 * si + 1); updateValueUtil(mid + 1, se, i, diff, 2 * si + 2); } } void updateValue(long arr[], int n, int i, int new_val) { if (i < 0 || i > n - 1) { System.out.println("Invalid Input"); return; } long diff = new_val - arr[i]; arr[i] = new_val; updateValueUtil(0, n - 1, i, diff, 0); } long getSum(int n, int qs, int qe) { if (qs < 0 || qe > n - 1 || qs > qe) { System.out.println("Invalid Input"); return -1; } return getSumUtil(0, n - 1, qs, qe, 0); } long constructSTUtil(long arr[], int ss, int se, int si) { if (ss == se) { st[si] = arr[ss]; return arr[ss]; } int mid = getMid(ss, se); st[si] = constructSTUtil(arr, ss, mid, si * 2 + 1) + constructSTUtil(arr, mid + 1, se, si * 2 + 2); return st[si]; } } static class UnionFind { // Number of connected components private int count; // Store a tree private int[] parent; // Record the "weight" of the tree private int[] size; public UnionFind(int n) { this.count = n; parent = new int[n]; size = new int[n]; for (int i = 0; i < n; i++) { parent[i] = i; size[i] = 1; } } public void union(int p, int q) { int rootP = find(p); int rootQ = find(q); if (rootP == rootQ) return; // The small tree is more balanced under the big tree if (size[rootP] > size[rootQ]) { parent[rootQ] = rootP; size[rootP] += size[rootQ]; } else { parent[rootP] = rootQ; size[rootQ] += size[rootP]; } count--; } public boolean connected(int p, int q) { int rootP = find(p); int rootQ = find(q); return rootP == rootQ; } private int find(int x) { while (parent[x] != x) { // Path compression parent[x] = parent[parent[x]]; x = parent[x]; } return x; } public int count() { return count; } } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream st) { this.stream = st; } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int [] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public long[] nextLongArray(int n) { long [] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } public static int[] shuffle(int[] a, Random gen) { for(int i = 0, n = a.length;i < n;i++) { int ind = gen.nextInt(n-i)+i; int d = a[i]; a[i] = a[ind]; a[ind] = d; } return a; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
e8fe72c1fea378897c0193e37f38cbd5
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) { FastScanner in=new FastScanner(); PrintWriter out=new PrintWriter(System.out); // int t=in.nextInt(); // while(t-->0) solve(in,out); out.close(); } static void solve(FastScanner in,PrintWriter out){ int n=in.nextInt(); int m=in.nextInt(); char s[]=in.next().toCharArray(); char tt[]=in.next().toCharArray(); TreeSet<Integer> t[]=new TreeSet[26]; Arrays.setAll(t,e->new TreeSet<Integer>()); for (int i = 0; i < n; i++) { t[s[i]-'a'].add(i); } int first[]=new int[m]; int last[]=new int[m]; int prev =-1; for (int i = 0; i < m; i++) { int x=t[tt[i]-'a'].ceiling(prev); prev=x+1; first[i]=x; } prev=n; for (int i = m-1; i >= 0; i--) { int x=t[tt[i]-'a'].floor(prev); prev=x-1; last[i]=x; } int max=0; for(int i=0;i<m-1;i++){ max=Math.max(max,last[i+1]-first[i]); } out.println(max); } static class pair<U extends Comparable<U>, V extends Comparable<V>> implements Comparable<pair<U, V>> { public U x; public V y; public pair(U x, V y) { this.x = x; this.y = y; } public int compareTo(pair<U, V> other) { int i = x.compareTo(other.x); if (i != 0) return i; return y.compareTo(other.y); } public String toString() { return x.toString() + " " + y.toString(); } public boolean equals(Object obj) { if (this.getClass() != obj.getClass()) return false; pair<U, V> other = (pair<U, V>) obj; return x.equals(other.x) && y.equals(other.y); } public int hashCode() { return 31 * x.hashCode() + y.hashCode(); } } 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 nextLong() { return Long.parseLong(next()); } } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
aca0779a301dc2f3b994a414ce5816d8
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
/*----------- ---------------* Author : Ryan Ranaut __Hope is a big word, never lose it__ ------------- --------------*/ import java.io.*; import java.util.*; public class Codeforces2 { static PrintWriter out = new PrintWriter(System.out); static final int mod = 1_000_000_007; 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 public static void main(String[] args) { FastReader s = new FastReader(); int n = s.nextInt(); int m = s.nextInt(); char[] s1 = s.nextLine().toCharArray(); char[] s2 = s.nextLine().toCharArray(); out.println(find(n, m, s1, s2)); out.close(); } public static int find(int n, int m, char[] s1, char[] s2) { int[] pre = new int[m]; int[] suff = new int[m]; int ind = 0; for(int i=0;i<n && ind<m; i++) { if(s1[i] == s2[ind]) pre[ind++] = i; } ind = m-1; for(int i=n-1;i>=0 && ind>=0; i--) { if(s1[i] == s2[ind]) suff[ind--] = i; } int res = 1; for(int i=1;i<m;i++) res = Math.max(res, suff[i]-pre[i-1]); return res; } /*-----------------------------------End of the road--------------------------------------*/ static class DSU { int[] parent; int[] ranks; int[] groupSize; int size; public DSU(int n) { size = n; parent = new int[n];//0 based ranks = new int[n]; groupSize = new int[n];//Size of each component for (int i = 0; i < n; i++) { parent[i] = i; ranks[i] = 1; groupSize[i] = 1; } } public int find(int x)//Path Compression { if (parent[x] == x) return x; else return parent[x] = find(parent[x]); } public void union(int x, int y)//Union by rank { int x_rep = find(x); int y_rep = find(y); if (x_rep == y_rep) return; if (ranks[x_rep] < ranks[y_rep]) { parent[x_rep] = y_rep; groupSize[y_rep] += groupSize[x_rep]; } else if (ranks[x_rep] > ranks[y_rep]) { parent[y_rep] = x_rep; groupSize[x_rep] += groupSize[y_rep]; } else { parent[y_rep] = x_rep; ranks[x_rep]++; groupSize[x_rep] += groupSize[y_rep]; } size--;//Total connected components } } public static int gcd(int x,int y) { return y==0?x:gcd(y,x%y); } public static long gcd(long x,long y) { return y==0L?x:gcd(y,x%y); } public static int lcm(int a, int b) { return (a * b) / gcd(a, b); } public static long lcm(long a, long b) { return (a * b) / gcd(a, b); } public static long pow(long a,long b) { if(b==0L) return 1L; long tmp=1; while(b>1L) { if((b&1L)==1) tmp*=a; a*=a; b>>=1; } return (tmp*a); } public static long modPow(long a,long b,long mod) { if(b==0L) return 1L; long tmp=1; while(b>1L) { if((b&1L)==1L) tmp*=a; a*=a; a%=mod; tmp%=mod; b>>=1; } return (tmp*a)%mod; } static long mul(long a, long b) { return a*b%mod; } static long fact(int n) { long ans=1; for (int i=2; i<=n; i++) ans=mul(ans, i); return ans; } static long fastPow(long base, long exp) { if (exp==0) return 1; long half=fastPow(base, exp/2); if (exp%2==0) return mul(half, half); return mul(half, mul(half, base)); } static void debug(int ...a) { for(int x: a) out.print(x+" "); out.println(); } static void debug(long ...a) { for(long x: a) out.print(x+" "); out.println(); } static void debugMatrix(int[][] a) { for(int[] x:a) out.println(Arrays.toString(x)); } static void debugMatrix(long[][] a) { for(long[] x:a) out.println(Arrays.toString(x)); } static void reverseArray(int[] a) { int n = a.length; int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = a[n - i - 1]; for (int i = 0; i < n; i++) a[i] = arr[i]; } static void reverseArray(long[] a) { int n = a.length; long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = a[n - i - 1]; for (int i = 0; i < n; i++) a[i] = arr[i]; } static void sort(int[] a) { ArrayList<Integer> ls = new ArrayList<>(); for(int x: a) ls.add(x); Collections.sort(ls); for(int i=0;i<a.length;i++) a[i] = ls.get(i); } static void sort(long[] a) { ArrayList<Long> ls = new ArrayList<>(); for(long x: a) ls.add(x); Collections.sort(ls); for(int i=0;i<a.length;i++) a[i] = ls.get(i); } static class Pair{ int x, y; Pair(int x, int y) { this.x = x; this.y = y; } } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
38ffd66d0ea59e5b87d21ec7f5723fc2
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 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 Codeforces { public static void main(String[] args) throws java.lang.Exception { /* your code goes here */ BufferedReader buf = new BufferedReader(new InputStreamReader(System.in)); //int t = Integer.parseInt(buf.readLine()); StringBuilder sb = new StringBuilder(); //for (int i = 0; i < t; i++) { String st1[]=(buf.readLine()).split(" "); int n=Integer.parseInt(st1[0]); int m=Integer.parseInt(st1[1]); char s[]=(buf.readLine()).toCharArray(); char t[]=(buf.readLine()).toCharArray(); int left[]=new int[m]; int right[]=new int[m]; int z=0; for(int j=0;j<n;j++) { if(z==m) break; if(t[z]==s[j]) { left[z]=j; z++; } } z=m-1; for(int j=n-1;j>=0;j--) { if(z==-1) break; if(t[z]==s[j]) { right[z]=j; z--; } } int max=0; for(int j=0;j<m-1;j++) max=Math.max(max,right[j+1]-left[j]); System.out.println(max); //} //System.out.println(sb); } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
5deec318846a0bc037b453fd089cde48
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
/* 5 3 abbbc abc */ import java.util.*; import java.io.*; public class Main{ public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer details = new StringTokenizer(br.readLine()); int n = Integer.parseInt(details.nextToken()); int m = Integer.parseInt(details.nextToken()); HashMap<Character, TreeSet<Integer>> positions = new HashMap<Character, TreeSet<Integer>>(); char[] a = br.readLine().toCharArray(); char[] b = br.readLine().toCharArray(); int[] smallestPositions = new int[m]; //smallest value of pi int[] largestPositions = new int[m]; //largest value of pi for(int c = 0; c < n; c++){ if(positions.containsKey(a[c])){ positions.get(a[c]).add(c); } else{ TreeSet<Integer> ts = new TreeSet<Integer>(); ts.add(c); positions.put(a[c], ts); } } //find earliest (closest you can pack all of the indexes at the start) int prev = -1; //last pi for(int i = 0; i < m; i++){ int cur = positions.get(b[i]).higher(prev); smallestPositions[i] = cur; prev = cur; } //find latest (closest you can pack all of the indices at the end) prev = 1000000000; for(int i = m - 1; i >= 0; i--){ int cur = positions.get(b[i]).lower(prev); largestPositions[i] = cur; prev = cur; } //System.out.println(Arrays.toString(smallestPositions) + " " + Arrays.toString(largestPositions)); int ret = 0; for(int c = 1; c < m; c++){ ret = Math.max(ret, largestPositions[c] - smallestPositions[c - 1]); } System.out.println(ret); br.close(); } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
262d4f7c51ec624855c8b1327e5aeeeb
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.io.*; import java.util.*; public class Main { static PrintWriter out; static Kioken sc; public static void main(String[] args) throws FileNotFoundException { boolean t = true; boolean f = false; if (f) { out = new PrintWriter("output.txt"); sc = new Kioken("input.txt"); } else { out = new PrintWriter((System.out)); sc = new Kioken(); } int tt = 1; solve(); out.flush(); out.close(); } public static void solve() { int n = sc.nextInt(); int m = sc.nextInt(); char[] s = sc.nextLine().toCharArray(); char[] t = sc.nextLine().toCharArray(); int[] fromLeft = new int[m]; int[] fromRight = new int[m]; int i = 0, j = 0; while(i < n && j < m){ if(s[i] == t[j]){ fromLeft[j] = i; j++; } i++; } i = n - 1; j = m - 1; while(i >= 0 && j >= 0){ if(s[i] == t[j]){ fromRight[j] = i; j--; } i--; } int max = Integer.MIN_VALUE; for(i = 1; i < m; i++){ max = Math.max(max, (fromRight[i] - fromLeft[i-1])); } out.println(max); } public static long gcd(long a,long b) { while(b!=0) {long rem=a%b; a=b; b=rem; } return a; } public static long leftShift(long a) { return (long) Math.pow(2, a); } public static void reverse(int[] arr) { Arrays.sort(arr); int n = arr.length; for (int i = 0; i < arr.length/2; i++) { int temp = arr[i]; arr[i] = arr[n - 1 - i]; arr[n - 1 - i] = temp; } return; } public static int lower_bound(ArrayList<Integer> ar, int k) { int s = 0, e = ar.size(); while (s != e) { int mid = s + e >> 1; if (ar.get(mid) <= k) { s = mid + 1; } else { e = mid; } } return Math.abs(s) - 1; } public static int upper_bound(ArrayList<Integer> ar, int k) { int s = 0; int e = ar.size(); while (s != e) { int mid = s + e >> 1; if (ar.get(mid) < k) { s = mid + 1; } else { e = mid; } } if (s == ar.size()) { return -1; } return s; } static class Kioken { // FileInputStream br = new FileInputStream("input.txt"); BufferedReader br; StringTokenizer st; Kioken(String filename) { try { FileReader fr = new FileReader(filename); br = new BufferedReader(fr); st = new StringTokenizer(""); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } Kioken() { try { br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(""); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } public String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { try { return br.readLine(); } catch (Exception e) { e.printStackTrace(); } return null; } public boolean hasNext() { String next = null; try { next = br.readLine(); } catch (Exception e) { } if (next == null || next.length() == 0) { return false; } st = new StringTokenizer(next); return true; } } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
78d904abaae53819b233be4d66ae9e65
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import com.sun.source.tree.LiteralTree; import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.lang.Math.ceil; import static java.util.Arrays.sort; public class C { static int mod = 1000000007; public static void main(String[] args) throws Exception { int test = 1; while (test-- > 0) { int n1 = rni(); int n2 = ni(); char s[] = rcha(); char t[] = rcha(); int[] min = new int[n2]; int[] max = new int[n2]; for (int i = 0, j = 0; i < n1 && j < n2; i++) { if (s[i] == t[j]) { min[j] = (i + 1); j++; } } for (int i = n1 - 1, j = n2 - 1; i >= 0 && j >= 0; i--) { if (s[i] == t[j]) { max[j] = (i + 1); j--; } } long ans = 0; for (int i = 0; i < n2 - 1; i++) { ans = Math.max(ans, max[i + 1] - min[i]); } prln(ans); } close(); } static class Nodes { int a; int b; Nodes(int a, int b) { this.a = a; this.b = b; } } static class DisjointSetUnion { int p[]; int count[]; public DisjointSetUnion(int n) { p = new int[n]; count = new int[n]; for (int i = 0; i < n; i++) { count[i] = 1; } clear(n); } public void clear(int n) { for (int i = 0; i < n; i++) { p[i] = i; } } public int get(int x) { return x != p[x] ? p[x] = get(p[x]) : x; } public int getCount(int x) { return count[x]; } public boolean union(int a, int b) { a = get(a); b = get(b); p[a] = b; if (a != b) { count[b] += count[a]; count[a] = 0; } return a != b; } } static BufferedReader __i = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter __o = new PrintWriter(new OutputStreamWriter(System.out)); static StringTokenizer input; static boolean[] isPrime; static Random __r = new Random(); // references // IBIG = 1e9 + 7 // IMAX ~= 2e9 // LMAX ~= 9e18 // constants static final int IBIG = 1000000007; static final int IMAX = 2147483647; static final long LMAX = 9223372036854775807L; // 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 long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % 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); } static void setTrue(int n) { for (int i = 0; i < n; i++) { isPrime[i] = true; } } static void prime(int n) { for (int i = 2; i * i < n; i++) { if (isPrime[i]) { for (int j = i * i; j < n; j += i) isPrime[j] = false; } } } public static long lcm(long number1, long number2) { if (number1 == 0 || number2 == 0) { return 0; } long absNumber1 = Math.abs(number1); long absNumber2 = Math.abs(number2); long absHigherNumber = Math.max(absNumber1, absNumber2); long absLowerNumber = Math.min(absNumber1, absNumber2); long lcm = absHigherNumber; while (lcm % absLowerNumber != 0) { lcm += absHigherNumber; } return lcm; } // 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 void resetBoolean(boolean[] vis, int n) { for (int i = 0; i < n; i++) { vis[i] = false; } } static void setMinusOne(int[][] matrix) { int row = matrix.length; int col = matrix[0].length; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { matrix[i][j] = -1; } } } // input static void r() throws IOException { input = new StringTokenizer(rline()); } static int ri() throws IOException { return Integer.parseInt(rline().split(" ")[0]); } static long rl() throws IOException { return Long.parseLong(rline()); } static double rd() throws IOException { return Double.parseDouble(rline()); } static int[] ria(int n) throws IOException { int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni(); return a; } static void ria(int[] a) throws IOException { int n = a.length; r(); for (int i = 0; i < n; ++i) a[i] = ni(); } static int[] riam1(int n) throws IOException { int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni() - 1; return a; } static void riam1(int[] a) throws IOException { int n = a.length; r(); for (int i = 0; i < n; ++i) a[i] = ni() - 1; } static long[] rla(int n) throws IOException { long[] a = new long[n]; r(); for (int i = 0; i < n; ++i) a[i] = nl(); return a; } static void rla(long[] a) throws IOException { int n = a.length; r(); for (int i = 0; i < n; ++i) a[i] = nl(); } static double[] rda(int n) throws IOException { double[] a = new double[n]; r(); for (int i = 0; i < n; ++i) a[i] = nd(); return a; } static void rda(double[] a) throws IOException { int n = a.length; r(); for (int i = 0; i < n; ++i) a[i] = nd(); } static char[] rcha() throws IOException { return rline().toCharArray(); } static void rcha(char[] a) throws IOException { int n = a.length, i = 0; for (char c : rline().toCharArray()) a[i++] = c; } static String rline() throws IOException { return __i.readLine(); } static String n() { return input.nextToken(); } static int rni() throws IOException { r(); return ni(); } static int ni() { return Integer.parseInt(n()); } static long rnl() throws IOException { r(); return nl(); } static long nl() { return Long.parseLong(n()); } static double rnd() throws IOException { r(); return nd(); } static double nd() { return Double.parseDouble(n()); } // output static void pr(int i) { __o.print(i); } static void prln(int i) { __o.println(i); } static void pr(long l) { __o.print(l); } static void prln(long l) { __o.println(l); } static void pr(double d) { __o.print(d); } static void prln(double d) { __o.println(d); } static void pr(char c) { __o.print(c); } static void prln(char c) { __o.println(c); } static void pr(char[] s) { __o.print(new String(s)); } static void prln(char[] s) { __o.println(new String(s)); } static void pr(String s) { __o.print(s); } static void prln(String s) { __o.println(s); } static void pr(Object o) { __o.print(o); } static void prln(Object o) { __o.println(o); } static void prln() { __o.println(); } static void pryes() { prln("yes"); } static void pry() { prln("Yes"); } static void prY() { prln("YES"); } static void prno() { prln("no"); } static void prn() { prln("No"); } static void prN() { prln("NO"); } static boolean pryesno(boolean b) { prln(b ? "yes" : "no"); return b; } ; static boolean pryn(boolean b) { prln(b ? "Yes" : "No"); return b; } static boolean prYN(boolean b) { prln(b ? "YES" : "NO"); return b; } static void prln(int... a) { for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i) ; if (a.length > 0) prln(a[a.length - 1]); else prln(); } static void prln(long... a) { for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i) ; if (a.length > 0) prln(a[a.length - 1]); else prln(); } static void prln(double... a) { for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i) ; if (a.length > 0) prln(a[a.length - 1]); else prln(); } static <T> void prln(Collection<T> c) { int n = c.size() - 1; Iterator<T> iter = c.iterator(); for (int i = 0; i < n; pr(iter.next()), pr(' '), ++i) ; if (n >= 0) prln(iter.next()); else prln(); } static void h() { prln("hlfd"); flush(); } static void flush() { __o.flush(); } static void close() { __o.close(); } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
cff56ebc42283486d7659f83547066f2
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 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 Pupil { static FastReader sc = new FastReader(); public static void main (String[] args) throws java.lang.Exception { // your code goes here int t=1; while(t>0){ int n=sc.nextInt(); int m=sc.nextInt(); String s=sc.next(); String s1=sc.next(); int max=0; ArrayList<Integer>arr=new ArrayList<Integer>(); ArrayList<Integer>brr=new ArrayList<Integer>(); int j=0; for(int i=0;i<s.length();i++) { if(s.charAt(i)==s1.charAt(j)) { arr.add(i+1); j++; } if(arr.size()==s1.length()) { break; } } j=s1.length()-1; for(int i=s.length()-1;i>=0;i--) { if(s.charAt(i)==s1.charAt(j)) { j--; brr.add(i+1); } if(brr.size()==s1.length()) { break; } } j=brr.size()-1; // System.out.println(arr); // System.out.println(brr); for(int i=0;i<s1.length()-1;i++) { // System.out.println(brr.get(j-1)+" "+arr.get(i)); max=Math.max(max,brr.get(j-1)-arr.get(i)); j--; } System.out.println(max); t--; } } // FAST I/O 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 boolean two(int n)//power of two { if((n&(n-1))==0) { return true; } else{ return false; } } public static boolean isPrime(long n){ for (int i = 2; i * i <= n; ++i) { if (n % i == 0) { return false; } } return true; } public static int digit(int n) { int n1=(int)Math.floor((int)Math.log10(n)) + 1; return n1; } } //CAAL THE BELOW FUNCTION IF PARING PRIORITY IS NEEDED // // PriorityQueue<pair> pq = new PriorityQueue<>(); **********declare the syntax in the main function****** // pq.add(1,2)/////// // class pair implements Comparable<pair> { // int value, index; // pair(int v, int i) { index = i; value = v; } // @Override // public int compareTo(pair o) { return o.value - value; } // } // User defined Pair class // class Pair { // int x; // int y; // // Constructor // public Pair(int x, int y) // { // this.x = x; // this.y = y; // } // } // Arrays.sort(arr, new Comparator<Pair>() { // @Override public int compare(Pair p1, Pair p2) // { // return p1.x - p2.x; // } // }); // class Pair { // int height, id; // // public Pair(int i, int s) { // this.height = s; // this.id = i; // } // } //Arrays.sort(trips, (a, b) -> Integer.compare(a[1], b[1])); // ArrayList<ArrayList<Integer>> connections = new ArrayList<ArrayList<Integer>>(); // for(int i = 0; i<n;i++) // connections.add(new ArrayList<Integer>());
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
480c0e69e81892858dee8ea0a07522dd
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.util.*; import java.io.*; public class Main { static long mod = 1000000007; static int max ; static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); public static void main(String[] args) throws IOException { FastReader sc = new FastReader(); int n = sc.nextInt(); int m =sc.nextInt(); char a[] = sc.next().toCharArray(); char b[] = sc.next().toCharArray(); ArrayList<Integer> fst = new ArrayList<>(); Stack<Integer> scnd = new Stack<>(); int j = 0 ; for( int i =0 ; i< n; i++) { if( j >= m) { break; } if( a[i] == b[j]) { fst.add(i); j++; } } j = m-1; for( int i = n-1 ; i>=0 ; i--) { if( j<0) { break; } if( a[i] == b[j]) { scnd.push(i); j--; } } ArrayList<Integer> scn = new ArrayList<>(); while( !scnd.isEmpty()) { scn.add(scnd.pop()); } int max = Integer.MIN_VALUE; for( int i =1 ;i< m;i++) { max = Math.max(max , scn.get(i) - fst.get(i-1)); } out.println(max); out.flush(); } public static int[] nextLargerElement(int[] arr, int n) { Stack<Integer> stack = new Stack<>(); int rtrn[] = new int[n]; rtrn[n-1] = -1; stack.push( n-1); for( int i = n-2 ;i >= 0 ; i--){ int temp = arr[i]; int lol = -1; while( !stack.isEmpty() && arr[stack.peek()] <= temp){ if(arr[stack.peek()] == temp ) { lol = stack.peek(); } stack.pop(); } if( stack.isEmpty()){ if( lol != -1) { rtrn[i] = lol; } else { rtrn[i] = -1; } } else{ rtrn[i] = stack.peek(); } stack.push( i); } return rtrn; } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } static HashMap<Long,Long> primefactor( long n){ HashMap<Long ,Long> hm = new HashMap<>(); long temp = 0; while( n%2 == 0) { temp++; n/=2; } if( temp!= 0) { hm.put( 2L, temp); } long c = (long)Math.sqrt(n); for( long i = 3 ; i <= c ; i+=2) { temp = 0; while( n% i == 0) { temp++; n/=i; } if( temp!= 0) { hm.put( i, temp); } } if( n!= 1) { hm.put( n , 1L); } return hm; } 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 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
096a01ebb45f90b55e93a742779d6bc0
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.File; import java.io.*; import java.util.*; public class Main { // static final File ip = new File("input.txt"); // static final File op = new File("output.txt"); // static { // try { // System.setOut(new PrintStream(op)); // System.setIn(new FileInputStream(ip)); // } catch (Exception e) { // } // } static long MOD = (long) 1e9 + 7; public static void main(String[] args) { FastReader sc = new FastReader(); // int test = sc.nextInt(); // while (test-- != 0) { int n = sc.nextInt(); int m = sc.nextInt(); String s = sc.next(); String t = sc.next(); int[] left = new int[m+1]; int[] right = new int[m+1]; int i=0,j=0; while(j < m) { while(s.charAt(i) != t.charAt(j)) i++; left[j] = i; i++; j++; } i = n-1; j = m-1; while(j>=0) { while(s.charAt(i) != t.charAt(j)) i--; right[j] = i; i--; j--; } long ans = 0; for(i=1;i<m;i++) { ans = Math.max(ans, right[i]-left[i-1]); } System.out.println(ans); // } } static long power(long x, long y, long p) { long res = 1; x = x % p; if (x == 0) return 0; while (y > 0) { if ((y & 1) != 0) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } public static int countSetBits(long number) { int count = 0; while (number > 0) { ++count; number &= number - 1; } return count; } private static <T> void swap(int[] a, int i, int j) { int tmp = a[i]; a[i] = a[j]; a[j] = tmp; } static class pair { long a, b; pair(long x, long y) { this.a = x; this.b = y; } // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof pair)) return false; // pair key = (pair) o; // return a == key.a && b == key.b; // } // @Override // public int hashCode() { // int result = a; // result = 31 * result + b; // return result; // } // public int compare(pair p1, pair p2) { // if(p1.a - p2.a > 0) return -1; // if(p1.a - p2.a < 0) return 1; // return 0; // } } static class comparator implements Comparator<pair> { public int compare(pair p1, pair p2) { if (p1.a - p2.a > 0) return 1; if (p1.a - p2.a < 0) return -1; if (p1.a == p2.a) { if (p1.b > p2.b) return -1; else if (p1.b < p2.b) return 1; } return 0; } } private static long getSum(int[] array) { long sum = 0; for (int value : array) { sum += value; } return sum; } private static boolean isPrime(Long x) { if (x < 2) return false; for (long d = 2; d * d <= x; ++d) { if (x % d == 0) return false; } return true; } static int[] reverse(int a[], int n) { int i, k, t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } return a; } private static boolean isPrimeInt(int x) { if (x < 2) return false; for (int d = 2; d * d <= x; ++d) { if (x % d == 0) return false; } return true; } public static String reverse(String input) { StringBuilder str = new StringBuilder(""); for (int i = input.length() - 1; i >= 0; i--) { str.append(input.charAt(i)); } return str.toString(); } private static int[] getPrimes(int n) { boolean[] used = new boolean[n + 1]; used[0] = used[1] = true; int size = 0; for (int i = 2; i <= n; ++i) { if (!used[i]) { ++size; for (int j = 2 * i; j <= n; j += i) { used[j] = true; } } } int[] primes = new int[size]; for (int i = 0, cur = 0; i <= n; ++i) { if (!used[i]) { primes[cur++] = i; } } return primes; } private static long lcm(long a, long b) { return a / gcd(a, b) * b; } private static long gcd(long a, long b) { return (a == 0 ? b : gcd(b % a, a)); } static void sortI(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 void shuffleList(ArrayList<Long> arr) { int n = arr.size(); Random rnd = new Random(); for (int i = 0; i < n; ++i) { long tmp = arr.get(i); int randomPos = i + rnd.nextInt(n - i); arr.set(i, arr.get(randomPos)); arr.set(randomPos, tmp); } } static void factorize(long n) { int count = 0; while (!(n % 2 > 0)) { n >>= 1; count++; } if (count > 0) { // System.out.println("2" + " " + count); } long i = 0; for (i = 3; i <= (long) Math.sqrt(n); i += 2) { count = 0; while (n % i == 0) { count++; n = n / i; } if (count > 0) { // System.out.println(i + " " + count); } } if (n > 2) { // System.out.println(i + " " + count); } } static void sortL(long[] arr) { int n = arr.length; Random rnd = new Random(); for (int i = 0; i < n; ++i) { long tmp = arr[i]; int randomPos = i + rnd.nextInt(n - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } Arrays.sort(arr); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public boolean hasNext() { return false; } 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 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
fa869614231495d12453b2e77a278480
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.io.*; import java.util.*; import java.math.BigInteger; import java.util.InputMismatchException; public class Main { static PrintWriter out; static Reader in; public static void main(String[] args) throws IOException { input_output(); Main solver = new Main(); solver.solve(); out.close(); out.flush(); } static long INF = (long)1e18; static int MAXN = (int)1e5 + 5; static int MOD = (int)1e9 + 7; static int q, t, n, m, k; static double pi = Math.PI; void solve() throws IOException { n = in.nextInt(); m = in.nextInt(); String a = in.next(), b = in.next(); int[] maxPre = new int[n]; int[] maxSuf = new int[n]; if (a.charAt(0) == b.charAt(0)) maxPre[0] = 1; for (int i = 1; i < n; i++) { if (maxPre[i-1] == m) maxPre[i] = m; else { if (a.charAt(i) == b.charAt(maxPre[i-1])) maxPre[i] = 1; maxPre[i] += maxPre[i-1]; } } if (a.charAt(n-1) == b.charAt(m-1)) maxSuf[n-1] = m-2; else maxSuf[n-1] = m-1; for (int i = n-2; i >= 0; i--) { if (maxSuf[i+1] == -1) maxSuf[i] = -1; else { if (a.charAt(i) == b.charAt(maxSuf[i+1])) maxSuf[i] = -1; maxSuf[i] += maxSuf[i+1]; } } int l = 0, r = 1, ans = 1; while (l < n && r < n) { if (maxPre[l] == 0) l++; if (maxSuf[r] == m-1) break; if (maxPre[l] >= maxSuf[r]+1) { ans = Math.max(ans, r-l); r++; } else { l++; } } out.println(ans); } static class Reader { private InputStream mIs; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public Reader() { this(System.in); } public Reader(InputStream is) { mIs = is; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = mIs.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String next() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } static void input_output() throws IOException { File f = new File("in.txt"); if (f.exists() && !f.isDirectory()) { in = new Reader(new FileInputStream("in.txt")); } else in = new Reader(); f = new File("out.txt"); if (f.exists() && !f.isDirectory()) { out = new PrintWriter(new File("out.txt")); } else out = new PrintWriter(System.out); } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
4dda84b0f764149a50570c95900c6018
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
// package codeforce.cf704; import java.io.PrintWriter; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.Scanner; public class C { public static void main(String[] args) { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); // int t = sc.nextInt(); int t = 1; for (int i = 0; i < t; i++) { solve(sc, pw); } pw.close(); } static void solve(Scanner in, PrintWriter out){ int n = in.nextInt(), m = in.nextInt(); char[] cs = in.next().toCharArray(); char[] ct = in.next().toCharArray(); LinkedList<Integer> q = new LinkedList<>(); Map<Character, LinkedList<Integer>> mp = new HashMap<>(); for (int i = 0; i < cs.length; i++) { if (!mp.containsKey(cs[i])) mp.put(cs[i], new LinkedList<>()); mp.get(cs[i]).add(i); } int pre = -1; for(int i = 0; i < m - 1; i++){ while (mp.get(ct[i]).peek() < pre) mp.get(ct[i]).poll(); q.add(mp.get(ct[i]).poll()); pre = q.getLast(); } int max = 0; mp = new HashMap<>(); for (int i = 0; i < cs.length; i++) { if (!mp.containsKey(cs[i])) mp.put(cs[i], new LinkedList<>()); mp.get(cs[i]).add(i); } max = Math.max(max, mp.get(ct[m - 1]).getLast() - q.getLast()); int last = mp.get(ct[m - 1]).getLast(); for (int i = m - 2; i >= 1; i--) { int cur = q.removeLast(); while (mp.get(ct[i]).size() > 0 && mp.get(ct[i]).getLast() >= last) mp.get(ct[i]).removeLast(); if (mp.get(ct[i]).size() > 0){ cur = mp.get(ct[i]).removeLast(); } max = Math.max(max, cur - q.getLast()); last = cur; } out.println(max); } static boolean check(char[] cs, char[] ct, int len){ Map<Character, LinkedList<Integer>> mp = new HashMap<>(); for (int i = 0; i < cs.length; i++) { if (!mp.containsKey(cs[i])) mp.put(cs[i], new LinkedList<>()); mp.get(cs[i]).add(i); } System.out.println("len:"+len); int pre = -len - 10; for (int i = 0; i < ct.length; i++) { while (mp.get(ct[i]).size() > 0 && mp.get(ct[i]).peek() - pre < len) mp.get(ct[i]).poll(); System.out.println("i:"+i+" mp:"+mp); if (mp.get(ct[i]).size() == 0){ return false; }else{ pre = mp.get(ct[i]).poll(); } } return true; } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
074f931539ccf133099281c48611edb7
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.lang.reflect.Array; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import java.util.Random; import java.util.Set; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeSet; import java.util.stream.Collectors; public class Main { static int mod = (int) (1e9) + 7; /* ======================DSU===================== */ static class dsu { static int parent[], n;// min[],value[]; static long size[]; dsu(int n) { parent = new int[n + 1]; size = new long[n + 1]; // min=new int[n+1]; // value=new int[n+1]; this.n = n; makeSet(); } static void makeSet() { for (int i = 1; i <= n; i++) { parent[i] = i; size[i] = 1; // min[i]=i; } } static int find(int a) { if (parent[a] == a) return a; else { return parent[a] = find(parent[a]);// Path Compression } } static void union(int a, int b) { int setA = find(a); int setB = find(b); if (setA == setB) return; if (size[setA] >= size[setB]) { parent[setB] = setA; size[setA] += size[setB]; } else { parent[setA] = setB; size[setB] += size[setA]; } } } /* ======================================================== */ static class Pair<X extends Number, Y extends Number> implements Comparator<Pair> { X x; Y y; // Constructor public Pair(X x, Y y) { this.x = x; this.y = y; } public Pair() { } @Override public int compare(Main.Pair o1, Main.Pair o2) { return ((int) (o1.y.intValue() - o2.y.intValue()));// Ascending Order based on 'y' } } /* ===============================Tries================================= */ static class TrieNode { private HashMap<Character, TrieNode> children = new HashMap<>(); public int size; boolean endOfWord; public void putChildIfAbsent(char ch) { children.putIfAbsent(ch, new TrieNode()); } public TrieNode getChild(char ch) { return children.get(ch); } } static private TrieNode root; public static void insert(String str) { TrieNode curr = root; for (char ch : str.toCharArray()) { curr.putChildIfAbsent(ch); curr = curr.getChild(ch); curr.size++; } // mark the current nodes endOfWord as true curr.endOfWord = true; } public static int search(String word) { TrieNode curr = root; for (char ch : word.toCharArray()) { curr = curr.getChild(ch); if (curr == null) { return 0; } } // size contains words starting with prefix- word return curr.size; } public boolean delete(TrieNode current, String word, int index) { if (index == word.length()) { // when end of word is reached only delete if currrent.endOfWord is true. if (!current.endOfWord) { return false; } current.endOfWord = false; // if current has no other mapping then return true return current.children.size() == 0; } char ch = word.charAt(index); TrieNode node = current.children.get(ch); if (node == null) { return false; } boolean shouldDeleteCurrentNode = delete(node, word, index + 1); // if true is returned then delete the mapping of character and trienode // reference from map. if (shouldDeleteCurrentNode) { current.children.remove(ch); // return true if no mappings are left in the map. return current.children.size() == 0; } 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; } int[] intArr(int n) { int res[] = new int[n]; for (int i = 0; i < n; i++) res[i] = nextInt(); return res; } long[] longArr(int n) { long res[] = new long[n]; for (int i = 0; i < n; i++) res[i] = nextLong(); return res; } } static FastReader f = new FastReader(); static BufferedWriter w = new BufferedWriter(new OutputStreamWriter(System.out)); 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 (long i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static int lowerBound(int a[], int x) { // x is the target, returns lowerBound. If not found return -1 int l = -1, r = a.length, flag = 0; while (l + 1 < r) { int m = (l + r) >>> 1; if (x == a[m]) flag = 1; if (a[m] >= x) r = m; else l = m; } return r; } static int upperBound(int a[], int x, int l, int r) {// x is the target, returns upperBound. If not found return -1 int flag = 0; while (l + 1 < r) { int m = (l + r) >>> 1; if (a[m] == x) return m; if (a[m] <= x) { l = m; flag = 1; } else r = m; } return l + 1; } 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 * b) / gcd(a, b); } static long power(long x, long y) { long res = 1; while (y > 0) { if (y % 2 == 1) res = (res * x); y >>= 1; x = (x * x); } return res; } public double binPow(double x, int n) {// binary exponentiation with negative power as well if (n == 0) return 1.0; double binPow = binPow(x, n / 2); if (n % 2 == 0) { return binPow * binPow; } else { return n > 0 ? (binPow * binPow * x) : (binPow * binPow / x); } } static long ceil(long x, long y) { return (x % y == 0 ? x / y : (x / y + 1)); } /* * ===========Modular Operations================== */ static long modPower(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } static long modInverse(long n, long p) { return modPower(n, p - 2, p); } static long modAdd(long a, long b) { return ((a + b + mod) % mod); } static long modMul(long a, long b) { return ((a % mod) * (b % mod)) % mod; } static long nCrModPFermat(int n, int r) { if (r == 0) return 1; long[] fac = new long[n + 1]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = fac[i - 1] * i % mod; return (fac[n] * modInverse(fac[r], mod) % mod * modInverse(fac[n - r], mod) % mod) % mod; } /* * =============================================== */ static void ruffleSort(long[] a) { 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; } Arrays.sort(a); } static void ruffleSort(int[] a) { 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; } Arrays.sort(a); } static String binString32(int n) { StringBuilder str = new StringBuilder(""); String bin = Integer.toBinaryString(n); if (bin.length() != 32) { for (int k = 0; k < 32 - bin.length(); k++) { str.append("0"); } str.append(bin); } return str.toString(); } static class sparseTable { public static int st[][]; public static int log = 4; static int func(int a, int b) {// make func as per question(here min range query) return (int) gcd(a, b); } void makeTable(int n, int a[]) { st = new int[n][log]; for (int i = 0; i < n; i++) { st[i][0] = a[i]; } for (int j = 1; j < log; j++) { for (int i = 0; i + (1 << j) <= n; i++) { st[i][j] = func(st[i][j - 1], st[i + (1 << (j - 1))][j - 1]); } } } static int query(int l, int r) { int length = r - l + 1; int k = 0; while ((1 << (k + 1)) <= length) { k++; } return func(st[l][k], st[r - (1 << k) + 1][k]); } static void printTable(int n) { for (int j = 0; j < log; j++) { for (int i = 0; i < n; i++) { System.out.print(st[i][j] + " "); } System.out.println(); } } } /* * ====================================Main================================= */ // static int st[], a[]; // static void buildTree(int treeIndex, int lo, int hi) { // if (hi == lo) { // st[treeIndex] = a[lo]; // return; // } // int mid = (lo + hi) / 2; // buildTree(treeIndex * 2 + 1, lo, mid); // buildTree(treeIndex * 2 + 2, mid + 1, hi); // st[treeIndex] = merge(st[treeIndex * 2 + 1], st[treeIndex * 2 + 2]); // } // static void update(int treeIndex, int lo, int hi, int arrIndex, int val) { // if (hi == lo) { // st[treeIndex] = val; // a[arrIndex] = val; // return; // } // int mid = (hi + lo) / 2; // if (mid < arrIndex) { // update(treeIndex * 2 + 2, mid + 1, hi, arrIndex, val); // } else { // update(treeIndex * 2 + 1, lo, mid, arrIndex, val); // } // st[treeIndex] = merge(st[treeIndex * 2 + 1], st[treeIndex * 2 + 2]); // } // static int query(int treeIndex, int lo, int hi, int l, int r) { // if (l <= lo && r >= hi) { // return st[treeIndex]; // } // if (l > hi || r < lo) { // return 0; // } // int mid = (hi + lo) / 2; // return query(treeIndex * 2 + 1, lo, mid, l, Math.min(mid, r)); // } // static int merge(int a, int b) { // return a + b; // } public static long findKthPositive(long[] A, long k) { int l = 0, r = A.length, m; while (l < r) { m = (l + r) / 2; if (A[m] - 1 - m < k) l = m + 1; else r = m; } return l + k; } static int[] z_function(char ar[]) { int[] z = new int[ar.length]; z[0] = ar.length; int l = 0; int r = 0; for (int i = 1; i < ar.length; i++) { if (r < i) { l = i; r = i; while (r < ar.length && ar[r - l] == ar[r]) r++; z[i] = r - l; r--; } else { int k = i - l; if (z[k] < r - i + 1) { z[i] = z[k]; } else { l = i; while (r < ar.length && ar[r - l] == ar[r]) r++; z[i] = r - l; r--; } } } return z; } public static void main(String args[]) throws Exception { // File file = new File("D:\\VS Code\\Java\\Output.txt"); // FileWriter fw = new FileWriter("D:\\VS Code\\Java\\Output.txt"); int t = 1; // t = f.nextInt(); int tc = 1; while (t-- != 0) { // BufferedReader br = new BufferedReader(new FileReader("PHOBIA.INP")); // PrintWriter pw = new PrintWriter(new BufferedWriter(new // FileWriter("PHOBIA.OUT"))); int n=f.nextInt(); int m=f.nextInt(); String s1=f.next(); String s2=f.next(); int min[]=new int[m]; int max[]=new int[m]; int pos=0; for(int i=0;i<n;i++){ if(s1.charAt(i)==s2.charAt(pos)){ min[pos]=i; pos++; } if(pos==m)break; } pos=m-1; for(int i=n-1;i>=0;i--){ if(s1.charAt(i)==s2.charAt(pos)){ max[pos]=i; pos--; } if(pos==0)break; } int ans=0; for(int i=0;i<m-1;i++){ ans=Math.max(ans,max[i+1]-min[i]); } w.write(ans+"\n"); } w.flush(); } } /* */
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
2f796f308e7b04b19d5b1d25e744c4a7
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.io.*; import java.lang.reflect.Array; import java.math.RoundingMode; import java.text.DecimalFormat; import java.util.*; public class copy { static long ans; public static long[] inv(long[] arr,int l,int r) { if(l>r) return null; if(l==r) { long[] sum=new long[1]; sum[0]=arr[l]; return sum; } int mid=(l+r)/2; long[] sum1=inv(arr,l,mid); long[] sum2=inv(arr,mid+1,r); long[] sum3=merge(arr,l,mid,r,sum1,sum2); return sum3; } public static long[] merge(long[] arr,int l,int mid,int r,long[] sum1,long[] sum2) { //System.out.println(l+" "+mid+" "+r+" "+ans); int N=mid-l+1; int M=r-mid; long[] arr1=new long[N]; long[] arr2=new long[N]; long[] mer=new long[N+M]; for(int i=0;i<N;i++) arr1[i]=arr[l+i]; for(int i=0;i<M;i++) arr2[i]=arr[mid+1+i]; int k=0; int c=0,d=0; while(c<N && d<M) { if(arr1[c]<=arr2[d]) { mer[k++]=arr1[c++]; } else { // System.out.println(arr2[d]+" hello "+arr1[c]); // System.out.println(sum[mid]+" LAUDE "+sum[c]+" "+arr1[c]); ans+=sum1[N-1]-sum1[c]+arr1[c]; mer[k++]=arr2[d++]; } } while(c<N) mer[k++]=arr1[c++]; while(d<M) mer[k++]=arr2[d++]; long s=0; long[] sum=new long[N+M]; //System.out.println("SUM"); for(int i=0;i<N+M;i++) { s+=mer[i]; //System.out.print(s+" "); sum[i]=s; } //System.out.println(); for(int i=0;i<mer.length;i++) { arr[l+i]=mer[i]; } //System.out.println("ANSWER "+ans); return sum; } public static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } public static int bin(ArrayList<Integer> arr,int check) { if(check<=arr.get(0)) return 0; if(check>arr.get(arr.size()-1)) return arr.size(); int l=0; int r=arr.size()-1; while(l<=r) { int mid=(l+r)/2; if(arr.get(mid)>=check) { if(mid-1>=0 && arr.get(mid-1)>=check) r=mid-1; else return mid; } else l=mid+1; } return -1; } public static int bin_right(ArrayList<Integer> arr,int check) { if(check<arr.get(0)) return -1; if(check>=arr.get(arr.size()-1)) return arr.size()-1; int l=0; int r=arr.size()-1; while(l<=r) { int mid=(l+r)/2; if(arr.get(mid)<=check) { if(mid+1<arr.size() && arr.get(mid+1)<=check) l=mid+1; else return mid; } else r=mid-1; } return -1; } public static void main(String[] args)throws IOException { Reader.init(System.in); BufferedWriter output=new BufferedWriter(new OutputStreamWriter(System.out)); int M=Reader.nextInt(); int N=Reader.nextInt(); String s1=Reader.next(); String s2=Reader.next(); int[] lower=new int[N]; int[] higher=new int[N]; lower[0]=s1.indexOf(s2.charAt(0)); for(int i=1;i<s2.length();i++) { char ch=s2.charAt(i); lower[i]=s1.indexOf(ch,lower[i-1]+1); } higher[N-1]=s1.lastIndexOf(s2.charAt(N-1)); for(int i=s2.length()-2;i>=0;i--) { char ch=s2.charAt(i); higher[i]=s1.lastIndexOf(ch,higher[i+1]-1); } int max=-1; for(int i=0;i<s2.length()-1;i++) { if(higher[i+1]-lower[i]>max) max=higher[i+1]-lower[i]; } output.write(max+""); output.flush(); } } class Reader { static BufferedReader reader; static StringTokenizer tokenizer; static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } static String next() throws IOException { while (!tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer( reader.readLine()); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } } class cp { int a,b; cp(int a,int b) { this.a=a; this.b=b; } } class sort_cp implements Comparator<cp> { public int compare(cp o1,cp o2) { return o1.a-o2.a; } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
bce2431333294d51a3e512f87dc5a8b4
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class new1 { public static int func(char[] s1, char[] s2, int[] first, int[] last, int i, int j) { if(i == s2.length - 1) { return 0; } int max = func(s1, s2, first, last, i + 1, first[i + 1]); max = Math.max(max, last[i + 1] - j); return max; } public static void main(String[] args) throws IOException { FastReader s = new FastReader(); int t = 1;//s.nextInt(); for(int i = 0; i < t; i++) { int a = s.nextInt(); int b = s.nextInt(); char[] s1 = s.next().toCharArray(); char[] s2 = s.next().toCharArray(); int ind = b - 1; int [] last = new int[b]; for(int j = a - 1; j >= 0; j--) { if(ind >= 0) { if(s1[j] == s2[ind]) { last[ind] = j; ind--; } } } int[] first = new int[b]; ind = 0; for(int j = 0; j < a; j++) { if(ind < b) { if(s1[j] == s2[ind]) { first[ind] = j; ind++; } } } //System.out.println(Arrays.toString(first)); int ans = func(s1, s2, first, last, 0, first[0]); System.out.println(ans); } } } 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(); } public 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 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
c2cb38ea2f0fb4d62e052486599b0e84
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.util.Scanner; import java.util.stream.IntStream; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); sc.nextInt(); sc.nextInt(); String s = sc.next(); String t = sc.next(); System.out.println(solve(s, t)); sc.close(); } static int solve(String s, String t) { int[] minIndices = new int[t.length()]; int minIndex = 0; for (int i = 0; i < minIndices.length; ++i) { char target = t.charAt(i); while (s.charAt(minIndex) != target) { ++minIndex; } minIndices[i] = minIndex; ++minIndex; } int[] maxIndices = new int[t.length()]; int maxIndex = s.length() - 1; for (int i = maxIndices.length - 1; i >= 0; --i) { char target = t.charAt(i); while (s.charAt(maxIndex) != target) { --maxIndex; } maxIndices[i] = maxIndex; --maxIndex; } return IntStream.range(0, t.length() - 1) .map(i -> maxIndices[i + 1] - minIndices[i]) .max() .getAsInt(); } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
9689d388b362649be630c20a60f71871
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
//package codeforces; import java.io.PrintWriter; import java.util.*; public class solution { public static void main(String args[]){ Scanner s=new Scanner(System.in); PrintWriter out=new PrintWriter(System.out); int t=1; for(int tt=0;tt<t;tt++) { int n=s.nextInt(),m=s.nextInt(); String a=s.next(),b=s.next(); int c[]=new int[n]; int d[]=new int[n]; int j=0; for(int i=0;i<b.length();i++) { while(a.length()>(j-1) && b.charAt(i)!=a.charAt(j)) { j++; } c[i]=j; j++; } j=n-1; for(int i=m-1;i>=0;i--) { while(a.length()>(j-1) && b.charAt(i)!=a.charAt(j)) { j--; } d[i]=j; j--; } int ans=0; for(int i=1;i<m;i++) { ans=Math.max(Math.abs(c[i-1]-d[i]), ans); } out.println(ans); } s.close(); out.close(); } 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 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 int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } static void sortcol(long a[][],int c) { Arrays.sort(a, (x, y) -> { if(x[c]!=y[c]) return (int)( x[c] - y[c]); else { return (int)(x[1]-y[1]); } }); } public static void printb(boolean ans) { if(ans) { System.out.println("YES"); }else { System.out.println("NO"); } } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
7419c0b88e96e8eef66b29d764497f6b
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.util.*; public class Solution { // static boolean[][] isVisited; static int[][] dp; static Scanner sc = new Scanner(System.in); public static void main(String args[]) { // int t=sc.nextInt(); // while(t-->0){ int n=sc.nextInt(),m=sc.nextInt(); sc.nextLine(); String a=sc.nextLine(); String b=sc.nextLine(); int i=a.indexOf(b.charAt(0)); int[] left=new int[m]; int[] right=new int[m]; boolean isVisited[]=new boolean[m]; isVisited[0]=true; int k=1; left[0]=i; for (int j=i+1;j<n ;j++ ) { if(k>=m) break; char c=b.charAt(k); if(c==a.charAt(j) && isVisited[k-1]==true){ left[k]=j; isVisited[k]=true; k++; } } k=m-2; i=a.lastIndexOf(b.charAt(m-1)); right[m-1]=i; for (int j=i-1;j>=0 ;j-- ) { if(k<0) break; char c=b.charAt(k); if(c==a.charAt(j) && isVisited[k+1]==true){ right[k]=j; isVisited[k]=true; k--; } } // for (int i1 :left ) { // System.out.println(i1+" "); // } // for (int i1 :right ) { // System.out.println(i1+" "); // } int ans=1; for (int i1=0;i1<m-1 ;i1++ ) { ans=Math.max(right[i1+1]-left[i1],ans); } System.out.println(ans); } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
211ff70e9ec192c6ca97ce93fd7b420c
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.util.*; import java.io.*; public class maximum_width { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer line = new StringTokenizer(in.readLine()); int n = Integer.parseInt(line.nextToken()); int m = Integer.parseInt(line.nextToken()); String s = in.readLine(); String t = in.readLine(); char[] c1 = s.toCharArray(); char[] c2 = t.toCharArray(); int[] start = new int[m]; int[] end = new int[m]; int j = 0; for(int i=0; i<n; i++){ if(c1[i] == c2[j]){ start[j++] = i; if(j >= m) break; } } j = m-1; for(int i=n-1; i>=0; i--){ if(c1[i] == c2[j]){ end[j--] = i; if(j<0) break; } } // System.out.println(Arrays.toString(start)); // System.out.println(Arrays.toString(end)); int max = 0; for(int i=1; i<m; i++) { max = Math.max(max, end[i] - start[i - 1]); } System.out.println(max); in.close(); } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
5bd4ae67d005f8ee63d7eca4f03cc3a0
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; import java.io.BufferedReader; import java.io.InputStreamReader; public class First { 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 a = 1; int t; //t = in.nextInt(); t = 1; while (t > 0) { //out.print("Case #"+(a++)+": "); solver.call(in,out); t--; } out.close(); } static class TaskA { public void call(InputReader in, PrintWriter out) { int n, m; n = in.nextInt(); m = in.nextInt(); char[] s = in.next().toCharArray(); char[] t = in.next().toCharArray(); Map<Character, ArrayList<Integer>> map = new HashMap<>(); for (int i = 0; i < m; i++) { if(map.getOrDefault(t[i] , null)==null){ map.put(t[i] , new ArrayList<>()); } } for (int i = 0; i < n; i++) { if(map.getOrDefault(s[i] , null)==null){ continue; } map.get(s[i]).add(i); } Stack<Integer> stack = new Stack<>(); int ans = 0; for (int i = n-1, j = m-1; i > 0 && j > 0; i--) { if(s[i]==t[j]){ stack.add(i); j--; } } int a, b = 0, l= -1, r = 0, mid; for (int i = 0; i < m-1; i++) { a = stack.pop(); if (i != 0) { l = -1; r = map.get(t[i]).size(); while (l + 1 < r) { mid = (l + r) / 2; if (map.get(t[i]).get(mid) <= b) { l = mid; } else { r = mid; } } } ans = Math.max(a - map.get(t[i]).get(r), ans); b = map.get(t[i]).get(r); } out.println(ans); } } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } static class answer implements Comparable<answer>{ int a; int b; public answer(int a, int b) { this.a = a; this.b = b; } @Override public int compareTo(answer o) { return o.a - this.a; } @Override public boolean equals(Object o){ if(o instanceof answer){ answer c = (answer)o; return a == c.a && b == c.b; } return false; } } static class answer1 implements Comparable<answer1>{ int a, b, c; public answer1(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } @Override public int compareTo(answer1 o) { if(o.c==this.c){ return this.a - o.a; } return o.c - this.c; } } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } 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 final Random random=new Random(); static void shuffleSort(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 class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong(){ return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
90a6849b192cdafcdad7fee632455849
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.io.*; import java.util.ArrayList; import java.util.List; public class MaximumWidth { public static void main(String[] args) throws Exception { // BufferedReader br = new BufferedReader(new FileReader(new File("input.txt"))); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); handleTestCase(br); } private static void handleMultipleTestCases(BufferedReader br) throws Exception { int T = readInt(br); for (int tc = 0; tc < T; tc++) { handleTestCase(br); } } private static void handleTestCase(BufferedReader br) throws Exception { br.readLine(); String str1 = br.readLine(); String str2 = br.readLine(); getMaxWidth(str1, str2); } private static int readInt(BufferedReader br) throws Exception { return Integer.parseInt(br.readLine()); } private static int[] readArrInt(BufferedReader br) throws Exception { String[] line = br.readLine().split(" "); int[] arr = new int[line.length]; for (int i = 0; i < line.length; i++) { arr[i] = Integer.parseInt(line[i]); } return arr; } private static List<Integer> readList(BufferedReader br) throws Exception { String[] line = br.readLine().split(" "); List<Integer> arr = new ArrayList<>(); for (int i = 0; i < line.length; i++) { arr.add(Integer.parseInt(line[i])); } return arr; } private static void print(int[][] mat) { System.out.println("----------------------------------------"); for (int i = 0; i < mat.length; i++) { System.out.print("{"); for (int j = 0; j < mat[0].length; j++) { System.out.print(mat[i][j] + " "); } System.out.println("}"); } System.out.println("----------------------------------------"); } private static void print(int[] mat) { System.out.print("{"); for (int i = 0; i < mat.length; i++) { System.out.print(mat[i] + " "); } System.out.println("}"); } private static void getMaxWidth(String s, String t) { int result = 0; int[] pp1 = new int[t.length()]; int[] pp2 = new int[t.length()]; int ff = 0; for (int i = 0; i < s.length() && ff < t.length(); i++) { if (s.charAt(i) == t.charAt(ff)) { pp1[ff] = i; ff++; } } ff = t.length() - 1; for (int i = s.length() - 1; i >= 0 && ff >= 0; i--) { if (s.charAt(i) == t.charAt(ff)) { pp2[ff] = i; ff--; } } for (int i = 0; i < t.length() - 1; i++) { result = Math.max(result, pp2[i + 1] - pp1[i]); } // print(pp1); // print(pp2); System.out.println(result); } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
8246956ac0a9b59c5e36fc05137d6ba2
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.io.*; import java.util.*; import java.io.File; // Import the File class import java.io.FileNotFoundException; // Import this class to handle errors import java.util.Scanner; public class Main { public static void main(String args[])throws Exception { BufferedReader bu=new BufferedReader(new InputStreamReader(System.in)); Scanner sc=new Scanner(System.in); StringBuilder sb=new StringBuilder(); Main m=new Main(); m.solve(); // int t=Integer.parseInt(bu.readLine()); // int t=sc.nextInt(); // while(t-->0){ // Main m=new Main(); // Set<String> se=new HashSet<>(); // // int b=sc.nextInt(); // // int c=sc.nextInt(); // String s="1001011"; // s=sc.next(); // // int j=0; // boolean f=false; // for(int i=s.length()-1;i>=0;i--,j++) // { // if(s.charAt(i)!='a') // { // f=true; // break; // } // } // // String res=""; // if(f){ // res+=s.substring(0, j); // res+='a'; // res+=s.substring(j, s.length()); // System.out.println("YES"); // System.out.println(res); // }else // { // System.out.println("NO"); // } // // // } } void solve() { Scanner sc=new Scanner(System.in); int n=sc.nextInt();//5; int m=sc.nextInt();//2; String s=sc.next();//"aaaaa"; String t=sc.next();//"aa"; int[] a=new int[m]; int[] b=new int[m]; int j=0; for(int i=0;j<m;i++) { if(s.charAt(i)==t.charAt(j)) { a[j]=i; j++; } } j=m-1; for(int i=n-1;j>=0;i--) { if(s.charAt(i)==t.charAt(j)) { b[j]=i; j--; } } int ans=0; for(int i=0;i<m-1;i++) { ans=Math.max(ans, b[i+1]-a[i]); } System.out.println(ans); } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
946c6959f12b1015550a3f59f559c1af
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.io.*; import java.util.LinkedList; import java.util.StringTokenizer; public class Main { private static void run(Reader in, PrintWriter out) throws IOException { int n = in.nextInt(); int m = in.nextInt(); char[] s = in.next().toCharArray(); char[] t = in.next().toCharArray(); int[] min_pos = new int[m]; int[] max_pos = new int[m]; int p; p = 0; for (int i = 0; i < n; i++) { if (t[p] == s[i]) { min_pos[p] = i; p++; } if (p == m) break; } p = m - 1; for (int i = n - 1; i >= 0; i--) { if (t[p] == s[i]) { max_pos[p] = i; p--; } if (p == -1) break; } int ans = 0; for (int i = 0; i < m - 1; i++) { ans = Math.max(ans, max_pos[i + 1] - min_pos[i]); } out.println(ans); } public static void main(String[] args) throws IOException { Reader in = new Reader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); run(in, out); out.flush(); in.close(); out.close(); } static class Reader { BufferedReader reader; StringTokenizer st; Reader(InputStreamReader stream) { reader = new BufferedReader(stream, 32768); st = null; } void close() throws IOException { reader.close(); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } String nextLine() throws IOException { return reader.readLine(); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
387f02b80d8e69c2e789ef45bb1d7cfb
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class MaximumWidth { public static void main(String[] args) { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int testCase = 1; for (int tc = 0; tc < testCase; tc++) { int n = fs.nextInt(), m = fs.nextInt(); char[] s = fs.next().toCharArray(); char[] t = fs.next().toCharArray(); List<Integer> left = new ArrayList<>(); List<Integer> right = new ArrayList<>(); for(int i = 0, j = 0; i < n && j < m; ++i) { if(s[i] == t[j]) { left.add(i); ++j; } } for(int i = n - 1, j = m - 1; i >= 0 && j >= 0; --i) { if(s[i] == t[j]) { right.add(i); --j; } } int ans = 1; for(int i = 0; i < m - 1; ++i) { ans = Math.max(ans, right.get(m - i - 2) - left.get(i)); //System.out.println(i + "\t" + (m - i - 2) + "\t" + right.get(m - i - 2) + "\t" + left.get(i)); } System.out.println(ans); } } static void ruffleSort(int[] a) { int n = a.length; Random r = new Random(); for(int i = 0; i < a.length; ++i) { int oi = r.nextInt(n), t = a[i]; a[i] = a[oi]; a[oi] = t; } Arrays.sort(a); } 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 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
f64486afc02fde2be1d038f74258e12b
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Comparator; import java.util.StringTokenizer; public class CMaxWidth { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Problem solver = new Problem(); solver.solve(0, in, out); out.close(); } static class Problem { public void solve(int testNumber, InputReader in, PrintWriter out) { int N = in.nextInt(), M = in.nextInt(); String s = in.next(), t = in.next(); int res = maxWidth(s, t); out.println(res); } private int maxWidth(String s, String t) { int[] left = new int[t.length()]; int i = 0, j = 0; while (i < s.length() && j < t.length()) { if (s.charAt(i) == t.charAt(j)) left[j++] = i; i++; } int[] right = new int[t.length()]; i = s.length() - 1; j = t.length() - 1; while (i >= 0 && j >= 0) { if (s.charAt(i) == t.charAt(j)) right[j--] = i; i--; } int res = 0; for (i = 0; i < t.length() - 1; i++) { res = Math.max(res, right[i + 1] - left[i]); } return res; } } 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 String nextLine() { String s; try { s = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return s; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public int[] nextIntArray(int N) { int[] arr = new int[N]; for (int i = 0; i < N; i++) { arr[i] = nextInt(); } return arr; } } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
062d918d430af2f9b89cf9dba905ba46
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.PriorityQueue; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.io.*; public class MaxWidth { private static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static int solution (String s, String t, int n, int m) { int[] find = new int[m]; int[] lind = new int[m]; int start = 0; for(int i = 0; i<m; i++) { char c = t.charAt(i); while(s.charAt(start)!=c) start++; find[i] = start; start++; } start = n-1; for(int i = m-1; i>=0; i--) { char c = t.charAt(i); while(s.charAt(start)!=c) start--; lind[i] = start; start--; } int max = 0; for(int i = 0; i<m-1 ;i++) { int curr = lind[i+1]-find[i]; if(curr>max) max = curr; } return max; } private static PrintWriter out = new PrintWriter(System.out); public static void main (String[] args) { MyScanner s = new MyScanner(); int n = s.nextInt(); int m = s.nextInt(); String st = s.nextLine(); String t = s.nextLine(); out.println(solution(st,t,n,m)); out.flush(); out.close(); } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
d73b5e91c266ba733c52f3765f7d5c17
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.util.Scanner; public class C { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(), m = sc.nextInt(); String s = sc.next(), t = sc.next(); int[] left = new int[n], right = new int[n]; int idx = 0; for (int i = 0; i < m; i++) { while (t.charAt(i) != s.charAt(idx)) { // System.out.println(idx); idx++; } left[i] = idx++; // idx++; } idx = n-1; for (int i = m-1; i >= 0; i--) { while (t.charAt(i) != s.charAt(idx)) { idx--; } right[i] = idx--; // idx--; } int ans = 0; for (int i = 0; i < m-1; i++) { ans = Math.max(right[i+1]-left[i], ans); } System.out.println(ans); } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
203d9086c44c76cdf4eef39d5aff0a76
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.io.*; import java.util.*; public class Codeforces { public static class FastReader { BufferedReader br; StringTokenizer st; public FastReader(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public FastReader() { 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 FastReader f = new FastReader(); static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st; static StringBuilder sb = new StringBuilder(""); private static int m = (int) 1e9 + 7; static int MAX = 500005; static long[] fact; static int[] inputArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = f.nextInt(); } return a; } private static class SegmentTree { int[] array; int[] tree; int n; int max; SegmentTree(int a[], int n) { this.tree = new int[4 * n + 1]; this.array = a; this.n = n; buildTree(); } void buildTree() { buildTreeHelper(0, 0, n - 1); } void buildTreeHelper(int i, int start, int end) { if (start > end) { return; } if (start == end) { tree[i] = array[start]; return; } int mid = (start + end) / 2; buildTreeHelper(2 * i + 1, start, mid); buildTreeHelper(2 * i + 2, mid + 1, end); tree[i] = Math.max(tree[2 * i + 1] , tree[2 * i + 2]); } char overlap(int start, int end, int qs, int qe) { if (qe < start || qs > end || start > end) { return 0; } if (qs <= start && qe >= end) { return 2; } return 1; } int query(int start, int end) { return andQueryHelper(0, 0, n - 1, start, end); } int andQueryHelper(int i, int start, int end, int qs, int qe) { if (overlap(start, end, qs, qe) == 0) { return 0; } if (overlap(start, end, qs, qe) == 1) { int mid = (start + end) / 2; return Math.max(andQueryHelper(2 * i + 1, start, mid, qs, qe) , andQueryHelper(2 * i + 2, mid + 1, end, qs, qe)); } else { return tree[i]; } } } public static void main(String[] args) throws IOException { int n = f.nextInt() , m = f.nextInt(); String s = f.nextToken(); String t = f.nextToken(); int[] legal_left = new int[m]; int[] legal_right = new int[m]; int j = 0; for(int i = 0 ; i < n ; i++) { if(j == m) break; if(s.charAt(i) == t.charAt(j)) { legal_left[j] = i; j++; } } j = m - 1; for(int i = n - 1 ; i >= 0 ; i--) { if(j == 0) break; if(s.charAt(i) == t.charAt(j)) { legal_right[j] = i; j--; } } int max_Width = 0; for(int i = 0 ; i < m ; i++) { if(i > 0) { max_Width = Math.max(max_Width , legal_right[i] - legal_left[i-1]); } } System.out.println(max_Width); } } /* 5 2 1 1 1 500 4 217871987498122 10 100000000000000001 1 */
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
f47a762ebae0b4b95be6158a9c50256e
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.util.*; public class Random { public static void main(String[] args) { Scanner sc = new Scanner(System.in); // int tc = sc.nextInt(); // while (tc-- > 0) { // } int n = sc.nextInt(); int m = sc.nextInt(); String s = sc.next(); String t = sc.next(); int[] subLeft = new int[m]; int[] subRight = new int[m]; int cur = 0; for (int i = 0; i < n; ++i) { if (cur == m) { break; } if (s.charAt(i) == t.charAt(cur)) { subLeft[cur] = i; ++cur; } } cur = m - 1; for (int i = n - 1; i >= 0; --i) { if (cur == -1) { break; } if (s.charAt(i) == t.charAt(cur)) { subRight[cur] = i; --cur; } } int ans = 0; for (int i = 0; i < m - 1; ++i) { ans = Math.max(ans, subRight[i + 1] - subLeft[i]); } System.out.println(ans); } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
580bd2e67f94421bfabe4033bcdbe120
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.util.*; import java.io.*; public class cc_march2020_long { public static void main(String[] args) { Scanner scn=new Scanner(System.in); int n=scn.nextInt(); int m=scn.nextInt(); scn.nextLine(); String s=scn.nextLine(); String t=scn.nextLine(); int[]low=new int[m]; int[]high=new int[m]; int idx=0; for(int i=0;i<n && idx<m;i++) { if(s.charAt(i)==t.charAt(idx)) { low[idx]=i; idx++; } } idx=m-1; for(int i=n-1;i>=0 && idx>=0;i--) { if(s.charAt(i)==t.charAt(idx)) { high[idx]=i; idx--; } } int ans=1; for(int i=1;i<m;i++) { ans=Math.max(ans,high[i]-low[i-1]); } System.out.println(ans); } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
24474c748ea07f0fab3a3283c5fa32e1
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.util.*; import java.io.*; public class three { public static void main(String[] args) throws IOException, FileNotFoundException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); //BufferedReader in = new BufferedReader(new FileReader("three")); int t = 1; while (t-- > 0) { StringTokenizer st = new StringTokenizer(in.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); char[] s = in.readLine().toCharArray(); char[] x = in.readLine().toCharArray(); int c=26; ArrayList<Integer>[] poss = new ArrayList[c]; for (int i=0; i<c; i++) { poss[i] = new ArrayList<>(); } for (int i=0; i<n; i++) { poss[s[i] - 'a'].add(i); } int[] minind = new int[m]; int[] maxind = new int[m]; int ans=0; minind[0] = poss[x[0] - 'a'].get(0); for (int i=1; i<m; i++) { int curc = x[i]-'a'; int min=0; int max=poss[curc].size()-1; while (min<max) { int middle = (min+max)/2; if (poss[curc].get(middle) > minind[i-1]) { max = middle; } else min = middle+1; } minind[i] = poss[curc].get(min); } maxind[m-1] = poss[x[m-1] - 'a'].get(poss[x[m-1] - 'a'].size()-1); for (int i=m-2; i>=0; i--) { int curc = x[i]-'a'; int min=0; int max=poss[curc].size()-1; while (min<max) { int middle = (min+max+1)/2; if (poss[curc].get(middle) < maxind[i+1]) { min = middle; } else max = middle-1; } maxind[i] = poss[curc].get(min); } for (int i=0; i<m-1; i++) { ans = Math.max(ans, maxind[i+1] - minind[i]); } System.out.println(ans); } } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
ba143bbd0d5c339e6314542d14943039
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.PriorityQueue; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; import java.util.concurrent.LinkedBlockingDeque; /* @author kalZor */ public class TaskC { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Solver solver = new Solver(); // int testCount = Integer.parseInt(in.next()); // for (int i = 1; i <= testCount; i++) solver.solve(1, in, out); out.close(); } static class Solver { public void solve(int testNumber, FastReader in, PrintWriter out) { int n = in.nextInt();int m = in.nextInt(); char[] s = in.next().toCharArray(); char[] t = in.next().toCharArray(); if(n==m){ out.println(1); return; } int[] left = new int[m]; int[] right = new int[m]; int index = 0; for(int i=0;i<n;i++){ if(s[i]==t[index]){ left[index] = i; index++; } if(index==m) break; } index = m-1; for(int i=n-1;i>=0;i--){ if(s[i]==t[index]){ right[index] = i; index--; } if(index==-1) break; } int ans = 1; for(int i=0;i<m-1;i++){ ans = Math.max(ans,right[i+1]-left[i]); } out.println(ans); } } static class Pair implements Comparable<Pair>{ int a; int b; public Pair(int a, int b) { this.a = a; this.b = b; } public int compareTo(Pair o) { if(this.a==o.a) return -1*(this.b - o.b); return this.a - o.a; } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader(InputStream stream){ br = new BufferedReader(new InputStreamReader(stream)); } public String next(){ while (st == null || !st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); } catch (IOException e){ e.printStackTrace(); } } return st.nextToken(); } public int nextInt(){ return Integer.parseInt(next()); } public long nextLong(){ return Long.parseLong(next()); } public double nextDouble(){ return Double.parseDouble(next()); } public String nextLine(){ String str = ""; try{ str = br.readLine(); } catch (IOException e){ e.printStackTrace(); } return str; } public int[] nextArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
31a9a747da0fec55e51933fdd7227fbc
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.nio.file.Paths; import java.util.*; public class Main extends PrintWriter { static BufferedReader s = new BufferedReader(new InputStreamReader(System.in));Main () { super(System.out); }public static void main(String[] args) throws IOException{ Main d1=new Main ();d1.main();d1.flush(); } void main() throws IOException { StringBuilder sb = new StringBuilder(); int t = 1; // t=i(s()[0]); // System.out.println(Math.log(10)); while(t-->0) { String[] s1 = s(); int n=i(s1[0]); int m=i(s1[1]); char[] a=s()[0].toCharArray(); char[] b=s()[0].toCharArray(); int[] min=new int[b.length]; int j=0; for(int i=0;i<m;i++){ while(a[j]!=b[i]){ j++; } min[i]=j;j++; }j=n-1; int ans=0; for(int i=m-1;i>=0;i--){ while(a[j]!=b[i]){ j--; } if(i>0) { ans=Math.max(ans,j-min[i-1]); }j--; } sb.append(ans+"\n"); } System.out.println(sb); } // System.out.println(sb); static String[] s() throws IOException { return s.readLine().trim().split("\\s+"); } static int i(String ss) {return Integer.parseInt(ss); } static long l(String ss) {return Long.parseLong(ss); } public void arr(long[] a,int n) throws IOException {String[] s2=s();for(int i=0;i<n;i++){ a[i]=l(s2[i]); }} public void arri(int[] a,int n) throws IOException {String[] s2=s();for(int i=0;i<n;i++){ a[i]=i(s2[i]); }} }class Pair{ int a,b; public Pair(int a,int b){ this.a=a;this.b=b; } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
4c77b4c787933b91bf56d1a442eb19fb
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
// Problem: C. Maximum width // Contest: Codeforces - Codeforces Round #704 (Div. 2) // URL: http://codeforces.com/contest/1492/problem/C // Memory Limit: 512 MB // Time Limit: 2000 ms // Powered by CP Editor (https://github.com/cpeditor/cpeditor) import java.io.*; import java.util.*; public class Main { private static PrintWriter pw = new PrintWriter(System.out); private static InputReader sc = new InputReader(); private static final int intmax = Integer.MAX_VALUE, intmin = Integer.MIN_VALUE; static class InputReader{ private static BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); private static StringTokenizer tk; private void next()throws IOException{ while(tk == null || !tk.hasMoreTokens()) tk = new StringTokenizer(r.readLine()); } private int nextInt()throws IOException{ next(); return Integer.parseInt(tk.nextToken()); } private long nextLong()throws IOException{ next(); return Long.parseLong(tk.nextToken()); } private String readString()throws IOException{ next(); return tk.nextToken(); } private double nextDouble()throws IOException{ next(); return Double.parseDouble(tk.nextToken()); } private int[] intArray(int n)throws IOException{ next(); int arr[] = new int[n]; for(int i=0; i<n; i++) arr[i] = nextInt(); return arr; } private long[] longArray(int n)throws IOException{ next(); long arr[] = new long[n]; for(int i=0; i<n; i++) arr[i] = nextLong(); return arr; } } public static void main(String args[])throws IOException{ // int t = sc.nextInt(); int t = 1; while(t-->0) solve(); pw.flush(); pw.close(); } private static int dist(int a, int b){ return Math.abs(a - b); } private static int max(int a, int b, int c, int d, int e){ return Math.max(a, Math.max(Math.max(b, c), Math.max(d, e))); } private static void solve()throws IOException{ int n = sc.nextInt(), m = sc.nextInt(); int pos[][] = new int[2][m]; char s[] = sc.readString().toCharArray(); char t[] = sc.readString().toCharArray(); int ptr = 0; for(int i = 0; i < m; i++){ while(s[ptr] != t[i]) ptr++; pos[0][i] = ptr++; } ptr = n - 1; for(int i = m - 1; i >= 0; i--){ while(s[ptr] != t[i]) ptr--; pos[1][i] = ptr--; } int ans = 0; for(int i = 1; i < m; i++) ans = Math.max(ans, pos[1][i] - pos[0][i - 1]); pw.println(ans); } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 11
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
e642c920f979386ab8f2f7a4d6602d7c
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
/****************************************************************************** Online Java Compiler. Code, Compile, Run and Debug java program online. Write your code in this editor and press "Run" button to execute it. *******************************************************************************/ import java.util.*; public class Main { public static boolean issorted(int []arr){ for(int i = 1;i<arr.length;i++){ if(arr[i]<arr[i-1]){ return false; } } return true; } public static long sum(int []arr){ long sum = 0; for(int i = 0;i<arr.length;i++){ sum+=arr[i]; } return sum; } public static class pair implements Comparable<pair>{ int x; int y; pair(int x,int y){ this.x = x; this.y = y; } public int compareTo(pair o){ return this.x - o.x; // sort increasingly on the basis of x // return o.x - this.x // sort decreasingly on the basis of x } } public static void swap(int []arr,int i,int j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } public static int gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b); } static int []parent = new int[1000]; static int []size = new int[1000]; public static void make(int v){ parent[v] = v; size[v] = 1; } public static int find(int v){ if(parent[v]==v){ return v; } else{ return parent[v] = find(parent[v]); } } public static void union(int a,int b){ a = find(a); b = find(b); if(a!=b){ if(size[a]>size[b]){ parent[b] = parent[a]; size[b]+=size[a]; } else{ parent[a] = parent[b]; size[a]+=size[b]; } } } static boolean []visited = new boolean[1000]; public static void dfs(int vertex,ArrayList<ArrayList<Integer>>graph){ if(visited[vertex] == true){ return; } System.out.println(vertex); for(int child : graph.get(vertex)){ // work to be done before entering the child dfs(child,graph); // work to be done after exitting the child } } public static void displayint(int []arr){ for(int i = 0;i<arr.length;i++){ System.out.print(arr[i]+" "); } System.out.println(); } public static void displaystr(String str){ StringBuilder sb = new StringBuilder(str); for(int i = 0;i<sb.length();i++){ System.out.print(sb.charAt(i)); } System.out.println(); } public static boolean checkbalanceparenthesis(StringBuilder ans){ Stack<Character>st = new Stack<>(); int i = 0; while(i<ans.length()){ if(ans.charAt(i) == '('){ st.push('('); } else{ if(st.size() == 0 || st.peek()!='('){ return false; } else{ st.pop(); } } } return st.size() == 0; } public static void main(String[] args) { Scanner scn = new Scanner(System.in); int n = scn.nextInt(); int m = scn.nextInt(); String s1 = scn.next(); String s2 = scn.next(); int []max = new int[m]; int []min = new int[m]; int k = 0; for(int i = 0;i<n;i++){ if(s1.charAt(i) == s2.charAt(k)){ min[k] = i; k++; } if(k == m){ break; } } k = m-1; for(int i = n-1;i>=0;i--){ if(s1.charAt(i) == s2.charAt(k)){ max[k] = i; k--; } if(k < 0 ){ break; } } int ans = 0; for(int i = 0;i<m-1;i++){ ans = Math.max(Math.abs(max[i+1]-min[i]),ans); } System.out.println(ans); } }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 17
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
42f5488ab7369e9c1904de9c4d582c57
train_109.jsonl
1614071100
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 &lt; p_2 &lt; \ldots &lt; p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i &lt; m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.
512 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; /** * * @author eslam */ public class Solution { // Beginning of the solution static Kattio input = new Kattio(); static BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out)); static ArrayList<ArrayList<Integer>> powerSet = new ArrayList<>(); static ArrayList<LinkedList<Integer>> allprem = new ArrayList<>(); static ArrayList<LinkedList<String>> allprems = new ArrayList<>(); static ArrayList<Long> luc = new ArrayList<>(); static long mod = (long) (Math.pow(10, 9) + 7); static int grid[][] = {{0, 0, 1, -1, 1, 1, -1, -1}, {1, -1, 0, 0, 1, -1, 1, -1}}; static int dp[][]; static double cmp = 0.000000001; public static void main(String[] args) throws IOException { // Kattio input = new Kattio("input"); // BufferedWriter log = new BufferedWriter(new FileWriter("output.txt")); int test = 1;//input.nextInt(); loop: for (int o = 1; o <= test; o++) { int n = input.nextInt(); int m = input.nextInt(); String w = input.next(); String s = input.next(); int fre[] = new int[m]; int ind = m - 1; for (int i = n - 1; i > -1 && ind > -1; i--) { if (w.charAt(i) == s.charAt(ind)) { fre[ind] = i; ind--; } } ind = 0; int ans = 0; for (int i = 0; i < w.length() && ind < s.length(); i++) { if (w.charAt(i) == s.charAt(ind)) { if (ind + 1 < m) { ans = Math.max(ans, fre[ind + 1] - i); } ind++; } } log.write(ans + "\n"); } log.flush(); } static int bs(int v, ArrayList<Integer> a) { int max = a.size() - 1; int min = 0; int ans = 0; while (max >= min) { int mid = (max + min) / 2; if (a.get(mid) >= v) { ans = a.size() - mid; max = mid - 1; } else { min = mid + 1; } } return ans; } static Comparator<tri> cmpTri() { Comparator<tri> c = new Comparator<tri>() { @Override public int compare(tri o1, tri o2) { if (o1.x > o2.x) { return 1; } else if (o1.x < o2.x) { return -1; } else { if (o1.y > o2.y) { return 1; } else if (o1.y < o2.y) { return -1; } else { if (o1.z > o2.z) { return 1; } else if (o1.z < o2.z) { return -1; } else { return 0; } } } } }; return c; } static Comparator<pair> cmpPair() { Comparator<pair> c = new Comparator<pair>() { @Override public int compare(pair o1, pair o2) { if (o1.x > o2.x) { return 1; } else if (o1.x < o2.x) { return -1; } else { if (o1.y > o2.y) { return 1; } else if (o1.y < o2.y) { return -1; } else { return 0; } } } }; return c; } static class rec { long x1; long x2; long y1; long y2; public rec(long x1, long y1, long x2, long y2) { this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; } public long getArea() { return (x2 - x1) * (y2 - y1); } } static int sumOfRange(int x1, int y1, int x2, int y2, int e, int a[][][]) { return (a[e][x2][y2] - a[e][x1 - 1][y2] - a[e][x2][y1 - 1]) + a[e][x1 - 1][y1 - 1]; } public static int[][] bfs(int i, int j, String w[]) { Queue<pair> q = new ArrayDeque<>(); q.add(new pair(i, j)); int dis[][] = new int[w.length][w[0].length()]; for (int k = 0; k < w.length; k++) { Arrays.fill(dis[k], -1); } dis[i][j] = 0; while (!q.isEmpty()) { pair p = q.poll(); int cost = dis[p.x][p.y]; for (int k = 0; k < 4; k++) { int nx = p.x + grid[0][k]; int ny = p.y + grid[1][k]; if (isValid(nx, ny, w.length, w[0].length())) { if (dis[nx][ny] == -1 && w[nx].charAt(ny) == '.') { q.add(new pair(nx, ny)); dis[nx][ny] = cost + 1; } } } } return dis; } public static void dfs(int node, ArrayList<Integer> a[], boolean vi[]) { vi[node] = true; for (Integer ch : a[node]) { if (!vi[ch]) { dfs(ch, a, vi); } } } public static void graphRepresintion(ArrayList<Integer>[] a, int q) throws IOException { for (int i = 0; i < a.length; i++) { a[i] = new ArrayList<>(); } while (q-- > 0) { int x = input.nextInt(); int y = input.nextInt(); a[x].add(y); a[y].add(x); } } public static boolean isValid(int i, int j, int n, int m) { return (i > -1 && i < n) && (j > -1 && j < m); } // present in the left and right indices public static int[] swap(int data[], int left, int right) { // Swap the data int temp = data[left]; data[left] = data[right]; data[right] = temp; // Return the updated array return data; } // Function to reverse the sub-array // starting from left to the right // both inclusive public static int[] reverse(int data[], int left, int right) { // Reverse the sub-array while (left < right) { int temp = data[left]; data[left++] = data[right]; data[right--] = temp; } // Return the updated array return data; } // Function to find the next permutation // of the given integer array public static boolean findNextPermutation(int data[]) { // If the given dataset is empty // or contains only one element // next_permutation is not possible if (data.length <= 1) { return false; } int last = data.length - 2; // find the longest non-increasing suffix // and find the pivot while (last >= 0) { if (data[last] < data[last + 1]) { break; } last--; } // If there is no increasing pair // there is no higher order permutation if (last < 0) { return false; } int nextGreater = data.length - 1; // Find the rightmost successor to the pivot for (int i = data.length - 1; i > last; i--) { if (data[i] > data[last]) { nextGreater = i; break; } } // Swap the successor and the pivot data = swap(data, nextGreater, last); // Reverse the suffix data = reverse(data, last + 1, data.length - 1); // Return true as the next_permutation is done return true; } public static pair[] dijkstra(int node, ArrayList<pair> a[]) { PriorityQueue<tri> q = new PriorityQueue<>(new Comparator<tri>() { @Override public int compare(tri o1, tri o2) { if (o1.y > o2.y) { return 1; } else if (o1.y < o2.y) { return -1; } else { return 0; } } }); q.add(new tri(node, 0, -1)); pair distance[] = new pair[a.length]; while (!q.isEmpty()) { tri p = q.poll(); int cost = p.y; if (distance[p.x] != null) { continue; } distance[p.x] = new pair(p.z, cost); ArrayList<pair> nodes = a[p.x]; for (pair node1 : nodes) { if (distance[node1.x] == null) { tri pa = new tri(node1.x, cost + node1.y, p.x); q.add(pa); } } } return distance; } public static String revs(String w) { String ans = ""; for (int i = w.length() - 1; i > -1; i--) { ans += w.charAt(i); } return ans; } public static boolean isPalindrome(String w) { for (int i = 0; i < w.length() / 2; i++) { if (w.charAt(i) != w.charAt(w.length() - i - 1)) { return false; } } return true; } public static void getPowerSet(Queue<Integer> a) { int n = a.poll(); if (!a.isEmpty()) { getPowerSet(a); } int s = powerSet.size(); for (int i = 0; i < s; i++) { ArrayList<Integer> ne = new ArrayList<>(); ne.add(n); for (int j = 0; j < powerSet.get(i).size(); j++) { ne.add(powerSet.get(i).get(j)); } powerSet.add(ne); } ArrayList<Integer> p = new ArrayList<>(); p.add(n); powerSet.add(p); } public static int getlo(int va) { int v = 1; while (v <= va) { if ((va&v) != 0) { return v; } v <<= 1; } return 0; } static long fast_pow(long a, long p, long mod) { long res = 1; while (p > 0) { if (p % 2 == 0) { a = (a * a) % mod; p /= 2; } else { res = (res * a) % mod; p--; } } return res; } public static int countPrimeInRange(int n, boolean isPrime[]) { int cnt = 0; Arrays.fill(isPrime, true); for (int i = 2; i * i <= n; i++) { if (isPrime[i]) { for (int j = i * 2; j <= n; j += i) { isPrime[j] = false; } } } for (int i = 2; i <= n; i++) { if (isPrime[i]) { cnt++; } } return cnt; } public static void create(long num) { luc.add(num); if (num > power(10, 9)) { return; } create(num * 10 + 4); create(num * 10 + 7); } public static long ceil(long a, long b) { return (a + b - 1) / b; } public static long round(long a, long b) { if (a < 0) { return (a - b / 2) / b; } return (a + b / 2) / b; } public static void allPremutationsst(LinkedList<String> l, boolean visited[], ArrayList<String> st) { if (l.size() == st.size()) { allprems.add(l); } for (int i = 0; i < st.size(); i++) { if (!visited[i]) { visited[i] = true; LinkedList<String> nl = new LinkedList<>(); for (String x : l) { nl.add(x); } nl.add(st.get(i)); allPremutationsst(nl, visited, st); visited[i] = false; } } } public static void allPremutations(LinkedList<Integer> l, boolean visited[], int a[]) { if (l.size() == a.length) { allprem.add(l); } for (int i = 0; i < a.length; i++) { if (!visited[i]) { visited[i] = true; LinkedList<Integer> nl = new LinkedList<>(); for (Integer x : l) { nl.add(x); } nl.add(a[i]); allPremutations(nl, visited, a); visited[i] = false; } } } public static int binarySearch(long[] a, long value) { int l = 0; int r = a.length - 1; while (l <= r) { int m = (l + r) / 2; if (a[m] == value) { return m; } else if (a[m] > value) { r = m - 1; } else { l = m + 1; } } return -1; } public static void reverse(int l, int r, char ch[]) { for (int i = 0; i < r / 2; i++) { char c = ch[i]; ch[i] = ch[r - i - 1]; ch[r - i - 1] = c; } } public static int logK(long v, long k) { int ans = 0; while (v > 1) { ans++; v /= k; } return ans; } public static long power(long a, long n) { if (n == 1) { return a; } long pow = power(a, n / 2); pow *= pow; if (n % 2 != 0) { pow *= a; } return pow; } public static long get(long max, long x) { if (x == 1) { return max; } int cnt = 0; while (max > 0) { cnt++; max /= x; } return cnt; } public static int numOF0(long v) { long x = 1; int cnt = 0; while (x <= v) { if ((x & v) == 0) { cnt++; } x <<= 1; } return cnt; } public static int log2(double n) { int cnt = 0; while (n > 1) { n /= 2; cnt++; } return cnt; } public static int[] bfs(int node, ArrayList<Integer> a[]) { Queue<Integer> q = new LinkedList<>(); q.add(node); int distances[] = new int[a.length]; Arrays.fill(distances, -1); distances[node] = 0; while (!q.isEmpty()) { int parent = q.poll(); ArrayList<Integer> nodes = a[parent]; int cost = distances[parent]; for (Integer node1 : nodes) { if (distances[node1] == -1) { q.add(node1); distances[node1] = cost + 1; } } } return distances; } public static ArrayList<Integer> primeFactors(int n) { ArrayList<Integer> a = new ArrayList<>(); while (n % 2 == 0) { a.add(2); n /= 2; } for (int i = 3; i <= Math.sqrt(n); i += 2) { while (n % i == 0) { a.add(i); n /= i; } if (n < i) { break; } } if (n > 2) { a.add(n); } return a; } public static ArrayList<Integer> printPrimeFactoriztion(int n) { ArrayList<Integer> a = new ArrayList<>(); for (int i = 1; i < Math.sqrt(n) + 1; i++) { if (n % i == 0) { if (isPrime(i)) { a.add(i); n /= i; i = 0; } else if (isPrime(n / i)) { a.add(n / i); n = i; i = 0; } } } return a; } // end of solution public static BigInteger f(long n) { if (n <= 1) { return BigInteger.ONE; } long t = n - 1; BigInteger b = new BigInteger(t + ""); BigInteger ans = new BigInteger(n + ""); while (t > 1) { ans = ans.multiply(b); b = b.subtract(BigInteger.ONE); t--; } return ans; } public static long factorial(long n) { if (n <= 1) { return 1; } long t = n - 1; while (t > 1) { n = mod((mod(n, mod) * mod(t, mod)), mod); t--; } return n; } public static long rev(long n) { long t = n; long ans = 0; while (t > 0) { ans = ans * 10 + t % 10; t /= 10; } return ans; } public static boolean isPalindrome(int n) { int t = n; int ans = 0; while (t > 0) { ans = ans * 10 + t % 10; t /= 10; } return ans == n; } static class tri { int x, y, z; public tri(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } @Override public String toString() { return x + " " + y + " " + z; } } static boolean isPrime(long num) { if (num == 1) { return false; } if (num == 2) { return true; } if (num % 2 == 0) { return false; } if (num == 3) { return true; } for (int i = 3; i <= Math.sqrt(num) + 1; i += 2) { if (num % i == 0) { return false; } } return true; } public static void prefixSum(int[] a) { for (int i = 1; i < a.length; i++) { a[i] = a[i] + a[i - 1]; } } public static void suffixSum(long[] a) { for (int i = a.length - 2; i > -1; i--) { a[i] = a[i] + a[i + 1]; } } static long mod(long a, long b) { long r = a % b; return r < 0 ? r + b : r; } public static long binaryToDecimal(String w) { long r = 0; long l = 0; for (int i = w.length() - 1; i > -1; i--) { long x = (w.charAt(i) - '0') * (long) Math.pow(2, l); r = r + x; l++; } return r; } public static String decimalToBinary(long n) { String w = ""; while (n > 0) { w = n % 2 + w; n /= 2; } return w; } public static boolean isSorted(int[] a) { for (int i = 0; i < a.length - 1; i++) { if (a[i] >= a[i + 1]) { return false; } } return true; } public static void print(int[] a) throws IOException { for (int i = 0; i < a.length; i++) { log.write(a[i] + " "); } log.write("\n"); } public static void read(int[] a) { for (int i = 0; i < a.length; i++) { a[i] = input.nextInt(); } } static class gepair { long x; long y; public gepair(long x, long y) { this.x = x; this.y = y; } @Override public String toString() { return x + " " + y; } } static class pair { int x; int y; public pair(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return x + " " + y; } } static class pai { long x; int y; public pai(long x, int y) { this.x = x; this.y = y; } @Override public String toString() { return x + " " + y; } } public static long LCM(long x, long y) { return x / GCD(x, y) * y; } public static long GCD(long x, long y) { if (y == 0) { return x; } return GCD(y, x % y); } public static void simplifyTheFraction(int a, int b) { long GCD = GCD(a, b); System.out.println(a / GCD + " " + b / GCD); } 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(problemName + ".out"); r = new BufferedReader(new FileReader(problemName + ".in")); } // returns null if no more input String nextLine() { String str = ""; try { str = r.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } 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()); } } /** */ // class RedBlackNode static class RedBlackNode<T extends Comparable<T>> { /** * Possible color for this node */ public static final int BLACK = 0; /** * Possible color for this node */ public static final int RED = 1; // the key of each node public T key; /** * Parent of node */ RedBlackNode<T> parent; /** * Left child */ RedBlackNode<T> left; /** * Right child */ RedBlackNode<T> right; // the number of elements to the left of each node public int numLeft = 0; // the number of elements to the right of each node public int numRight = 0; // the color of a node public int color; RedBlackNode() { color = BLACK; numLeft = 0; numRight = 0; parent = null; left = null; right = null; } // Constructor which sets key to the argument. RedBlackNode(T key) { this(); this.key = key; } }// end class RedBlackNode static class RedBlackTree<T extends Comparable<T>> { // Root initialized to nil. private RedBlackNode<T> nil = new RedBlackNode<T>(); private RedBlackNode<T> root = nil; public RedBlackTree() { root.left = nil; root.right = nil; root.parent = nil; } // @param: X, The node which the lefRotate is to be performed on. // Performs a leftRotate around X. private void leftRotate(RedBlackNode<T> x) { // Call leftRotateFixup() which updates the numLeft // and numRight values. leftRotateFixup(x); // Perform the left rotate as described in the algorithm // in the course text. RedBlackNode<T> y; y = x.right; x.right = y.left; // Check for existence of y.left and make pointer changes if (!isNil(y.left)) { y.left.parent = x; } y.parent = x.parent; // X's parent is nul if (isNil(x.parent)) { root = y; } // X is the left child of it's parent else if (x.parent.left == x) { x.parent.left = y; } // X is the right child of it's parent. else { x.parent.right = y; } // Finish of the leftRotate y.left = x; x.parent = y; }// end leftRotate(RedBlackNode X) // @param: X, The node which the leftRotate is to be performed on. // Updates the numLeft & numRight values affected by leftRotate. private void leftRotateFixup(RedBlackNode x) { // Case 1: Only X, X.right and X.right.right always are not nil. if (isNil(x.left) && isNil(x.right.left)) { x.numLeft = 0; x.numRight = 0; x.right.numLeft = 1; } // Case 2: X.right.left also exists in addition to Case 1 else if (isNil(x.left) && !isNil(x.right.left)) { x.numLeft = 0; x.numRight = 1 + x.right.left.numLeft + x.right.left.numRight; x.right.numLeft = 2 + x.right.left.numLeft + x.right.left.numRight; } // Case 3: X.left also exists in addition to Case 1 else if (!isNil(x.left) && isNil(x.right.left)) { x.numRight = 0; x.right.numLeft = 2 + x.left.numLeft + x.left.numRight; } // Case 4: X.left and X.right.left both exist in addtion to Case 1 else { x.numRight = 1 + x.right.left.numLeft + x.right.left.numRight; x.right.numLeft = 3 + x.left.numLeft + x.left.numRight + x.right.left.numLeft + x.right.left.numRight; } }// end leftRotateFixup(RedBlackNode X) // @param: X, The node which the rightRotate is to be performed on. // Updates the numLeft and numRight values affected by the Rotate. private void rightRotate(RedBlackNode<T> y) { // Call rightRotateFixup to adjust numRight and numLeft values rightRotateFixup(y); // Perform the rotate as described in the course text. RedBlackNode<T> x = y.left; y.left = x.right; // Check for existence of X.right if (!isNil(x.right)) { x.right.parent = y; } x.parent = y.parent; // y.parent is nil if (isNil(y.parent)) { root = x; } // y is a right child of it's parent. else if (y.parent.right == y) { y.parent.right = x; } // y is a left child of it's parent. else { y.parent.left = x; } x.right = y; y.parent = x; }// end rightRotate(RedBlackNode y) // @param: y, the node around which the righRotate is to be performed. // Updates the numLeft and numRight values affected by the rotate private void rightRotateFixup(RedBlackNode y) { // Case 1: Only y, y.left and y.left.left exists. if (isNil(y.right) && isNil(y.left.right)) { y.numRight = 0; y.numLeft = 0; y.left.numRight = 1; } // Case 2: y.left.right also exists in addition to Case 1 else if (isNil(y.right) && !isNil(y.left.right)) { y.numRight = 0; y.numLeft = 1 + y.left.right.numRight + y.left.right.numLeft; y.left.numRight = 2 + y.left.right.numRight + y.left.right.numLeft; } // Case 3: y.right also exists in addition to Case 1 else if (!isNil(y.right) && isNil(y.left.right)) { y.numLeft = 0; y.left.numRight = 2 + y.right.numRight + y.right.numLeft; } // Case 4: y.right & y.left.right exist in addition to Case 1 else { y.numLeft = 1 + y.left.right.numRight + y.left.right.numLeft; y.left.numRight = 3 + y.right.numRight + y.right.numLeft + y.left.right.numRight + y.left.right.numLeft; } }// end rightRotateFixup(RedBlackNode y) public void insert(T key) { insert(new RedBlackNode<T>(key)); } // @param: z, the node to be inserted into the Tree rooted at root // Inserts z into the appropriate position in the RedBlackTree while // updating numLeft and numRight values. private void insert(RedBlackNode<T> z) { // Create a reference to root & initialize a node to nil RedBlackNode<T> y = nil; RedBlackNode<T> x = root; // While we haven't reached a the end of the tree keep // tryint to figure out where z should go while (!isNil(x)) { y = x; // if z.key is < than the current key, go left if (z.key.compareTo(x.key) < 0) { // Update X.numLeft as z is < than X x.numLeft++; x = x.left; } // else z.key >= X.key so go right. else { // Update X.numGreater as z is => X x.numRight++; x = x.right; } } // y will hold z's parent z.parent = y; // Depending on the value of y.key, put z as the left or // right child of y if (isNil(y)) { root = z; } else if (z.key.compareTo(y.key) < 0) { y.left = z; } else { y.right = z; } // Initialize z's children to nil and z's color to red z.left = nil; z.right = nil; z.color = RedBlackNode.RED; // Call insertFixup(z) insertFixup(z); }// end insert(RedBlackNode z) // @param: z, the node which was inserted and may have caused a violation // of the RedBlackTree properties // Fixes up the violation of the RedBlackTree properties that may have // been caused during insert(z) private void insertFixup(RedBlackNode<T> z) { RedBlackNode<T> y = nil; // While there is a violation of the RedBlackTree properties.. while (z.parent.color == RedBlackNode.RED) { // If z's parent is the the left child of it's parent. if (z.parent == z.parent.parent.left) { // Initialize y to z 's cousin y = z.parent.parent.right; // Case 1: if y is red...recolor if (y.color == RedBlackNode.RED) { z.parent.color = RedBlackNode.BLACK; y.color = RedBlackNode.BLACK; z.parent.parent.color = RedBlackNode.RED; z = z.parent.parent; } // Case 2: if y is black & z is a right child else if (z == z.parent.right) { // leftRotaet around z's parent z = z.parent; leftRotate(z); } // Case 3: else y is black & z is a left child else { // recolor and rotate round z's grandpa z.parent.color = RedBlackNode.BLACK; z.parent.parent.color = RedBlackNode.RED; rightRotate(z.parent.parent); } } // If z's parent is the right child of it's parent. else { // Initialize y to z's cousin y = z.parent.parent.left; // Case 1: if y is red...recolor if (y.color == RedBlackNode.RED) { z.parent.color = RedBlackNode.BLACK; y.color = RedBlackNode.BLACK; z.parent.parent.color = RedBlackNode.RED; z = z.parent.parent; } // Case 2: if y is black and z is a left child else if (z == z.parent.left) { // rightRotate around z's parent z = z.parent; rightRotate(z); } // Case 3: if y is black and z is a right child else { // recolor and rotate around z's grandpa z.parent.color = RedBlackNode.BLACK; z.parent.parent.color = RedBlackNode.RED; leftRotate(z.parent.parent); } } } // Color root black at all times root.color = RedBlackNode.BLACK; }// end insertFixup(RedBlackNode z) // @param: node, a RedBlackNode // @param: node, the node with the smallest key rooted at node public RedBlackNode<T> treeMinimum(RedBlackNode<T> node) { // while there is a smaller key, keep going left while (!isNil(node.left)) { node = node.left; } return node; }// end treeMinimum(RedBlackNode node) // @param: X, a RedBlackNode whose successor we must find // @return: return's the node the with the next largest key // from X.key public RedBlackNode<T> treeSuccessor(RedBlackNode<T> x) { // if X.left is not nil, call treeMinimum(X.right) and // return it's value if (!isNil(x.left)) { return treeMinimum(x.right); } RedBlackNode<T> y = x.parent; // while X is it's parent's right child... while (!isNil(y) && x == y.right) { // Keep moving up in the tree x = y; y = y.parent; } // Return successor return y; }// end treeMinimum(RedBlackNode X) // @param: z, the RedBlackNode which is to be removed from the the tree // Remove's z from the RedBlackTree rooted at root public void remove(RedBlackNode<T> v) { RedBlackNode<T> z = search(v.key); // Declare variables RedBlackNode<T> x = nil; RedBlackNode<T> y = nil; // if either one of z's children is nil, then we must remove z if (isNil(z.left) || isNil(z.right)) { y = z; } // else we must remove the successor of z else { y = treeSuccessor(z); } // Let X be the left or right child of y (y can only have one child) if (!isNil(y.left)) { x = y.left; } else { x = y.right; } // link X's parent to y's parent x.parent = y.parent; // If y's parent is nil, then X is the root if (isNil(y.parent)) { root = x; } // else if y is a left child, set X to be y's left sibling else if (!isNil(y.parent.left) && y.parent.left == y) { y.parent.left = x; } // else if y is a right child, set X to be y's right sibling else if (!isNil(y.parent.right) && y.parent.right == y) { y.parent.right = x; } // if y != z, trasfer y's satellite data into z. if (y != z) { z.key = y.key; } // Update the numLeft and numRight numbers which might need // updating due to the deletion of z.key. fixNodeData(x, y); // If y's color is black, it is a violation of the // RedBlackTree properties so call removeFixup() if (y.color == RedBlackNode.BLACK) { removeFixup(x); } }// end remove(RedBlackNode z) // @param: y, the RedBlackNode which was actually deleted from the tree // @param: key, the value of the key that used to be in y private void fixNodeData(RedBlackNode<T> x, RedBlackNode<T> y) { // Initialize two variables which will help us traverse the tree RedBlackNode<T> current = nil; RedBlackNode<T> track = nil; // if X is nil, then we will start updating at y.parent // Set track to y, y.parent's child if (isNil(x)) { current = y.parent; track = y; } // if X is not nil, then we start updating at X.parent // Set track to X, X.parent's child else { current = x.parent; track = x; } // while we haven't reached the root while (!isNil(current)) { // if the node we deleted has a different key than // the current node if (y.key != current.key) { // if the node we deleted is greater than // current.key then decrement current.numRight if (y.key.compareTo(current.key) > 0) { current.numRight--; } // if the node we deleted is less than // current.key thendecrement current.numLeft if (y.key.compareTo(current.key) < 0) { current.numLeft--; } } // if the node we deleted has the same key as the // current node we are checking else { // the cases where the current node has any nil // children and update appropriately if (isNil(current.left)) { current.numLeft--; } else if (isNil(current.right)) { current.numRight--; } // the cases where current has two children and // we must determine whether track is it's left // or right child and update appropriately else if (track == current.right) { current.numRight--; } else if (track == current.left) { current.numLeft--; } } // update track and current track = current; current = current.parent; } }//end fixNodeData() // @param: X, the child of the deleted node from remove(RedBlackNode v) // Restores the Red Black properties that may have been violated during // the removal of a node in remove(RedBlackNode v) private void removeFixup(RedBlackNode<T> x) { RedBlackNode<T> w; // While we haven't fixed the tree completely... while (x != root && x.color == RedBlackNode.BLACK) { // if X is it's parent's left child if (x == x.parent.left) { // set w = X's sibling w = x.parent.right; // Case 1, w's color is red. if (w.color == RedBlackNode.RED) { w.color = RedBlackNode.BLACK; x.parent.color = RedBlackNode.RED; leftRotate(x.parent); w = x.parent.right; } // Case 2, both of w's children are black if (w.left.color == RedBlackNode.BLACK && w.right.color == RedBlackNode.BLACK) { w.color = RedBlackNode.RED; x = x.parent; } // Case 3 / Case 4 else { // Case 3, w's right child is black if (w.right.color == RedBlackNode.BLACK) { w.left.color = RedBlackNode.BLACK; w.color = RedBlackNode.RED; rightRotate(w); w = x.parent.right; } // Case 4, w = black, w.right = red w.color = x.parent.color; x.parent.color = RedBlackNode.BLACK; w.right.color = RedBlackNode.BLACK; leftRotate(x.parent); x = root; } } // if X is it's parent's right child else { // set w to X's sibling w = x.parent.left; // Case 1, w's color is red if (w.color == RedBlackNode.RED) { w.color = RedBlackNode.BLACK; x.parent.color = RedBlackNode.RED; rightRotate(x.parent); w = x.parent.left; } // Case 2, both of w's children are black if (w.right.color == RedBlackNode.BLACK && w.left.color == RedBlackNode.BLACK) { w.color = RedBlackNode.RED; x = x.parent; } // Case 3 / Case 4 else { // Case 3, w's left child is black if (w.left.color == RedBlackNode.BLACK) { w.right.color = RedBlackNode.BLACK; w.color = RedBlackNode.RED; leftRotate(w); w = x.parent.left; } // Case 4, w = black, and w.left = red w.color = x.parent.color; x.parent.color = RedBlackNode.BLACK; w.left.color = RedBlackNode.BLACK; rightRotate(x.parent); x = root; } } }// end while // set X to black to ensure there is no violation of // RedBlack tree Properties x.color = RedBlackNode.BLACK; }// end removeFixup(RedBlackNode X) // @param: key, the key whose node we want to search for // @return: returns a node with the key, key, if not found, returns null // Searches for a node with key k and returns the first such node, if no // such node is found returns null public RedBlackNode<T> search(T key) { // Initialize a pointer to the root to traverse the tree RedBlackNode<T> current = root; // While we haven't reached the end of the tree while (!isNil(current)) { // If we have found a node with a key equal to key if (current.key.equals(key)) // return that node and exit search(int) { return current; } // go left or right based on value of current and key else if (current.key.compareTo(key) < 0) { current = current.right; } // go left or right based on value of current and key else { current = current.left; } } // we have not found a node whose key is "key" return null; }// end search(int key) // @param: key, any Comparable object // @return: return's the number of elements greater than key public int numGreater(T key) { // Call findNumGreater(root, key) which will return the number // of nodes whose key is greater than key return findNumGreater(root, key); }// end numGreater(int key) // @param: key, any Comparable object // @return: return's teh number of elements smaller than key public int numSmaller(T key) { // Call findNumSmaller(root,key) which will return // the number of nodes whose key is greater than key return findNumSmaller(root, key); }// end numSmaller(int key) // @param: node, the root of the tree, the key who we must // compare other node key's to. // @return: the number of nodes greater than key. public int findNumGreater(RedBlackNode<T> node, T key) { // Base Case: if node is nil, return 0 if (isNil(node)) { return 0; } // If key is less than node.key, all elements right of node are // greater than key, add this to our total and look to the left else if (key.compareTo(node.key) < 0) { return 1 + node.numRight + findNumGreater(node.left, key); } // If key is greater than node.key, then look to the right as // all elements to the left of node are smaller than key else { return findNumGreater(node.right, key); } }// end findNumGreater(RedBlackNode, int key) /** * Returns sorted list of keys greater than key. Size of list will not * exceed maxReturned * * @param key Key to search for * @param maxReturned Maximum number of results to return * @return List of keys greater than key. List may not exceed * maxReturned */ public List<T> getGreaterThan(T key, Integer maxReturned) { List<T> list = new ArrayList<T>(); getGreaterThan(root, key, list); return list.subList(0, Math.min(maxReturned, list.size())); } private void getGreaterThan(RedBlackNode<T> node, T key, List<T> list) { if (isNil(node)) { return; } else if (node.key.compareTo(key) > 0) { getGreaterThan(node.left, key, list); list.add(node.key); getGreaterThan(node.right, key, list); } else { getGreaterThan(node.right, key, list); } } // @param: node, the root of the tree, the key who we must compare other // node key's to. // @return: the number of nodes smaller than key. public int findNumSmaller(RedBlackNode<T> node, T key) { // Base Case: if node is nil, return 0 if (isNil(node)) { return 0; } // If key is less than node.key, look to the left as all // elements on the right of node are greater than key else if (key.compareTo(node.key) <= 0) { return findNumSmaller(node.left, key); } // If key is larger than node.key, all elements to the left of // node are smaller than key, add this to our total and look // to the right. else { return 1 + node.numLeft + findNumSmaller(node.right, key); } }// end findNumSmaller(RedBlackNode nod, int key) // @param: node, the RedBlackNode we must check to see whether it's nil // @return: return's true of node is nil and false otherwise private boolean isNil(RedBlackNode node) { // return appropriate value return node == nil; }// end isNil(RedBlackNode node) // @return: return's the size of the tree // Return's the # of nodes including the root which the RedBlackTree // rooted at root has. public int size() { // Return the number of nodes to the root's left + the number of // nodes on the root's right + the root itself. return root.numLeft + root.numRight + 1; }// end size() }// end class RedBlackTree }
Java
["5 3\nabbbc\nabc", "5 2\naaaaa\naa", "5 5\nabcdf\nabcdf", "2 2\nab\nab"]
2 seconds
["3", "4", "1", "1"]
NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.
Java 17
standard input
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
17fff01f943ad467ceca5dce5b962169
The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.
1,500
Output one integer — the maximum width of a beautiful sequence.
standard output
PASSED
acf1d2f97a9afa6edf03c9d37ec09968
train_109.jsonl
1614071100
You have a deck of $$$n$$$ cards, and you'd like to reorder it to a new one.Each card has a value between $$$1$$$ and $$$n$$$ equal to $$$p_i$$$. All $$$p_i$$$ are pairwise distinct. Cards in a deck are numbered from bottom to top, i. e. $$$p_1$$$ stands for the bottom card, $$$p_n$$$ is the top card. In each step you pick some integer $$$k &gt; 0$$$, take the top $$$k$$$ cards from the original deck and place them, in the order they are now, on top of the new deck. You perform this operation until the original deck is empty. (Refer to the notes section for the better understanding.)Let's define an order of a deck as $$$\sum\limits_{i = 1}^{n}{n^{n - i} \cdot p_i}$$$.Given the original deck, output the deck with maximum possible order you can make using the operation above.
512 megabytes
import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashMap; public class CardDeck { public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int t = Integer.parseInt(br.readLine()); while(t-->0) { int n = Integer.parseInt(br.readLine()); String input[] = br.readLine().split(" "); int deck[] = new int[n]; HashMap<Integer,Integer> map = new HashMap<Integer,Integer>(); for(int i=0;i<n;i++) { deck[i] = Integer.parseInt(input[i]); map.put(deck[i],i); } int l = n; for(int i=n;i>0;i--) { int index = map.get(i); if(l>index) { for(int j=index; j<l;j++) out.print(deck[j]+" "); l=index; } } out.println(); } out.close(); } }
Java
["4\n4\n1 2 3 4\n5\n1 5 2 4 3\n6\n4 2 5 3 6 1\n1\n1"]
1 second
["4 3 2 1\n5 2 4 3 1\n6 1 5 3 4 2\n1"]
NoteIn the first test case, one of the optimal strategies is the next one: take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1, 2, 3]$$$, $$$p'$$$ becomes $$$[4]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1, 2]$$$, $$$p'$$$ becomes $$$[4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[4, 3, 2]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[4, 3, 2, 1]$$$. In result, $$$p'$$$ has order equal to $$$4^3 \cdot 4 + 4^2 \cdot 3 + 4^1 \cdot 2 + 4^0 \cdot 1$$$ $$$=$$$ $$$256 + 48 + 8 + 1 = 313$$$.In the second test case, one of the optimal strategies is: take $$$4$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[5, 2, 4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[5, 2, 4, 3, 1]$$$; In result, $$$p'$$$ has order equal to $$$5^4 \cdot 5 + 5^3 \cdot 2 + 5^2 \cdot 4 + 5^1 \cdot 3 + 5^0 \cdot 1$$$ $$$=$$$ $$$3125 + 250 + 100 + 15 + 1 = 3491$$$.In the third test case, one of the optimal strategies is: take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2, 5, 3]$$$, $$$p'$$$ becomes $$$[6, 1]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2]$$$, $$$p'$$$ becomes $$$[6, 1, 5, 3]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[6, 1, 5, 3, 4, 2]$$$. In result, $$$p'$$$ has order equal to $$$6^5 \cdot 6 + 6^4 \cdot 1 + 6^3 \cdot 5 + 6^2 \cdot 3 + 6^1 \cdot 4 + 6^0 \cdot 2$$$ $$$=$$$ $$$46656 + 1296 + 1080 + 108 + 24 + 2 = 49166$$$.
Java 8
standard input
[ "data structures", "greedy", "math" ]
1637670255f8bd82a01e2ab20cdcc9aa
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the size of deck you have. The second line contains $$$n$$$ integers $$$p_1, p_2,\dots, p_n$$$ ($$$1 \le p_i \le n$$$; $$$p_i \neq p_j$$$ if $$$i \neq j$$$) — values of card in the deck from bottom to top. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,100
For each test case print the deck with maximum possible order. Print values of cards in the deck from bottom to top. If there are multiple answers, print any of them.
standard output
PASSED
9b98aa24fbb982a3fed25deff5a0cd96
train_109.jsonl
1614071100
You have a deck of $$$n$$$ cards, and you'd like to reorder it to a new one.Each card has a value between $$$1$$$ and $$$n$$$ equal to $$$p_i$$$. All $$$p_i$$$ are pairwise distinct. Cards in a deck are numbered from bottom to top, i. e. $$$p_1$$$ stands for the bottom card, $$$p_n$$$ is the top card. In each step you pick some integer $$$k &gt; 0$$$, take the top $$$k$$$ cards from the original deck and place them, in the order they are now, on top of the new deck. You perform this operation until the original deck is empty. (Refer to the notes section for the better understanding.)Let's define an order of a deck as $$$\sum\limits_{i = 1}^{n}{n^{n - i} \cdot p_i}$$$.Given the original deck, output the deck with maximum possible order you can make using the operation above.
512 megabytes
import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; public class CardDeck { public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int t = Integer.parseInt(br.readLine()); while(t-->0) { int n = Integer.parseInt(br.readLine()); String input[] = br.readLine().split(" "); int deck[] = new int[n]; int pos[] = new int[n+1]; for(int i=0;i<n;i++) { deck[i] = Integer.parseInt(input[i]); pos[deck[i]] = i; } int l = n; for(int i=n;i>0;i--) { int index = pos[i]; if(l>index) { for(int j=index; j<l;j++) out.print(deck[j]+" "); l=index; } } out.println(); } out.close(); } }
Java
["4\n4\n1 2 3 4\n5\n1 5 2 4 3\n6\n4 2 5 3 6 1\n1\n1"]
1 second
["4 3 2 1\n5 2 4 3 1\n6 1 5 3 4 2\n1"]
NoteIn the first test case, one of the optimal strategies is the next one: take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1, 2, 3]$$$, $$$p'$$$ becomes $$$[4]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1, 2]$$$, $$$p'$$$ becomes $$$[4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[4, 3, 2]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[4, 3, 2, 1]$$$. In result, $$$p'$$$ has order equal to $$$4^3 \cdot 4 + 4^2 \cdot 3 + 4^1 \cdot 2 + 4^0 \cdot 1$$$ $$$=$$$ $$$256 + 48 + 8 + 1 = 313$$$.In the second test case, one of the optimal strategies is: take $$$4$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[5, 2, 4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[5, 2, 4, 3, 1]$$$; In result, $$$p'$$$ has order equal to $$$5^4 \cdot 5 + 5^3 \cdot 2 + 5^2 \cdot 4 + 5^1 \cdot 3 + 5^0 \cdot 1$$$ $$$=$$$ $$$3125 + 250 + 100 + 15 + 1 = 3491$$$.In the third test case, one of the optimal strategies is: take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2, 5, 3]$$$, $$$p'$$$ becomes $$$[6, 1]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2]$$$, $$$p'$$$ becomes $$$[6, 1, 5, 3]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[6, 1, 5, 3, 4, 2]$$$. In result, $$$p'$$$ has order equal to $$$6^5 \cdot 6 + 6^4 \cdot 1 + 6^3 \cdot 5 + 6^2 \cdot 3 + 6^1 \cdot 4 + 6^0 \cdot 2$$$ $$$=$$$ $$$46656 + 1296 + 1080 + 108 + 24 + 2 = 49166$$$.
Java 8
standard input
[ "data structures", "greedy", "math" ]
1637670255f8bd82a01e2ab20cdcc9aa
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the size of deck you have. The second line contains $$$n$$$ integers $$$p_1, p_2,\dots, p_n$$$ ($$$1 \le p_i \le n$$$; $$$p_i \neq p_j$$$ if $$$i \neq j$$$) — values of card in the deck from bottom to top. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,100
For each test case print the deck with maximum possible order. Print values of cards in the deck from bottom to top. If there are multiple answers, print any of them.
standard output
PASSED
df3f381a2d27989f081e37d4719173f3
train_109.jsonl
1614071100
You have a deck of $$$n$$$ cards, and you'd like to reorder it to a new one.Each card has a value between $$$1$$$ and $$$n$$$ equal to $$$p_i$$$. All $$$p_i$$$ are pairwise distinct. Cards in a deck are numbered from bottom to top, i. e. $$$p_1$$$ stands for the bottom card, $$$p_n$$$ is the top card. In each step you pick some integer $$$k &gt; 0$$$, take the top $$$k$$$ cards from the original deck and place them, in the order they are now, on top of the new deck. You perform this operation until the original deck is empty. (Refer to the notes section for the better understanding.)Let's define an order of a deck as $$$\sum\limits_{i = 1}^{n}{n^{n - i} \cdot p_i}$$$.Given the original deck, output the deck with maximum possible order you can make using the operation above.
512 megabytes
import java.util.*; public class CodeForces704 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for (int i = 0; i<t; i++){ System.out.println(solve(sc)); } } static int[] dp; static String solve(Scanner sc) { int n = sc.nextInt(); int[] p = new int[n]; int[] t = new int[n+1]; for (int i = 0; i<n; i++){ p[i] = sc.nextInt(); t[p[i]] = i; } StringBuilder r = new StringBuilder(""); int start = 0; int end = n; for (int i = n; i>0; i--){ start = t[i]; if (end > start){ for (int j = start; j<end; j++){ r.append(p[j] + " "); } end = start; } } return r.toString(); } }
Java
["4\n4\n1 2 3 4\n5\n1 5 2 4 3\n6\n4 2 5 3 6 1\n1\n1"]
1 second
["4 3 2 1\n5 2 4 3 1\n6 1 5 3 4 2\n1"]
NoteIn the first test case, one of the optimal strategies is the next one: take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1, 2, 3]$$$, $$$p'$$$ becomes $$$[4]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1, 2]$$$, $$$p'$$$ becomes $$$[4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[4, 3, 2]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[4, 3, 2, 1]$$$. In result, $$$p'$$$ has order equal to $$$4^3 \cdot 4 + 4^2 \cdot 3 + 4^1 \cdot 2 + 4^0 \cdot 1$$$ $$$=$$$ $$$256 + 48 + 8 + 1 = 313$$$.In the second test case, one of the optimal strategies is: take $$$4$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[5, 2, 4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[5, 2, 4, 3, 1]$$$; In result, $$$p'$$$ has order equal to $$$5^4 \cdot 5 + 5^3 \cdot 2 + 5^2 \cdot 4 + 5^1 \cdot 3 + 5^0 \cdot 1$$$ $$$=$$$ $$$3125 + 250 + 100 + 15 + 1 = 3491$$$.In the third test case, one of the optimal strategies is: take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2, 5, 3]$$$, $$$p'$$$ becomes $$$[6, 1]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2]$$$, $$$p'$$$ becomes $$$[6, 1, 5, 3]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[6, 1, 5, 3, 4, 2]$$$. In result, $$$p'$$$ has order equal to $$$6^5 \cdot 6 + 6^4 \cdot 1 + 6^3 \cdot 5 + 6^2 \cdot 3 + 6^1 \cdot 4 + 6^0 \cdot 2$$$ $$$=$$$ $$$46656 + 1296 + 1080 + 108 + 24 + 2 = 49166$$$.
Java 8
standard input
[ "data structures", "greedy", "math" ]
1637670255f8bd82a01e2ab20cdcc9aa
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the size of deck you have. The second line contains $$$n$$$ integers $$$p_1, p_2,\dots, p_n$$$ ($$$1 \le p_i \le n$$$; $$$p_i \neq p_j$$$ if $$$i \neq j$$$) — values of card in the deck from bottom to top. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,100
For each test case print the deck with maximum possible order. Print values of cards in the deck from bottom to top. If there are multiple answers, print any of them.
standard output
PASSED
0dc5daa74861772e890e7b8928db8aa3
train_109.jsonl
1614071100
You have a deck of $$$n$$$ cards, and you'd like to reorder it to a new one.Each card has a value between $$$1$$$ and $$$n$$$ equal to $$$p_i$$$. All $$$p_i$$$ are pairwise distinct. Cards in a deck are numbered from bottom to top, i. e. $$$p_1$$$ stands for the bottom card, $$$p_n$$$ is the top card. In each step you pick some integer $$$k &gt; 0$$$, take the top $$$k$$$ cards from the original deck and place them, in the order they are now, on top of the new deck. You perform this operation until the original deck is empty. (Refer to the notes section for the better understanding.)Let's define an order of a deck as $$$\sum\limits_{i = 1}^{n}{n^{n - i} \cdot p_i}$$$.Given the original deck, output the deck with maximum possible order you can make using the operation above.
512 megabytes
// 23-Feb-2021 import java.util.*; import java.io.*; public class Solution { static class FastReader { BufferedReader br; StringTokenizer st; private 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[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArrayOne(int n) { int[] a = new int[n + 1]; for (int i = 1; i < n + 1; i++) a[i] = nextInt(); return a; } long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long[] nextLongArrayOne(int n) { long[] a = new long[n + 1]; for (int i = 1; i < n + 1; 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; } } public static void main(String[] args) { FastReader s = new FastReader(); StringBuilder str = new StringBuilder(); int t = s.nextInt(); while (t-- > 0) { int n = s.nextInt(); int arr[] = s.nextIntArray(n); int i = n - 1; TreeSet<Integer> pq = new TreeSet<>(); for(int num = 1; num <= n; num++) { pq.add(num); } while( i >= 0) { ArrayList<Integer> list = new ArrayList<>(); int max = pq.last(); while(i >= 0) { list.add(arr[i]); pq.remove(arr[i]); if(arr[i] == max) { i--; break; } i--; } for(int k = list.size() - 1; k >= 0; k--) { str.append(list.get(k)+" "); } } str.append("\n"); } System.out.println(str); } }
Java
["4\n4\n1 2 3 4\n5\n1 5 2 4 3\n6\n4 2 5 3 6 1\n1\n1"]
1 second
["4 3 2 1\n5 2 4 3 1\n6 1 5 3 4 2\n1"]
NoteIn the first test case, one of the optimal strategies is the next one: take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1, 2, 3]$$$, $$$p'$$$ becomes $$$[4]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1, 2]$$$, $$$p'$$$ becomes $$$[4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[4, 3, 2]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[4, 3, 2, 1]$$$. In result, $$$p'$$$ has order equal to $$$4^3 \cdot 4 + 4^2 \cdot 3 + 4^1 \cdot 2 + 4^0 \cdot 1$$$ $$$=$$$ $$$256 + 48 + 8 + 1 = 313$$$.In the second test case, one of the optimal strategies is: take $$$4$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[5, 2, 4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[5, 2, 4, 3, 1]$$$; In result, $$$p'$$$ has order equal to $$$5^4 \cdot 5 + 5^3 \cdot 2 + 5^2 \cdot 4 + 5^1 \cdot 3 + 5^0 \cdot 1$$$ $$$=$$$ $$$3125 + 250 + 100 + 15 + 1 = 3491$$$.In the third test case, one of the optimal strategies is: take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2, 5, 3]$$$, $$$p'$$$ becomes $$$[6, 1]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2]$$$, $$$p'$$$ becomes $$$[6, 1, 5, 3]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[6, 1, 5, 3, 4, 2]$$$. In result, $$$p'$$$ has order equal to $$$6^5 \cdot 6 + 6^4 \cdot 1 + 6^3 \cdot 5 + 6^2 \cdot 3 + 6^1 \cdot 4 + 6^0 \cdot 2$$$ $$$=$$$ $$$46656 + 1296 + 1080 + 108 + 24 + 2 = 49166$$$.
Java 8
standard input
[ "data structures", "greedy", "math" ]
1637670255f8bd82a01e2ab20cdcc9aa
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the size of deck you have. The second line contains $$$n$$$ integers $$$p_1, p_2,\dots, p_n$$$ ($$$1 \le p_i \le n$$$; $$$p_i \neq p_j$$$ if $$$i \neq j$$$) — values of card in the deck from bottom to top. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,100
For each test case print the deck with maximum possible order. Print values of cards in the deck from bottom to top. If there are multiple answers, print any of them.
standard output
PASSED
e412c1b54a6e688f8573c76f99a387bc
train_109.jsonl
1614071100
You have a deck of $$$n$$$ cards, and you'd like to reorder it to a new one.Each card has a value between $$$1$$$ and $$$n$$$ equal to $$$p_i$$$. All $$$p_i$$$ are pairwise distinct. Cards in a deck are numbered from bottom to top, i. e. $$$p_1$$$ stands for the bottom card, $$$p_n$$$ is the top card. In each step you pick some integer $$$k &gt; 0$$$, take the top $$$k$$$ cards from the original deck and place them, in the order they are now, on top of the new deck. You perform this operation until the original deck is empty. (Refer to the notes section for the better understanding.)Let's define an order of a deck as $$$\sum\limits_{i = 1}^{n}{n^{n - i} \cdot p_i}$$$.Given the original deck, output the deck with maximum possible order you can make using the operation above.
512 megabytes
// 23-Feb-2021 import java.util.*; import java.io.*; public class Solution { static class FastReader { BufferedReader br; StringTokenizer st; private 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[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArrayOne(int n) { int[] a = new int[n + 1]; for (int i = 1; i < n + 1; i++) a[i] = nextInt(); return a; } long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long[] nextLongArrayOne(int n) { long[] a = new long[n + 1]; for (int i = 1; i < n + 1; 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; } } public static void main(String[] args) { FastReader s = new FastReader(); StringBuilder str = new StringBuilder(); int t = s.nextInt(); while (t-- > 0) { int n = s.nextInt(); int arr[] = new int[n]; TreeSet<Integer> pq = new TreeSet<>(); for(int j = 0; j < n; j++) { arr[j] = s.nextInt(); pq.add(j + 1); } int i = n - 1; while(!pq.isEmpty()) { ArrayList<Integer> list = new ArrayList<>(); int max = pq.last(); while(arr[i] != max) { list.add(arr[i]); i--; } list.add(arr[i--]); for(int k = list.size() - 1; k >= 0; k--) { str.append(list.get(k)+" "); pq.remove(list.get(k)); } } str.append("\n"); } System.out.println(str); } }
Java
["4\n4\n1 2 3 4\n5\n1 5 2 4 3\n6\n4 2 5 3 6 1\n1\n1"]
1 second
["4 3 2 1\n5 2 4 3 1\n6 1 5 3 4 2\n1"]
NoteIn the first test case, one of the optimal strategies is the next one: take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1, 2, 3]$$$, $$$p'$$$ becomes $$$[4]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1, 2]$$$, $$$p'$$$ becomes $$$[4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[4, 3, 2]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[4, 3, 2, 1]$$$. In result, $$$p'$$$ has order equal to $$$4^3 \cdot 4 + 4^2 \cdot 3 + 4^1 \cdot 2 + 4^0 \cdot 1$$$ $$$=$$$ $$$256 + 48 + 8 + 1 = 313$$$.In the second test case, one of the optimal strategies is: take $$$4$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[5, 2, 4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[5, 2, 4, 3, 1]$$$; In result, $$$p'$$$ has order equal to $$$5^4 \cdot 5 + 5^3 \cdot 2 + 5^2 \cdot 4 + 5^1 \cdot 3 + 5^0 \cdot 1$$$ $$$=$$$ $$$3125 + 250 + 100 + 15 + 1 = 3491$$$.In the third test case, one of the optimal strategies is: take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2, 5, 3]$$$, $$$p'$$$ becomes $$$[6, 1]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2]$$$, $$$p'$$$ becomes $$$[6, 1, 5, 3]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[6, 1, 5, 3, 4, 2]$$$. In result, $$$p'$$$ has order equal to $$$6^5 \cdot 6 + 6^4 \cdot 1 + 6^3 \cdot 5 + 6^2 \cdot 3 + 6^1 \cdot 4 + 6^0 \cdot 2$$$ $$$=$$$ $$$46656 + 1296 + 1080 + 108 + 24 + 2 = 49166$$$.
Java 8
standard input
[ "data structures", "greedy", "math" ]
1637670255f8bd82a01e2ab20cdcc9aa
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the size of deck you have. The second line contains $$$n$$$ integers $$$p_1, p_2,\dots, p_n$$$ ($$$1 \le p_i \le n$$$; $$$p_i \neq p_j$$$ if $$$i \neq j$$$) — values of card in the deck from bottom to top. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,100
For each test case print the deck with maximum possible order. Print values of cards in the deck from bottom to top. If there are multiple answers, print any of them.
standard output
PASSED
c2ccac16544d485a1db79dc30e8ebc5b
train_109.jsonl
1614071100
You have a deck of $$$n$$$ cards, and you'd like to reorder it to a new one.Each card has a value between $$$1$$$ and $$$n$$$ equal to $$$p_i$$$. All $$$p_i$$$ are pairwise distinct. Cards in a deck are numbered from bottom to top, i. e. $$$p_1$$$ stands for the bottom card, $$$p_n$$$ is the top card. In each step you pick some integer $$$k &gt; 0$$$, take the top $$$k$$$ cards from the original deck and place them, in the order they are now, on top of the new deck. You perform this operation until the original deck is empty. (Refer to the notes section for the better understanding.)Let's define an order of a deck as $$$\sum\limits_{i = 1}^{n}{n^{n - i} \cdot p_i}$$$.Given the original deck, output the deck with maximum possible order you can make using the operation above.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.*; public class contest704_B { public static void main(String[] args) throws IOException { BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); int test = Integer.parseInt(read.readLine()); while (test-- > 0) { int n = Integer.parseInt(read.readLine()); int[] arr = new int[n]; int[] cs = new int[n+1]; String[] str = read.readLine().split(" "); boolean[] isVis = new boolean[n+1]; for (int i = 0; i <n ; i++) { cs[arr[i]=Integer.parseInt(str[i])]=i; } cs[0]=-1; StringBuilder sb = new StringBuilder(); int prefMaxIndex = n; for (int k = n; k >0 ; k--) { if(!isVis[k]) { for (int i = cs[k]; i <prefMaxIndex ; i++) { sb.append(arr[i]).append(" "); isVis[arr[i]]=true; } prefMaxIndex=cs[k]; } } System.out.println(sb.toString()); } } }
Java
["4\n4\n1 2 3 4\n5\n1 5 2 4 3\n6\n4 2 5 3 6 1\n1\n1"]
1 second
["4 3 2 1\n5 2 4 3 1\n6 1 5 3 4 2\n1"]
NoteIn the first test case, one of the optimal strategies is the next one: take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1, 2, 3]$$$, $$$p'$$$ becomes $$$[4]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1, 2]$$$, $$$p'$$$ becomes $$$[4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[4, 3, 2]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[4, 3, 2, 1]$$$. In result, $$$p'$$$ has order equal to $$$4^3 \cdot 4 + 4^2 \cdot 3 + 4^1 \cdot 2 + 4^0 \cdot 1$$$ $$$=$$$ $$$256 + 48 + 8 + 1 = 313$$$.In the second test case, one of the optimal strategies is: take $$$4$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[5, 2, 4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[5, 2, 4, 3, 1]$$$; In result, $$$p'$$$ has order equal to $$$5^4 \cdot 5 + 5^3 \cdot 2 + 5^2 \cdot 4 + 5^1 \cdot 3 + 5^0 \cdot 1$$$ $$$=$$$ $$$3125 + 250 + 100 + 15 + 1 = 3491$$$.In the third test case, one of the optimal strategies is: take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2, 5, 3]$$$, $$$p'$$$ becomes $$$[6, 1]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2]$$$, $$$p'$$$ becomes $$$[6, 1, 5, 3]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[6, 1, 5, 3, 4, 2]$$$. In result, $$$p'$$$ has order equal to $$$6^5 \cdot 6 + 6^4 \cdot 1 + 6^3 \cdot 5 + 6^2 \cdot 3 + 6^1 \cdot 4 + 6^0 \cdot 2$$$ $$$=$$$ $$$46656 + 1296 + 1080 + 108 + 24 + 2 = 49166$$$.
Java 8
standard input
[ "data structures", "greedy", "math" ]
1637670255f8bd82a01e2ab20cdcc9aa
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the size of deck you have. The second line contains $$$n$$$ integers $$$p_1, p_2,\dots, p_n$$$ ($$$1 \le p_i \le n$$$; $$$p_i \neq p_j$$$ if $$$i \neq j$$$) — values of card in the deck from bottom to top. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,100
For each test case print the deck with maximum possible order. Print values of cards in the deck from bottom to top. If there are multiple answers, print any of them.
standard output
PASSED
1b3e7af56b5d54a3894750f20784bc21
train_109.jsonl
1614071100
You have a deck of $$$n$$$ cards, and you'd like to reorder it to a new one.Each card has a value between $$$1$$$ and $$$n$$$ equal to $$$p_i$$$. All $$$p_i$$$ are pairwise distinct. Cards in a deck are numbered from bottom to top, i. e. $$$p_1$$$ stands for the bottom card, $$$p_n$$$ is the top card. In each step you pick some integer $$$k &gt; 0$$$, take the top $$$k$$$ cards from the original deck and place them, in the order they are now, on top of the new deck. You perform this operation until the original deck is empty. (Refer to the notes section for the better understanding.)Let's define an order of a deck as $$$\sum\limits_{i = 1}^{n}{n^{n - i} \cdot p_i}$$$.Given the original deck, output the deck with maximum possible order you can make using the operation above.
512 megabytes
import java.util.Scanner; public class cf1492B { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int t = scan.nextInt(); int n = 0; int k = 0; int[] a,b; StringBuilder sb = new StringBuilder(); while(t-->0){ n = scan.nextInt(); a = new int[n]; b = new int[n]; int mx = Integer.MIN_VALUE; for(int i=0;i<n;i++){ a[i] = scan.nextInt(); } for(int i=0;i<n;i++){ if(a[i]>mx){ mx = a[i]; k = i; } b[i] = k; } int l = n-1; while(l>=0){ int z = b[l]; for(int i=z;i<=l;i++){ sb.append(a[i]+" "); } l = z-1; } sb.append("\n"); } System.out.println(sb); } }
Java
["4\n4\n1 2 3 4\n5\n1 5 2 4 3\n6\n4 2 5 3 6 1\n1\n1"]
1 second
["4 3 2 1\n5 2 4 3 1\n6 1 5 3 4 2\n1"]
NoteIn the first test case, one of the optimal strategies is the next one: take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1, 2, 3]$$$, $$$p'$$$ becomes $$$[4]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1, 2]$$$, $$$p'$$$ becomes $$$[4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[4, 3, 2]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[4, 3, 2, 1]$$$. In result, $$$p'$$$ has order equal to $$$4^3 \cdot 4 + 4^2 \cdot 3 + 4^1 \cdot 2 + 4^0 \cdot 1$$$ $$$=$$$ $$$256 + 48 + 8 + 1 = 313$$$.In the second test case, one of the optimal strategies is: take $$$4$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[5, 2, 4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[5, 2, 4, 3, 1]$$$; In result, $$$p'$$$ has order equal to $$$5^4 \cdot 5 + 5^3 \cdot 2 + 5^2 \cdot 4 + 5^1 \cdot 3 + 5^0 \cdot 1$$$ $$$=$$$ $$$3125 + 250 + 100 + 15 + 1 = 3491$$$.In the third test case, one of the optimal strategies is: take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2, 5, 3]$$$, $$$p'$$$ becomes $$$[6, 1]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2]$$$, $$$p'$$$ becomes $$$[6, 1, 5, 3]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[6, 1, 5, 3, 4, 2]$$$. In result, $$$p'$$$ has order equal to $$$6^5 \cdot 6 + 6^4 \cdot 1 + 6^3 \cdot 5 + 6^2 \cdot 3 + 6^1 \cdot 4 + 6^0 \cdot 2$$$ $$$=$$$ $$$46656 + 1296 + 1080 + 108 + 24 + 2 = 49166$$$.
Java 8
standard input
[ "data structures", "greedy", "math" ]
1637670255f8bd82a01e2ab20cdcc9aa
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the size of deck you have. The second line contains $$$n$$$ integers $$$p_1, p_2,\dots, p_n$$$ ($$$1 \le p_i \le n$$$; $$$p_i \neq p_j$$$ if $$$i \neq j$$$) — values of card in the deck from bottom to top. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,100
For each test case print the deck with maximum possible order. Print values of cards in the deck from bottom to top. If there are multiple answers, print any of them.
standard output
PASSED
6c796ecd8033ceaa84a87d919eef6e63
train_109.jsonl
1614071100
You have a deck of $$$n$$$ cards, and you'd like to reorder it to a new one.Each card has a value between $$$1$$$ and $$$n$$$ equal to $$$p_i$$$. All $$$p_i$$$ are pairwise distinct. Cards in a deck are numbered from bottom to top, i. e. $$$p_1$$$ stands for the bottom card, $$$p_n$$$ is the top card. In each step you pick some integer $$$k &gt; 0$$$, take the top $$$k$$$ cards from the original deck and place them, in the order they are now, on top of the new deck. You perform this operation until the original deck is empty. (Refer to the notes section for the better understanding.)Let's define an order of a deck as $$$\sum\limits_{i = 1}^{n}{n^{n - i} \cdot p_i}$$$.Given the original deck, output the deck with maximum possible order you can make using the operation above.
512 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; public class Main { static List<Integer> list = new ArrayList<>(); static StringBuilder ans; static boolean[] V; static int mv; static StringBuilder sb = new StringBuilder(""); public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine()); StringTokenizer st; for(int t = 0; t < T; t++) { list.clear(); ans = new StringBuilder(""); int N = Integer.parseInt(br.readLine()); V = new boolean[N + 1]; V[0] = true; mv = N; st = new StringTokenizer(br.readLine(), " "); for(int i = 0; i < N; i++) list.add(Integer.parseInt(st.nextToken())); search(0, N); sb.append(ans + "\n"); } System.out.println(sb.toString()); } public static void search(int start, int end) { if(end - start == 0) return; int maxi = 0; for(int i = end - 1; i >= start; i--) { int size = list.get(i); V[size] = true; if(mv == size) { maxi = i; break; } } for(int i = mv - 1; i > 0; i--) { if(!V[i]) { mv = i; break; } } for(int i = maxi; i < end; i++) ans.append(list.get(i) + " "); search(0, maxi); } }
Java
["4\n4\n1 2 3 4\n5\n1 5 2 4 3\n6\n4 2 5 3 6 1\n1\n1"]
1 second
["4 3 2 1\n5 2 4 3 1\n6 1 5 3 4 2\n1"]
NoteIn the first test case, one of the optimal strategies is the next one: take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1, 2, 3]$$$, $$$p'$$$ becomes $$$[4]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1, 2]$$$, $$$p'$$$ becomes $$$[4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[4, 3, 2]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[4, 3, 2, 1]$$$. In result, $$$p'$$$ has order equal to $$$4^3 \cdot 4 + 4^2 \cdot 3 + 4^1 \cdot 2 + 4^0 \cdot 1$$$ $$$=$$$ $$$256 + 48 + 8 + 1 = 313$$$.In the second test case, one of the optimal strategies is: take $$$4$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[5, 2, 4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[5, 2, 4, 3, 1]$$$; In result, $$$p'$$$ has order equal to $$$5^4 \cdot 5 + 5^3 \cdot 2 + 5^2 \cdot 4 + 5^1 \cdot 3 + 5^0 \cdot 1$$$ $$$=$$$ $$$3125 + 250 + 100 + 15 + 1 = 3491$$$.In the third test case, one of the optimal strategies is: take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2, 5, 3]$$$, $$$p'$$$ becomes $$$[6, 1]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2]$$$, $$$p'$$$ becomes $$$[6, 1, 5, 3]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[6, 1, 5, 3, 4, 2]$$$. In result, $$$p'$$$ has order equal to $$$6^5 \cdot 6 + 6^4 \cdot 1 + 6^3 \cdot 5 + 6^2 \cdot 3 + 6^1 \cdot 4 + 6^0 \cdot 2$$$ $$$=$$$ $$$46656 + 1296 + 1080 + 108 + 24 + 2 = 49166$$$.
Java 8
standard input
[ "data structures", "greedy", "math" ]
1637670255f8bd82a01e2ab20cdcc9aa
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the size of deck you have. The second line contains $$$n$$$ integers $$$p_1, p_2,\dots, p_n$$$ ($$$1 \le p_i \le n$$$; $$$p_i \neq p_j$$$ if $$$i \neq j$$$) — values of card in the deck from bottom to top. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,100
For each test case print the deck with maximum possible order. Print values of cards in the deck from bottom to top. If there are multiple answers, print any of them.
standard output
PASSED
1e2ddb6f570849e91abb76a5509044bb
train_109.jsonl
1614071100
You have a deck of $$$n$$$ cards, and you'd like to reorder it to a new one.Each card has a value between $$$1$$$ and $$$n$$$ equal to $$$p_i$$$. All $$$p_i$$$ are pairwise distinct. Cards in a deck are numbered from bottom to top, i. e. $$$p_1$$$ stands for the bottom card, $$$p_n$$$ is the top card. In each step you pick some integer $$$k &gt; 0$$$, take the top $$$k$$$ cards from the original deck and place them, in the order they are now, on top of the new deck. You perform this operation until the original deck is empty. (Refer to the notes section for the better understanding.)Let's define an order of a deck as $$$\sum\limits_{i = 1}^{n}{n^{n - i} \cdot p_i}$$$.Given the original deck, output the deck with maximum possible order you can make using the operation above.
512 megabytes
//package com.math; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.LinkedList; import java.util.StringTokenizer; public class CardDeck { public void solve(){ FastScanner in = new FastScanner(System.in); int t = in.nextInt(); while(t > 0){ int n = in.nextInt(); int [] p = new int[n]; int [] mx = new int[n]; int mxi = 0; for(int i = 0; i < n; i ++){ p[i] = in.nextInt(); if(p[i] >= p[mxi]){ mxi = i; } mx[i] = mxi; } if(n == 1){ System.out.println(p[0]); }else{ /*for(int j = 0; j < n; j ++){ System.out.print(mx[j] +" "); } System.out.println();*/ LinkedList<Integer> ans = new LinkedList<>(); int x = mx[n - 1]; int end = n , j = 0; while(true){ for(int i = x; i < end; i ++){ ans.add(p[i]); j ++; } if(j < n) { end = x; x = mx[end - 1]; }else break; } for(int k: ans){ System.out.print(k +" "); } System.out.println(); } t --; } } public static void main(String [] args){ CardDeck cd = new CardDeck(); cd.solve(); } private class FastScanner { public BufferedReader r; public StringTokenizer st = null; public FastScanner(InputStream stream) { r = new BufferedReader(new InputStreamReader(stream), 32728); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(r.readLine()); } catch (IOException e) { throw new RuntimeException(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public Long nextLong(){ return Long.parseLong(next()); } } }
Java
["4\n4\n1 2 3 4\n5\n1 5 2 4 3\n6\n4 2 5 3 6 1\n1\n1"]
1 second
["4 3 2 1\n5 2 4 3 1\n6 1 5 3 4 2\n1"]
NoteIn the first test case, one of the optimal strategies is the next one: take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1, 2, 3]$$$, $$$p'$$$ becomes $$$[4]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1, 2]$$$, $$$p'$$$ becomes $$$[4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[4, 3, 2]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[4, 3, 2, 1]$$$. In result, $$$p'$$$ has order equal to $$$4^3 \cdot 4 + 4^2 \cdot 3 + 4^1 \cdot 2 + 4^0 \cdot 1$$$ $$$=$$$ $$$256 + 48 + 8 + 1 = 313$$$.In the second test case, one of the optimal strategies is: take $$$4$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[5, 2, 4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[5, 2, 4, 3, 1]$$$; In result, $$$p'$$$ has order equal to $$$5^4 \cdot 5 + 5^3 \cdot 2 + 5^2 \cdot 4 + 5^1 \cdot 3 + 5^0 \cdot 1$$$ $$$=$$$ $$$3125 + 250 + 100 + 15 + 1 = 3491$$$.In the third test case, one of the optimal strategies is: take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2, 5, 3]$$$, $$$p'$$$ becomes $$$[6, 1]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2]$$$, $$$p'$$$ becomes $$$[6, 1, 5, 3]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[6, 1, 5, 3, 4, 2]$$$. In result, $$$p'$$$ has order equal to $$$6^5 \cdot 6 + 6^4 \cdot 1 + 6^3 \cdot 5 + 6^2 \cdot 3 + 6^1 \cdot 4 + 6^0 \cdot 2$$$ $$$=$$$ $$$46656 + 1296 + 1080 + 108 + 24 + 2 = 49166$$$.
Java 8
standard input
[ "data structures", "greedy", "math" ]
1637670255f8bd82a01e2ab20cdcc9aa
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the size of deck you have. The second line contains $$$n$$$ integers $$$p_1, p_2,\dots, p_n$$$ ($$$1 \le p_i \le n$$$; $$$p_i \neq p_j$$$ if $$$i \neq j$$$) — values of card in the deck from bottom to top. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,100
For each test case print the deck with maximum possible order. Print values of cards in the deck from bottom to top. If there are multiple answers, print any of them.
standard output
PASSED
b2dfd71d7bb67d3ba068a93eda6c7056
train_109.jsonl
1614071100
You have a deck of $$$n$$$ cards, and you'd like to reorder it to a new one.Each card has a value between $$$1$$$ and $$$n$$$ equal to $$$p_i$$$. All $$$p_i$$$ are pairwise distinct. Cards in a deck are numbered from bottom to top, i. e. $$$p_1$$$ stands for the bottom card, $$$p_n$$$ is the top card. In each step you pick some integer $$$k &gt; 0$$$, take the top $$$k$$$ cards from the original deck and place them, in the order they are now, on top of the new deck. You perform this operation until the original deck is empty. (Refer to the notes section for the better understanding.)Let's define an order of a deck as $$$\sum\limits_{i = 1}^{n}{n^{n - i} \cdot p_i}$$$.Given the original deck, output the deck with maximum possible order you can make using the operation above.
512 megabytes
import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.PriorityQueue; import java.util.Scanner; public class code { static int x[]; static int y[]=new int [100000000]; public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while (--t>=0) { int n=sc.nextInt(); int x[]=new int[n]; int y[]=new int[n]; PriorityQueue<Integer> pQueue = new PriorityQueue<Integer>(Collections.reverseOrder()); for (int i = 0; i < x.length; i++) { int k=sc.nextInt(); x[i]=k; pQueue.add(k); } int c[]=new int [(int)1e5+1]; for (int i=0;i<n;i++) { c[x[i]]=i; } boolean z[]=new boolean[n]; int j=0; int n1=0; while (j<x.length) { int m=pQueue.poll(); int p=c[m]; for (int i = p; i < x.length&&!z[i]; i++) { System.out.print(x[i]+" "); z[i]=true; j++; } n1++; } System.out.println(); } } }
Java
["4\n4\n1 2 3 4\n5\n1 5 2 4 3\n6\n4 2 5 3 6 1\n1\n1"]
1 second
["4 3 2 1\n5 2 4 3 1\n6 1 5 3 4 2\n1"]
NoteIn the first test case, one of the optimal strategies is the next one: take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1, 2, 3]$$$, $$$p'$$$ becomes $$$[4]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1, 2]$$$, $$$p'$$$ becomes $$$[4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[4, 3, 2]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[4, 3, 2, 1]$$$. In result, $$$p'$$$ has order equal to $$$4^3 \cdot 4 + 4^2 \cdot 3 + 4^1 \cdot 2 + 4^0 \cdot 1$$$ $$$=$$$ $$$256 + 48 + 8 + 1 = 313$$$.In the second test case, one of the optimal strategies is: take $$$4$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[5, 2, 4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[5, 2, 4, 3, 1]$$$; In result, $$$p'$$$ has order equal to $$$5^4 \cdot 5 + 5^3 \cdot 2 + 5^2 \cdot 4 + 5^1 \cdot 3 + 5^0 \cdot 1$$$ $$$=$$$ $$$3125 + 250 + 100 + 15 + 1 = 3491$$$.In the third test case, one of the optimal strategies is: take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2, 5, 3]$$$, $$$p'$$$ becomes $$$[6, 1]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2]$$$, $$$p'$$$ becomes $$$[6, 1, 5, 3]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[6, 1, 5, 3, 4, 2]$$$. In result, $$$p'$$$ has order equal to $$$6^5 \cdot 6 + 6^4 \cdot 1 + 6^3 \cdot 5 + 6^2 \cdot 3 + 6^1 \cdot 4 + 6^0 \cdot 2$$$ $$$=$$$ $$$46656 + 1296 + 1080 + 108 + 24 + 2 = 49166$$$.
Java 8
standard input
[ "data structures", "greedy", "math" ]
1637670255f8bd82a01e2ab20cdcc9aa
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the size of deck you have. The second line contains $$$n$$$ integers $$$p_1, p_2,\dots, p_n$$$ ($$$1 \le p_i \le n$$$; $$$p_i \neq p_j$$$ if $$$i \neq j$$$) — values of card in the deck from bottom to top. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,100
For each test case print the deck with maximum possible order. Print values of cards in the deck from bottom to top. If there are multiple answers, print any of them.
standard output
PASSED
d7845390fc708366d96b40b269f28038
train_109.jsonl
1614071100
You have a deck of $$$n$$$ cards, and you'd like to reorder it to a new one.Each card has a value between $$$1$$$ and $$$n$$$ equal to $$$p_i$$$. All $$$p_i$$$ are pairwise distinct. Cards in a deck are numbered from bottom to top, i. e. $$$p_1$$$ stands for the bottom card, $$$p_n$$$ is the top card. In each step you pick some integer $$$k &gt; 0$$$, take the top $$$k$$$ cards from the original deck and place them, in the order they are now, on top of the new deck. You perform this operation until the original deck is empty. (Refer to the notes section for the better understanding.)Let's define an order of a deck as $$$\sum\limits_{i = 1}^{n}{n^{n - i} \cdot p_i}$$$.Given the original deck, output the deck with maximum possible order you can make using the operation above.
512 megabytes
import java.util.*; public class CardDeck0520 { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for(int t1 = 1; t1 <= t; t1++){ int n = sc.nextInt(); int[] ar = new int[n+1]; int[] ind = new int[n+1]; int max = 0; for(int i = 1; i <= n; i++){ ar[i] = sc.nextInt(); if(ar[i] > max){ max = ar[i]; ind[i] = i; }else{ ind[i] = ind[i-1]; } } int tmp = n; while(tmp > 0){ int cur = ind[tmp]; for(int i = cur; i <= tmp; i++){ System.out.print(ar[i] + " "); } tmp = cur -1; } System.out.println(); } } }
Java
["4\n4\n1 2 3 4\n5\n1 5 2 4 3\n6\n4 2 5 3 6 1\n1\n1"]
1 second
["4 3 2 1\n5 2 4 3 1\n6 1 5 3 4 2\n1"]
NoteIn the first test case, one of the optimal strategies is the next one: take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1, 2, 3]$$$, $$$p'$$$ becomes $$$[4]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1, 2]$$$, $$$p'$$$ becomes $$$[4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[4, 3, 2]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[4, 3, 2, 1]$$$. In result, $$$p'$$$ has order equal to $$$4^3 \cdot 4 + 4^2 \cdot 3 + 4^1 \cdot 2 + 4^0 \cdot 1$$$ $$$=$$$ $$$256 + 48 + 8 + 1 = 313$$$.In the second test case, one of the optimal strategies is: take $$$4$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[5, 2, 4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[5, 2, 4, 3, 1]$$$; In result, $$$p'$$$ has order equal to $$$5^4 \cdot 5 + 5^3 \cdot 2 + 5^2 \cdot 4 + 5^1 \cdot 3 + 5^0 \cdot 1$$$ $$$=$$$ $$$3125 + 250 + 100 + 15 + 1 = 3491$$$.In the third test case, one of the optimal strategies is: take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2, 5, 3]$$$, $$$p'$$$ becomes $$$[6, 1]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2]$$$, $$$p'$$$ becomes $$$[6, 1, 5, 3]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[6, 1, 5, 3, 4, 2]$$$. In result, $$$p'$$$ has order equal to $$$6^5 \cdot 6 + 6^4 \cdot 1 + 6^3 \cdot 5 + 6^2 \cdot 3 + 6^1 \cdot 4 + 6^0 \cdot 2$$$ $$$=$$$ $$$46656 + 1296 + 1080 + 108 + 24 + 2 = 49166$$$.
Java 8
standard input
[ "data structures", "greedy", "math" ]
1637670255f8bd82a01e2ab20cdcc9aa
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the size of deck you have. The second line contains $$$n$$$ integers $$$p_1, p_2,\dots, p_n$$$ ($$$1 \le p_i \le n$$$; $$$p_i \neq p_j$$$ if $$$i \neq j$$$) — values of card in the deck from bottom to top. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,100
For each test case print the deck with maximum possible order. Print values of cards in the deck from bottom to top. If there are multiple answers, print any of them.
standard output
PASSED
8827dfa3f0ba881c6cdebd8c754f3ecd
train_109.jsonl
1614071100
You have a deck of $$$n$$$ cards, and you'd like to reorder it to a new one.Each card has a value between $$$1$$$ and $$$n$$$ equal to $$$p_i$$$. All $$$p_i$$$ are pairwise distinct. Cards in a deck are numbered from bottom to top, i. e. $$$p_1$$$ stands for the bottom card, $$$p_n$$$ is the top card. In each step you pick some integer $$$k &gt; 0$$$, take the top $$$k$$$ cards from the original deck and place them, in the order they are now, on top of the new deck. You perform this operation until the original deck is empty. (Refer to the notes section for the better understanding.)Let's define an order of a deck as $$$\sum\limits_{i = 1}^{n}{n^{n - i} \cdot p_i}$$$.Given the original deck, output the deck with maximum possible order you can make using the operation above.
512 megabytes
import java.util.*; public class Check2 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for (int i = 0; i < t; i++) { /* long p=sc.nextLong(); long a=sc.nextLong(); long b=sc.nextLong(); long c=sc.nextLong(); long a1=(long)(Math.ceil(p/(double)a))*a-p; long b1=(long)(Math.ceil(p/(double)b))*b-p; long c1=(long)(Math.ceil(p/(double)c))*c-p; System.out.println(Math.max(Math.min(a1,Math.min(b1,c1)),0));*/ int n = sc.nextInt(); int[] indexar = new int[n + 1]; List<Integer> list = new ArrayList<>(); for (int j = 0; j < n; j++) { int num = sc.nextInt(); list.add(num); indexar[num] = j; } List<Integer> list1 = new ArrayList<>(); boolean[] found = new boolean[n + 1]; Stack<Integer> stack=new Stack<>(); // stack.push(list.get(list.size()-1)); int big=n; //int prev_big=Integer.MIN_VALUE; for(int j=list.size()-1;j>=0;j--){ if(list.get(j)!=big){ int y=list.get(j); stack.push(y); }else { stack.push(big); while (!stack.empty()){ int op=stack.pop(); System.out.println(op); } int max=Integer.MIN_VALUE; for(int k=big-1;k>=1;k--){ if(indexar[k]<=indexar[big]){ max=k; break; } } big=max; } } while (!stack.empty()){ System.out.println(stack.pop()); } /* // int num=n; process: for (int j = n; j >= 1; j--) { int index = indexar[j]; int big = j; if (!found[j]) { for (int k = index; k < n; k++) { int u = list.get(k); if (u <= big) { if (!found[u]) { list1.add(u); big = u; found[u] = true; }else { break ; } if (list1.size() == n) { break process; } } else { break; } } } }*/ /*for (Integer integer : list1) { System.out.println(integer); }*/ } } /* public static int getAns(int n,int[] ar,int orig){ int y1=n-ar[0]; int y2=n-ar[1]; int y3=n-ar[2]; if(y1==ar[0] || y1==ar[1] || y1==ar[2]){ } if(y2==ar[0] || y2==ar[1] || y2==ar[2]){ } if(y3==ar[0] || y3==ar[1] || y3==ar[2]){ } }*/ public static long power(long a, long b, long c) { long ans = 1; while (b != 0) { if (b % 2 == 1) { ans = ans * a; ans %= c; } a = a * a; a %= c; b /= 2; } return ans; } public static long power1(long a, long b, long c) { long ans = 1; while (b != 0) { if (b % 2 == 1) { ans = multiply(ans, a, c); } a = multiply(a, a, c); b /= 2; } return ans; } public static long multiply(long a, long b, long c) { long res = 0; a %= c; while (b > 0) { if (b % 2 == 1) { res = (res + a) % c; } a = (a + a) % c; b /= 2; } return res % c; } public static long totient(long n) { long result = n; for (long i = 2; i * i <= n; i++) { if (n % i == 0) { //sum=sum+2*i; while (n % i == 0) { n /= i; // sum=sum+n; } result -= result / i; } } if (n > 1) { result -= result / n; } return result; } public static long gcd(long a, long b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } public static boolean[] primes(int n) { boolean[] p = new boolean[n + 1]; p[0] = false; p[1] = false; for (int i = 2; i <= n; i++) { p[i] = true; } for (int i = 2; i * i <= n; i++) { if (p[i]) { for (int j = i * i; j <= n; j += i) { p[j] = false; } } } return p; } static int val(char c) { if (c >= '0' && c <= '9') return (int) c - '0'; else return (int) c - 'A' + 10; } // Function to convert a // number from given base // 'b' to decimal static int toDeci(String str, int base) { int len = str.length(); int power = 1; // Initialize // power of base int num = 0; // Initialize result int i; // Decimal equivalent is // str[len-1]*1 + str[len-2] * // base + str[len-3]*(base^2) + ... for (i = len - 1; i >= 0; i--) { // A digit in input number // must be less than // number's base if (val(str.charAt(i)) >= base) { System.out.println("Invalid Number"); return -1; } num += val(str.charAt(i)) * power; power = power * base; } return num; } }
Java
["4\n4\n1 2 3 4\n5\n1 5 2 4 3\n6\n4 2 5 3 6 1\n1\n1"]
1 second
["4 3 2 1\n5 2 4 3 1\n6 1 5 3 4 2\n1"]
NoteIn the first test case, one of the optimal strategies is the next one: take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1, 2, 3]$$$, $$$p'$$$ becomes $$$[4]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1, 2]$$$, $$$p'$$$ becomes $$$[4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[4, 3, 2]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[4, 3, 2, 1]$$$. In result, $$$p'$$$ has order equal to $$$4^3 \cdot 4 + 4^2 \cdot 3 + 4^1 \cdot 2 + 4^0 \cdot 1$$$ $$$=$$$ $$$256 + 48 + 8 + 1 = 313$$$.In the second test case, one of the optimal strategies is: take $$$4$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[5, 2, 4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[5, 2, 4, 3, 1]$$$; In result, $$$p'$$$ has order equal to $$$5^4 \cdot 5 + 5^3 \cdot 2 + 5^2 \cdot 4 + 5^1 \cdot 3 + 5^0 \cdot 1$$$ $$$=$$$ $$$3125 + 250 + 100 + 15 + 1 = 3491$$$.In the third test case, one of the optimal strategies is: take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2, 5, 3]$$$, $$$p'$$$ becomes $$$[6, 1]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2]$$$, $$$p'$$$ becomes $$$[6, 1, 5, 3]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[6, 1, 5, 3, 4, 2]$$$. In result, $$$p'$$$ has order equal to $$$6^5 \cdot 6 + 6^4 \cdot 1 + 6^3 \cdot 5 + 6^2 \cdot 3 + 6^1 \cdot 4 + 6^0 \cdot 2$$$ $$$=$$$ $$$46656 + 1296 + 1080 + 108 + 24 + 2 = 49166$$$.
Java 8
standard input
[ "data structures", "greedy", "math" ]
1637670255f8bd82a01e2ab20cdcc9aa
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the size of deck you have. The second line contains $$$n$$$ integers $$$p_1, p_2,\dots, p_n$$$ ($$$1 \le p_i \le n$$$; $$$p_i \neq p_j$$$ if $$$i \neq j$$$) — values of card in the deck from bottom to top. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,100
For each test case print the deck with maximum possible order. Print values of cards in the deck from bottom to top. If there are multiple answers, print any of them.
standard output
PASSED
ce94ccbbc6db8e0e56b6ccbb02035d36
train_109.jsonl
1614071100
You have a deck of $$$n$$$ cards, and you'd like to reorder it to a new one.Each card has a value between $$$1$$$ and $$$n$$$ equal to $$$p_i$$$. All $$$p_i$$$ are pairwise distinct. Cards in a deck are numbered from bottom to top, i. e. $$$p_1$$$ stands for the bottom card, $$$p_n$$$ is the top card. In each step you pick some integer $$$k &gt; 0$$$, take the top $$$k$$$ cards from the original deck and place them, in the order they are now, on top of the new deck. You perform this operation until the original deck is empty. (Refer to the notes section for the better understanding.)Let's define an order of a deck as $$$\sum\limits_{i = 1}^{n}{n^{n - i} \cdot p_i}$$$.Given the original deck, output the deck with maximum possible order you can make using the operation above.
512 megabytes
import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.util.Comparator; import java.util.HashMap; import java.util.Scanner; import java.util.Stack; public class Main { static class point { long val, time, t3; point(long val, long time, int t3) { this.val = val; this.time = time; this.t3 = t3; } } 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 class comp implements Comparator<point> { public int compare(point a, point b) { if (a.val == b.val) { return Long.compare(b.time, a.time); } return Long.compare(a.val, b.val); } } static class TreeNode { int val; TreeNode left,right; TreeNode(int val){ this.val=val;left=null;right=null; } } static TreeNode maxx(int start,int end,int[] arr){ if(start>end){ return null; } int ind=0; int max=-1; for(int j=start;j<=end;j++){ if(arr[j]>max){ max=arr[j]; ind=j; } } TreeNode jj=new TreeNode(arr[ind]); jj.left=maxx(start,ind-1,arr); jj.right=maxx(ind+1,end,arr); return jj; } static void dfs(TreeNode root,int dep){ if(root==null){ return; } ans[hashMap.get(root.val)]=dep; dfs(root.left,dep+1); dfs(root.right,dep+1); } static int[] ans; static HashMap<Integer,Integer> hashMap; static class pont{ int val,index; pont(int val,int index){ this.val=val; this.index=index; } } static class compr implements Comparator<pont>{ public int compare(pont a,pont b){ return a.val-b.val; } } static class poin{ int src; long val; poin(int src,long val){ this.src=src; this.val=val; } } public static void main(String[] args) throws IOException { Scanner s=new Scanner(System.in); int t=s.nextInt(); for(int j=0;j<t;j++){ int n=s.nextInt(); int[] arr=new int[n]; StringBuilder str=new StringBuilder(); arr[0]=s.nextInt(); int[] arrr=new int[n];arrr[0]=arr[0]; for(int i=1;i<n;i++){ arrr[i]=s.nextInt(); arr[i]=Math.max(arr[i-1],arrr[i]); } Stack<Integer> st=new Stack<>(); st.push(arrr[n-1]); for(int i=n-2;i>=0;i--){ if(arr[i]!=arr[i+1]){ while (!st.isEmpty()){ str.append(st.pop()); str.append(" "); } st=new Stack<>(); st.push(arrr[i]); }else{ st.push(arrr[i]); } } while (!st.isEmpty()){ str.append(st.pop()); str.append(" "); } System.out.println(str.toString().trim()); } // int t=s.nextInt(); // int t=1; // for(int jj=0;jj<t;jj++){ // int n=s.nextInt(); // HashMap<Integer,HashMap<Integer,Integer>> has=new HashMap<>(); // int m=s.nextInt(); // int x=s.nextInt(); // int y=s.nextInt(); // long[] ti=new long[m]; // long[] ki=new long[m]; // HashMap<Integer,HashSet<Integer>> hash=new HashMap<>(); // for(int i=0;i<=n;i++){ // has.put(i,new HashMap<>()); // hash.put(i,new HashSet<>()); // } // for(int i=0;i<m;i++){ // int a=s.nextInt(); // int b=s.nextInt(); //// if(has.get(a)==null){ //// has.put(a,new HashMap<>()); //// } //// if(has.get(b)==null){ //// has.put(b,new HashMap<>()); //// } // has.get(a).put(b,i); // has.get(b).put(a,i); // ti[i]=s.nextLong(); // ki[i]=s.nextLong(); // } // // long[] vis=new long[n+1]; // Arrays.fill(vis,Long.MAX_VALUE); // vis[x]=0; // Queue<poin> qu=new LinkedList<>(); // qu.add(new poin(x,0)); // long ans=Long.MAX_VALUE; // while(!qu.isEmpty()){ // poin te=qu.poll(); // if(te.src==y){ // ans=Math.min(ans,te.val);continue; // } // for(Integer v:has.get(te.src).keySet()){ // long ll=(ki[has.get(te.src).get(v)]+(te.val%ki[has.get(te.src).get(v)]))%ki[has.get(te.src).get(v)]+ti[has.get(te.src).get(v)]; //// if(te.val>ki[has.get(te.src).get(v)]){ //// long ij=(long)Math.ceil((double)te.val/(double)ki[has.get(te.src).get(v)]); //// ll=(long)((long)ij*(long)ki[has.get(te.src).get(v)]); //// }else{ //// // long ij=(long)Math.ceil((double)ki[has.get(te.src).get(v)]/(double)te.val); //// if(te.val==0){ //// ll=0; //// }else{ //// ll=(long)((long)(long)ki[has.get(te.src).get(v)]);} //// } //// ll=(long)((long)ll+(long)ti[has.get(te.src).get(v)]); //// long ll= (long)Math.max((long)((long)te.val+(long)ti[has.get(te.src).get(v)]), (long)((long)ki[has.get(te.src).get(v)]*(long)Math.floor((double)ki[has.get(te.src).get(v)]/(double)(te.val+ti[has.get(te.src).get(v)])))); //// if( !hash.get(v).contains(te.src) ){ //// vis[v]=ll; //// hash.get(v).add(te.src); //// qu.add(new poin( v,vis[v])); //// } // if(vis[v]>=ll){ // vis[v]=ll; //// hash.get(v).add(te.src); // qu.add(new poin( v,vis[v])); // // } // } // } // if(ans==Long.MAX_VALUE){ // System.out.println(-1); // }else{ // System.out.println(ans);} // } } }
Java
["4\n4\n1 2 3 4\n5\n1 5 2 4 3\n6\n4 2 5 3 6 1\n1\n1"]
1 second
["4 3 2 1\n5 2 4 3 1\n6 1 5 3 4 2\n1"]
NoteIn the first test case, one of the optimal strategies is the next one: take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1, 2, 3]$$$, $$$p'$$$ becomes $$$[4]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1, 2]$$$, $$$p'$$$ becomes $$$[4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[4, 3, 2]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[4, 3, 2, 1]$$$. In result, $$$p'$$$ has order equal to $$$4^3 \cdot 4 + 4^2 \cdot 3 + 4^1 \cdot 2 + 4^0 \cdot 1$$$ $$$=$$$ $$$256 + 48 + 8 + 1 = 313$$$.In the second test case, one of the optimal strategies is: take $$$4$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[5, 2, 4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[5, 2, 4, 3, 1]$$$; In result, $$$p'$$$ has order equal to $$$5^4 \cdot 5 + 5^3 \cdot 2 + 5^2 \cdot 4 + 5^1 \cdot 3 + 5^0 \cdot 1$$$ $$$=$$$ $$$3125 + 250 + 100 + 15 + 1 = 3491$$$.In the third test case, one of the optimal strategies is: take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2, 5, 3]$$$, $$$p'$$$ becomes $$$[6, 1]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2]$$$, $$$p'$$$ becomes $$$[6, 1, 5, 3]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[6, 1, 5, 3, 4, 2]$$$. In result, $$$p'$$$ has order equal to $$$6^5 \cdot 6 + 6^4 \cdot 1 + 6^3 \cdot 5 + 6^2 \cdot 3 + 6^1 \cdot 4 + 6^0 \cdot 2$$$ $$$=$$$ $$$46656 + 1296 + 1080 + 108 + 24 + 2 = 49166$$$.
Java 8
standard input
[ "data structures", "greedy", "math" ]
1637670255f8bd82a01e2ab20cdcc9aa
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the size of deck you have. The second line contains $$$n$$$ integers $$$p_1, p_2,\dots, p_n$$$ ($$$1 \le p_i \le n$$$; $$$p_i \neq p_j$$$ if $$$i \neq j$$$) — values of card in the deck from bottom to top. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,100
For each test case print the deck with maximum possible order. Print values of cards in the deck from bottom to top. If there are multiple answers, print any of them.
standard output
PASSED
24a1bb070a32dc54b1b550d885bd1579
train_109.jsonl
1614071100
You have a deck of $$$n$$$ cards, and you'd like to reorder it to a new one.Each card has a value between $$$1$$$ and $$$n$$$ equal to $$$p_i$$$. All $$$p_i$$$ are pairwise distinct. Cards in a deck are numbered from bottom to top, i. e. $$$p_1$$$ stands for the bottom card, $$$p_n$$$ is the top card. In each step you pick some integer $$$k &gt; 0$$$, take the top $$$k$$$ cards from the original deck and place them, in the order they are now, on top of the new deck. You perform this operation until the original deck is empty. (Refer to the notes section for the better understanding.)Let's define an order of a deck as $$$\sum\limits_{i = 1}^{n}{n^{n - i} \cdot p_i}$$$.Given the original deck, output the deck with maximum possible order you can make using the operation above.
512 megabytes
import java.util.*; import java.util.HashMap; public class Q23__2 { 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]; int b[]=new int[n]; int i=0,s=0,e=n-1,k=0,p=n; boolean br=false; for(i=0;i<n;i++) { a[i]=sc.nextInt(); } HashMap <Integer,Integer> map= new HashMap<>(); for(i=0;i<n;i++) { map.put(a[i],i); } for(i=n;i>=1 && k!=n ;i--) { br=false; s= map.get(i); if(s<p) for(int j=s;j<=e;j++) { b[k]=a[j]; k++; br=true; } if(br==true) { e=s-1; p=s; } } for(i=0;i<n;i++) System.out.print(b[i]+" "); System.out.println(); } } }
Java
["4\n4\n1 2 3 4\n5\n1 5 2 4 3\n6\n4 2 5 3 6 1\n1\n1"]
1 second
["4 3 2 1\n5 2 4 3 1\n6 1 5 3 4 2\n1"]
NoteIn the first test case, one of the optimal strategies is the next one: take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1, 2, 3]$$$, $$$p'$$$ becomes $$$[4]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1, 2]$$$, $$$p'$$$ becomes $$$[4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[4, 3, 2]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[4, 3, 2, 1]$$$. In result, $$$p'$$$ has order equal to $$$4^3 \cdot 4 + 4^2 \cdot 3 + 4^1 \cdot 2 + 4^0 \cdot 1$$$ $$$=$$$ $$$256 + 48 + 8 + 1 = 313$$$.In the second test case, one of the optimal strategies is: take $$$4$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[5, 2, 4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[5, 2, 4, 3, 1]$$$; In result, $$$p'$$$ has order equal to $$$5^4 \cdot 5 + 5^3 \cdot 2 + 5^2 \cdot 4 + 5^1 \cdot 3 + 5^0 \cdot 1$$$ $$$=$$$ $$$3125 + 250 + 100 + 15 + 1 = 3491$$$.In the third test case, one of the optimal strategies is: take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2, 5, 3]$$$, $$$p'$$$ becomes $$$[6, 1]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2]$$$, $$$p'$$$ becomes $$$[6, 1, 5, 3]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[6, 1, 5, 3, 4, 2]$$$. In result, $$$p'$$$ has order equal to $$$6^5 \cdot 6 + 6^4 \cdot 1 + 6^3 \cdot 5 + 6^2 \cdot 3 + 6^1 \cdot 4 + 6^0 \cdot 2$$$ $$$=$$$ $$$46656 + 1296 + 1080 + 108 + 24 + 2 = 49166$$$.
Java 8
standard input
[ "data structures", "greedy", "math" ]
1637670255f8bd82a01e2ab20cdcc9aa
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the size of deck you have. The second line contains $$$n$$$ integers $$$p_1, p_2,\dots, p_n$$$ ($$$1 \le p_i \le n$$$; $$$p_i \neq p_j$$$ if $$$i \neq j$$$) — values of card in the deck from bottom to top. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,100
For each test case print the deck with maximum possible order. Print values of cards in the deck from bottom to top. If there are multiple answers, print any of them.
standard output
PASSED
2d13129f91a4aba12f276ca3f223e6b0
train_109.jsonl
1614071100
You have a deck of $$$n$$$ cards, and you'd like to reorder it to a new one.Each card has a value between $$$1$$$ and $$$n$$$ equal to $$$p_i$$$. All $$$p_i$$$ are pairwise distinct. Cards in a deck are numbered from bottom to top, i. e. $$$p_1$$$ stands for the bottom card, $$$p_n$$$ is the top card. In each step you pick some integer $$$k &gt; 0$$$, take the top $$$k$$$ cards from the original deck and place them, in the order they are now, on top of the new deck. You perform this operation until the original deck is empty. (Refer to the notes section for the better understanding.)Let's define an order of a deck as $$$\sum\limits_{i = 1}^{n}{n^{n - i} \cdot p_i}$$$.Given the original deck, output the deck with maximum possible order you can make using the operation above.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class F { static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st; static PrintWriter out; public static String next() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } public static int nextInt() throws IOException { return Integer.parseInt(next()); } public static long nextLong() throws IOException { return Long.parseLong(next()); } public static void main(String[] args) throws IOException { int t = nextInt(); for (int i = 0; i < t; i++) { int n = nextInt(); int[] arr = new int[n]; int[] pos = new int[n]; for (int j = 0; j < n; j++) { arr[j] = nextInt(); pos[arr[j] - 1] = j; } int last = n - 1; for (int j = n - 1; j >= 0; j--) { if (pos[j] <= last) { for (int k = pos[j]; k <= last; k++) { System.out.print(arr[k] + " "); } last = pos[j] - 1; } } System.out.println(); } } }
Java
["4\n4\n1 2 3 4\n5\n1 5 2 4 3\n6\n4 2 5 3 6 1\n1\n1"]
1 second
["4 3 2 1\n5 2 4 3 1\n6 1 5 3 4 2\n1"]
NoteIn the first test case, one of the optimal strategies is the next one: take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1, 2, 3]$$$, $$$p'$$$ becomes $$$[4]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1, 2]$$$, $$$p'$$$ becomes $$$[4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[4, 3, 2]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[4, 3, 2, 1]$$$. In result, $$$p'$$$ has order equal to $$$4^3 \cdot 4 + 4^2 \cdot 3 + 4^1 \cdot 2 + 4^0 \cdot 1$$$ $$$=$$$ $$$256 + 48 + 8 + 1 = 313$$$.In the second test case, one of the optimal strategies is: take $$$4$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[5, 2, 4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[5, 2, 4, 3, 1]$$$; In result, $$$p'$$$ has order equal to $$$5^4 \cdot 5 + 5^3 \cdot 2 + 5^2 \cdot 4 + 5^1 \cdot 3 + 5^0 \cdot 1$$$ $$$=$$$ $$$3125 + 250 + 100 + 15 + 1 = 3491$$$.In the third test case, one of the optimal strategies is: take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2, 5, 3]$$$, $$$p'$$$ becomes $$$[6, 1]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2]$$$, $$$p'$$$ becomes $$$[6, 1, 5, 3]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[6, 1, 5, 3, 4, 2]$$$. In result, $$$p'$$$ has order equal to $$$6^5 \cdot 6 + 6^4 \cdot 1 + 6^3 \cdot 5 + 6^2 \cdot 3 + 6^1 \cdot 4 + 6^0 \cdot 2$$$ $$$=$$$ $$$46656 + 1296 + 1080 + 108 + 24 + 2 = 49166$$$.
Java 8
standard input
[ "data structures", "greedy", "math" ]
1637670255f8bd82a01e2ab20cdcc9aa
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the size of deck you have. The second line contains $$$n$$$ integers $$$p_1, p_2,\dots, p_n$$$ ($$$1 \le p_i \le n$$$; $$$p_i \neq p_j$$$ if $$$i \neq j$$$) — values of card in the deck from bottom to top. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,100
For each test case print the deck with maximum possible order. Print values of cards in the deck from bottom to top. If there are multiple answers, print any of them.
standard output
PASSED
8dd09b194454c4558dcb6187daf0d491
train_109.jsonl
1614071100
You have a deck of $$$n$$$ cards, and you'd like to reorder it to a new one.Each card has a value between $$$1$$$ and $$$n$$$ equal to $$$p_i$$$. All $$$p_i$$$ are pairwise distinct. Cards in a deck are numbered from bottom to top, i. e. $$$p_1$$$ stands for the bottom card, $$$p_n$$$ is the top card. In each step you pick some integer $$$k &gt; 0$$$, take the top $$$k$$$ cards from the original deck and place them, in the order they are now, on top of the new deck. You perform this operation until the original deck is empty. (Refer to the notes section for the better understanding.)Let's define an order of a deck as $$$\sum\limits_{i = 1}^{n}{n^{n - i} \cdot p_i}$$$.Given the original deck, output the deck with maximum possible order you can make using the operation above.
512 megabytes
/* "जय श्री कृष्णा" */ import java.util.*; import java.io.*; public class Deck_B implements Runnable { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] nextIntArray(int size) { int[] arr = new int[size]; for (int i = 0; i < size; ++i) arr[i] = nextInt(); return arr; } long[] nextLongArray(int size) { long[] arr = new long[size]; for (int i = 0; i < size; ++i) arr[i] = nextLong(); return arr; } double[] nextDoubleArray(int size) { double[] arr = new double[size]; for (int i = 0; i < size; ++i) arr[i] = nextDouble(); return arr; } } static int mod = (int) (1e9 + 7); static final PrintWriter out = new PrintWriter(System.out); static final FastReader fr = new FastReader(); public static void main(String[] args) throws java.lang.Exception { new Thread(null, new Deck_B(), "Main", 1 << 26).start(); } void solve() { int n = fr.nextInt(); int a[]=new int[n]; int p[]=new int[n + 1]; for(int i=0; i<n; i++) { a[i]=fr.nextInt(); p[a[i]]=i; } Set<Integer> ans=new LinkedHashSet<>(); int last=n; for(int i=n; i>=1; i--) { if(p[i]<last) { for(int j=p[i]; j<last; j++ ) { ans.add(a[j]); } last=p[i]; } } for(int X: ans) out.print(X+" "); } @Override public void run() { long start = System.nanoTime(); // Program Start boolean testcase = true; int t = testcase ? fr.nextInt() : 1; while (t-- > 0) { solve(); out.print("\n"); out.flush(); } long end = System.nanoTime(); // Program End System.err.println("Time taken: " + (end - start) / 1000000 + " ms"); } static class CP { static boolean isPrime(long n) { if (n <= 1) return false; if (n == 2 || n == 3) 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; } static long binary_Expo(long a, long b) { // calculating a^b long res = 1; while (b != 0) { if ((b & 1) == 1) { res *= a; --b; } a *= a; b /= 2; } return res; } static long Modular_Expo(long a, long b) { long res = 1; while (b != 0) { if ((b & 1) == 1) { res = (res * a) % mod; --b; } a = (a * a) % mod; b /= 2; } return res; } static int i_gcd(int a, int b) {// iterative way to calculate gcd. while (true) { if (b == 0) return a; int c = a; a = b; b = c % b; } } static long gcd(long a, long b) {// here b is the remainder if (b == 0) return a; //because each time b will divide a. return gcd(b, a % b); } static long ceil_div(long a, long b) { // a numerator b denominator return (a + b - 1) / b; } static int getIthBitFromInt(int bits, int i) { return (bits >> (i - 1)) & 1; } static int upper_Bound(int a[], int x) {//closest to the left+1 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 int lower_Bound(int a[], int x) {//closest to the right 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 void sort(int a[]) { PriorityQueue<Integer> q = new PriorityQueue<>(); for (int i = 0; i < a.length; i++) q.add(a[i]); for (int i = 0; i < a.length; i++) a[i] = q.poll(); } static int getMax(int arr[], int n) { int mx = arr[0]; for (int i = 1; i < n; i++) if (arr[i] > mx) mx = arr[i]; return mx; } } }
Java
["4\n4\n1 2 3 4\n5\n1 5 2 4 3\n6\n4 2 5 3 6 1\n1\n1"]
1 second
["4 3 2 1\n5 2 4 3 1\n6 1 5 3 4 2\n1"]
NoteIn the first test case, one of the optimal strategies is the next one: take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1, 2, 3]$$$, $$$p'$$$ becomes $$$[4]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1, 2]$$$, $$$p'$$$ becomes $$$[4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[4, 3, 2]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[4, 3, 2, 1]$$$. In result, $$$p'$$$ has order equal to $$$4^3 \cdot 4 + 4^2 \cdot 3 + 4^1 \cdot 2 + 4^0 \cdot 1$$$ $$$=$$$ $$$256 + 48 + 8 + 1 = 313$$$.In the second test case, one of the optimal strategies is: take $$$4$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[5, 2, 4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[5, 2, 4, 3, 1]$$$; In result, $$$p'$$$ has order equal to $$$5^4 \cdot 5 + 5^3 \cdot 2 + 5^2 \cdot 4 + 5^1 \cdot 3 + 5^0 \cdot 1$$$ $$$=$$$ $$$3125 + 250 + 100 + 15 + 1 = 3491$$$.In the third test case, one of the optimal strategies is: take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2, 5, 3]$$$, $$$p'$$$ becomes $$$[6, 1]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2]$$$, $$$p'$$$ becomes $$$[6, 1, 5, 3]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[6, 1, 5, 3, 4, 2]$$$. In result, $$$p'$$$ has order equal to $$$6^5 \cdot 6 + 6^4 \cdot 1 + 6^3 \cdot 5 + 6^2 \cdot 3 + 6^1 \cdot 4 + 6^0 \cdot 2$$$ $$$=$$$ $$$46656 + 1296 + 1080 + 108 + 24 + 2 = 49166$$$.
Java 8
standard input
[ "data structures", "greedy", "math" ]
1637670255f8bd82a01e2ab20cdcc9aa
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the size of deck you have. The second line contains $$$n$$$ integers $$$p_1, p_2,\dots, p_n$$$ ($$$1 \le p_i \le n$$$; $$$p_i \neq p_j$$$ if $$$i \neq j$$$) — values of card in the deck from bottom to top. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,100
For each test case print the deck with maximum possible order. Print values of cards in the deck from bottom to top. If there are multiple answers, print any of them.
standard output
PASSED
6c4dfc43d108436cede9ce538e6c17a1
train_109.jsonl
1614071100
You have a deck of $$$n$$$ cards, and you'd like to reorder it to a new one.Each card has a value between $$$1$$$ and $$$n$$$ equal to $$$p_i$$$. All $$$p_i$$$ are pairwise distinct. Cards in a deck are numbered from bottom to top, i. e. $$$p_1$$$ stands for the bottom card, $$$p_n$$$ is the top card. In each step you pick some integer $$$k &gt; 0$$$, take the top $$$k$$$ cards from the original deck and place them, in the order they are now, on top of the new deck. You perform this operation until the original deck is empty. (Refer to the notes section for the better understanding.)Let's define an order of a deck as $$$\sum\limits_{i = 1}^{n}{n^{n - i} \cdot p_i}$$$.Given the original deck, output the deck with maximum possible order you can make using the operation above.
512 megabytes
/* "जय श्री कृष्णा" */ import java.util.*; import java.io.*; public class Deck_B implements Runnable { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] nextIntArray(int size) { int[] arr = new int[size]; for (int i = 0; i < size; ++i) arr[i] = nextInt(); return arr; } long[] nextLongArray(int size) { long[] arr = new long[size]; for (int i = 0; i < size; ++i) arr[i] = nextLong(); return arr; } double[] nextDoubleArray(int size) { double[] arr = new double[size]; for (int i = 0; i < size; ++i) arr[i] = nextDouble(); return arr; } } static int mod = (int) (1e9 + 7); static final PrintWriter out = new PrintWriter(System.out); static final FastReader fr = new FastReader(); public static void main(String[] args) throws java.lang.Exception { new Thread(null, new Deck_B(), "Main", 1 << 26).start(); } void solve() { int n = fr.nextInt(); int a[]=new int[n]; int p[]=new int[n + 1]; for(int i=0; i<n; i++) { a[i]=fr.nextInt(); p[a[i]]=i; } Set<Integer> ans=new LinkedHashSet<>(); int last=n; for(int i=n; i>=1; i--) { if(p[i]<last) { for(int j=p[i]; j<last; j++ ) { ans.add(a[j]); } last=p[i]; } } for(int X: ans) out.print(X+" "); } @Override public void run() { long start = System.nanoTime(); // Program Start boolean testcase = true; int t = testcase ? fr.nextInt() : 1; while (t-- > 0) { solve(); out.print("\n"); out.flush(); } long end = System.nanoTime(); // Program End System.err.println("Time taken: " + (end - start) / 1000000 + " ms"); } static class CP { static boolean isPrime(long n) { if (n <= 1) return false; if (n == 2 || n == 3) 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; } static long binary_Expo(long a, long b) { // calculating a^b long res = 1; while (b != 0) { if ((b & 1) == 1) { res *= a; --b; } a *= a; b /= 2; } return res; } static long Modular_Expo(long a, long b) { long res = 1; while (b != 0) { if ((b & 1) == 1) { res = (res * a) % mod; --b; } a = (a * a) % mod; b /= 2; } return res; } static int i_gcd(int a, int b) {// iterative way to calculate gcd. while (true) { if (b == 0) return a; int c = a; a = b; b = c % b; } } static long gcd(long a, long b) {// here b is the remainder if (b == 0) return a; //because each time b will divide a. return gcd(b, a % b); } static long ceil_div(long a, long b) { // a numerator b denominator return (a + b - 1) / b; } static int getIthBitFromInt(int bits, int i) { return (bits >> (i - 1)) & 1; } static int upper_Bound(int a[], int x) {//closest to the left+1 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 int lower_Bound(int a[], int x) {//closest to the right 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 void sort(int a[]) { PriorityQueue<Integer> q = new PriorityQueue<>(); for (int i = 0; i < a.length; i++) q.add(a[i]); for (int i = 0; i < a.length; i++) a[i] = q.poll(); } static int getMax(int arr[], int n) { int mx = arr[0]; for (int i = 1; i < n; i++) if (arr[i] > mx) mx = arr[i]; return mx; } } }
Java
["4\n4\n1 2 3 4\n5\n1 5 2 4 3\n6\n4 2 5 3 6 1\n1\n1"]
1 second
["4 3 2 1\n5 2 4 3 1\n6 1 5 3 4 2\n1"]
NoteIn the first test case, one of the optimal strategies is the next one: take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1, 2, 3]$$$, $$$p'$$$ becomes $$$[4]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1, 2]$$$, $$$p'$$$ becomes $$$[4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[4, 3, 2]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[4, 3, 2, 1]$$$. In result, $$$p'$$$ has order equal to $$$4^3 \cdot 4 + 4^2 \cdot 3 + 4^1 \cdot 2 + 4^0 \cdot 1$$$ $$$=$$$ $$$256 + 48 + 8 + 1 = 313$$$.In the second test case, one of the optimal strategies is: take $$$4$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[5, 2, 4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[5, 2, 4, 3, 1]$$$; In result, $$$p'$$$ has order equal to $$$5^4 \cdot 5 + 5^3 \cdot 2 + 5^2 \cdot 4 + 5^1 \cdot 3 + 5^0 \cdot 1$$$ $$$=$$$ $$$3125 + 250 + 100 + 15 + 1 = 3491$$$.In the third test case, one of the optimal strategies is: take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2, 5, 3]$$$, $$$p'$$$ becomes $$$[6, 1]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2]$$$, $$$p'$$$ becomes $$$[6, 1, 5, 3]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[6, 1, 5, 3, 4, 2]$$$. In result, $$$p'$$$ has order equal to $$$6^5 \cdot 6 + 6^4 \cdot 1 + 6^3 \cdot 5 + 6^2 \cdot 3 + 6^1 \cdot 4 + 6^0 \cdot 2$$$ $$$=$$$ $$$46656 + 1296 + 1080 + 108 + 24 + 2 = 49166$$$.
Java 8
standard input
[ "data structures", "greedy", "math" ]
1637670255f8bd82a01e2ab20cdcc9aa
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the size of deck you have. The second line contains $$$n$$$ integers $$$p_1, p_2,\dots, p_n$$$ ($$$1 \le p_i \le n$$$; $$$p_i \neq p_j$$$ if $$$i \neq j$$$) — values of card in the deck from bottom to top. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,100
For each test case print the deck with maximum possible order. Print values of cards in the deck from bottom to top. If there are multiple answers, print any of them.
standard output
PASSED
b04ecc2cdb49eb64e961b05bc0c1d8f5
train_109.jsonl
1614071100
You have a deck of $$$n$$$ cards, and you'd like to reorder it to a new one.Each card has a value between $$$1$$$ and $$$n$$$ equal to $$$p_i$$$. All $$$p_i$$$ are pairwise distinct. Cards in a deck are numbered from bottom to top, i. e. $$$p_1$$$ stands for the bottom card, $$$p_n$$$ is the top card. In each step you pick some integer $$$k &gt; 0$$$, take the top $$$k$$$ cards from the original deck and place them, in the order they are now, on top of the new deck. You perform this operation until the original deck is empty. (Refer to the notes section for the better understanding.)Let's define an order of a deck as $$$\sum\limits_{i = 1}^{n}{n^{n - i} \cdot p_i}$$$.Given the original deck, output the deck with maximum possible order you can make using the operation above.
512 megabytes
/* "जय श्री कृष्णा" */ import java.util.*; import java.io.*; public class Deck_B implements Runnable { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] nextIntArray(int size) { int[] arr = new int[size]; for (int i = 0; i < size; ++i) arr[i] = nextInt(); return arr; } long[] nextLongArray(int size) { long[] arr = new long[size]; for (int i = 0; i < size; ++i) arr[i] = nextLong(); return arr; } double[] nextDoubleArray(int size) { double[] arr = new double[size]; for (int i = 0; i < size; ++i) arr[i] = nextDouble(); return arr; } } static int mod = (int) (1e9 + 7); static final PrintWriter out = new PrintWriter(System.out); static final FastReader fr = new FastReader(); public static void main(String[] args) throws java.lang.Exception { new Thread(null, new Deck_B(), "Main", 1 << 26).start(); } void solve() { int n = fr.nextInt(); int a[]=new int[n]; int p[]=new int[n + 1]; for(int i=0; i<n; i++) { a[i]=fr.nextInt(); p[a[i]]=i; } int last=n; for(int i=n; i>=1; i--) { if(p[i]<last) { for(int j=p[i]; j<last; j++ ) { out.print(a[j]+" "); } last=p[i]; } } } @Override public void run() { long start = System.nanoTime(); // Program Start boolean testcase = true; int t = testcase ? fr.nextInt() : 1; while (t-- > 0) { solve(); out.print("\n"); out.flush(); } long end = System.nanoTime(); // Program End System.err.println("Time taken: " + (end - start) / 1000000 + " ms"); } static class CP { static boolean isPrime(long n) { if (n <= 1) return false; if (n == 2 || n == 3) 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; } static long binary_Expo(long a, long b) { // calculating a^b long res = 1; while (b != 0) { if ((b & 1) == 1) { res *= a; --b; } a *= a; b /= 2; } return res; } static long Modular_Expo(long a, long b) { long res = 1; while (b != 0) { if ((b & 1) == 1) { res = (res * a) % mod; --b; } a = (a * a) % mod; b /= 2; } return res; } static int i_gcd(int a, int b) {// iterative way to calculate gcd. while (true) { if (b == 0) return a; int c = a; a = b; b = c % b; } } static long gcd(long a, long b) {// here b is the remainder if (b == 0) return a; //because each time b will divide a. return gcd(b, a % b); } static long ceil_div(long a, long b) { // a numerator b denominator return (a + b - 1) / b; } static int getIthBitFromInt(int bits, int i) { return (bits >> (i - 1)) & 1; } static int upper_Bound(int a[], int x) {//closest to the left+1 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 int lower_Bound(int a[], int x) {//closest to the right 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 void sort(int a[]) { PriorityQueue<Integer> q = new PriorityQueue<>(); for (int i = 0; i < a.length; i++) q.add(a[i]); for (int i = 0; i < a.length; i++) a[i] = q.poll(); } static int getMax(int arr[], int n) { int mx = arr[0]; for (int i = 1; i < n; i++) if (arr[i] > mx) mx = arr[i]; return mx; } } }
Java
["4\n4\n1 2 3 4\n5\n1 5 2 4 3\n6\n4 2 5 3 6 1\n1\n1"]
1 second
["4 3 2 1\n5 2 4 3 1\n6 1 5 3 4 2\n1"]
NoteIn the first test case, one of the optimal strategies is the next one: take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1, 2, 3]$$$, $$$p'$$$ becomes $$$[4]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1, 2]$$$, $$$p'$$$ becomes $$$[4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[4, 3, 2]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[4, 3, 2, 1]$$$. In result, $$$p'$$$ has order equal to $$$4^3 \cdot 4 + 4^2 \cdot 3 + 4^1 \cdot 2 + 4^0 \cdot 1$$$ $$$=$$$ $$$256 + 48 + 8 + 1 = 313$$$.In the second test case, one of the optimal strategies is: take $$$4$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[5, 2, 4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[5, 2, 4, 3, 1]$$$; In result, $$$p'$$$ has order equal to $$$5^4 \cdot 5 + 5^3 \cdot 2 + 5^2 \cdot 4 + 5^1 \cdot 3 + 5^0 \cdot 1$$$ $$$=$$$ $$$3125 + 250 + 100 + 15 + 1 = 3491$$$.In the third test case, one of the optimal strategies is: take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2, 5, 3]$$$, $$$p'$$$ becomes $$$[6, 1]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2]$$$, $$$p'$$$ becomes $$$[6, 1, 5, 3]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[6, 1, 5, 3, 4, 2]$$$. In result, $$$p'$$$ has order equal to $$$6^5 \cdot 6 + 6^4 \cdot 1 + 6^3 \cdot 5 + 6^2 \cdot 3 + 6^1 \cdot 4 + 6^0 \cdot 2$$$ $$$=$$$ $$$46656 + 1296 + 1080 + 108 + 24 + 2 = 49166$$$.
Java 8
standard input
[ "data structures", "greedy", "math" ]
1637670255f8bd82a01e2ab20cdcc9aa
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the size of deck you have. The second line contains $$$n$$$ integers $$$p_1, p_2,\dots, p_n$$$ ($$$1 \le p_i \le n$$$; $$$p_i \neq p_j$$$ if $$$i \neq j$$$) — values of card in the deck from bottom to top. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,100
For each test case print the deck with maximum possible order. Print values of cards in the deck from bottom to top. If there are multiple answers, print any of them.
standard output
PASSED
7a2d121f3817df971f66701dc94d8bc8
train_109.jsonl
1614071100
You have a deck of $$$n$$$ cards, and you'd like to reorder it to a new one.Each card has a value between $$$1$$$ and $$$n$$$ equal to $$$p_i$$$. All $$$p_i$$$ are pairwise distinct. Cards in a deck are numbered from bottom to top, i. e. $$$p_1$$$ stands for the bottom card, $$$p_n$$$ is the top card. In each step you pick some integer $$$k &gt; 0$$$, take the top $$$k$$$ cards from the original deck and place them, in the order they are now, on top of the new deck. You perform this operation until the original deck is empty. (Refer to the notes section for the better understanding.)Let's define an order of a deck as $$$\sum\limits_{i = 1}^{n}{n^{n - i} \cdot p_i}$$$.Given the original deck, output the deck with maximum possible order you can make using the operation above.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; public class Main { /* Need to notice deck order is optimal when we move the greatest element as far to the left as we can */ public static void main(String[] args) { FastScanner sc = new FastScanner(); PrintWriter out = new PrintWriter(System.out); // read number of test cases int t; t = sc.nextInt(); // runs for the number of test cases while(t-->0) { //read n int n; n = sc.nextInt(); // arr: array that maps index to elements // indexOf: maps elements to indices int[] arr = new int[n+1]; int[] indexOf = new int[n+1]; for(int i=1;i<=n;i++) { arr[i] = sc.nextInt(); indexOf[arr[i]] = i; } // least index that we already moved to the new deck int least = n+1; // answer array ArrayList<Integer> ans = new ArrayList<Integer>(); // count down elements from greatest to least for(int e=n;e>=1;e--) { // find index of this element int ind = indexOf[e]; // continue if this element is already in the new deck if(ind>=least) continue; // move this card and all cards above to the new deck // NOTE: this program will still run in O(n) time // despite the nested loop because we add each element // to the new deck only once for(int j=ind;j<least;j++) ans.add(arr[j]); // update least = ind least = ind; } // print elements of answer for(int e:ans) out.print(e + " "); out.println(); } out.close(); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["4\n4\n1 2 3 4\n5\n1 5 2 4 3\n6\n4 2 5 3 6 1\n1\n1"]
1 second
["4 3 2 1\n5 2 4 3 1\n6 1 5 3 4 2\n1"]
NoteIn the first test case, one of the optimal strategies is the next one: take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1, 2, 3]$$$, $$$p'$$$ becomes $$$[4]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1, 2]$$$, $$$p'$$$ becomes $$$[4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[4, 3, 2]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[4, 3, 2, 1]$$$. In result, $$$p'$$$ has order equal to $$$4^3 \cdot 4 + 4^2 \cdot 3 + 4^1 \cdot 2 + 4^0 \cdot 1$$$ $$$=$$$ $$$256 + 48 + 8 + 1 = 313$$$.In the second test case, one of the optimal strategies is: take $$$4$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[5, 2, 4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[5, 2, 4, 3, 1]$$$; In result, $$$p'$$$ has order equal to $$$5^4 \cdot 5 + 5^3 \cdot 2 + 5^2 \cdot 4 + 5^1 \cdot 3 + 5^0 \cdot 1$$$ $$$=$$$ $$$3125 + 250 + 100 + 15 + 1 = 3491$$$.In the third test case, one of the optimal strategies is: take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2, 5, 3]$$$, $$$p'$$$ becomes $$$[6, 1]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2]$$$, $$$p'$$$ becomes $$$[6, 1, 5, 3]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[6, 1, 5, 3, 4, 2]$$$. In result, $$$p'$$$ has order equal to $$$6^5 \cdot 6 + 6^4 \cdot 1 + 6^3 \cdot 5 + 6^2 \cdot 3 + 6^1 \cdot 4 + 6^0 \cdot 2$$$ $$$=$$$ $$$46656 + 1296 + 1080 + 108 + 24 + 2 = 49166$$$.
Java 8
standard input
[ "data structures", "greedy", "math" ]
1637670255f8bd82a01e2ab20cdcc9aa
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the size of deck you have. The second line contains $$$n$$$ integers $$$p_1, p_2,\dots, p_n$$$ ($$$1 \le p_i \le n$$$; $$$p_i \neq p_j$$$ if $$$i \neq j$$$) — values of card in the deck from bottom to top. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,100
For each test case print the deck with maximum possible order. Print values of cards in the deck from bottom to top. If there are multiple answers, print any of them.
standard output
PASSED
5e8dd284fc2b02c728a612dac632470f
train_109.jsonl
1614071100
You have a deck of $$$n$$$ cards, and you'd like to reorder it to a new one.Each card has a value between $$$1$$$ and $$$n$$$ equal to $$$p_i$$$. All $$$p_i$$$ are pairwise distinct. Cards in a deck are numbered from bottom to top, i. e. $$$p_1$$$ stands for the bottom card, $$$p_n$$$ is the top card. In each step you pick some integer $$$k &gt; 0$$$, take the top $$$k$$$ cards from the original deck and place them, in the order they are now, on top of the new deck. You perform this operation until the original deck is empty. (Refer to the notes section for the better understanding.)Let's define an order of a deck as $$$\sum\limits_{i = 1}^{n}{n^{n - i} \cdot p_i}$$$.Given the original deck, output the deck with maximum possible order you can make using the operation above.
512 megabytes
import java.util.*; public class CardDeck { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int tests = sc.nextInt(); sc.nextLine(); int[] A = new int[101010]; int[] pos = new int[101010]; while (tests > 0) { long stackSize = sc.nextInt(); sc.nextLine(); for (int i = 1; i <= stackSize; i++) { A[i] = sc.nextInt(); pos[A[i]] = i; } long p = stackSize; long l = stackSize + 1; while (p >= 1) { if (pos[(int) p] >= l) { p--; } else { for (int i = pos[(int) p]; i < l; i++) { System.out.print(A[i] + " "); } l = pos[(int)p]; } } System.out.print("\n"); tests--; } } }
Java
["4\n4\n1 2 3 4\n5\n1 5 2 4 3\n6\n4 2 5 3 6 1\n1\n1"]
1 second
["4 3 2 1\n5 2 4 3 1\n6 1 5 3 4 2\n1"]
NoteIn the first test case, one of the optimal strategies is the next one: take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1, 2, 3]$$$, $$$p'$$$ becomes $$$[4]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1, 2]$$$, $$$p'$$$ becomes $$$[4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[4, 3, 2]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[4, 3, 2, 1]$$$. In result, $$$p'$$$ has order equal to $$$4^3 \cdot 4 + 4^2 \cdot 3 + 4^1 \cdot 2 + 4^0 \cdot 1$$$ $$$=$$$ $$$256 + 48 + 8 + 1 = 313$$$.In the second test case, one of the optimal strategies is: take $$$4$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[5, 2, 4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[5, 2, 4, 3, 1]$$$; In result, $$$p'$$$ has order equal to $$$5^4 \cdot 5 + 5^3 \cdot 2 + 5^2 \cdot 4 + 5^1 \cdot 3 + 5^0 \cdot 1$$$ $$$=$$$ $$$3125 + 250 + 100 + 15 + 1 = 3491$$$.In the third test case, one of the optimal strategies is: take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2, 5, 3]$$$, $$$p'$$$ becomes $$$[6, 1]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2]$$$, $$$p'$$$ becomes $$$[6, 1, 5, 3]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[6, 1, 5, 3, 4, 2]$$$. In result, $$$p'$$$ has order equal to $$$6^5 \cdot 6 + 6^4 \cdot 1 + 6^3 \cdot 5 + 6^2 \cdot 3 + 6^1 \cdot 4 + 6^0 \cdot 2$$$ $$$=$$$ $$$46656 + 1296 + 1080 + 108 + 24 + 2 = 49166$$$.
Java 8
standard input
[ "data structures", "greedy", "math" ]
1637670255f8bd82a01e2ab20cdcc9aa
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the size of deck you have. The second line contains $$$n$$$ integers $$$p_1, p_2,\dots, p_n$$$ ($$$1 \le p_i \le n$$$; $$$p_i \neq p_j$$$ if $$$i \neq j$$$) — values of card in the deck from bottom to top. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,100
For each test case print the deck with maximum possible order. Print values of cards in the deck from bottom to top. If there are multiple answers, print any of them.
standard output
PASSED
1c149189da99027518201324adcc4156
train_109.jsonl
1614071100
You have a deck of $$$n$$$ cards, and you'd like to reorder it to a new one.Each card has a value between $$$1$$$ and $$$n$$$ equal to $$$p_i$$$. All $$$p_i$$$ are pairwise distinct. Cards in a deck are numbered from bottom to top, i. e. $$$p_1$$$ stands for the bottom card, $$$p_n$$$ is the top card. In each step you pick some integer $$$k &gt; 0$$$, take the top $$$k$$$ cards from the original deck and place them, in the order they are now, on top of the new deck. You perform this operation until the original deck is empty. (Refer to the notes section for the better understanding.)Let's define an order of a deck as $$$\sum\limits_{i = 1}^{n}{n^{n - i} \cdot p_i}$$$.Given the original deck, output the deck with maximum possible order you can make using the operation above.
512 megabytes
import java.util.ArrayList; import java.util.Scanner; 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[] indexOf = new int[n]; int[] arr = new int[n]; for(int i=0;i<n;i++) arr[i] = sc.nextInt()-1; for(int i=0;i<n;i++) indexOf[arr[i]] = i; int left = n; ArrayList<Integer> ans = new ArrayList<Integer>(); for(int i=n-1;i>=0;i--) { int cur = indexOf[i]; if(cur>=left) continue; for(int j=cur;j<left;j++) ans.add(arr[j]); left = cur; } for(int e:ans) { System.out.print(e+1+" "); } System.out.println(); } } }
Java
["4\n4\n1 2 3 4\n5\n1 5 2 4 3\n6\n4 2 5 3 6 1\n1\n1"]
1 second
["4 3 2 1\n5 2 4 3 1\n6 1 5 3 4 2\n1"]
NoteIn the first test case, one of the optimal strategies is the next one: take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1, 2, 3]$$$, $$$p'$$$ becomes $$$[4]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1, 2]$$$, $$$p'$$$ becomes $$$[4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[4, 3, 2]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[4, 3, 2, 1]$$$. In result, $$$p'$$$ has order equal to $$$4^3 \cdot 4 + 4^2 \cdot 3 + 4^1 \cdot 2 + 4^0 \cdot 1$$$ $$$=$$$ $$$256 + 48 + 8 + 1 = 313$$$.In the second test case, one of the optimal strategies is: take $$$4$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[5, 2, 4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[5, 2, 4, 3, 1]$$$; In result, $$$p'$$$ has order equal to $$$5^4 \cdot 5 + 5^3 \cdot 2 + 5^2 \cdot 4 + 5^1 \cdot 3 + 5^0 \cdot 1$$$ $$$=$$$ $$$3125 + 250 + 100 + 15 + 1 = 3491$$$.In the third test case, one of the optimal strategies is: take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2, 5, 3]$$$, $$$p'$$$ becomes $$$[6, 1]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2]$$$, $$$p'$$$ becomes $$$[6, 1, 5, 3]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[6, 1, 5, 3, 4, 2]$$$. In result, $$$p'$$$ has order equal to $$$6^5 \cdot 6 + 6^4 \cdot 1 + 6^3 \cdot 5 + 6^2 \cdot 3 + 6^1 \cdot 4 + 6^0 \cdot 2$$$ $$$=$$$ $$$46656 + 1296 + 1080 + 108 + 24 + 2 = 49166$$$.
Java 8
standard input
[ "data structures", "greedy", "math" ]
1637670255f8bd82a01e2ab20cdcc9aa
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the size of deck you have. The second line contains $$$n$$$ integers $$$p_1, p_2,\dots, p_n$$$ ($$$1 \le p_i \le n$$$; $$$p_i \neq p_j$$$ if $$$i \neq j$$$) — values of card in the deck from bottom to top. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,100
For each test case print the deck with maximum possible order. Print values of cards in the deck from bottom to top. If there are multiple answers, print any of them.
standard output
PASSED
035fc77b68d6452d8fbf8f1237d31423
train_109.jsonl
1614071100
You have a deck of $$$n$$$ cards, and you'd like to reorder it to a new one.Each card has a value between $$$1$$$ and $$$n$$$ equal to $$$p_i$$$. All $$$p_i$$$ are pairwise distinct. Cards in a deck are numbered from bottom to top, i. e. $$$p_1$$$ stands for the bottom card, $$$p_n$$$ is the top card. In each step you pick some integer $$$k &gt; 0$$$, take the top $$$k$$$ cards from the original deck and place them, in the order they are now, on top of the new deck. You perform this operation until the original deck is empty. (Refer to the notes section for the better understanding.)Let's define an order of a deck as $$$\sum\limits_{i = 1}^{n}{n^{n - i} \cdot p_i}$$$.Given the original deck, output the deck with maximum possible order you can make using the operation above.
512 megabytes
import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedList; import java.util.TreeSet; public class CardDeck { public static void solve(ArrayList<Integer> q,int max,int n) { // System.out.println(q); // System.out.println(max); TreeSet<Integer> set=new TreeSet<Integer>(); set.addAll(q); ArrayList<Integer> fq=new ArrayList<>(); while(q.size()>0) { max=set.last(); int k=0; for(int i=q.size()-1;i>=0;i--) { if(q.get(i)==max) { for(int j=i;j<q.size();j++) { int x=q.get(j); fq.add(x); set.remove(x); } k++; break; } k++; } for(int i=0;i<k;i++) { q.remove(q.size()-1); } } // System.out.println(fq); // rec(q, fq, k); StringBuilder sb=new StringBuilder(); for(int i=0;i<fq.size();i++) { sb.append(fq.get(i)+" "); } System.out.println(sb.toString()); // System.out.println(fq); } // public static void rec(LinkedList<Integer> q,LinkedList<Integer> fq,int k) { // // if(q.size() == 0) return; // // if(q.size()>k&&q.get(q.size()-k)>q.getFirst()) { //// System.out.println("hi"+q); //// System.out.println("hi"+fq); // for (int i =q.size()-k ; i < q.size();i++) { // fq.add(q.get(i)); // } // for (int i =0; i < k;i++) { // q.removeLast(); // } // rec(q, fq, k); // } // else { //// System.out.println("hlo"+q); //// System.out.println("hlo"+fq); // for (int i =0 ; i < q.size();i++) { // fq.add(q.get(i)); // } // for (int i =0 ; i <q.size();i++) { // q.pollLast(); // } //// rec(q, fq, k); // } // } public static void main(String[] args) throws IOException { // TODO Auto-generated method stub Reader in=new Reader(); int t=in.nextInt(); for (int i = 0; i < t; i++) { int n=in.nextInt(); ArrayList<Integer> q=new ArrayList<>(); int max=0; for(int j=0;j<n;j++) { int x=in.nextInt(); if(x>max) { max=x; } q.add(x); } solve(q, max,n); } } 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[120]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } }
Java
["4\n4\n1 2 3 4\n5\n1 5 2 4 3\n6\n4 2 5 3 6 1\n1\n1"]
1 second
["4 3 2 1\n5 2 4 3 1\n6 1 5 3 4 2\n1"]
NoteIn the first test case, one of the optimal strategies is the next one: take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1, 2, 3]$$$, $$$p'$$$ becomes $$$[4]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1, 2]$$$, $$$p'$$$ becomes $$$[4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[4, 3, 2]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[4, 3, 2, 1]$$$. In result, $$$p'$$$ has order equal to $$$4^3 \cdot 4 + 4^2 \cdot 3 + 4^1 \cdot 2 + 4^0 \cdot 1$$$ $$$=$$$ $$$256 + 48 + 8 + 1 = 313$$$.In the second test case, one of the optimal strategies is: take $$$4$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[5, 2, 4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[5, 2, 4, 3, 1]$$$; In result, $$$p'$$$ has order equal to $$$5^4 \cdot 5 + 5^3 \cdot 2 + 5^2 \cdot 4 + 5^1 \cdot 3 + 5^0 \cdot 1$$$ $$$=$$$ $$$3125 + 250 + 100 + 15 + 1 = 3491$$$.In the third test case, one of the optimal strategies is: take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2, 5, 3]$$$, $$$p'$$$ becomes $$$[6, 1]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2]$$$, $$$p'$$$ becomes $$$[6, 1, 5, 3]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[6, 1, 5, 3, 4, 2]$$$. In result, $$$p'$$$ has order equal to $$$6^5 \cdot 6 + 6^4 \cdot 1 + 6^3 \cdot 5 + 6^2 \cdot 3 + 6^1 \cdot 4 + 6^0 \cdot 2$$$ $$$=$$$ $$$46656 + 1296 + 1080 + 108 + 24 + 2 = 49166$$$.
Java 8
standard input
[ "data structures", "greedy", "math" ]
1637670255f8bd82a01e2ab20cdcc9aa
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the size of deck you have. The second line contains $$$n$$$ integers $$$p_1, p_2,\dots, p_n$$$ ($$$1 \le p_i \le n$$$; $$$p_i \neq p_j$$$ if $$$i \neq j$$$) — values of card in the deck from bottom to top. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,100
For each test case print the deck with maximum possible order. Print values of cards in the deck from bottom to top. If there are multiple answers, print any of them.
standard output
PASSED
88975de93f087826f5c61c6d2032b752
train_109.jsonl
1614071100
You have a deck of $$$n$$$ cards, and you'd like to reorder it to a new one.Each card has a value between $$$1$$$ and $$$n$$$ equal to $$$p_i$$$. All $$$p_i$$$ are pairwise distinct. Cards in a deck are numbered from bottom to top, i. e. $$$p_1$$$ stands for the bottom card, $$$p_n$$$ is the top card. In each step you pick some integer $$$k &gt; 0$$$, take the top $$$k$$$ cards from the original deck and place them, in the order they are now, on top of the new deck. You perform this operation until the original deck is empty. (Refer to the notes section for the better understanding.)Let's define an order of a deck as $$$\sum\limits_{i = 1}^{n}{n^{n - i} \cdot p_i}$$$.Given the original deck, output the deck with maximum possible order you can make using the operation above.
512 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int i,j,k,l,m,n,t,p; t = Integer.parseInt(st.nextToken()); for(p=1;p<=t;p++) { st = new StringTokenizer(br.readLine()); n = Integer.parseInt(st.nextToken()); int a[] = new int[n]; int b[] = new int[n]; int c[] = new int[n]; Set<Integer> s = new HashSet<Integer>(); st = new StringTokenizer(br.readLine()); for(i=0;i<n;i++) { a[i]=Integer.parseInt(st.nextToken()); b[i]=a[i]; } Arrays.sort(b); i = n-1; k = 0; l=n-1; while(i>=0) { j = l; if(k>=n) break; if(s.contains(b[i])) { i--; continue; } while(j>=0) { if(b[i]==a[j]) break; j--; } if(j!=-1) l=j-1; while(j<n && j>=0) { if(a[j]==0 || k>=n) break; else{ c[k] = a[j]; s.add(a[j]); a[j]=0; j++; k++; } } i--; } for(i=0;i<n;i++) System.out.print(c[i]+" "); System.out.println(); } } }
Java
["4\n4\n1 2 3 4\n5\n1 5 2 4 3\n6\n4 2 5 3 6 1\n1\n1"]
1 second
["4 3 2 1\n5 2 4 3 1\n6 1 5 3 4 2\n1"]
NoteIn the first test case, one of the optimal strategies is the next one: take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1, 2, 3]$$$, $$$p'$$$ becomes $$$[4]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1, 2]$$$, $$$p'$$$ becomes $$$[4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[4, 3, 2]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[4, 3, 2, 1]$$$. In result, $$$p'$$$ has order equal to $$$4^3 \cdot 4 + 4^2 \cdot 3 + 4^1 \cdot 2 + 4^0 \cdot 1$$$ $$$=$$$ $$$256 + 48 + 8 + 1 = 313$$$.In the second test case, one of the optimal strategies is: take $$$4$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[5, 2, 4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[5, 2, 4, 3, 1]$$$; In result, $$$p'$$$ has order equal to $$$5^4 \cdot 5 + 5^3 \cdot 2 + 5^2 \cdot 4 + 5^1 \cdot 3 + 5^0 \cdot 1$$$ $$$=$$$ $$$3125 + 250 + 100 + 15 + 1 = 3491$$$.In the third test case, one of the optimal strategies is: take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2, 5, 3]$$$, $$$p'$$$ becomes $$$[6, 1]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2]$$$, $$$p'$$$ becomes $$$[6, 1, 5, 3]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[6, 1, 5, 3, 4, 2]$$$. In result, $$$p'$$$ has order equal to $$$6^5 \cdot 6 + 6^4 \cdot 1 + 6^3 \cdot 5 + 6^2 \cdot 3 + 6^1 \cdot 4 + 6^0 \cdot 2$$$ $$$=$$$ $$$46656 + 1296 + 1080 + 108 + 24 + 2 = 49166$$$.
Java 8
standard input
[ "data structures", "greedy", "math" ]
1637670255f8bd82a01e2ab20cdcc9aa
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the size of deck you have. The second line contains $$$n$$$ integers $$$p_1, p_2,\dots, p_n$$$ ($$$1 \le p_i \le n$$$; $$$p_i \neq p_j$$$ if $$$i \neq j$$$) — values of card in the deck from bottom to top. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,100
For each test case print the deck with maximum possible order. Print values of cards in the deck from bottom to top. If there are multiple answers, print any of them.
standard output
PASSED
e33a9d3dd51c9080eea4d9dffb21d017
train_109.jsonl
1614071100
You have a deck of $$$n$$$ cards, and you'd like to reorder it to a new one.Each card has a value between $$$1$$$ and $$$n$$$ equal to $$$p_i$$$. All $$$p_i$$$ are pairwise distinct. Cards in a deck are numbered from bottom to top, i. e. $$$p_1$$$ stands for the bottom card, $$$p_n$$$ is the top card. In each step you pick some integer $$$k &gt; 0$$$, take the top $$$k$$$ cards from the original deck and place them, in the order they are now, on top of the new deck. You perform this operation until the original deck is empty. (Refer to the notes section for the better understanding.)Let's define an order of a deck as $$$\sum\limits_{i = 1}^{n}{n^{n - i} \cdot p_i}$$$.Given the original deck, output the deck with maximum possible order you can make using the operation above.
512 megabytes
import java.io.*; import java.math.BigInteger; import java.text.DecimalFormat; import java.util.*; //import jdk.javadoc.internal.doclets.toolkit.NestedClassWriter; public class Codeforces { static String a,b; static class Node { int val; Node left; Node right; public Node(int x) { // TODO Auto-generated constructor stub this.val=x; this.left=null; this.right=null; } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] nextArray(int n) { int arr[]=new int[n]; for(int i=0;i<n;i++) arr[i]=nextInt(); return arr; } } static String string; 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); } static long gcd(long a, long b) { // Everything divides 0 for(long i=2;i<=b;i++) { if(a%i==0&&b%i==0) return i; } return 1; } static int fac(int n) { int c=1; for(int i=2;i<n;i++) if(n%i==0) c=i; return c; } static boolean ab(int i,HashSet<Integer> hs,int n,int prev) { if(i==n) return true; int cur=2; while(i<4*n) { if(prev==-1) { hs.add(cur); if(ab(i+1, hs, n, cur)) { string=cur+" "+string; return true; } else hs.remove(hs.size()-1); } else { if(!hs.contains(cur)&&gcd(cur, prev)>1) { hs.add(cur); Iterator<Integer> iterator=hs.iterator(); int flag=0; while(iterator.hasNext()) { int x=iterator.next(); if(x%cur==0||cur%x==0) { flag=1; break; } } if(flag==0&&ab(i+1, hs, n, cur)) { string=cur+" "+string; return true; } hs.remove(hs.size()-1); } } cur+=2; } return false; } static boolean check(String all,String ch,int i,int k,boolean flag) { //System.out.println(i+","+k); if(i==all.length()||ch.length()==k) { if(ch.length()==k&&flag) return true; return false; } for(int j=i;j<all.length();j++) { if(i>0&&j!=i&&ch.charAt(k)==all.charAt(j)&&check(all, ch, j+1,k+1, true)) return true; else if(ch.charAt(k)==all.charAt(j)&&check(all, ch, j+1,k+1, flag)) return true; } return false; } static int lcm(int a,int b) { for(int i=Math.min(a, b);i<=a*b;i++) if(i%a==0&&i%b==0) return i; return 0; } static int maxheight(char[][] ch,int i,int j,String[] arr) { int h=1; if(i==ch.length-1||j==0||j==ch[0].length-1) return 1; while(i+h<ch.length&&j-h>=0&&j+h<ch[0].length&&ch[i+h][j-h]=='*'&&ch[i+h][j+h]=='*') { String whole=arr[i+h]; //System.out.println(whole.substring(j-h,j+h+1)); if(whole.substring(j-h,j+h+1).replace("*","").length()>0) return h; h++; } return h; } static boolean all(BigInteger n) { BigInteger c=n; HashSet<Character> hs=new HashSet<>(); while((c+"").compareTo("0")>0) { String d=""+c; char ch=d.charAt(d.length()-1); if(d.length()==1) { c=new BigInteger("0"); } else c=new BigInteger(d.substring(0,d.length()-1)); if(hs.contains(ch)) continue; if(d.charAt(d.length()-1)=='0') continue; if(!(n.mod(new BigInteger(""+ch)).equals(new BigInteger("0")))) return false; hs.add(ch); } return true; } static int cal(long n,long k) { System.out.println(n+","+k); if(n==k) return 2; if(n<k) return 1; if(k==1) return 1+cal(n, k+1); if(k>=32) return 1+cal(n/k, k); return 1+Math.min(cal(n/k, k),cal(n, k+1)); } static Node buildTree(int i,int j,int[] arr) { if(i==j) { //System.out.print(arr[i]); return new Node(arr[i]); } int max=i; for(int k=i+1;k<=j;k++) { if(arr[max]<arr[k]) max=k; } Node root=new Node(arr[max]); //System.out.print(arr[max]); if(max>i) root.left=buildTree(i, max-1, arr); else { root.left=null; } if(max<j) root.right=buildTree(max+1, j, arr); else { root.right=null; } return root; } static int height(Node root,int val) { if(root==null) return Integer.MAX_VALUE-32; if(root.val==val) return 0; if((root.left==null&&root.right==null)) return Integer.MAX_VALUE-32; return Math.min(height(root.left, val), height(root.right, val))+1; } static void shuffle(int a[], int n) { for (int i = 0; i < n; i++) { // getting the random index int t = (int)Math.random() * a.length; // and swapping values a random index // with the current index int x = a[t]; a[t] = a[i]; a[i] = x; } } static void sort(int[] arr ) { shuffle(arr, arr.length); Arrays.sort(arr); } static int helper(int i,boolean flag,int n,int c,int val,int[][][] dp) { if(i<=0||i>=n+1) { c++; return 1; } int last=flag?1:0; if(dp[i][val][last]!=0) return dp[i][val][last]; int ans=0; if(flag) { ans=helper(i+1, flag, n, c, val,dp); if(val>1) ans+=helper(i-1, !flag, n, c, val-1,dp); } else { ans=helper(i-1, flag, n, c, val,dp); if(val>1) ans+=helper(i+1, !flag, n, c, val-1,dp); } return dp[i][val][last]=ans; } static boolean valid(char[] arr,int k) { int[] count=new int[26]; for(int i=0;i<arr.length;i++) count[(int)arr[i]-'a']++; for(int i=0;i<26;i++) if(count[i]%k!=0) return false; return true; } static boolean helper(char[] text,int i,int o1,int c1,int o2,int c2,String temp1,String temp2,HashSet<String> hs) { if(i==text.length) { a=temp1; b=temp2; return true; } if(hs.contains(temp2+temp1)||hs.contains(temp1+temp2)) return false; hs.add(temp1+temp2); hs.add(temp2+temp1); if(text[i]=='1') { if(o1<text.length/2&&o2<text.length/2&&helper(text, i+1, o1+1, c1, o2+1, c2, temp1+"(", temp2+"(", hs)) return true; if(c1<o1&&c2<o2&&helper(text, i+1, o1, c1+1, o2, c2+1, temp1+")", temp2+")", hs)) return true; } else { if(o1<text.length/2&&c2<o2&&helper(text, i+1, o1+1, c1, o2, c2+1, temp1+"(", temp2+")", hs)) return true; if(o2<text.length/2&&c1<o1&&helper(text, i+1, o1, c1+1, o2+1, c2, temp1+")", temp2+"(", hs)) return true; } return false; } static int compute(int c,int r) { if(r<c/2) r=c-r; int ans=1; for(int i=c;i>r;i--) ans*=i; int fac=fac(c-r); return ans/fac; } static long helper(int[] arr,int in,int x,int y,HashMap<String,Long> hm) { if(in==arr.length||x==arr.length||y==arr.length) { if(in==arr.length||(x==arr.length&&y==arr.length)) return 0; else { return (arr.length-x)*arr[in]+(arr.length-y)*arr[in]; } } String key=x+","+y+","+in; if(hm.containsKey(key)) return hm.get(key); Long ans=Long.MAX_VALUE; if(in%2==0) { if(in>=arr.length-2) { return (arr.length-x)*arr[in]+helper(arr, in+1, arr.length, y,hm); } for(int i=x+1;i<=arr.length;i++) { ans=Math.min(ans,(i-x)*arr[in]+helper(arr, in+1, i, y,hm)); } } else { if(in>=arr.length-2) { return (arr.length-y)*arr[in]+helper(arr, in+1,x, arr.length,hm); } for(int i=y+1;i<=arr.length;i++) { ans=Math.min(ans,(i-y)*arr[in]+helper(arr, in+1, x, i,hm)); } } hm.put(key,ans); return ans; } public static void main(String[] args)throws IOException { BufferedReader bReader=new BufferedReader(new InputStreamReader(System.in)); FastReader fs=new FastReader(); PrintWriter out=new PrintWriter(System.out); int T=fs.nextInt(); StringBuilder sb=new StringBuilder(); while(T-->0) { string=""; int n=fs.nextInt(); int[] nums=fs.nextArray(n); Stack<Integer> st=new Stack<>(); st.push(0); int max=0; for(int i=1;i<n;i++) { if(nums[i]>nums[max]) { st.push(i); max=i; } } while(!st.isEmpty()) { int start=st.pop(); for(int i=start;i<n;i++) { sb.append(nums[i]+" "); } n=start; } sb.append("\n"); } System.out.println(sb); } }
Java
["4\n4\n1 2 3 4\n5\n1 5 2 4 3\n6\n4 2 5 3 6 1\n1\n1"]
1 second
["4 3 2 1\n5 2 4 3 1\n6 1 5 3 4 2\n1"]
NoteIn the first test case, one of the optimal strategies is the next one: take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1, 2, 3]$$$, $$$p'$$$ becomes $$$[4]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1, 2]$$$, $$$p'$$$ becomes $$$[4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[4, 3, 2]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[4, 3, 2, 1]$$$. In result, $$$p'$$$ has order equal to $$$4^3 \cdot 4 + 4^2 \cdot 3 + 4^1 \cdot 2 + 4^0 \cdot 1$$$ $$$=$$$ $$$256 + 48 + 8 + 1 = 313$$$.In the second test case, one of the optimal strategies is: take $$$4$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[5, 2, 4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[5, 2, 4, 3, 1]$$$; In result, $$$p'$$$ has order equal to $$$5^4 \cdot 5 + 5^3 \cdot 2 + 5^2 \cdot 4 + 5^1 \cdot 3 + 5^0 \cdot 1$$$ $$$=$$$ $$$3125 + 250 + 100 + 15 + 1 = 3491$$$.In the third test case, one of the optimal strategies is: take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2, 5, 3]$$$, $$$p'$$$ becomes $$$[6, 1]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2]$$$, $$$p'$$$ becomes $$$[6, 1, 5, 3]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[6, 1, 5, 3, 4, 2]$$$. In result, $$$p'$$$ has order equal to $$$6^5 \cdot 6 + 6^4 \cdot 1 + 6^3 \cdot 5 + 6^2 \cdot 3 + 6^1 \cdot 4 + 6^0 \cdot 2$$$ $$$=$$$ $$$46656 + 1296 + 1080 + 108 + 24 + 2 = 49166$$$.
Java 8
standard input
[ "data structures", "greedy", "math" ]
1637670255f8bd82a01e2ab20cdcc9aa
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the size of deck you have. The second line contains $$$n$$$ integers $$$p_1, p_2,\dots, p_n$$$ ($$$1 \le p_i \le n$$$; $$$p_i \neq p_j$$$ if $$$i \neq j$$$) — values of card in the deck from bottom to top. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,100
For each test case print the deck with maximum possible order. Print values of cards in the deck from bottom to top. If there are multiple answers, print any of them.
standard output