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
89b6e114edf9635b88571de7a42df89c
train_002.jsonl
1582448700
Nikolay has only recently started in competitive programming, but already qualified to the finals of one prestigious olympiad. There going to be $$$n$$$ participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took $$$x$$$-th place and in the second round — $$$y$$$-th place. Then the total score of the participant A is sum $$$x + y$$$. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every $$$i$$$ from $$$1$$$ to $$$n$$$ exactly one participant took $$$i$$$-th place in first round and exactly one participant took $$$i$$$-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got $$$x$$$-th place in first round and $$$y$$$-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.
256 megabytes
// practice with kaiboy import java.io.*; import java.util.*; public class CF1313B extends PrintWriter { CF1313B() { super(System.out, true); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1313B o = new CF1313B(); o.main(); o.flush(); } void main() { int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int x = sc.nextInt(); int y = sc.nextInt(); int kx = Math.min(x - 1, n - y); int ky = Math.min(y - 1, n - x); int imax = 1 + kx + ky + Math.min(x - 1 - kx, y - 1 - ky); int imin; if (x == n && y == n) { imin = n; } else if (x == n) { kx = Math.min(x - 1, n - 1 - y); imin = n - kx; } else if (y == n) { ky = Math.min(y - 1, n - 1 - x); imin = n - ky; } else { kx = Math.min(x - 1, n - 1 - y); ky = Math.min(y - 1, n - 1 - x); imin = n - 1 - kx - ky - Math.min(n - 1 - x - ky, n - 1 - y - kx); } println(imin + " " + imax); } } }
Java
["1\n5 1 3", "1\n6 3 4"]
1 second
["1 3", "2 6"]
NoteExplanation for the first example:Suppose there were 5 participants A-E. Let's denote Nikolay as A. The the most favorable results for Nikolay could look as follows: However, the results of the Olympiad could also look like this: In the first case Nikolay would have taken first place, and in the second — third place.
Java 11
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
58c887568002d947706c448e6faa0f77
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases to solve. Each of the following $$$t$$$ lines contains integers $$$n$$$, $$$x$$$, $$$y$$$ ($$$1 \leq n \leq 10^9$$$, $$$1 \le x, y \le n$$$) — the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round.
1,700
Print two integers — the minimum and maximum possible overall place Nikolay could take.
standard output
PASSED
206bfb7ae74d2f509633fec385e6c114
train_002.jsonl
1582448700
Nikolay has only recently started in competitive programming, but already qualified to the finals of one prestigious olympiad. There going to be $$$n$$$ participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took $$$x$$$-th place and in the second round — $$$y$$$-th place. Then the total score of the participant A is sum $$$x + y$$$. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every $$$i$$$ from $$$1$$$ to $$$n$$$ exactly one participant took $$$i$$$-th place in first round and exactly one participant took $$$i$$$-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got $$$x$$$-th place in first round and $$$y$$$-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.
256 megabytes
import java.util.*; public class MyClass { public static void main(String args[]) { Scanner in=new Scanner(System.in); int t=in.nextInt(); while(t-->0) { int n=in.nextInt(); int min=in.nextInt(); int max=in.nextInt(); int sum=max+min; int f=0; if(sum+1>n) f=Math.min(sum+1-n,n); else f=1; System.out.println(f+" "+Math.min(n,sum-1)); } } }
Java
["1\n5 1 3", "1\n6 3 4"]
1 second
["1 3", "2 6"]
NoteExplanation for the first example:Suppose there were 5 participants A-E. Let's denote Nikolay as A. The the most favorable results for Nikolay could look as follows: However, the results of the Olympiad could also look like this: In the first case Nikolay would have taken first place, and in the second — third place.
Java 11
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
58c887568002d947706c448e6faa0f77
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases to solve. Each of the following $$$t$$$ lines contains integers $$$n$$$, $$$x$$$, $$$y$$$ ($$$1 \leq n \leq 10^9$$$, $$$1 \le x, y \le n$$$) — the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round.
1,700
Print two integers — the minimum and maximum possible overall place Nikolay could take.
standard output
PASSED
c0dc1dd1077d041f47830da177d7d2cf
train_002.jsonl
1582448700
Nikolay has only recently started in competitive programming, but already qualified to the finals of one prestigious olympiad. There going to be $$$n$$$ participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took $$$x$$$-th place and in the second round — $$$y$$$-th place. Then the total score of the participant A is sum $$$x + y$$$. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every $$$i$$$ from $$$1$$$ to $$$n$$$ exactly one participant took $$$i$$$-th place in first round and exactly one participant took $$$i$$$-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got $$$x$$$-th place in first round and $$$y$$$-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.
256 megabytes
import java.io.*; import java.util.*; public class gym{ public static void main(String[] args) throws Exception{ MScanner sc=new MScanner(System.in); PrintWriter pw=new PrintWriter(System.out); int tc=sc.nextInt(); while(tc-->0) { long n=sc.nextLong(),x=sc.nextLong(),y=sc.nextLong(); long max=x+y-n; if(max<=0) { pw.print(1+" "); } else { pw.print(Math.min(n,(max+1))+" "); } long remx=n-x,remy=n-y; long takey=Math.min(remx, y-1); long takex=Math.min(remy, x-1); long xx=x-takex-1,yy=y-takey-1; pw.println(takex+takey+Math.min(xx, yy)+1); } pw.flush(); } static class MScanner { StringTokenizer st; BufferedReader br; public MScanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public MScanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int[] takearr(int n) throws IOException { int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public long[] takearrl(int n) throws IOException { long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public Integer[] takearrobj(int n) throws IOException { Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public Long[] takearrlobj(int n) throws IOException { Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } }
Java
["1\n5 1 3", "1\n6 3 4"]
1 second
["1 3", "2 6"]
NoteExplanation for the first example:Suppose there were 5 participants A-E. Let's denote Nikolay as A. The the most favorable results for Nikolay could look as follows: However, the results of the Olympiad could also look like this: In the first case Nikolay would have taken first place, and in the second — third place.
Java 11
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
58c887568002d947706c448e6faa0f77
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases to solve. Each of the following $$$t$$$ lines contains integers $$$n$$$, $$$x$$$, $$$y$$$ ($$$1 \leq n \leq 10^9$$$, $$$1 \le x, y \le n$$$) — the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round.
1,700
Print two integers — the minimum and maximum possible overall place Nikolay could take.
standard output
PASSED
1853914f3f053c28ffc8e78a7ccc6493
train_002.jsonl
1582448700
Nikolay has only recently started in competitive programming, but already qualified to the finals of one prestigious olympiad. There going to be $$$n$$$ participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took $$$x$$$-th place and in the second round — $$$y$$$-th place. Then the total score of the participant A is sum $$$x + y$$$. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every $$$i$$$ from $$$1$$$ to $$$n$$$ exactly one participant took $$$i$$$-th place in first round and exactly one participant took $$$i$$$-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got $$$x$$$-th place in first round and $$$y$$$-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.
256 megabytes
import java.io.*; import java.lang.*; import java.math.*; import java.util.*; public class B2 { static InputReader in = new InputReader(System.in); static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) throws Exception { int n = in.nextInt(); int par, first, second; int best =0; int worst = 0; while(n --> 0) { par=in.nextInt(); first = in.nextInt(); second = in.nextInt(); worst= Math.min(first+second-1, par); best = Math.max(1 , Math.min(first+second+1-par,par)); out.println(best+ " " +worst); } out.close(); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { try { return reader.readLine(); } catch (Exception e) { e.printStackTrace(); } return null; } public boolean hasNext() { String next = null; try { next = reader.readLine(); } catch (Exception e) { } if (next == null) { return false; } tokenizer = new StringTokenizer(next); return true; } public BigInteger nextBigInteger() { return new BigInteger(next()); } public int[] intArr() throws Exception { String[] strarray = reader.readLine().trim().split(" "); int[] intarray = new int[strarray.length]; for (int i = 0; i < intarray.length; i++) { intarray[i] = Integer.parseInt(strarray[i]); } return intarray; } /* long Array*/ public long[] longArr() throws Exception { String[] strarray = reader.readLine().trim().split(" "); long[] longarray = new long[strarray.length]; for (int i = 0; i < longarray.length; i++) { longarray[i] = Long.parseLong(strarray[i]); } return longarray; } } }
Java
["1\n5 1 3", "1\n6 3 4"]
1 second
["1 3", "2 6"]
NoteExplanation for the first example:Suppose there were 5 participants A-E. Let's denote Nikolay as A. The the most favorable results for Nikolay could look as follows: However, the results of the Olympiad could also look like this: In the first case Nikolay would have taken first place, and in the second — third place.
Java 11
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
58c887568002d947706c448e6faa0f77
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases to solve. Each of the following $$$t$$$ lines contains integers $$$n$$$, $$$x$$$, $$$y$$$ ($$$1 \leq n \leq 10^9$$$, $$$1 \le x, y \le n$$$) — the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round.
1,700
Print two integers — the minimum and maximum possible overall place Nikolay could take.
standard output
PASSED
38356ed22ea89f1d34b0f646e902e79f
train_002.jsonl
1582448700
Nikolay has only recently started in competitive programming, but already qualified to the finals of one prestigious olympiad. There going to be $$$n$$$ participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took $$$x$$$-th place and in the second round — $$$y$$$-th place. Then the total score of the participant A is sum $$$x + y$$$. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every $$$i$$$ from $$$1$$$ to $$$n$$$ exactly one participant took $$$i$$$-th place in first round and exactly one participant took $$$i$$$-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got $$$x$$$-th place in first round and $$$y$$$-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class cf1313b { public static void main(String[] args) throws IOException { int t = ri(); while(t --> 0) { int n = rni(), x = ni(), y = ni(); prln(max(1, x + y + 1 - n - (min(x, y) == n ? 1 : 0)), min(n, x + y - 1)); } close(); } static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out)); static StringTokenizer input; static Random rand = new Random(); // references // IBIG = 1e9 + 7 // IRAND ~= 3e8 // IMAX ~= 2e10 // LMAX ~= 9e18 // constants static final int IBIG = 1000000007; static final int IRAND = 327859546; static final int IMAX = 2147483647; static final int IMIN = -2147483648; static final long LMAX = 9223372036854775807L; static final long LMIN = -9223372036854775808L; // util static int minof(int a, int b, int c) {return min(a, min(b, c));} static int minof(int... x) {return x.length == 1 ? x[0] : x.length == 2 ? min(x[0], x[1]) : min(x[0], minstarting(1, x));} static int minstarting(int offset, int... x) {assert x.length > 2; return offset == x.length - 2 ? min(x[offset], x[offset + 1]) : min(x[offset], minstarting(offset + 1, x));} static long minof(long a, long b, long c) {return min(a, min(b, c));} static long minof(long... x) {return x.length == 1 ? x[0] : x.length == 2 ? min(x[0], x[1]) : min(x[0], minstarting(1, x));} static long minstarting(int offset, long... x) {assert x.length > 2; return offset == x.length - 2 ? min(x[offset], x[offset + 1]) : min(x[offset], minstarting(offset + 1, x));} static int maxof(int a, int b, int c) {return max(a, max(b, c));} static int maxof(int... x) {return x.length == 1 ? x[0] : x.length == 2 ? max(x[0], x[1]) : max(x[0], maxstarting(1, x));} static int maxstarting(int offset, int... x) {assert x.length > 2; return offset == x.length - 2 ? max(x[offset], x[offset + 1]) : max(x[offset], maxstarting(offset + 1, x));} static long maxof(long a, long b, long c) {return max(a, max(b, c));} static long maxof(long... x) {return x.length == 1 ? x[0] : x.length == 2 ? max(x[0], x[1]) : max(x[0], maxstarting(1, x));} static long maxstarting(int offset, long... x) {assert x.length > 2; return offset == x.length - 2 ? max(x[offset], x[offset + 1]) : max(x[offset], maxstarting(offset + 1, x));} 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 floori(double d) {return (int)d;} static int ceili(double d) {return (int)ceil(d);} static long floorl(double d) {return (long)d;} static long ceill(double d) {return (long)ceil(d);} 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 <T> void shuffle(T[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); T swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void sort(int[] a) {shuffle(a); Arrays.sort(a);} static void sort(long[] a) {shuffle(a); Arrays.sort(a);} static void sort(double[] a) {shuffle(a); Arrays.sort(a);} static void qsort(int[] a) {Arrays.sort(a);} static void qsort(long[] a) {Arrays.sort(a);} static void qsort(double[] a) {Arrays.sort(a);} static int randInt(int min, int max) {return rand.nextInt(max - min + 1) + min;} // input static void r() throws IOException {input = new StringTokenizer(__in.readLine());} static int ri() throws IOException {return Integer.parseInt(__in.readLine());} static long rl() throws IOException {return Long.parseLong(__in.readLine());} static int[] ria(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()); return a;} static long[] rla(int n) throws IOException {long[] a = new long[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Long.parseLong(input.nextToken()); return a;} static char[] rcha() throws IOException {return __in.readLine().toCharArray();} static String rline() throws IOException {return __in.readLine();} static int rni() throws IOException {input = new StringTokenizer(__in.readLine()); return Integer.parseInt(input.nextToken());} static int ni() {return Integer.parseInt(input.nextToken());} static long rnl() throws IOException {input = new StringTokenizer(__in.readLine()); return Long.parseLong(input.nextToken());} static long nl() {return Long.parseLong(input.nextToken());} // output static void pr(int i) {__out.print(i);} static void prln(int i) {__out.println(i);} static void pr(long l) {__out.print(l);} static void prln(long l) {__out.println(l);} static void pr(double d) {__out.print(d);} static void prln(double d) {__out.println(d);} static void pr(char c) {__out.print(c);} static void prln(char c) {__out.println(c);} static void pr(char[] s) {__out.print(new String(s));} static void prln(char[] s) {__out.println(new String(s));} static void pr(String s) {__out.print(s);} static void prln(String s) {__out.println(s);} static void pr(Object o) {__out.print(o);} static void prln(Object o) {__out.println(o);} static void prln() {__out.println();} static void pryes() {__out.println("yes");} static void pry() {__out.println("Yes");} static void prY() {__out.println("YES");} static void prno() {__out.println("no");} static void prn() {__out.println("No");} static void prN() {__out.println("NO");} static void pryesno(boolean b) {__out.println(b ? "yes" : "no");}; static void pryn(boolean b) {__out.println(b ? "Yes" : "No");} static void prYN(boolean b) {__out.println(b ? "YES" : "NO");} static void prln(int... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static void prln(long... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for(int i = 0; i < n; __out.print(iter.next()), __out.print(' '), ++i); if(n >= 0) __out.println(iter.next());} static void h() {__out.println("hlfd");} static void flush() {__out.flush();} static void close() {__out.close();} }
Java
["1\n5 1 3", "1\n6 3 4"]
1 second
["1 3", "2 6"]
NoteExplanation for the first example:Suppose there were 5 participants A-E. Let's denote Nikolay as A. The the most favorable results for Nikolay could look as follows: However, the results of the Olympiad could also look like this: In the first case Nikolay would have taken first place, and in the second — third place.
Java 11
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
58c887568002d947706c448e6faa0f77
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases to solve. Each of the following $$$t$$$ lines contains integers $$$n$$$, $$$x$$$, $$$y$$$ ($$$1 \leq n \leq 10^9$$$, $$$1 \le x, y \le n$$$) — the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round.
1,700
Print two integers — the minimum and maximum possible overall place Nikolay could take.
standard output
PASSED
639fceb90889284a7d208d4430b69cf4
train_002.jsonl
1582448700
Nikolay has only recently started in competitive programming, but already qualified to the finals of one prestigious olympiad. There going to be $$$n$$$ participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took $$$x$$$-th place and in the second round — $$$y$$$-th place. Then the total score of the participant A is sum $$$x + y$$$. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every $$$i$$$ from $$$1$$$ to $$$n$$$ exactly one participant took $$$i$$$-th place in first round and exactly one participant took $$$i$$$-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got $$$x$$$-th place in first round and $$$y$$$-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; import java.util.Arrays; import java.util.StringTokenizer; import java.util.function.*; import java.util.stream.*; public class B { private static final FastReader in = new FastReader(); private static final FastWriter out = new FastWriter(); public static void main(String[] args) { new B().run(); } private void run() { var t = in.nextInt(); while (t-- > 0) { solve(); } out.flush(); } private void solve() { var n = in.nextLong(); var x = in.nextLong(); var y = in.nextLong(); var min = Math.max((x - 1 - Math.min(x - 1, Math.max(n - y - 1, 0))), (y - 1 - Math.min(Math.max(n - x - 1, 0), y - 1))) + 1; var max = n - Math.min((n - x - Math.min(n - x, y - 1)), (n - y - Math.min(x - 1, n - y))); out.println(min + " " + max); } } class FastReader { private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); private static StringTokenizer in; public String next() { while (in == null || !in.hasMoreTokens()) { try { in = new StringTokenizer(br.readLine()); } catch (IOException e) { return null; } } return in.nextToken(); } public BigDecimal nextBigDecimal() { return new BigDecimal(next()); } public BigInteger nextBigInteger() { return new BigInteger(next()); } public boolean nextBoolean() { return Boolean.valueOf(next()); } public byte nextByte() { return Byte.valueOf(next()); } public double nextDouble() { return Double.valueOf(next()); } public double[] nextDoubleArray(int length) { var a = new double[length]; for (var i = 0; i < length; i++) { a[i] = nextDouble(); } return a; } public int nextInt() { return Integer.valueOf(next()); } public int[] nextIntArray(int length) { var a = new int[length]; for (var i = 0; i < length; i++) { a[i] = nextInt(); } return a; } public long nextLong() { return Long.valueOf(next()); } public long[] nextLongArray(int length) { var a = new long[length]; for (var i = 0; i < length; i++) { a[i] = nextLong(); } return a; } } class FastWriter extends PrintWriter { public FastWriter() { super(System.out); } public void println(double[] a) { for (var i = 0; i < a.length; i++) { print(a[i]); print(i + 1 < a.length ? ' ' : '\n'); } } public void println(int[] a) { for (var i = 0; i < a.length; i++) { print(a[i]); print(i + 1 < a.length ? ' ' : '\n'); } } public void println(long[] a) { for (var i = 0; i < a.length; i++) { print(a[i]); print(i + 1 < a.length ? ' ' : '\n'); } } public <T> void println(T[] a) { for (var i = 0; i < a.length; i++) { print(a[i]); print(i + 1 < a.length ? ' ' : '\n'); } } public void debug(String name, Object o) { String value = Arrays.deepToString(new Object[] { o }); value = value.substring(1, value.length() - 1); System.err.println(name + " => " + value); } }
Java
["1\n5 1 3", "1\n6 3 4"]
1 second
["1 3", "2 6"]
NoteExplanation for the first example:Suppose there were 5 participants A-E. Let's denote Nikolay as A. The the most favorable results for Nikolay could look as follows: However, the results of the Olympiad could also look like this: In the first case Nikolay would have taken first place, and in the second — third place.
Java 11
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
58c887568002d947706c448e6faa0f77
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases to solve. Each of the following $$$t$$$ lines contains integers $$$n$$$, $$$x$$$, $$$y$$$ ($$$1 \leq n \leq 10^9$$$, $$$1 \le x, y \le n$$$) — the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round.
1,700
Print two integers — the minimum and maximum possible overall place Nikolay could take.
standard output
PASSED
82d250c5d63d070f2680b290728fc057
train_002.jsonl
1582448700
Nikolay has only recently started in competitive programming, but already qualified to the finals of one prestigious olympiad. There going to be $$$n$$$ participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took $$$x$$$-th place and in the second round — $$$y$$$-th place. Then the total score of the participant A is sum $$$x + y$$$. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every $$$i$$$ from $$$1$$$ to $$$n$$$ exactly one participant took $$$i$$$-th place in first round and exactly one participant took $$$i$$$-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got $$$x$$$-th place in first round and $$$y$$$-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; import java.util.Arrays; import java.util.StringTokenizer; import java.util.function.*; import java.util.stream.*; public class B { private static final FastReader in = new FastReader(); private static final FastWriter out = new FastWriter(); public static void main(String[] args) { new B().run(); } private void run() { var t = in.nextInt(); while (t-- > 0) { solve(); } out.flush(); } private void solve() { var n = in.nextInt(); var x = in.nextInt(); var y = in.nextInt(); var min = Math.max((x - 1 - Math.min(x - 1, Math.max(n - y - 1, 0))), (y - 1 - Math.min(Math.max(n - x - 1, 0), y - 1))) + 1; var max = n - Math.min((n - x - Math.min(n - x, y - 1)), (n - y - Math.min(x - 1, n - y))); out.println(min + " " + max); } } class FastReader { private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); private static StringTokenizer in; public String next() { while (in == null || !in.hasMoreTokens()) { try { in = new StringTokenizer(br.readLine()); } catch (IOException e) { return null; } } return in.nextToken(); } public BigDecimal nextBigDecimal() { return new BigDecimal(next()); } public BigInteger nextBigInteger() { return new BigInteger(next()); } public boolean nextBoolean() { return Boolean.valueOf(next()); } public byte nextByte() { return Byte.valueOf(next()); } public double nextDouble() { return Double.valueOf(next()); } public double[] nextDoubleArray(int length) { var a = new double[length]; for (var i = 0; i < length; i++) { a[i] = nextDouble(); } return a; } public int nextInt() { return Integer.valueOf(next()); } public int[] nextIntArray(int length) { var a = new int[length]; for (var i = 0; i < length; i++) { a[i] = nextInt(); } return a; } public long nextLong() { return Long.valueOf(next()); } public long[] nextLongArray(int length) { var a = new long[length]; for (var i = 0; i < length; i++) { a[i] = nextLong(); } return a; } } class FastWriter extends PrintWriter { public FastWriter() { super(System.out); } public void println(double[] a) { for (var i = 0; i < a.length; i++) { print(a[i]); print(i + 1 < a.length ? ' ' : '\n'); } } public void println(int[] a) { for (var i = 0; i < a.length; i++) { print(a[i]); print(i + 1 < a.length ? ' ' : '\n'); } } public void println(long[] a) { for (var i = 0; i < a.length; i++) { print(a[i]); print(i + 1 < a.length ? ' ' : '\n'); } } public <T> void println(T[] a) { for (var i = 0; i < a.length; i++) { print(a[i]); print(i + 1 < a.length ? ' ' : '\n'); } } public void debug(String name, Object o) { String value = Arrays.deepToString(new Object[] { o }); value = value.substring(1, value.length() - 1); System.err.println(name + " => " + value); } }
Java
["1\n5 1 3", "1\n6 3 4"]
1 second
["1 3", "2 6"]
NoteExplanation for the first example:Suppose there were 5 participants A-E. Let's denote Nikolay as A. The the most favorable results for Nikolay could look as follows: However, the results of the Olympiad could also look like this: In the first case Nikolay would have taken first place, and in the second — third place.
Java 11
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
58c887568002d947706c448e6faa0f77
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases to solve. Each of the following $$$t$$$ lines contains integers $$$n$$$, $$$x$$$, $$$y$$$ ($$$1 \leq n \leq 10^9$$$, $$$1 \le x, y \le n$$$) — the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round.
1,700
Print two integers — the minimum and maximum possible overall place Nikolay could take.
standard output
PASSED
14cbc7ebbad0eeba97a7ecbb23c7d3ca
train_002.jsonl
1582448700
Nikolay has only recently started in competitive programming, but already qualified to the finals of one prestigious olympiad. There going to be $$$n$$$ participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took $$$x$$$-th place and in the second round — $$$y$$$-th place. Then the total score of the participant A is sum $$$x + y$$$. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every $$$i$$$ from $$$1$$$ to $$$n$$$ exactly one participant took $$$i$$$-th place in first round and exactly one participant took $$$i$$$-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got $$$x$$$-th place in first round and $$$y$$$-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.
256 megabytes
import java.sql.PseudoColumnUsage; import java.util.*; public class D { public static void main(String args[]) { Scanner sc=new Scanner(System.in); int cases = sc.nextInt(); for(int i=0;i<cases;i++) { //int arr[] =new int[3]; int n =sc.nextInt(); int x=sc.nextInt(); int y=sc.nextInt(); int max=Math.min(n,(x+y)-1); int min=Math.min(n,x+y-n+1); if(min<1) { min=1; } System.out.println(min+" "+max); } } }
Java
["1\n5 1 3", "1\n6 3 4"]
1 second
["1 3", "2 6"]
NoteExplanation for the first example:Suppose there were 5 participants A-E. Let's denote Nikolay as A. The the most favorable results for Nikolay could look as follows: However, the results of the Olympiad could also look like this: In the first case Nikolay would have taken first place, and in the second — third place.
Java 11
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
58c887568002d947706c448e6faa0f77
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases to solve. Each of the following $$$t$$$ lines contains integers $$$n$$$, $$$x$$$, $$$y$$$ ($$$1 \leq n \leq 10^9$$$, $$$1 \le x, y \le n$$$) — the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round.
1,700
Print two integers — the minimum and maximum possible overall place Nikolay could take.
standard output
PASSED
a5262e8aa19cd099086c255cff553ccc
train_002.jsonl
1582448700
Nikolay has only recently started in competitive programming, but already qualified to the finals of one prestigious olympiad. There going to be $$$n$$$ participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took $$$x$$$-th place and in the second round — $$$y$$$-th place. Then the total score of the participant A is sum $$$x + y$$$. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every $$$i$$$ from $$$1$$$ to $$$n$$$ exactly one participant took $$$i$$$-th place in first round and exactly one participant took $$$i$$$-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got $$$x$$$-th place in first round and $$$y$$$-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.
256 megabytes
import java.util.*; import java.io.*; public class B622 { public static void main(String [] args) { MyScanner sc = new MyScanner(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int t = sc.nextInt(); while (t > 0) { int n = sc.nextInt(); int x = sc.nextInt(); int y = sc.nextInt(); if (x + y < n + 1) { System.out.println(1 + " " + (x + y - 1)); } else if (x + y > n + 1) { System.out.println(Math.min(x + y - n + 1, n) + " " + n); } else { if (x == 1 && y == 1) { System.out.println(1 + " " + 1); }else System.out.println(2 + " " + n); } t--; } out.close(); } //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["1\n5 1 3", "1\n6 3 4"]
1 second
["1 3", "2 6"]
NoteExplanation for the first example:Suppose there were 5 participants A-E. Let's denote Nikolay as A. The the most favorable results for Nikolay could look as follows: However, the results of the Olympiad could also look like this: In the first case Nikolay would have taken first place, and in the second — third place.
Java 11
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
58c887568002d947706c448e6faa0f77
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases to solve. Each of the following $$$t$$$ lines contains integers $$$n$$$, $$$x$$$, $$$y$$$ ($$$1 \leq n \leq 10^9$$$, $$$1 \le x, y \le n$$$) — the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round.
1,700
Print two integers — the minimum and maximum possible overall place Nikolay could take.
standard output
PASSED
69b8a1f6629ddf6333000b00b44f4883
train_002.jsonl
1582448700
Nikolay has only recently started in competitive programming, but already qualified to the finals of one prestigious olympiad. There going to be $$$n$$$ participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took $$$x$$$-th place and in the second round — $$$y$$$-th place. Then the total score of the participant A is sum $$$x + y$$$. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every $$$i$$$ from $$$1$$$ to $$$n$$$ exactly one participant took $$$i$$$-th place in first round and exactly one participant took $$$i$$$-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got $$$x$$$-th place in first round and $$$y$$$-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; public class Class2 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int tt = Integer.parseInt(br.readLine()); StringBuffer res = new StringBuffer(); while (tt-- > 0) { StringTokenizer st = new StringTokenizer(br.readLine(), " "); long n=Long.parseLong(st.nextToken()); long x=Long.parseLong(st.nextToken()); long y=Long.parseLong(st.nextToken()); long s=x+y+1; long ans=s-n; if(ans<1){ ans=1; } if(ans>n){ ans=n; } long ans1=s-2; if(ans1<1){ ans1=1; } if (ans1>n){ ans1=n; } res.append(ans+" "+ans1+"\n"); } System.out.println(res); } }
Java
["1\n5 1 3", "1\n6 3 4"]
1 second
["1 3", "2 6"]
NoteExplanation for the first example:Suppose there were 5 participants A-E. Let's denote Nikolay as A. The the most favorable results for Nikolay could look as follows: However, the results of the Olympiad could also look like this: In the first case Nikolay would have taken first place, and in the second — third place.
Java 11
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
58c887568002d947706c448e6faa0f77
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases to solve. Each of the following $$$t$$$ lines contains integers $$$n$$$, $$$x$$$, $$$y$$$ ($$$1 \leq n \leq 10^9$$$, $$$1 \le x, y \le n$$$) — the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round.
1,700
Print two integers — the minimum and maximum possible overall place Nikolay could take.
standard output
PASSED
66a58df3e87ea428e3432d6cf6c8ff9d
train_002.jsonl
1582448700
Nikolay has only recently started in competitive programming, but already qualified to the finals of one prestigious olympiad. There going to be $$$n$$$ participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took $$$x$$$-th place and in the second round — $$$y$$$-th place. Then the total score of the participant A is sum $$$x + y$$$. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every $$$i$$$ from $$$1$$$ to $$$n$$$ exactly one participant took $$$i$$$-th place in first round and exactly one participant took $$$i$$$-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got $$$x$$$-th place in first round and $$$y$$$-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.
256 megabytes
import java.util.*; import java.math.*; import java.io.*; public class solution { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); for(int i=0;i<t;i++) { StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int x = Integer.parseInt(st.nextToken()); int y = Integer.parseInt(st.nextToken()); System.out.println(Math.max(1,Math.min(n,x+y-n+1))+ " " + Math.min(n,x+y-1)); } } }
Java
["1\n5 1 3", "1\n6 3 4"]
1 second
["1 3", "2 6"]
NoteExplanation for the first example:Suppose there were 5 participants A-E. Let's denote Nikolay as A. The the most favorable results for Nikolay could look as follows: However, the results of the Olympiad could also look like this: In the first case Nikolay would have taken first place, and in the second — third place.
Java 11
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
58c887568002d947706c448e6faa0f77
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases to solve. Each of the following $$$t$$$ lines contains integers $$$n$$$, $$$x$$$, $$$y$$$ ($$$1 \leq n \leq 10^9$$$, $$$1 \le x, y \le n$$$) — the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round.
1,700
Print two integers — the minimum and maximum possible overall place Nikolay could take.
standard output
PASSED
5d66fe429333c36d3ab81582a793be6c
train_002.jsonl
1582448700
Nikolay has only recently started in competitive programming, but already qualified to the finals of one prestigious olympiad. There going to be $$$n$$$ participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took $$$x$$$-th place and in the second round — $$$y$$$-th place. Then the total score of the participant A is sum $$$x + y$$$. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every $$$i$$$ from $$$1$$$ to $$$n$$$ exactly one participant took $$$i$$$-th place in first round and exactly one participant took $$$i$$$-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got $$$x$$$-th place in first round and $$$y$$$-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.
256 megabytes
import java.io.*; import java.util.*; //import javafx.util.*; import java.math.*; //import java.lang.*; public class Main { // static int n; static HashSet<Integer> adj[]; static boolean vis[]; // static long ans[]; // static int arr[]; static long mod=1000000007; static final long oo=(long)1e18; // static int n; public static void main(String[] args) throws IOException { // Scanner sc=new Scanner(System.in); PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); br = new BufferedReader(new InputStreamReader(System.in)); int test=nextInt(); //int test=1; outer:while(test-->0){ long n=nextLong(); long x=nextLong(); long y=nextLong(); long worst=Math.min(y-1,n-x)+Math.min(x-1,n-y)+1; worst+=Math.min(Math.max(x-1-Math.min(x-1,n-y),0),Math.max(y-1-Math.min(y-1,n-x),0)); long req=Math.max(Math.max(y-1-Math.max(Math.min(y-1,n-x-1),0),0),Math.max(x-1-Math.max(Math.min(x-1,n-y-1),0),0)); long best=req+1; // long best=Math.max(y-1-Math.min(y-1,n-x-1),0)+Math.max(x-1-Math.min(x-1,n-y-1),0)+1; pw.println(best+" "+worst); } pw.close(); } static class Pair implements Comparable<Pair>{ int time; HashMap<Integer,ArrayList<Integer> > hm; int maxbooks; int i; int sum; Pair(int time,HashMap<Integer,ArrayList<Integer> > hm,int maxbooks, int i,int sum){ this.time=time; this.hm=hm; this.maxbooks=maxbooks; this.i=i; this.sum=sum; } public int compareTo(Pair p){ if(time==p.time) return (sum-p.sum); return time-p.time; } } static void decToBinary(int n) { // array to store binary number int[] binaryNum = new int[1000]; // counter for binary array int i = 0; while (n > 0) { // storing remainder in binary array binaryNum[i] = n % 2; n = n / 2; i++; } // printing binary array in reverse order for (int j = i - 1; j >= 0; j--) System.out.print(binaryNum[j]); System.out.println(); } static long ncr(long n,long r){ if(r==0) return 1; long val=ncr(n-1,r-1); val=(n*val)%mod; val=(val*modInverse(r,mod))%mod; return val; } static int find(ArrayList<Integer> a,int i){ if(a.size()==0||i<0)return 0; ArrayList<Integer> l=new ArrayList<Integer>(); ArrayList<Integer> r=new ArrayList<Integer>(); for(int v:a){ if((v&(1<<i))!=0)l.add(v); else r.add(v); } if(l.size()==0)return find(r,i-1); if(r.size()==0)return find(l,i-1); return Math.min(find(l,i-1),find(r,i-1))+(1<<i); } public static BufferedReader br; public static StringTokenizer st; public static String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(e); } } return st.nextToken(); } public static Integer nextInt() { return Integer.parseInt(next()); } public static Long nextLong() { return Long.parseLong(next()); } public static Double nextDouble() { return Double.parseDouble(next()); } // static class Pair{ // int x;int y; // Pair(int x,int y,int z){ // this.x=x; // this.y=y; // // this.z=z; // // this.z=z; // // this.i=i; // } // } // static class sorting implements Comparator<Pair>{ // public int compare(Pair a,Pair b){ // //return (a.y)-(b.y); // if(a.y==b.y){ // return -1*(a.z-b.z); // } // return (a.y-b.y); // } // } public static int[] na(int n)throws IOException{ int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = nextInt(); return a; } static class query implements Comparable<query>{ int l,r,idx,block; static int len; query(int l,int r,int i){ this.l=l; this.r=r; this.idx=i; this.block=l/len; } public int compareTo(query a){ return block==a.block?r-a.r:block-a.block; } } // static class sorting implements Comparator<Pair>{ // public int compare(Pair a1,Pair a2){ // if(o1.a==o2.a) // return (o1.b>o2.b)?1:-1; // else if(o1.a>o2.a) // return 1; // else // return -1; // } // } static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } // To compute x^y under modulo m 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; } static long fast_pow(long base,long n,long M){ if(n==0) return 1; if(n==1) return base; long halfn=fast_pow(base,n/2,M); if(n%2==0) return ( halfn * halfn ) % M; else return ( ( ( halfn * halfn ) % M ) * base ) % M; } static long modInverse(long n,long M){ return fast_pow(n,M-2,M); } // (1,1) // (3,2) (3,5) }
Java
["1\n5 1 3", "1\n6 3 4"]
1 second
["1 3", "2 6"]
NoteExplanation for the first example:Suppose there were 5 participants A-E. Let's denote Nikolay as A. The the most favorable results for Nikolay could look as follows: However, the results of the Olympiad could also look like this: In the first case Nikolay would have taken first place, and in the second — third place.
Java 11
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
58c887568002d947706c448e6faa0f77
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases to solve. Each of the following $$$t$$$ lines contains integers $$$n$$$, $$$x$$$, $$$y$$$ ($$$1 \leq n \leq 10^9$$$, $$$1 \le x, y \le n$$$) — the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round.
1,700
Print two integers — the minimum and maximum possible overall place Nikolay could take.
standard output
PASSED
33eb6f7f1e834810dfa406d487350f0a
train_002.jsonl
1582448700
Nikolay has only recently started in competitive programming, but already qualified to the finals of one prestigious olympiad. There going to be $$$n$$$ participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took $$$x$$$-th place and in the second round — $$$y$$$-th place. Then the total score of the participant A is sum $$$x + y$$$. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every $$$i$$$ from $$$1$$$ to $$$n$$$ exactly one participant took $$$i$$$-th place in first round and exactly one participant took $$$i$$$-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got $$$x$$$-th place in first round and $$$y$$$-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Rustam Musin (t.me/musin_acm) */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); BAlternativniePravila solver = new BAlternativniePravila(); solver.solve(1, in, out); out.close(); } static class BAlternativniePravila { public void solve(int testNumber, InputReader in, OutputWriter out) { int t = in.readInt(); while (t-- > 0) { int n = in.readInt(); int a = in.readInt(); int b = in.readInt(); IntIntPair res = solve(a, b, n); out.printLine(res.first, res.second); } } IntIntPair solve(int a, int b, int n) { int min = findMin(a, b, n); int max = findMax(a, b, n); return IntIntPair.makePair(min, max); } int findMin(int a, int b, int n) { int x = Math.max(a + b + 1 - n, 1); int y = n; int ans = 0; while (y > 0 && x <= n) { if (x == a) { x++; continue; } if (y == b) { y--; if (x + y < a + b + 1) x++; continue; } int step1 = x > a ? (n - x + 1) : (a - x); int step2 = y < b ? (y) : (y - b); int step = Math.min(step1, step2); ans += step; x += step; y -= step; } return n - ans; } int findMax(int a, int b, int n) { int x = 1; int y = Math.min(n, a + b - 1); int ans = 0; while (y > 0 && x <= n) { if (y == b) { y--; continue; } if (x == a) { x++; if (x + y > a + b) y--; continue; } int step1 = x < a ? (a - x) : (n - x + 1); int step2 = y > b ? (y - b) : (y); int step = Math.min(step1, step2); ans += step; x += step; y -= step; } return ans + 1; } } static class IntIntPair implements Comparable<IntIntPair> { public final int first; public final int second; public static IntIntPair makePair(int first, int second) { return new IntIntPair(first, second); } public IntIntPair(int first, int second) { this.first = first; this.second = second; } public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } IntIntPair pair = (IntIntPair) o; return first == pair.first && second == pair.second; } public int hashCode() { int result = first; result = 31 * result + second; return result; } public String toString() { return "(" + first + "," + second + ")"; } public int compareTo(IntIntPair o) { int value = Integer.compare(first, o.first); if (value != 0) { return value; } return Integer.compare(second, o.second); } } 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(); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["1\n5 1 3", "1\n6 3 4"]
1 second
["1 3", "2 6"]
NoteExplanation for the first example:Suppose there were 5 participants A-E. Let's denote Nikolay as A. The the most favorable results for Nikolay could look as follows: However, the results of the Olympiad could also look like this: In the first case Nikolay would have taken first place, and in the second — third place.
Java 11
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
58c887568002d947706c448e6faa0f77
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases to solve. Each of the following $$$t$$$ lines contains integers $$$n$$$, $$$x$$$, $$$y$$$ ($$$1 \leq n \leq 10^9$$$, $$$1 \le x, y \le n$$$) — the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round.
1,700
Print two integers — the minimum and maximum possible overall place Nikolay could take.
standard output
PASSED
34804d30d1f24210a2e859591d7dd976
train_002.jsonl
1582448700
Nikolay has only recently started in competitive programming, but already qualified to the finals of one prestigious olympiad. There going to be $$$n$$$ participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took $$$x$$$-th place and in the second round — $$$y$$$-th place. Then the total score of the participant A is sum $$$x + y$$$. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every $$$i$$$ from $$$1$$$ to $$$n$$$ exactly one participant took $$$i$$$-th place in first round and exactly one participant took $$$i$$$-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got $$$x$$$-th place in first round and $$$y$$$-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.
256 megabytes
import java.io.PrintWriter; import java.util.Scanner; public class B { public static void main(String[] args) { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int t = in.nextInt(); while (t > 0) { int n, x, y; n = in.nextInt(); x = in.nextInt(); y = in.nextInt(); int min=n,max=1; int a=x-1,b=y-1,c=n-x,d=n-y; //bestCase int d1=0,c1=0; if(d>a) { min-=a; d1=d-a; } else { if(d!=0){min-=(d-1);d1=1;} } if(c>b) { min -= b; c1=c-b; } else { if(c!=0) {min-=(c-1);c1=1;} } min-=Math.min(c1,d1); //worstCase if(d>=a) max+=a; else { max+=d; } if(c>=b) max+=b; else { max+=c; } max+=Math.max(0,Math.max(a-d,b-c)); System.out.println(String.format("%d %d",min,max)); t--; } out.close(); } }
Java
["1\n5 1 3", "1\n6 3 4"]
1 second
["1 3", "2 6"]
NoteExplanation for the first example:Suppose there were 5 participants A-E. Let's denote Nikolay as A. The the most favorable results for Nikolay could look as follows: However, the results of the Olympiad could also look like this: In the first case Nikolay would have taken first place, and in the second — third place.
Java 11
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
58c887568002d947706c448e6faa0f77
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases to solve. Each of the following $$$t$$$ lines contains integers $$$n$$$, $$$x$$$, $$$y$$$ ($$$1 \leq n \leq 10^9$$$, $$$1 \le x, y \le n$$$) — the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round.
1,700
Print two integers — the minimum and maximum possible overall place Nikolay could take.
standard output
PASSED
e057c341d78c2c984f4feec09fa9783a
train_002.jsonl
1582448700
Nikolay has only recently started in competitive programming, but already qualified to the finals of one prestigious olympiad. There going to be $$$n$$$ participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took $$$x$$$-th place and in the second round — $$$y$$$-th place. Then the total score of the participant A is sum $$$x + y$$$. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every $$$i$$$ from $$$1$$$ to $$$n$$$ exactly one participant took $$$i$$$-th place in first round and exactly one participant took $$$i$$$-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got $$$x$$$-th place in first round and $$$y$$$-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.
256 megabytes
import java.util.*;import java.io.*;import java.math.*; public class temp { public static void process()throws IOException { long n=nl(); long a=nl(); long b=nl(); long best=0,worst=0; if(a+b<=n) { best=1; worst=a+b-1; } else { best=Math.min(a+b+1-n,n); worst=n; } pn(best+" "+worst); } static AnotherReader sc; static PrintWriter out; public static void main(String[]args)throws IOException { boolean oj = System.getProperty("ONLINE_JUDGE") != null; if(oj){sc=new AnotherReader();out=new PrintWriter(System.out);} else{sc=new AnotherReader(100);out=new PrintWriter("output.txt");} int t=1; t=ni(); while(t-->0) {process();} out.flush();out.close(); } static long mod=(long)1e9+7; static void pn(Object o){out.println(o);} static void p(Object o){out.print(o);} static void pni(Object o){out.println(o);out.flush();} static int ni()throws IOException{return sc.nextInt();} static long nl()throws IOException{return sc.nextLong();} static double nd()throws IOException{return sc.nextDouble();} static String nln()throws IOException{return sc.nextLine();} static int[] nai(int N)throws IOException{int[]A=new int[N];for(int i=0;i!=N;i++){A[i]=ni();}return A;} static long[] nal(int N)throws IOException{long[]A=new long[N];for(int i=0;i!=N;i++){A[i]=nl();}return A;} static long gcd(long a, long b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int gcd(int a, int b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int bit(long n)throws IOException{return (n==0)?0:(1+bit(n&(n-1)));} ///////////////////////////////////////////////////////////////////////////////////////////////////////// static class AnotherReader{BufferedReader br; StringTokenizer st; AnotherReader()throws FileNotFoundException{ br=new BufferedReader(new InputStreamReader(System.in));} AnotherReader(int a)throws FileNotFoundException{ br = new BufferedReader(new FileReader("input.txt"));} String next()throws IOException{ while (st == null || !st.hasMoreElements()) {try{ st = new StringTokenizer(br.readLine());} catch (IOException e){ e.printStackTrace(); }} return st.nextToken(); } int nextInt() throws IOException{ return Integer.parseInt(next());} long nextLong() throws IOException {return Long.parseLong(next());} double nextDouble()throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException{ String str = ""; try{ str = br.readLine();} catch (IOException e){ e.printStackTrace();} return str;}} ///////////////////////////////////////////////////////////////////////////////////////////////////////////// }
Java
["1\n5 1 3", "1\n6 3 4"]
1 second
["1 3", "2 6"]
NoteExplanation for the first example:Suppose there were 5 participants A-E. Let's denote Nikolay as A. The the most favorable results for Nikolay could look as follows: However, the results of the Olympiad could also look like this: In the first case Nikolay would have taken first place, and in the second — third place.
Java 11
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
58c887568002d947706c448e6faa0f77
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases to solve. Each of the following $$$t$$$ lines contains integers $$$n$$$, $$$x$$$, $$$y$$$ ($$$1 \leq n \leq 10^9$$$, $$$1 \le x, y \le n$$$) — the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round.
1,700
Print two integers — the minimum and maximum possible overall place Nikolay could take.
standard output
PASSED
41a00c8c84416c41cdcf3e77c560d847
train_002.jsonl
1582448700
Nikolay has only recently started in competitive programming, but already qualified to the finals of one prestigious olympiad. There going to be $$$n$$$ participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took $$$x$$$-th place and in the second round — $$$y$$$-th place. Then the total score of the participant A is sum $$$x + y$$$. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every $$$i$$$ from $$$1$$$ to $$$n$$$ exactly one participant took $$$i$$$-th place in first round and exactly one participant took $$$i$$$-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got $$$x$$$-th place in first round and $$$y$$$-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.
256 megabytes
// package com.company; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Array; import java.sql.SQLOutput; import java.util.*; public class Main { public static void main(String[] args) throws IOException { Scanner s = new Scanner(System.in); //BufferedReader s=new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb1 = new StringBuilder();//int n=Integer.parseInt(s.readLine()); int t=s.nextInt(); while(t-->0){ long ans=0; int n=s.nextInt(); long x=s.nextInt();int flag=0; long y=s.nextInt();long val=0; long min=Math.min(x,y); long max=Math.max(x,y); x=max; y=min; ans+=Math.max(0,x-1-Math.max(0,Math.min(n-y-1,x-1))); val+=Math.max(0,x-1-Math.max(0,Math.min(n-y-1,x-1))); ans+=Math.max(0,y-1-val-Math.max(0,Math.min(n-x-1,y-1-val))); /* if(x-1>(n-y-1)){ ans+=x-1-(n-y-1);val+=x-1-(n-y-1);} else if(y-1>(n-x-1+val)){flag=1; ans+=y-1-(n-x-1+val);val+=y-1-(n-x-1); if(x-1>(n-y-1+val)){ ans+=x-1-(n-y-1+val);val+=x-1-(n-y-1);} } if(flag==0&&y-1>(n-x-1+val)) ans+=y-1-(n-x-1+val); */ long amax=0;val=0; if(y-1>(n- x)) {amax+=y-1;val+=y-1-(n-x);} else { amax+=y-1; } amax+=Math.min(n-y,x-1-val); sb1.append((ans+1)+" "+(amax+1)+"\n"); } System.out.println(sb1.toString()); }static int min=Integer.MAX_VALUE;static long ans=0;static long count=0; static void dfs(int i,int[] vis,HashMap<Integer,Integer> h,int [] a,int[] c,int ts){ //if(vis[i]!= vis1[i]) return; if(vis[i]>0&&(!h.containsKey(i)||h.get(i)!=vis[i])) return; if(vis[i]==2) return; if(h.containsKey(i)&&h.get(i)==2) return; if(h.containsKey(i)) h.put(i,h.get(i)+1); else h.put(i,1); vis[i]+=1; //vis1[i]+=1; if(h.get(i)==2) min=Math.min(min,c[i]) ; // if(vis[i]==1) min=c[i]; dfs(a[i],vis,h,a,c,ts); } static void computeLPSArray(String pat, int M, int lps[]) { int len = 0; int i = 1; lps[0] = 0; while (i < M) { if (pat.charAt(i) == pat.charAt(len)) { len++; lps[i] = len; i++; } else // (pat[i] != pat[len]) { if (len != 0) { len = lps[len - 1]; } else // if (len == 0) { lps[i] = len; i++; } } } } static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static double power(double x, long y, int p) { double res = 1; x = x % p; while (y > 0) { if ((y & 1) == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } public static void fracion(double x) { String a = "" + x; String spilts[] = a.split("\\."); // split using decimal int b = spilts[1].length(); // find the decimal length int denominator = (int) Math.pow(10, b); // calculate the denominator int numerator = (int) (x * denominator); // calculate the nerumrator Ex // 1.2*10 = 12 int gcd = (int)gcd((long)numerator, denominator); // Find the greatest common // divisor bw them String fraction = "" + numerator / gcd + "/" + denominator / gcd; // System.out.println((denominator/gcd)); long x1=modInverse(denominator / gcd,998244353 ); // System.out.println(x1); System.out.println((((numerator / gcd )%998244353 *(x1%998244353 ))%998244353 ) ); }static int anst=Integer.MAX_VALUE; static StringBuilder sb1=new StringBuilder(); public static int bfs(int i1, ArrayList<Integer>[] h, int[] vis, int n,int val1) { Queue<Integer> q = new LinkedList<Integer>(); q.add(i1);Queue<Integer> aq=new LinkedList<Integer>(); aq.add(0); while(!q.isEmpty()){ int i=q.poll(); int val=aq.poll(); if(i==n){ return val; } if(h[i]!=null){ for(Integer j:h[i]){ if(vis[j]==0){ q.add(j);vis[j]=1; aq.add(val+1);} } } }return -1; } static int i(String a) { return Integer.parseInt(a); } static long l(String a) { return Long.parseLong(a); } static String[] inp() throws IOException { BufferedReader s = new BufferedReader(new InputStreamReader(System.in)); return s.readLine().trim().split("\\s+"); } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static long modInverse(int a, int m) { { // If a and m are relatively prime, then modulo inverse // is a^(m-2) mode m return (power(a, m - 2, m)); } } // To compute x^y under modulo m static long power(int x, int y, int 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; } // Function to return gcd of a and b } class Student { int l;int r; public Student(int l, int r) { this.l = l; this.r = r; } // Constructor // Used to print student details in main() public String toString() { return this.l+" "; } } class Sortbyroll implements Comparator<Student> { // Used for sorting in ascending order of // roll number public int compare(Student a, Student b){ return a.l-b.l; } } class Sortbyroll1 implements Comparator<Student> { // Used for sorting in ascending order of // roll number public int compare(Student a, Student b){ if(a.r==b.r) return a.l-b.l; return a.r-b.r; } }
Java
["1\n5 1 3", "1\n6 3 4"]
1 second
["1 3", "2 6"]
NoteExplanation for the first example:Suppose there were 5 participants A-E. Let's denote Nikolay as A. The the most favorable results for Nikolay could look as follows: However, the results of the Olympiad could also look like this: In the first case Nikolay would have taken first place, and in the second — third place.
Java 11
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
58c887568002d947706c448e6faa0f77
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases to solve. Each of the following $$$t$$$ lines contains integers $$$n$$$, $$$x$$$, $$$y$$$ ($$$1 \leq n \leq 10^9$$$, $$$1 \le x, y \le n$$$) — the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round.
1,700
Print two integers — the minimum and maximum possible overall place Nikolay could take.
standard output
PASSED
e0e15684bb8c613996fffc27f73fc2f6
train_002.jsonl
1582448700
Nikolay has only recently started in competitive programming, but already qualified to the finals of one prestigious olympiad. There going to be $$$n$$$ participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took $$$x$$$-th place and in the second round — $$$y$$$-th place. Then the total score of the participant A is sum $$$x + y$$$. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every $$$i$$$ from $$$1$$$ to $$$n$$$ exactly one participant took $$$i$$$-th place in first round and exactly one participant took $$$i$$$-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got $$$x$$$-th place in first round and $$$y$$$-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); int t = input.nextInt(); while (t-- > 0) { int a = input.nextInt(); int b = input.nextInt(); int c = input.nextInt(); int score = b + c; int bestPlace = Math.min(Math.max(score - a, 0) + 1, a); int lostplace = Math.min(score - 1 , a); System.out.println(bestPlace + " " + lostplace); } } }
Java
["1\n5 1 3", "1\n6 3 4"]
1 second
["1 3", "2 6"]
NoteExplanation for the first example:Suppose there were 5 participants A-E. Let's denote Nikolay as A. The the most favorable results for Nikolay could look as follows: However, the results of the Olympiad could also look like this: In the first case Nikolay would have taken first place, and in the second — third place.
Java 11
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
58c887568002d947706c448e6faa0f77
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases to solve. Each of the following $$$t$$$ lines contains integers $$$n$$$, $$$x$$$, $$$y$$$ ($$$1 \leq n \leq 10^9$$$, $$$1 \le x, y \le n$$$) — the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round.
1,700
Print two integers — the minimum and maximum possible overall place Nikolay could take.
standard output
PASSED
1d3b19118314ee1c737a4b742de2f145
train_002.jsonl
1582448700
Nikolay has only recently started in competitive programming, but already qualified to the finals of one prestigious olympiad. There going to be $$$n$$$ participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took $$$x$$$-th place and in the second round — $$$y$$$-th place. Then the total score of the participant A is sum $$$x + y$$$. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every $$$i$$$ from $$$1$$$ to $$$n$$$ exactly one participant took $$$i$$$-th place in first round and exactly one participant took $$$i$$$-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got $$$x$$$-th place in first round and $$$y$$$-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.math.BigInteger; import java.net.StandardSocketOptions; import java.security.cert.CollectionCertStoreParameters; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import java.util.Scanner; import java.util.Set; import java.util.SortedSet; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; import java.util.Vector; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; public class mai { public static int lowerBound(ArrayList<Integer> array, int length, long value) { int low = 0; int high = length; while (low < high) { final int mid = (low + high) / 2; if (value <= array.get(mid)) { high = mid; } else { low = mid + 1; } } return low; } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static 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); } public static void sortbyColumn(int arr[][], int col) { // Using built-in sort function Arrays.sort Arrays.sort(arr, new Comparator<int[]>() { @Override // Compare values according to columns public int compare(final int[] entry1, final int[] entry2) { // To sort in descending order revert // the '>' Operator // if (entry1[col] > entry2[col]) // return 1; // else //(entry1[col] >= entry2[col]) // return -1; return new Integer(entry1[col]).compareTo(entry2[col]); // return entry1[col]. } }); // End of function call sort(). } class pair<X, Y> { // utilizing Java "Generics" X _first; Y _second; public pair(X f, Y s) { _first = f; _second = s; } X first() { return _first; } Y second() { return _second; } void setFirst(X f) { _first = f; } void setSecond(Y s) { _second = s; } } public static long[] swap(long[] brr, int left, int right) { int temp = (int) brr[left]; brr[left] = brr[right]; brr[right] = temp; return brr; } public static long[] reverse(long[] brr, int left, int right) { while (left < right) { int temp = (int) brr[left]; brr[left++] = brr[right]; brr[right--] = temp; } return brr; } static boolean findNextPermutation(long[] p) { for (int a = p.length - 2; a >= 0; --a) if (p[a] < p[a + 1]) for (int b = p.length - 1;; --b) if (p[b] > p[a]) { int t = (int) p[a]; p[a] = p[b]; p[b] = t; for (++a, b = p.length - 1; a < b; ++a, --b) { t = (int) p[a]; p[a] = p[b]; p[b] = t; } return true; } return false; } static long nCr(long n, long r) { long x = 1; long yu = n - r; while (n > r) { x = x * n; n--; } while (yu > 0) { x /= yu; yu--; } return x; } static boolean prime[] = new boolean[1000007]; public static void sieveOfEratosthenes(int n) { for (int i = 0; i < n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * p; i <= n; i += p) prime[i] = false; } } // Print all prime numbers // for(int i = 2; i <= n; i++) // { // // if(prime[i] == true) // System.out.print(i + " "); // } } public static final int mod = 1000000007; public static long mode(long a, long n) { long r = 1; while (n > 0) { if ((n & 1) == 1) r = (r * a) % mod; a = (a * a) % mod; n >>= 1; } return r; } static long a1[] = new long[10000003]; static long arr2[] = new long[10000003]; public static void main(String[] args) throws NumberFormatException, IOException, ScriptException { FastReader sc = new FastReader(); PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); // BufferedReader br = new BufferedReader(new // InputStreamReader(System.in)); // Scanner scn = new Scanner(System.in); // int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); int x=sc.nextInt(); int y=sc.nextInt(); int sum=x+y; pr.print(Math.max(1, Math.min(n, sum-n+1))+" "); pr.println((int)Math.min(n, sum-1)); } // // coded to perfection by Rohan Mukhija pr.flush(); pr.close(); } private static boolean possible(long[] arr, int[] f, long mid, long k) { long c = 0; for (int i = 0; i < arr.length; i++) { if ((arr[i] * f[f.length - i - 1]) > mid) { c += (arr[i] - (mid / f[f.length - i - 1])); } } // System.out.println(mid+" "+c); if (c <= k) return true; return false; } }
Java
["1\n5 1 3", "1\n6 3 4"]
1 second
["1 3", "2 6"]
NoteExplanation for the first example:Suppose there were 5 participants A-E. Let's denote Nikolay as A. The the most favorable results for Nikolay could look as follows: However, the results of the Olympiad could also look like this: In the first case Nikolay would have taken first place, and in the second — third place.
Java 11
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
58c887568002d947706c448e6faa0f77
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases to solve. Each of the following $$$t$$$ lines contains integers $$$n$$$, $$$x$$$, $$$y$$$ ($$$1 \leq n \leq 10^9$$$, $$$1 \le x, y \le n$$$) — the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round.
1,700
Print two integers — the minimum and maximum possible overall place Nikolay could take.
standard output
PASSED
9095a1c6ba6db4179427fee5f3bd70cd
train_002.jsonl
1582448700
Nikolay has only recently started in competitive programming, but already qualified to the finals of one prestigious olympiad. There going to be $$$n$$$ participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took $$$x$$$-th place and in the second round — $$$y$$$-th place. Then the total score of the participant A is sum $$$x + y$$$. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every $$$i$$$ from $$$1$$$ to $$$n$$$ exactly one participant took $$$i$$$-th place in first round and exactly one participant took $$$i$$$-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got $$$x$$$-th place in first round and $$$y$$$-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) throws Exception { // FCApplicationManager applicationManager = new FCApplicationManager(); //applicationManager.init(); Scanner sc = new Scanner(System.in); Integer testcases = sc.nextInt(); sc.nextLine(); for (int i = 0; i < testcases; i++) { Integer n, x, y, totalPoints, minPosition = 1, maxPosition = 1; n = sc.nextInt(); x = sc.nextInt(); y = sc.nextInt(); maxPosition = Integer.min(n, x + y - 1); minPosition = Integer.max(1, Integer.min(n, x + y - n + 1)); System.out.println(Integer.toString(minPosition) + ' ' + Integer.toString(maxPosition)); if (i != testcases - 1) { sc.nextLine(); } } //System.exit(0); } }
Java
["1\n5 1 3", "1\n6 3 4"]
1 second
["1 3", "2 6"]
NoteExplanation for the first example:Suppose there were 5 participants A-E. Let's denote Nikolay as A. The the most favorable results for Nikolay could look as follows: However, the results of the Olympiad could also look like this: In the first case Nikolay would have taken first place, and in the second — third place.
Java 11
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
58c887568002d947706c448e6faa0f77
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases to solve. Each of the following $$$t$$$ lines contains integers $$$n$$$, $$$x$$$, $$$y$$$ ($$$1 \leq n \leq 10^9$$$, $$$1 \le x, y \le n$$$) — the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round.
1,700
Print two integers — the minimum and maximum possible overall place Nikolay could take.
standard output
PASSED
c2bf1759be04293528149446d17a3044
train_002.jsonl
1605796500
Alice and Bob are playing a game. They have a tree consisting of $$$n$$$ vertices. Initially, Bob has $$$k$$$ chips, the $$$i$$$-th chip is located in the vertex $$$a_i$$$ (all these vertices are unique). Before the game starts, Alice will place a chip into one of the vertices of the tree.The game consists of turns. Each turn, the following events happen (sequentially, exactly in the following order): Alice either moves her chip to an adjacent vertex or doesn't move it; for each Bob's chip, he either moves it to an adjacent vertex or doesn't move it. Note that this choice is done independently for each chip. The game ends when Alice's chip shares the same vertex with one (or multiple) of Bob's chips. Note that Bob's chips may share the same vertex, even though they are in different vertices at the beginning of the game.Alice wants to maximize the number of turns, Bob wants to minimize it. If the game ends in the middle of some turn (Alice moves her chip to a vertex that contains one or multiple Bob's chips), this turn is counted.For each vertex, calculate the number of turns the game will last if Alice places her chip in that vertex.
512 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class cf1452g_3 { public static void main(String[] args) throws IOException { int n = ri(), dist[] = new int[n], ans[], t[] = new int[n]; fill(dist, -1); Graph g = tree(n); int k = ri(), a[] = riam1(k); Queue<Integer> bfs = new LinkedList<>(); for (int i : a) { bfs.offer(i); dist[i] = 0; } while (!bfs.isEmpty()) { int i = bfs.poll(); for (int j : g.get(i)) { if (dist[j] == -1) { dist[j] = dist[i] + 1; bfs.offer(j); } } } ans = copy(dist); fill(t, -1); PriorityQueue<Integer> pq = new PriorityQueue<>((x, y) -> dist[y] - dist[x]); for (int i = 0; i < n; ++i) { pq.offer(i); } next: while (!pq.isEmpty()) { int i = pq.poll(); for (int j : g.get(i)) { if (dist[j] > dist[i]) { continue next; } } dfs(dist[i], g, i, -1, dist[i], t, ans); } prln(ans); close(); } static void dfs(int dist, Graph g, int i, int p, int d, int t[], int[] ans) { if (d == 0) { return; } if (d > t[i]) { t[i] = d; ans[i] = max(ans[i], dist); for (int j : g.get(i)) { if (j != p) { dfs(dist, g, j, i, d - 1, t, ans); } } } } static Graph graph(int n) { Graph g = new Graph(); for (int i = 0; i < n; ++i) { g.add(new ArrayList<>()); } return g; } static Graph graph(int n, int m) throws IOException { Graph g = graph(n); for (int i = 0; i < m; ++i) { g.c(rni() - 1, ni() - 1); } return g; } static Graph tree(int n) throws IOException { return graph(n, n - 1); } static class Graph extends ArrayList<List<Integer>> { void cto(int u, int v) { get(u).add(v); } void c(int u, int v) { cto(u, v); cto(v, u); } boolean is_leaf(int i) { return get(i).size() == 1; } } static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out)); static StringTokenizer input; static Random __rand = new Random(); // references // IBIG = 1e9 + 7 // IMAX ~= 2e9 // LMAX ~= 9e18 // constants static final int IBIG = 1000000007; static final int IMAX = 2147483647; static final int IMIN = -2147483648; static final long LMAX = 9223372036854775807L; static final long LMIN = -9223372036854775808L; // 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 gcf(int a, int b) {return b == 0 ? a : gcf(b, a % b);} static long gcf(long a, long b) {return b == 0 ? a : gcf(b, a % b);} static int lcm(int a, int b) {return a * b / gcf(a, b);} static long lcm(long a, long b) {return a * b / gcf(a, b);} static int randInt(int min, int max) {return __rand.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);} // 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;} // input static void r() throws IOException {input = new StringTokenizer(rline());} static int ri() throws IOException {return Integer.parseInt(rline());} 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 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 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 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 char[] rcha() throws IOException {return rline().toCharArray();} static String rline() throws IOException {return __in.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) {__out.print(i);} static void prln(int i) {__out.println(i);} static void pr(long l) {__out.print(l);} static void prln(long l) {__out.println(l);} static void pr(double d) {__out.print(d);} static void prln(double d) {__out.println(d);} static void pr(char c) {__out.print(c);} static void prln(char c) {__out.println(c);} static void pr(char[] s) {__out.print(new String(s));} static void prln(char[] s) {__out.println(new String(s));} static void pr(String s) {__out.print(s);} static void prln(String s) {__out.println(s);} static void pr(Object o) {__out.print(o);} static void prln(Object o) {__out.println(o);} static void prln() {__out.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() {__out.flush();} static void close() {__out.close();} }
Java
["5\n2 4\n3 1\n3 4\n3 5\n2\n4 5", "8\n4 1\n8 4\n4 5\n6 4\n2 5\n4 3\n1 7\n3\n2 8 3", "10\n2 5\n4 3\n7 3\n7 2\n5 8\n3 6\n8 10\n7 9\n7 1\n4\n10 6 9 1"]
3 seconds
["2 1 2 0 0", "3 0 0 3 1 2 3 0", "0 2 2 2 2 0 2 2 0 0"]
null
Java 11
standard input
[ "data structures", "dfs and similar", "greedy", "trees" ]
7c64045ad4b9ec35467a6f6536b76323
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of vertices in the tree. Then $$$n - 1$$$ lines follow, each line contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \ne v_i$$$) that denote the endpoints of an edge. These edges form a tree. The next line contains one integer $$$k$$$ ($$$1 \le k \le n - 1$$$) — the number of Bob's chips. The last line contains $$$k$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_k$$$ ($$$1 \le a_i \le n$$$; $$$a_i \ne a_j$$$ if $$$i \ne j$$$) — the vertices where the Bob's chips are initially placed.
2,700
Print $$$n$$$ integers. The $$$i$$$-th of them should be equal to the number of turns the game will last if Alice initially places her chip in the vertex $$$i$$$. If one of Bob's chips is already placed in vertex $$$i$$$, then the answer for vertex $$$i$$$ is $$$0$$$.
standard output
PASSED
0e22a7a9a3f97d7eb0eb943a636c0f02
train_002.jsonl
1440261000
You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Suptee */ public class Arrays_572A { /** * @param args the command line arguments */ public static void main(String[] args) { try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int nA = Integer.parseInt(st.nextToken()); int nB = Integer.parseInt(st.nextToken()); StringTokenizer st1 = new StringTokenizer(br.readLine()); int k = Integer.parseInt(st1.nextToken()); int m = Integer.parseInt(st1.nextToken()); int[] arrayA = new int[k]; int[] arrayB = new int[nB]; StringTokenizer st2 = new StringTokenizer(br.readLine()); int i = 0; while (st2.hasMoreTokens() && i < k) { arrayA[i] = Integer.parseInt(st2.nextToken()); //System.out.println("arrayA : "+arrayA[i]); i++; } StringTokenizer st3 = new StringTokenizer(br.readLine()); int j = 0; while (st3.hasMoreTokens() && j < nB) { arrayB[j] = Integer.parseInt(st3.nextToken()); //System.out.println("arrayB : "+arrayB[j]); j++; } boolean found = true; // for (int indexA = 0; indexA < k; indexA++) { for(int indexB = nB - 1; indexB >= (nB - m); indexB --) { if(!(arrayA[k-1] < arrayB[indexB])) { found = false; } } //} if(found) { System.out.println("YES"); } else { System.out.println("NO"); } } catch (IOException ex) { Logger.getLogger(Arrays_572A.class.getName()).log(Level.SEVERE, null, ex); } } }
Java
["3 3\n2 1\n1 2 3\n3 4 5", "3 3\n3 3\n1 2 3\n3 4 5", "5 2\n3 1\n1 1 1 1 1\n2 2"]
2 seconds
["YES", "NO", "YES"]
NoteIn the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 &lt; 3 and 2 &lt; 3).In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: .
Java 8
standard input
[ "sortings" ]
8e0581cce19d6bf5eba30a0aebee9a08
The first line contains two integers nA, nB (1 ≤ nA, nB ≤ 105), separated by a space — the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≤ k ≤ nA, 1 ≤ m ≤ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≤ a1 ≤ a2 ≤ ... ≤ anA ≤ 109), separated by spaces — elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≤ b1 ≤ b2 ≤ ... ≤ bnB ≤ 109), separated by spaces — elements of array B.
900
Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes).
standard output
PASSED
91246a48ad4f03abeb571c2845399804
train_002.jsonl
1440261000
You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class Strings { public static void main(String[] args) { Scanner sc= new Scanner(System.in); int na=sc.nextInt();int nb=sc.nextInt(); int k = sc.nextInt();int m=sc.nextInt(); int[]a=new int[na];int[]b=new int[nb]; for (int i = 0; i < na; i++) { a[i]=sc.nextInt(); } for (int i = 0; i < nb; i++) { b[i]=sc.nextInt(); } if(a[k-1]<b[nb-m]) System.out.println("YES"); else System.out.println("NO"); } }
Java
["3 3\n2 1\n1 2 3\n3 4 5", "3 3\n3 3\n1 2 3\n3 4 5", "5 2\n3 1\n1 1 1 1 1\n2 2"]
2 seconds
["YES", "NO", "YES"]
NoteIn the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 &lt; 3 and 2 &lt; 3).In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: .
Java 8
standard input
[ "sortings" ]
8e0581cce19d6bf5eba30a0aebee9a08
The first line contains two integers nA, nB (1 ≤ nA, nB ≤ 105), separated by a space — the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≤ k ≤ nA, 1 ≤ m ≤ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≤ a1 ≤ a2 ≤ ... ≤ anA ≤ 109), separated by spaces — elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≤ b1 ≤ b2 ≤ ... ≤ bnB ≤ 109), separated by spaces — elements of array B.
900
Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes).
standard output
PASSED
c4837544d8590df1ff41edb0fc4e36e3
train_002.jsonl
1440261000
You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.
256 megabytes
import java.util.*; public class mom { public static void main (String [] args){ Scanner sc = new Scanner (System.in); int arr[] = new int [2]; arr[0]= sc.nextInt(); arr[1]= sc.nextInt(); int arr2[] = new int [2]; arr2 [0]=sc.nextInt(); arr2 [1]=sc.nextInt(); int arr3[]= new int [arr[0]]; for (int i =0; i<arr[0];i++){ arr3[i]= sc.nextInt(); } int arr4[]= new int [arr[1]]; for (int i=0;i<arr[1];i++){ arr4[i]=sc.nextInt(); } if (arr3[arr[0]-1] < arr4[0]){ System.out.print("YES"); } else{ int i = 0; boolean fl = true; while (i <arr2[1] && fl){ if (arr3[arr2[0]-1]>=arr4[arr[1]-1]){ System.out.print("NO"); fl = false; break; } else{ i++; arr[1]=arr[1]-1; } } if (fl==true){ System.out.print("YES"); } } } }
Java
["3 3\n2 1\n1 2 3\n3 4 5", "3 3\n3 3\n1 2 3\n3 4 5", "5 2\n3 1\n1 1 1 1 1\n2 2"]
2 seconds
["YES", "NO", "YES"]
NoteIn the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 &lt; 3 and 2 &lt; 3).In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: .
Java 8
standard input
[ "sortings" ]
8e0581cce19d6bf5eba30a0aebee9a08
The first line contains two integers nA, nB (1 ≤ nA, nB ≤ 105), separated by a space — the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≤ k ≤ nA, 1 ≤ m ≤ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≤ a1 ≤ a2 ≤ ... ≤ anA ≤ 109), separated by spaces — elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≤ b1 ≤ b2 ≤ ... ≤ bnB ≤ 109), separated by spaces — elements of array B.
900
Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes).
standard output
PASSED
83439656a2a521d750341ee4500e1b0f
train_002.jsonl
1440261000
You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.
256 megabytes
import java.util.ArrayList; import java.util.Scanner; public class Arrays { public static void main(String[] args) { int nA, nB; int k, m; ArrayList<Integer> A = new ArrayList<Integer>(); ArrayList<Integer> B = new ArrayList<Integer>(); Scanner sc = new Scanner(System.in); nA = sc.nextInt(); nB = sc.nextInt(); k = sc.nextInt(); m = sc.nextInt(); for(int i = 0; i < nA; i++) { A.add(sc.nextInt()); } for(int j = 0; j < nB; j++) { B.add(sc.nextInt()); } if(A.get(k - 1) >= B.get(nB - m)) { System.out.println("NO"); } else System.out.println("YES"); } }
Java
["3 3\n2 1\n1 2 3\n3 4 5", "3 3\n3 3\n1 2 3\n3 4 5", "5 2\n3 1\n1 1 1 1 1\n2 2"]
2 seconds
["YES", "NO", "YES"]
NoteIn the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 &lt; 3 and 2 &lt; 3).In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: .
Java 8
standard input
[ "sortings" ]
8e0581cce19d6bf5eba30a0aebee9a08
The first line contains two integers nA, nB (1 ≤ nA, nB ≤ 105), separated by a space — the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≤ k ≤ nA, 1 ≤ m ≤ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≤ a1 ≤ a2 ≤ ... ≤ anA ≤ 109), separated by spaces — elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≤ b1 ≤ b2 ≤ ... ≤ bnB ≤ 109), separated by spaces — elements of array B.
900
Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes).
standard output
PASSED
d97ba9e8e79266e0dbf5a91f5348b1b3
train_002.jsonl
1440261000
You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.
256 megabytes
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Lecture1 { public static void main (String[] args) { Scanner scanner = new Scanner (System.in); int numberOfArraysA = scanner.nextInt(); int numberOfArraysB = scanner.nextInt(); scanner.nextLine(); int numbersA = scanner.nextInt(); int numbersB = scanner.nextInt(); scanner.nextLine(); List<Integer> arrA = new ArrayList<Integer> (); List<Integer> arrB = new ArrayList<Integer> (); while (numberOfArraysA > 0) { arrA.add (scanner.nextInt()); numberOfArraysA--; } scanner.nextLine(); while (numberOfArraysB > 0) { arrB.add (scanner.nextInt()); numberOfArraysB--; } scanner.close(); int maxA = arrA.get (numbersA - 1); for (int number : arrB) { if (number > maxA && numbersB > 0) { numbersB--; if (numbersB == 0) break; } } if (numbersB == 0) System.out.println("YES"); else System.out.println("NO"); } }
Java
["3 3\n2 1\n1 2 3\n3 4 5", "3 3\n3 3\n1 2 3\n3 4 5", "5 2\n3 1\n1 1 1 1 1\n2 2"]
2 seconds
["YES", "NO", "YES"]
NoteIn the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 &lt; 3 and 2 &lt; 3).In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: .
Java 8
standard input
[ "sortings" ]
8e0581cce19d6bf5eba30a0aebee9a08
The first line contains two integers nA, nB (1 ≤ nA, nB ≤ 105), separated by a space — the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≤ k ≤ nA, 1 ≤ m ≤ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≤ a1 ≤ a2 ≤ ... ≤ anA ≤ 109), separated by spaces — elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≤ b1 ≤ b2 ≤ ... ≤ bnB ≤ 109), separated by spaces — elements of array B.
900
Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes).
standard output
PASSED
94331a2727027c5d6effb373b1734272
train_002.jsonl
1440261000
You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Collections; import java.util.Comparator; import java.util.Map; import java.util.PriorityQueue; import java.util.StringTokenizer; import java.util.TreeMap; public class Soly { static int obe(int a, int b, char s) { if (s == '+') { return a + b; } return a * b; } public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); try (PrintWriter or = new PrintWriter(System.out)) { int na= in.nextInt(),nb=in.nextInt(); int k=in.nextInt()-1,m=in.nextInt()-1; int[]a= new int[na]; int []b= new int[nb]; for (int i = 0; i < na; i++) a[i]=in.nextInt(); for (int i = nb-1; i>=0; i--) b[i]=in.nextInt(); or.println(a[k]<b[m]?"YES":"NO"); } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) { if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) { f *= 10; } } } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } } class Pair8 { int from; int to; // int min; public Pair8(int from, int to) { this.from = from; this.to = to; //min = m; } }
Java
["3 3\n2 1\n1 2 3\n3 4 5", "3 3\n3 3\n1 2 3\n3 4 5", "5 2\n3 1\n1 1 1 1 1\n2 2"]
2 seconds
["YES", "NO", "YES"]
NoteIn the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 &lt; 3 and 2 &lt; 3).In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: .
Java 8
standard input
[ "sortings" ]
8e0581cce19d6bf5eba30a0aebee9a08
The first line contains two integers nA, nB (1 ≤ nA, nB ≤ 105), separated by a space — the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≤ k ≤ nA, 1 ≤ m ≤ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≤ a1 ≤ a2 ≤ ... ≤ anA ≤ 109), separated by spaces — elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≤ b1 ≤ b2 ≤ ... ≤ bnB ≤ 109), separated by spaces — elements of array B.
900
Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes).
standard output
PASSED
f446d45e2056bd4b50f4342398282a8e
train_002.jsonl
1440261000
You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.
256 megabytes
import java.io.*; import java.util.*; public class NewClass { public static void main(String[] args) throws IOException { InputReader in = new InputReader(System.in); OutputWriter out = new OutputWriter(System.out); int na = in.nextInt(),nb=in.nextInt(),k=in.nextInt(),m=in.nextInt(); int[] a = new int[na]; int[] b = new int[nb]; for (int i = 0; i < na; i++){ a[i]=in.nextInt(); } for (int i = 0; i < nb; i++){ b[i]=in.nextInt(); } if (a[k-1]<b[nb-m]) { out.printLine("YES"); out.flush(); } else{ out.printLine("NO"); out.flush(); } } public static class Solver { public static void solve(InputReader in, OutputWriter out) { } } } class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (snumChars == -1) { throw new InputMismatchException(); } if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } }
Java
["3 3\n2 1\n1 2 3\n3 4 5", "3 3\n3 3\n1 2 3\n3 4 5", "5 2\n3 1\n1 1 1 1 1\n2 2"]
2 seconds
["YES", "NO", "YES"]
NoteIn the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 &lt; 3 and 2 &lt; 3).In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: .
Java 8
standard input
[ "sortings" ]
8e0581cce19d6bf5eba30a0aebee9a08
The first line contains two integers nA, nB (1 ≤ nA, nB ≤ 105), separated by a space — the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≤ k ≤ nA, 1 ≤ m ≤ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≤ a1 ≤ a2 ≤ ... ≤ anA ≤ 109), separated by spaces — elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≤ b1 ≤ b2 ≤ ... ≤ bnB ≤ 109), separated by spaces — elements of array B.
900
Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes).
standard output
PASSED
c3cf3f6ad8bb9e8827d8d01935ad3754
train_002.jsonl
1440261000
You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.
256 megabytes
import java.util.Scanner; public class Arrays { public static void main(String args[]) { Scanner scan = new Scanner(System.in); int na = scan.nextInt(); int nb = scan.nextInt(); int n = scan.nextInt(); int m = scan.nextInt(); int[] a = new int[na]; int[] b = new int[nb]; for (int i = 0; i < na; i++) { a[i] = scan.nextInt(); } for (int i = 0; i < nb; i++) { b[i] = scan.nextInt(); } int p = nb - m; int mx = b[p]; int i = 0; for (; i < na; i++) { if (a[i] >= mx) { break; } } if (i >= n) { System.out.println("YES"); } else { System.out.println("NO"); } } }
Java
["3 3\n2 1\n1 2 3\n3 4 5", "3 3\n3 3\n1 2 3\n3 4 5", "5 2\n3 1\n1 1 1 1 1\n2 2"]
2 seconds
["YES", "NO", "YES"]
NoteIn the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 &lt; 3 and 2 &lt; 3).In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: .
Java 8
standard input
[ "sortings" ]
8e0581cce19d6bf5eba30a0aebee9a08
The first line contains two integers nA, nB (1 ≤ nA, nB ≤ 105), separated by a space — the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≤ k ≤ nA, 1 ≤ m ≤ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≤ a1 ≤ a2 ≤ ... ≤ anA ≤ 109), separated by spaces — elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≤ b1 ≤ b2 ≤ ... ≤ bnB ≤ 109), separated by spaces — elements of array B.
900
Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes).
standard output
PASSED
f74f1003aaabcc16121791a5602595c6
train_002.jsonl
1440261000
You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.
256 megabytes
//package Contests; import java.util.*; import java.io.*; public class ArraysCF { public static void disp(int[] arr){ for(Integer x: arr) System.out.print(x+" "); } public static void main(String[] args) { MyScanner sc=new MyScanner(); PrintWriter out=new PrintWriter(System.out); int a1,b1; a1=sc.nextInt(); b1=sc.nextInt(); int k=sc.nextInt(); int m=sc.nextInt(); int arr1[]=new int[a1]; int arr2[]=new int[b1]; for(int i=0;i<a1;i++) arr1[i]=sc.nextInt(); for(int i=0;i<b1;i++) arr2[i]=sc.nextInt(); if(arr1[k-1]>=arr2[b1-m]) System.out.println("NO"); else System.out.println("YES"); } } 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
["3 3\n2 1\n1 2 3\n3 4 5", "3 3\n3 3\n1 2 3\n3 4 5", "5 2\n3 1\n1 1 1 1 1\n2 2"]
2 seconds
["YES", "NO", "YES"]
NoteIn the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 &lt; 3 and 2 &lt; 3).In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: .
Java 8
standard input
[ "sortings" ]
8e0581cce19d6bf5eba30a0aebee9a08
The first line contains two integers nA, nB (1 ≤ nA, nB ≤ 105), separated by a space — the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≤ k ≤ nA, 1 ≤ m ≤ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≤ a1 ≤ a2 ≤ ... ≤ anA ≤ 109), separated by spaces — elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≤ b1 ≤ b2 ≤ ... ≤ bnB ≤ 109), separated by spaces — elements of array B.
900
Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes).
standard output
PASSED
2ffe9629f3ec8a7563e327fb5812e325
train_002.jsonl
1440261000
You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.
256 megabytes
/* package whatever; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class array { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String size_input; size_input = br.readLine(); String num_input = br.readLine(); String a_str = br.readLine(); String b_str = br.readLine(); String size[] = size_input.split(" "); int size_A = Integer.parseInt(size[0]); int size_B = Integer.parseInt(size[1]); String num[] = num_input.split(" "); int k = Integer.parseInt(num[0]); int m = Integer.parseInt(num[1]); String a[] = a_str.split(" "); int[] aa = new int[size_A]; for (int i = 0; i <= size_A - 1; i++) aa[i] = Integer.parseInt(a[i]); String b[] = b_str.split(" "); int[] bb = new int[size_B]; for (int i = 0; i <= size_B - 1; i++) bb[i] = Integer.parseInt(b[i]); if (k <= size_A && m <= size_B) { if (aa[k - 1] < bb[size_B - m]) { System.out.println("YES"); return; } } System.out.println("NO"); } }
Java
["3 3\n2 1\n1 2 3\n3 4 5", "3 3\n3 3\n1 2 3\n3 4 5", "5 2\n3 1\n1 1 1 1 1\n2 2"]
2 seconds
["YES", "NO", "YES"]
NoteIn the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 &lt; 3 and 2 &lt; 3).In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: .
Java 8
standard input
[ "sortings" ]
8e0581cce19d6bf5eba30a0aebee9a08
The first line contains two integers nA, nB (1 ≤ nA, nB ≤ 105), separated by a space — the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≤ k ≤ nA, 1 ≤ m ≤ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≤ a1 ≤ a2 ≤ ... ≤ anA ≤ 109), separated by spaces — elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≤ b1 ≤ b2 ≤ ... ≤ bnB ≤ 109), separated by spaces — elements of array B.
900
Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes).
standard output
PASSED
76ec96d8d7a5dafd41397027776b49f3
train_002.jsonl
1440261000
You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.
256 megabytes
import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.util.InputMismatchException; import java.io.BufferedWriter; import java.io.PrintWriter; import java.io.Writer; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.IOException; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, InputReader in, OutputWriter out) { int na = in.readInt(); int nb = in.readInt(); int k = in.readInt(); int m = in.readInt(); int[] naAry = IOUtils.readIntArray(in, na); int[] nbAry = IOUtils.readIntArray(in, nb); if (naAry[k - 1] >= nbAry[nb - m]) out.print("NO"); else out.print("YES"); } } 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 readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = in.readInt(); return array; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void close() { writer.close(); } } }
Java
["3 3\n2 1\n1 2 3\n3 4 5", "3 3\n3 3\n1 2 3\n3 4 5", "5 2\n3 1\n1 1 1 1 1\n2 2"]
2 seconds
["YES", "NO", "YES"]
NoteIn the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 &lt; 3 and 2 &lt; 3).In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: .
Java 8
standard input
[ "sortings" ]
8e0581cce19d6bf5eba30a0aebee9a08
The first line contains two integers nA, nB (1 ≤ nA, nB ≤ 105), separated by a space — the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≤ k ≤ nA, 1 ≤ m ≤ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≤ a1 ≤ a2 ≤ ... ≤ anA ≤ 109), separated by spaces — elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≤ b1 ≤ b2 ≤ ... ≤ bnB ≤ 109), separated by spaces — elements of array B.
900
Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes).
standard output
PASSED
a6461bb98603d7e0ca1d30cc5931e9d1
train_002.jsonl
1440261000
You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.
256 megabytes
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ //package arrays; import java.util.Scanner; /** * * @author hacnguyen12 */ public class Arrays { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner scan= new Scanner(System.in); int n1,n2; n1=scan.nextInt(); n2=scan.nextInt(); int az; int k,m; k=scan.nextInt(); m=scan.nextInt(); int [] a, b; a=new int[n1]; b=new int[n2]; for (int i=0; i<n1; i++) a[i]=scan.nextInt(); for (int i=0; i<n2; i++) b[i]=scan.nextInt(); if (a[k-1]<b[n2-m]) System.out.println("YES"); else System.out.println("NO"); // TODO code application logic here } }
Java
["3 3\n2 1\n1 2 3\n3 4 5", "3 3\n3 3\n1 2 3\n3 4 5", "5 2\n3 1\n1 1 1 1 1\n2 2"]
2 seconds
["YES", "NO", "YES"]
NoteIn the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 &lt; 3 and 2 &lt; 3).In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: .
Java 8
standard input
[ "sortings" ]
8e0581cce19d6bf5eba30a0aebee9a08
The first line contains two integers nA, nB (1 ≤ nA, nB ≤ 105), separated by a space — the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≤ k ≤ nA, 1 ≤ m ≤ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≤ a1 ≤ a2 ≤ ... ≤ anA ≤ 109), separated by spaces — elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≤ b1 ≤ b2 ≤ ... ≤ bnB ≤ 109), separated by spaces — elements of array B.
900
Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes).
standard output
PASSED
a2ef3df1e6faecd7477be3c20fc2b94e
train_002.jsonl
1440261000
You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); long [] a, b; int na = in.nextInt(); int nb = in.nextInt(); a = new long[na]; b = new long[nb]; int k = in.nextInt(); int m = in.nextInt(); for (int i = 0; i < na; i++) a[i] = in.nextLong(); for (int i = 0; i < nb; i++) b[i] = in.nextLong(); Arrays.sort(a); Arrays.sort(b); boolean f =false; for (int i = 0; i < b.length; i++){ if (a[k-1] < b[i] && b.length - i >= m) { System.out.println("YES"); f = true; break; } } if (!f) System.out.println("NO"); } }
Java
["3 3\n2 1\n1 2 3\n3 4 5", "3 3\n3 3\n1 2 3\n3 4 5", "5 2\n3 1\n1 1 1 1 1\n2 2"]
2 seconds
["YES", "NO", "YES"]
NoteIn the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 &lt; 3 and 2 &lt; 3).In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: .
Java 8
standard input
[ "sortings" ]
8e0581cce19d6bf5eba30a0aebee9a08
The first line contains two integers nA, nB (1 ≤ nA, nB ≤ 105), separated by a space — the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≤ k ≤ nA, 1 ≤ m ≤ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≤ a1 ≤ a2 ≤ ... ≤ anA ≤ 109), separated by spaces — elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≤ b1 ≤ b2 ≤ ... ≤ bnB ≤ 109), separated by spaces — elements of array B.
900
Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes).
standard output
PASSED
a00e516151b2444f4d22a403dd2f2c72
train_002.jsonl
1440261000
You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.
256 megabytes
import java.util.*; import java.util.Map.Entry; import javax.lang.model.util.ElementScanner6; public class Main { public static void main(String[] args) { Scanner scan=new Scanner(System.in); int n=scan.nextInt(); int m=scan.nextInt(); int a=scan.nextInt(); int b=scan.nextInt(); int x[]=new int[n]; for(int i=0;i<n;++i){ x[i]=scan.nextInt(); } int y[]=new int[m]; for(int i=0;i<m;++i){ y[i]=scan.nextInt(); } if(x[a-1]<y[m-b]){ System.out.print("YES"); } else System.out.println("NO"); } }
Java
["3 3\n2 1\n1 2 3\n3 4 5", "3 3\n3 3\n1 2 3\n3 4 5", "5 2\n3 1\n1 1 1 1 1\n2 2"]
2 seconds
["YES", "NO", "YES"]
NoteIn the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 &lt; 3 and 2 &lt; 3).In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: .
Java 8
standard input
[ "sortings" ]
8e0581cce19d6bf5eba30a0aebee9a08
The first line contains two integers nA, nB (1 ≤ nA, nB ≤ 105), separated by a space — the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≤ k ≤ nA, 1 ≤ m ≤ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≤ a1 ≤ a2 ≤ ... ≤ anA ≤ 109), separated by spaces — elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≤ b1 ≤ b2 ≤ ... ≤ bnB ≤ 109), separated by spaces — elements of array B.
900
Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes).
standard output
PASSED
6bdfebaf47dc3de188cb2ee28d31568b
train_002.jsonl
1440261000
You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.
256 megabytes
import java.util.Scanner; public class Array { public static void main(String[] args) { Scanner s = new Scanner(System.in); int na = s.nextInt(); int nb = s.nextInt(); int k = s.nextInt(); int m = s.nextInt(); long[] a = new long[na]; long[] b = new long[nb]; for (int i = 0; i < na; i++) a[i] = s.nextLong(); for (int i = 0; i < nb; i++) b[i] = s.nextLong(); System.out.println(a[k - 1] < b[nb - m] ? "YES" : "NO"); } }
Java
["3 3\n2 1\n1 2 3\n3 4 5", "3 3\n3 3\n1 2 3\n3 4 5", "5 2\n3 1\n1 1 1 1 1\n2 2"]
2 seconds
["YES", "NO", "YES"]
NoteIn the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 &lt; 3 and 2 &lt; 3).In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: .
Java 8
standard input
[ "sortings" ]
8e0581cce19d6bf5eba30a0aebee9a08
The first line contains two integers nA, nB (1 ≤ nA, nB ≤ 105), separated by a space — the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≤ k ≤ nA, 1 ≤ m ≤ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≤ a1 ≤ a2 ≤ ... ≤ anA ≤ 109), separated by spaces — elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≤ b1 ≤ b2 ≤ ... ≤ bnB ≤ 109), separated by spaces — elements of array B.
900
Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes).
standard output
PASSED
e3e39b44b0248aff86f2b37c2cc79fcd
train_002.jsonl
1440261000
You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.
256 megabytes
import org.omg.PortableInterceptor.INACTIVE; import java.io.*; import java.util.*; /** * Created by Алексей on 06/26/2016. */ import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.random; import static java.lang.Math.*; public class TriangleEasy { public static void main(String [] args){ InputStream inputStream = System.in; OutputStream outputStream = System.out; Integer readFromFile=new Integer(1); InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, PrintWriter out) { int nA = in.nextInt(); int nB = in.nextInt(); int k = in.nextInt(); int m = in.nextInt(); List<Integer> a = new ArrayList<>(nA); for(int i=0; i<nA; i++){ a.add(in.nextInt()); } List<Integer> b = new ArrayList<>(nB); for(int i=0; i<nB; i++){ b.add(in.nextInt()); } if(b.get(nB-m)>a.get(k-1)){ out.println("YES"); }else{ out.println("NO"); } } } static class InputReader { BufferedReader br; StringTokenizer st; String st1; File file = new File("text.txt"); public InputReader(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = null; } public InputReader(int i) { try { br = new BufferedReader( new InputStreamReader(new FileInputStream(file))); } catch (FileNotFoundException e1) { System.out.println("File is not find"); } st = null; } public String next(){ while (st==null || !st.hasMoreTokens()){ try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public String nextLine(){ try { st1 = new String(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } return st1; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong(){ return Long.parseLong(next()); } public Double nextDouble(){ return Double.parseDouble(next()); } public Byte nextByte() { return Byte.parseByte(next()); } private int idx; public Character nextChar() { if(st1==null) { st1 = next(); idx = 0; } if(idx!=(st1.length())-1){ return st1.charAt(idx++); }else{ char c= st1.charAt(idx); st1 = null; return c; } } public void newFile() { try { FileWriter write = new FileWriter(file); write.write("something for cheaking"); write.close(); } catch (IOException e) { e.printStackTrace(); } } } }
Java
["3 3\n2 1\n1 2 3\n3 4 5", "3 3\n3 3\n1 2 3\n3 4 5", "5 2\n3 1\n1 1 1 1 1\n2 2"]
2 seconds
["YES", "NO", "YES"]
NoteIn the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 &lt; 3 and 2 &lt; 3).In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: .
Java 8
standard input
[ "sortings" ]
8e0581cce19d6bf5eba30a0aebee9a08
The first line contains two integers nA, nB (1 ≤ nA, nB ≤ 105), separated by a space — the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≤ k ≤ nA, 1 ≤ m ≤ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≤ a1 ≤ a2 ≤ ... ≤ anA ≤ 109), separated by spaces — elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≤ b1 ≤ b2 ≤ ... ≤ bnB ≤ 109), separated by spaces — elements of array B.
900
Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes).
standard output
PASSED
5101137e07e5e88a542a25153a57d2b4
train_002.jsonl
1440261000
You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.
256 megabytes
import org.omg.PortableInterceptor.INACTIVE; import java.io.*; import java.util.*; /** * Created by Алексей on 06/26/2016. */ import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.random; import static java.lang.Math.*; public class TriangleEasy { public static void main(String [] args){ InputStream inputStream = System.in; OutputStream outputStream = System.out; Integer readFromFile=new Integer(1); InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, PrintWriter out) { int nA = in.nextInt(); int nB = in.nextInt(); int k = in.nextInt(); int m = in.nextInt(); int needA=0; int needB=0; for(int i=0; i<nA; i++){ int value = in.nextInt(); if(i==k-1){ needA = value; } } for(int i=0; i<nB; i++){ int value = in.nextInt(); if(i==nB-m){ needB = value; } } if(needB>needA){ out.println("YES"); }else{ out.println("NO"); } } } static class InputReader { BufferedReader br; StringTokenizer st; String st1; File file = new File("text.txt"); public InputReader(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = null; } public InputReader(int i) { try { br = new BufferedReader( new InputStreamReader(new FileInputStream(file))); } catch (FileNotFoundException e1) { System.out.println("File is not find"); } st = null; } public String next(){ while (st==null || !st.hasMoreTokens()){ try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public String nextLine(){ try { st1 = new String(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } return st1; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong(){ return Long.parseLong(next()); } public Double nextDouble(){ return Double.parseDouble(next()); } public Byte nextByte() { return Byte.parseByte(next()); } private int idx; public Character nextChar() { if(st1==null) { st1 = next(); idx = 0; } if(idx!=(st1.length())-1){ return st1.charAt(idx++); }else{ char c= st1.charAt(idx); st1 = null; return c; } } public void newFile() { try { FileWriter write = new FileWriter(file); write.write("something for cheaking"); write.close(); } catch (IOException e) { e.printStackTrace(); } } } }
Java
["3 3\n2 1\n1 2 3\n3 4 5", "3 3\n3 3\n1 2 3\n3 4 5", "5 2\n3 1\n1 1 1 1 1\n2 2"]
2 seconds
["YES", "NO", "YES"]
NoteIn the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 &lt; 3 and 2 &lt; 3).In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: .
Java 8
standard input
[ "sortings" ]
8e0581cce19d6bf5eba30a0aebee9a08
The first line contains two integers nA, nB (1 ≤ nA, nB ≤ 105), separated by a space — the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≤ k ≤ nA, 1 ≤ m ≤ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≤ a1 ≤ a2 ≤ ... ≤ anA ≤ 109), separated by spaces — elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≤ b1 ≤ b2 ≤ ... ≤ bnB ≤ 109), separated by spaces — elements of array B.
900
Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes).
standard output
PASSED
2246093e6c63f8e8861f6156b44ce070
train_002.jsonl
1440261000
You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.
256 megabytes
import java.util.ArrayList; import java.util.Scanner; public class Main { public static void main(String[] args) { int sizeOfA, sizeOfB; int numChosenA, numChosenB; ArrayList<Integer> Array_A = new ArrayList<Integer>(); ArrayList<Integer> Array_B = new ArrayList<Integer>(); @SuppressWarnings("resource") Scanner scanner = new Scanner(System.in); sizeOfA = scanner.nextInt(); sizeOfB = scanner.nextInt(); numChosenA = scanner.nextInt(); numChosenB = scanner.nextInt(); for(int i = 0; i < sizeOfA; i++) { Array_A.add(scanner.nextInt()); } for(int i = 0; i < sizeOfB; i++) { Array_B.add(scanner.nextInt()); } ArrayList<Integer> temp_A = new ArrayList<Integer>(); ArrayList<Integer> temp_B = new ArrayList<Integer>(); String Result; for(int i = 0; i < numChosenA; i++) { temp_A.add(Array_A.get(i)); } int gap = Array_B.size() - numChosenB; for(int i = 0; i < numChosenB; i++) { temp_B.add(Array_B.get(i+gap)); } int check = 0; int count = 0; for(int i = 0; i < temp_B.size(); i++) { for(int j = 0; j < temp_A.size();j++) { if(temp_A.get(j) < temp_B.get(i)) check = 1; else { check = 0; break; } } break; } if(check == 1) Result = "YES"; else Result = "NO"; System.out.println(Result); } }
Java
["3 3\n2 1\n1 2 3\n3 4 5", "3 3\n3 3\n1 2 3\n3 4 5", "5 2\n3 1\n1 1 1 1 1\n2 2"]
2 seconds
["YES", "NO", "YES"]
NoteIn the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 &lt; 3 and 2 &lt; 3).In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: .
Java 8
standard input
[ "sortings" ]
8e0581cce19d6bf5eba30a0aebee9a08
The first line contains two integers nA, nB (1 ≤ nA, nB ≤ 105), separated by a space — the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≤ k ≤ nA, 1 ≤ m ≤ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≤ a1 ≤ a2 ≤ ... ≤ anA ≤ 109), separated by spaces — elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≤ b1 ≤ b2 ≤ ... ≤ bnB ≤ 109), separated by spaces — elements of array B.
900
Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes).
standard output
PASSED
5c71032358b54eb8605b13763b44ebc6
train_002.jsonl
1440261000
You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.
256 megabytes
import java.util.ArrayList; import java.util.Scanner; public class Main { public static void main(String[] args) { int sizeOfA, sizeOfB; int numChosenA, numChosenB; ArrayList<Integer> Array_A = new ArrayList<Integer>(); ArrayList<Integer> Array_B = new ArrayList<Integer>(); @SuppressWarnings("resource") Scanner scanner = new Scanner(System.in); sizeOfA = scanner.nextInt(); sizeOfB = scanner.nextInt(); numChosenA = scanner.nextInt(); numChosenB = scanner.nextInt(); for(int i = 0; i < sizeOfA; i++) { Array_A.add(scanner.nextInt()); } for(int i = 0; i < sizeOfB; i++) { Array_B.add(scanner.nextInt()); } ArrayList<Integer> temp_A = new ArrayList<Integer>(); ArrayList<Integer> temp_B = new ArrayList<Integer>(); String Result; for(int i = 0; i < numChosenA; i++) { temp_A.add(Array_A.get(i)); } int gap = Array_B.size() - numChosenB; for(int i = 0; i < numChosenB; i++) { temp_B.add(Array_B.get(i+gap)); } int check = 0; for(int i = 0; i < temp_B.size(); i++) { for(int j = 0; j < temp_A.size();j++) { if(temp_A.get(j) < temp_B.get(i)) check = 1; else { check = 0; break; } } break; } if(check == 1) Result = "YES"; else Result = "NO"; System.out.println(Result); } }
Java
["3 3\n2 1\n1 2 3\n3 4 5", "3 3\n3 3\n1 2 3\n3 4 5", "5 2\n3 1\n1 1 1 1 1\n2 2"]
2 seconds
["YES", "NO", "YES"]
NoteIn the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 &lt; 3 and 2 &lt; 3).In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: .
Java 8
standard input
[ "sortings" ]
8e0581cce19d6bf5eba30a0aebee9a08
The first line contains two integers nA, nB (1 ≤ nA, nB ≤ 105), separated by a space — the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≤ k ≤ nA, 1 ≤ m ≤ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≤ a1 ≤ a2 ≤ ... ≤ anA ≤ 109), separated by spaces — elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≤ b1 ≤ b2 ≤ ... ≤ bnB ≤ 109), separated by spaces — elements of array B.
900
Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes).
standard output
PASSED
db31cc2d05d922eae56c16515fe078bf
train_002.jsonl
1440261000
You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.
256 megabytes
import java.util.ArrayList; import java.util.Scanner; public class Main { public static void main(String[] args) { int sizeOfA, sizeOfB; int numChosenA, numChosenB; ArrayList<Integer> Array_A = new ArrayList<Integer>(); ArrayList<Integer> Array_B = new ArrayList<Integer>(); @SuppressWarnings("resource") Scanner scanner = new Scanner(System.in); sizeOfA = scanner.nextInt(); sizeOfB = scanner.nextInt(); numChosenA = scanner.nextInt(); numChosenB = scanner.nextInt(); for(int i = 0; i < sizeOfA; i++) { Array_A.add(scanner.nextInt()); } for(int i = 0; i < sizeOfB; i++) { Array_B.add(scanner.nextInt()); } ArrayList<Integer> temp_A = new ArrayList<Integer>(); ArrayList<Integer> temp_B = new ArrayList<Integer>(); String Result; for(int i = 0; i < numChosenA; i++) { temp_A.add(Array_A.get(i)); } int gap = Array_B.size() - numChosenB; for(int i = 0; i < numChosenB; i++) { temp_B.add(Array_B.get(i+gap)); } int check = 0; if(temp_A.get(temp_A.size()-1) < temp_B.get(0)) check = 1; else check = 0; if(check == 1) Result = "YES"; else Result = "NO"; System.out.println(Result); } }
Java
["3 3\n2 1\n1 2 3\n3 4 5", "3 3\n3 3\n1 2 3\n3 4 5", "5 2\n3 1\n1 1 1 1 1\n2 2"]
2 seconds
["YES", "NO", "YES"]
NoteIn the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 &lt; 3 and 2 &lt; 3).In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: .
Java 8
standard input
[ "sortings" ]
8e0581cce19d6bf5eba30a0aebee9a08
The first line contains two integers nA, nB (1 ≤ nA, nB ≤ 105), separated by a space — the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≤ k ≤ nA, 1 ≤ m ≤ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≤ a1 ≤ a2 ≤ ... ≤ anA ≤ 109), separated by spaces — elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≤ b1 ≤ b2 ≤ ... ≤ bnB ≤ 109), separated by spaces — elements of array B.
900
Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes).
standard output
PASSED
0bb93d93feee51653e18d0c2dd1ad6cb
train_002.jsonl
1440261000
You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.
256 megabytes
import java.util.Scanner; public class Problem { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n_A = scanner.nextInt(); int n_B = scanner.nextInt(); scanner.nextLine(); int k = scanner.nextInt(); int m = scanner.nextInt(); scanner.nextLine(); int[] A = new int[n_A]; int[] B = new int[n_B]; for (int i = 0; i < n_A; i++) { A[i] = scanner.nextInt(); } for (int i = 0; i < n_B; i++) { B[i] = scanner.nextInt(); } int i1 = A[k - 1]; for (int i = 0; i < n_B; i++) { if (B[i] > i1) { if (n_B - i >= m) { System.out.println("YES"); } else { System.out.println("NO"); } return; } } System.out.println("NO"); } }
Java
["3 3\n2 1\n1 2 3\n3 4 5", "3 3\n3 3\n1 2 3\n3 4 5", "5 2\n3 1\n1 1 1 1 1\n2 2"]
2 seconds
["YES", "NO", "YES"]
NoteIn the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 &lt; 3 and 2 &lt; 3).In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: .
Java 8
standard input
[ "sortings" ]
8e0581cce19d6bf5eba30a0aebee9a08
The first line contains two integers nA, nB (1 ≤ nA, nB ≤ 105), separated by a space — the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≤ k ≤ nA, 1 ≤ m ≤ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≤ a1 ≤ a2 ≤ ... ≤ anA ≤ 109), separated by spaces — elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≤ b1 ≤ b2 ≤ ... ≤ bnB ≤ 109), separated by spaces — elements of array B.
900
Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes).
standard output
PASSED
f8b4eb746fa505adc1ea15edb6405cf8
train_002.jsonl
1440261000
You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.
256 megabytes
import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Scanner; import java.util.function.IntBinaryOperator; public class ArraysTask { public static int[] getArray(int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = sr.nextInt(); } return array; } public static int[][] getMatrix(int sizeI, int sizeJ) { int[][] array = new int[sizeI][sizeJ]; for (int i = 0; i < sizeI; i++) { for (int j = 0; j < sizeJ; j++) { array[i][j] = sr.nextInt(); } } return array; } public static int arraySum(int[] array) { int sum = 0; for (int i = 0; i < array.length; i++) { sum += array[i]; } return sum; } public static int max(int[] array) { int max = Integer.MIN_VALUE; for (int i = 0; i < array.length; i++) { if (array[i] > max) max = array[i]; } return max; } public static int min(int[] array) { int min = Integer.MAX_VALUE; for (int i = 0; i < array.length; i++) { if (array[i] < min) min = array[i]; } return min; } static Scanner sr = new Scanner(System.in); public static void main(String[] args) { int arrayASize = sr.nextInt(); int arrayBSize = sr.nextInt(); int arrayAChoiceSize = sr.nextInt(); int arrayBChoiceSize = sr.nextInt(); int arrayA[] = new int[arrayASize]; int arrayB[] = new int[arrayBSize]; arrayA = getArray(arrayASize); arrayB = getArray(arrayBSize); // Arrays.sort(arrayA); // Arrays.sort(arrayB); int subArrayA[] = new int[arrayAChoiceSize]; int subArrayB[] = new int[arrayBChoiceSize]; for (int i = 0; i < subArrayA.length; i++) { subArrayA[i] = arrayA[i]; } for (int i = 0; i < subArrayB.length; i++) { subArrayB[i] = arrayB[arrayB.length - 1 -i]; } // System.out.println(Arrays.toString(subArrayA)); // System.out.println(Arrays.toString(subArrayB)); int subArrayAMax = max(subArrayA); int subArrayBMin = min(subArrayB); // System.out.println(subArrayBMin); // System.out.println(subArrayAMax); if(subArrayBMin > subArrayAMax){ System.out.println("YES"); } else{ System.out.println("NO"); } } }
Java
["3 3\n2 1\n1 2 3\n3 4 5", "3 3\n3 3\n1 2 3\n3 4 5", "5 2\n3 1\n1 1 1 1 1\n2 2"]
2 seconds
["YES", "NO", "YES"]
NoteIn the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 &lt; 3 and 2 &lt; 3).In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: .
Java 8
standard input
[ "sortings" ]
8e0581cce19d6bf5eba30a0aebee9a08
The first line contains two integers nA, nB (1 ≤ nA, nB ≤ 105), separated by a space — the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≤ k ≤ nA, 1 ≤ m ≤ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≤ a1 ≤ a2 ≤ ... ≤ anA ≤ 109), separated by spaces — elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≤ b1 ≤ b2 ≤ ... ≤ bnB ≤ 109), separated by spaces — elements of array B.
900
Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes).
standard output
PASSED
f8781e88789345c47c79a7604a62db26
train_002.jsonl
1440261000
You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.
256 megabytes
import java.util.Scanner; public class Arrays { public static void main(String[] args) { Scanner input = new Scanner (System.in); int a = input.nextInt(); int b = input.nextInt(); int n = input.nextInt(); int k = input.nextInt(); int [] array1 = new int [a+1]; int [] array2 = new int [b+1]; for (int i = 1 ; i <= a ; i++) array1[i] = input.nextInt(); for (int i = 1 ; i <= b ; i++) array2[i] = input.nextInt(); if(array2[1] > array1[n]) System.out.println("YES"); else { boolean B = true; for (int i = 2 ; i <= b ; i++) { if(array2[i] > array1[n] && b - (i-1) >= k) { System.out.println("YES"); B = false; break; } } if(B) System.out.println("NO"); } } }
Java
["3 3\n2 1\n1 2 3\n3 4 5", "3 3\n3 3\n1 2 3\n3 4 5", "5 2\n3 1\n1 1 1 1 1\n2 2"]
2 seconds
["YES", "NO", "YES"]
NoteIn the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 &lt; 3 and 2 &lt; 3).In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: .
Java 8
standard input
[ "sortings" ]
8e0581cce19d6bf5eba30a0aebee9a08
The first line contains two integers nA, nB (1 ≤ nA, nB ≤ 105), separated by a space — the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≤ k ≤ nA, 1 ≤ m ≤ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≤ a1 ≤ a2 ≤ ... ≤ anA ≤ 109), separated by spaces — elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≤ b1 ≤ b2 ≤ ... ≤ bnB ≤ 109), separated by spaces — elements of array B.
900
Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes).
standard output
PASSED
681a0550700dd13102255e52cb742649
train_002.jsonl
1440261000
You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.
256 megabytes
//package codeforces; import java.util.Scanner; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.TreeMap; import java.util.TreeSet; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Stack; import java.util.Set; public class q { // Integer.bitCount(i); count no of 1 bit in a given number static Scanner scn = new Scanner(System.in); static ArrayList<Integer>list=new ArrayList<Integer>(); public static void main(String[] args) { /* TODO Auto-generated method stub */ // System.out.format("%.10f", ans);char c = sc.next().charAt(0); // code int n=scn.nextInt(),n1=scn.nextInt(),k=scn.nextInt(),m=scn.nextInt(),count=0; Integer arr[]=new Integer[n]; Integer brr[]=new Integer[n1]; for(int i=0;i<n;i++) arr[i]=scn.nextInt(); for(int i=0;i<n1;i++) brr[i]=scn.nextInt(); Arrays.parallelSort(arr); Arrays.parallelSort(brr); for(int i=0;i<n1;i++) { if(arr[k-1]<brr[i]) count++; } if(count>=m) System.out.println("YES"); else System.out.println("NO"); } public static void sieveOfEratosthenes(int n) { boolean prime[] = new boolean[n+1]; for(int i=0;i<n;i++) prime[i] = true; for(int p = 2; p*p <=n; p++) { // If prime[p] is not changed, then it is a prime if(prime[p] == true) { // Update all multiples of p for(int i = p*p; i <= n; i += p) prime[i] = false; } } for(int i = 2; i <= n; i++) { if(prime[i] == true) { list.add(i); } } } public static String binary(int n) { StringBuilder sb = new StringBuilder(); int rem = 0; if (n == 1) return "1"; while (n != 1) { rem = n % 2; sb.append(rem); n = n / 2; if (n == 1) sb.append(n); } sb.reverse(); return sb.toString(); } public static class Pair implements Comparable { int x; int y; int z; Pair(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } public int compareTo(Object o) { Pair pp = (Pair) o; if (pp.x == x) return 0; else if (x > pp.x) return 1; else return -1; } } }
Java
["3 3\n2 1\n1 2 3\n3 4 5", "3 3\n3 3\n1 2 3\n3 4 5", "5 2\n3 1\n1 1 1 1 1\n2 2"]
2 seconds
["YES", "NO", "YES"]
NoteIn the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 &lt; 3 and 2 &lt; 3).In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: .
Java 8
standard input
[ "sortings" ]
8e0581cce19d6bf5eba30a0aebee9a08
The first line contains two integers nA, nB (1 ≤ nA, nB ≤ 105), separated by a space — the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≤ k ≤ nA, 1 ≤ m ≤ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≤ a1 ≤ a2 ≤ ... ≤ anA ≤ 109), separated by spaces — elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≤ b1 ≤ b2 ≤ ... ≤ bnB ≤ 109), separated by spaces — elements of array B.
900
Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes).
standard output
PASSED
13e4705b99c7b19177db89a9316b3881
train_002.jsonl
1440261000
You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Sample implements Runnable { static int n,m; static int max=1000005; static int[] s=new int[max]; static int[] a=new int[max]; public static void solve() { n=i(); m=i(); int k=i(); int t=i(); for(int i=0;i<n;i++) { a[i]=i(); } for(int j=0;j<m;j++) { s[j]=i(); } int ans=m; for (int kk=0;kk<m;kk++) { if(s[kk]>a[k-1]) { ans=kk; break; } } if((m-ans)>=t)out.println("YES"); else out.println("NO"); } public void run() { solve(); out.close(); } public static void main(String[] args) throws IOException { new Thread(null, new Sample(), "whatever", 1<<26).start(); } static class Pair implements Comparable<Pair> { long a; int b; Pair(){} Pair(long a,int b) { this.a=a; this.b=b; } public int compareTo(Pair x) { return Long.compare(x.a,this.a); } } ////////////////////////////////////////////////////// Merge Sort //////////////////////////////////////////////////////////////////////// static class Merge { public static void sort(long inputArr[]) { int length = inputArr.length; doMergeSort(inputArr,0, length - 1); } private static void doMergeSort(long[] arr,int lowerIndex, int higherIndex) { if (lowerIndex < higherIndex) { int middle = lowerIndex + (higherIndex - lowerIndex) / 2; doMergeSort(arr,lowerIndex, middle); doMergeSort(arr,middle + 1, higherIndex); mergeParts(arr,lowerIndex, middle, higherIndex); } } private static void mergeParts(long[]array,int lowerIndex, int middle, int higherIndex) { long[] temp=new long[higherIndex-lowerIndex+1]; for (int i = lowerIndex; i <= higherIndex; i++) { temp[i-lowerIndex] = array[i]; } int i = lowerIndex; int j = middle + 1; int k = lowerIndex; while (i <= middle && j <= higherIndex) { if (temp[i-lowerIndex] < temp[j-lowerIndex]) { array[k] = temp[i-lowerIndex]; i++; } else { array[k] = temp[j-lowerIndex]; j++; } k++; } while (i <= middle) { array[k] = temp[i-lowerIndex]; k++; i++; } while(j<=higherIndex) { array[k]=temp[j-lowerIndex]; k++; j++; } } } /////////////////////////////////////////////////////////// Methods //////////////////////////////////////////////////////////////////////// static boolean isPal(String s) { for(int i=0, j=s.length()-1;i<=j;i++,j--) { if(s.charAt(i)!=s.charAt(j)) return false; } return true; } static String rev(String s) { StringBuilder sb=new StringBuilder(s); sb.reverse(); return sb.toString(); } static int gcd(int a,int b){return (a==0)?b:gcd(b%a,a);} static long gcdExtended(long a,long b,long[] x) { if(a==0){ x[0]=0; x[1]=1; return b; } long[] y=new long[2]; long gcd=gcdExtended(b%a, a, y); x[0]=y[1]-(b/a)*y[0]; x[1]=y[0]; return gcd; } boolean findSum(int set[], int n, long sum) { if (sum == 0) return true; if (n == 0 && sum != 0) return false; if (set[n-1] > sum) return findSum(set, n-1, sum); return findSum(set, n-1, sum) ||findSum(set, n-1, sum-set[n-1]); } public static long modPow(long base, long exp, long mod) { base = base % mod; long result = 1; while (exp > 0) { if (exp % 2 == 1) { result = (result * base) % mod; } base = (base * base) % mod; exp = exp >> 1; } return result; } static long[] fac; static long[] inv; static long mod=(long)1e9+7; public static void cal() { fac = new long[1000005]; inv = new long[1000005]; fac[0] = 1; inv[0] = 1; for (int i = 1; i <= 1000000; i++) { fac[i] = (fac[i - 1] * i) % mod; inv[i] = (inv[i - 1] * modPow(i, mod - 2, mod)) % mod; } } public static long ncr(int n, int r) { return (((fac[n] * inv[r]) % mod) * inv[n - r]) % mod; } ////////////////////////////////////////// Input Reader //////////////////////////////////////////////////////////////////////////////////////////////////// static InputReader sc = new InputReader(System.in); static PrintWriter out= new PrintWriter(System.out); static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public long[] nextLongArray(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static int i() { return sc.nextInt(); } static long l(){ return sc.nextLong(); } static int[] iarr(int n) { return sc.nextIntArray(n); } static long[] larr(int n) { return sc.nextLongArray(n); } static String s(){ return sc.nextLine(); } }
Java
["3 3\n2 1\n1 2 3\n3 4 5", "3 3\n3 3\n1 2 3\n3 4 5", "5 2\n3 1\n1 1 1 1 1\n2 2"]
2 seconds
["YES", "NO", "YES"]
NoteIn the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 &lt; 3 and 2 &lt; 3).In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: .
Java 8
standard input
[ "sortings" ]
8e0581cce19d6bf5eba30a0aebee9a08
The first line contains two integers nA, nB (1 ≤ nA, nB ≤ 105), separated by a space — the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≤ k ≤ nA, 1 ≤ m ≤ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≤ a1 ≤ a2 ≤ ... ≤ anA ≤ 109), separated by spaces — elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≤ b1 ≤ b2 ≤ ... ≤ bnB ≤ 109), separated by spaces — elements of array B.
900
Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes).
standard output
PASSED
8f2a4a312427a8386a9921c52ff16fb2
train_002.jsonl
1553965800
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation $$$p$$$ of length $$$n$$$, and Skynyrd bought an array $$$a$$$ of length $$$m$$$, consisting of integers from $$$1$$$ to $$$n$$$. Lynyrd and Skynyrd became bored, so they asked you $$$q$$$ queries, each of which has the following form: "does the subsegment of $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, have a subsequence that is a cyclic shift of $$$p$$$?" Please answer the queries.A permutation of length $$$n$$$ is a sequence of $$$n$$$ integers such that each integer from $$$1$$$ to $$$n$$$ appears exactly once in it.A cyclic shift of a permutation $$$(p_1, p_2, \ldots, p_n)$$$ is a permutation $$$(p_i, p_{i + 1}, \ldots, p_{n}, p_1, p_2, \ldots, p_{i - 1})$$$ for some $$$i$$$ from $$$1$$$ to $$$n$$$. For example, a permutation $$$(2, 1, 3)$$$ has three distinct cyclic shifts: $$$(2, 1, 3)$$$, $$$(1, 3, 2)$$$, $$$(3, 2, 1)$$$.A subsequence of a subsegment of array $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, is a sequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ for some $$$i_1, i_2, \ldots, i_k$$$ such that $$$l \leq i_1 &lt; i_2 &lt; \ldots &lt; i_k \leq r$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; // import java.util.StringTokenizer; import java.util.*; public class Starter { public void Run() throws IOException { int n = in.nextInt(); int m = in.nextInt(); int q = in.nextInt(); int[] reor = new int[n+1]; for (int i = 0; i < n; i++) reor[in.nextInt()] = i; int[] A = new int[m]; for (int i = 0; i < m; i++) A[i] = reor[in.nextInt()]; LinkedList<Integer>[] vd = new LinkedList[n]; int[] R = new int[m]; Arrays.fill(R, 0x3f3f3f3f); for (int i = 0; i < m; i++) { int a = A[i]; int last = a-1; if(last < 0) last+=n; LinkedList<Integer> cur; if (vd[last] == null) cur = new LinkedList(); else { cur = vd[last]; vd[last] = null; } cur.addLast(i); if(vd[a] == null || vd[a].size() < cur.size()) { vd[a] = cur; } else { for (int j = 0; j < cur.size(); j++) vd[a].removeLast(); for (Integer j : cur) vd[a].addLast(j); } if (vd[a].size() == n) { int f = vd[a].pollFirst(); R[f]=i; } } for (int i = m-2; i>=0; i--) R[i] = Math.min(R[i+1], R[i]); for (int i = 0; i < q; i++) { int l = in.nextInt(); int r = in.nextInt(); l--; r--; if (R[l] <= r) out.print(1); else out.print(0); } } static FastReader in; static PrintWriter out; static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } } public static void main(String[] args) { try { in = new FastReader(); out = new PrintWriter(System.out); (new Starter()).Run(); in.br.close(); out.close(); } catch (Throwable e) { e.printStackTrace(); System.exit(1); } } }
Java
["3 6 3\n2 1 3\n1 2 3 1 2 3\n1 5\n2 6\n3 5", "2 4 3\n2 1\n1 1 2 2\n1 2\n2 3\n3 4"]
2 seconds
["110", "010"]
NoteIn the first example the segment from the $$$1$$$-st to the $$$5$$$-th positions is $$$1, 2, 3, 1, 2$$$. There is a subsequence $$$1, 3, 2$$$ that is a cyclic shift of the permutation. The subsegment from the $$$2$$$-nd to the $$$6$$$-th positions also contains a subsequence $$$2, 1, 3$$$ that is equal to the permutation. The subsegment from the $$$3$$$-rd to the $$$5$$$-th positions is $$$3, 1, 2$$$, there is only one subsequence of length $$$3$$$ ($$$3, 1, 2$$$), but it is not a cyclic shift of the permutation.In the second example the possible cyclic shifts are $$$1, 2$$$ and $$$2, 1$$$. The subsegment from the $$$1$$$-st to the $$$2$$$-nd positions is $$$1, 1$$$, its subsequences are not cyclic shifts of the permutation. The subsegment from the $$$2$$$-nd to the $$$3$$$-rd positions is $$$1, 2$$$, it coincides with the permutation. The subsegment from the $$$3$$$ to the $$$4$$$ positions is $$$2, 2$$$, its subsequences are not cyclic shifts of the permutation.
Java 8
standard input
[ "dp", "math", "data structures", "dfs and similar", "trees" ]
4aaeff1b38d501daf9a877667e075d49
The first line contains three integers $$$n$$$, $$$m$$$, $$$q$$$ ($$$1 \le n, m, q \le 2 \cdot 10^5$$$) — the length of the permutation $$$p$$$, the length of the array $$$a$$$ and the number of queries. The next line contains $$$n$$$ integers from $$$1$$$ to $$$n$$$, where the $$$i$$$-th of them is the $$$i$$$-th element of the permutation. Each integer from $$$1$$$ to $$$n$$$ appears exactly once. The next line contains $$$m$$$ integers from $$$1$$$ to $$$n$$$, the $$$i$$$-th of them is the $$$i$$$-th element of the array $$$a$$$. The next $$$q$$$ lines describe queries. The $$$i$$$-th of these lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le m$$$), meaning that the $$$i$$$-th query is about the subsegment of the array from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive.
2,000
Print a single string of length $$$q$$$, consisting of $$$0$$$ and $$$1$$$, the digit on the $$$i$$$-th positions should be $$$1$$$, if the subsegment of array $$$a$$$ from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive, contains a subsequence that is a cyclic shift of $$$p$$$, and $$$0$$$ otherwise.
standard output
PASSED
6e06b8baf6f35c08760aa233c6a9e6cc
train_002.jsonl
1553965800
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation $$$p$$$ of length $$$n$$$, and Skynyrd bought an array $$$a$$$ of length $$$m$$$, consisting of integers from $$$1$$$ to $$$n$$$. Lynyrd and Skynyrd became bored, so they asked you $$$q$$$ queries, each of which has the following form: "does the subsegment of $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, have a subsequence that is a cyclic shift of $$$p$$$?" Please answer the queries.A permutation of length $$$n$$$ is a sequence of $$$n$$$ integers such that each integer from $$$1$$$ to $$$n$$$ appears exactly once in it.A cyclic shift of a permutation $$$(p_1, p_2, \ldots, p_n)$$$ is a permutation $$$(p_i, p_{i + 1}, \ldots, p_{n}, p_1, p_2, \ldots, p_{i - 1})$$$ for some $$$i$$$ from $$$1$$$ to $$$n$$$. For example, a permutation $$$(2, 1, 3)$$$ has three distinct cyclic shifts: $$$(2, 1, 3)$$$, $$$(1, 3, 2)$$$, $$$(3, 2, 1)$$$.A subsequence of a subsegment of array $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, is a sequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ for some $$$i_1, i_2, \ldots, i_k$$$ such that $$$l \leq i_1 &lt; i_2 &lt; \ldots &lt; i_k \leq r$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; // import java.util.StringTokenizer; import java.util.*; public class Starter { public void Run() throws IOException { int n = in.nextInt(); int m = in.nextInt(); int q = in.nextInt(); int[] reor = new int[n+1]; for (int i = 0; i < n; i++) reor[in.nextInt()] = i; int[] A = new int[m]; for (int i = 0; i < m; i++) A[i] = reor[in.nextInt()]; ArrayDeque<Integer> [] vd = new ArrayDeque[n]; int[] R = new int[m]; Arrays.fill(R, 0x3f3f3f3f); for (int i = 0; i < m; i++) { int a = A[i]; int last = a-1; if(last < 0) last+=n; ArrayDeque<Integer> cur; if (vd[last] == null) cur = new ArrayDeque<>(); else { cur = vd[last]; vd[last] = null; } cur.addLast(i); if(vd[a] == null || vd[a].size() < cur.size()) { vd[a] = cur; } else { for (int j = 0; j < cur.size(); j++) vd[a].removeLast(); for (Integer j : cur) vd[a].addLast(j); } if (vd[a].size() == n) { int f = vd[a].pollFirst(); R[f]=i; } } for (int i = m-2; i>=0; i--) R[i] = Math.min(R[i+1], R[i]); for (int i = 0; i < q; i++) { int l = in.nextInt(); int r = in.nextInt(); l--; r--; if (R[l] <= r) out.print(1); else out.print(0); } } static FastReader in; static PrintWriter out; static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } } public static void main(String[] args) { try { in = new FastReader(); out = new PrintWriter(System.out); (new Starter()).Run(); in.br.close(); out.close(); } catch (Throwable e) { e.printStackTrace(); System.exit(1); } } }
Java
["3 6 3\n2 1 3\n1 2 3 1 2 3\n1 5\n2 6\n3 5", "2 4 3\n2 1\n1 1 2 2\n1 2\n2 3\n3 4"]
2 seconds
["110", "010"]
NoteIn the first example the segment from the $$$1$$$-st to the $$$5$$$-th positions is $$$1, 2, 3, 1, 2$$$. There is a subsequence $$$1, 3, 2$$$ that is a cyclic shift of the permutation. The subsegment from the $$$2$$$-nd to the $$$6$$$-th positions also contains a subsequence $$$2, 1, 3$$$ that is equal to the permutation. The subsegment from the $$$3$$$-rd to the $$$5$$$-th positions is $$$3, 1, 2$$$, there is only one subsequence of length $$$3$$$ ($$$3, 1, 2$$$), but it is not a cyclic shift of the permutation.In the second example the possible cyclic shifts are $$$1, 2$$$ and $$$2, 1$$$. The subsegment from the $$$1$$$-st to the $$$2$$$-nd positions is $$$1, 1$$$, its subsequences are not cyclic shifts of the permutation. The subsegment from the $$$2$$$-nd to the $$$3$$$-rd positions is $$$1, 2$$$, it coincides with the permutation. The subsegment from the $$$3$$$ to the $$$4$$$ positions is $$$2, 2$$$, its subsequences are not cyclic shifts of the permutation.
Java 8
standard input
[ "dp", "math", "data structures", "dfs and similar", "trees" ]
4aaeff1b38d501daf9a877667e075d49
The first line contains three integers $$$n$$$, $$$m$$$, $$$q$$$ ($$$1 \le n, m, q \le 2 \cdot 10^5$$$) — the length of the permutation $$$p$$$, the length of the array $$$a$$$ and the number of queries. The next line contains $$$n$$$ integers from $$$1$$$ to $$$n$$$, where the $$$i$$$-th of them is the $$$i$$$-th element of the permutation. Each integer from $$$1$$$ to $$$n$$$ appears exactly once. The next line contains $$$m$$$ integers from $$$1$$$ to $$$n$$$, the $$$i$$$-th of them is the $$$i$$$-th element of the array $$$a$$$. The next $$$q$$$ lines describe queries. The $$$i$$$-th of these lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le m$$$), meaning that the $$$i$$$-th query is about the subsegment of the array from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive.
2,000
Print a single string of length $$$q$$$, consisting of $$$0$$$ and $$$1$$$, the digit on the $$$i$$$-th positions should be $$$1$$$, if the subsegment of array $$$a$$$ from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive, contains a subsequence that is a cyclic shift of $$$p$$$, and $$$0$$$ otherwise.
standard output
PASSED
7f288f596c97c55097813da45b00633f
train_002.jsonl
1553965800
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation $$$p$$$ of length $$$n$$$, and Skynyrd bought an array $$$a$$$ of length $$$m$$$, consisting of integers from $$$1$$$ to $$$n$$$. Lynyrd and Skynyrd became bored, so they asked you $$$q$$$ queries, each of which has the following form: "does the subsegment of $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, have a subsequence that is a cyclic shift of $$$p$$$?" Please answer the queries.A permutation of length $$$n$$$ is a sequence of $$$n$$$ integers such that each integer from $$$1$$$ to $$$n$$$ appears exactly once in it.A cyclic shift of a permutation $$$(p_1, p_2, \ldots, p_n)$$$ is a permutation $$$(p_i, p_{i + 1}, \ldots, p_{n}, p_1, p_2, \ldots, p_{i - 1})$$$ for some $$$i$$$ from $$$1$$$ to $$$n$$$. For example, a permutation $$$(2, 1, 3)$$$ has three distinct cyclic shifts: $$$(2, 1, 3)$$$, $$$(1, 3, 2)$$$, $$$(3, 2, 1)$$$.A subsequence of a subsegment of array $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, is a sequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ for some $$$i_1, i_2, \ldots, i_k$$$ such that $$$l \leq i_1 &lt; i_2 &lt; \ldots &lt; i_k \leq r$$$.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.lang.reflect.Array; import java.util.*; import java.io.BufferedWriter; import java.io.IOException; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); int n = in.readInt(); int m = in.readInt(); int q = in.readInt(); int[] reor = new int[n+1]; for (int i = 0; i < n; i++) reor[in.readInt()] = i; int[] A = new int[m]; for (int i = 0; i < m; i++) A[i] = reor[in.readInt()]; LinkedList<Integer>[] vd = new LinkedList[n]; int[] R = new int[m]; Arrays.fill(R, 0x3f3f3f3f); for (int i = 0; i < m; i++) { int a = A[i]; int last = a-1; if(last < 0) last+=n; LinkedList<Integer> cur; if (vd[last] == null) cur = new LinkedList(); else { cur = vd[last]; vd[last] = null; } cur.addLast(i); if(vd[a] == null || vd[a].size() < cur.size()) { vd[a] = cur; } else { for (int j = 0; j < cur.size(); j++) vd[a].removeLast(); for (Integer j : cur) vd[a].addLast(j); } if (vd[a].size() == n) { int f = vd[a].pollFirst(); R[f]=i; } } for (int i = m-2; i>=0; i--) R[i] = Math.min(R[i+1], R[i]); for (int i = 0; i < q; i++) { int l = in.readInt(); int r = in.readInt(); l--; r--; if (R[l] <= r) out.print(1); else out.print(0); } out.close(); } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int[] readIntArray(int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = readInt(); } return array; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(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(); } } }
Java
["3 6 3\n2 1 3\n1 2 3 1 2 3\n1 5\n2 6\n3 5", "2 4 3\n2 1\n1 1 2 2\n1 2\n2 3\n3 4"]
2 seconds
["110", "010"]
NoteIn the first example the segment from the $$$1$$$-st to the $$$5$$$-th positions is $$$1, 2, 3, 1, 2$$$. There is a subsequence $$$1, 3, 2$$$ that is a cyclic shift of the permutation. The subsegment from the $$$2$$$-nd to the $$$6$$$-th positions also contains a subsequence $$$2, 1, 3$$$ that is equal to the permutation. The subsegment from the $$$3$$$-rd to the $$$5$$$-th positions is $$$3, 1, 2$$$, there is only one subsequence of length $$$3$$$ ($$$3, 1, 2$$$), but it is not a cyclic shift of the permutation.In the second example the possible cyclic shifts are $$$1, 2$$$ and $$$2, 1$$$. The subsegment from the $$$1$$$-st to the $$$2$$$-nd positions is $$$1, 1$$$, its subsequences are not cyclic shifts of the permutation. The subsegment from the $$$2$$$-nd to the $$$3$$$-rd positions is $$$1, 2$$$, it coincides with the permutation. The subsegment from the $$$3$$$ to the $$$4$$$ positions is $$$2, 2$$$, its subsequences are not cyclic shifts of the permutation.
Java 8
standard input
[ "dp", "math", "data structures", "dfs and similar", "trees" ]
4aaeff1b38d501daf9a877667e075d49
The first line contains three integers $$$n$$$, $$$m$$$, $$$q$$$ ($$$1 \le n, m, q \le 2 \cdot 10^5$$$) — the length of the permutation $$$p$$$, the length of the array $$$a$$$ and the number of queries. The next line contains $$$n$$$ integers from $$$1$$$ to $$$n$$$, where the $$$i$$$-th of them is the $$$i$$$-th element of the permutation. Each integer from $$$1$$$ to $$$n$$$ appears exactly once. The next line contains $$$m$$$ integers from $$$1$$$ to $$$n$$$, the $$$i$$$-th of them is the $$$i$$$-th element of the array $$$a$$$. The next $$$q$$$ lines describe queries. The $$$i$$$-th of these lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le m$$$), meaning that the $$$i$$$-th query is about the subsegment of the array from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive.
2,000
Print a single string of length $$$q$$$, consisting of $$$0$$$ and $$$1$$$, the digit on the $$$i$$$-th positions should be $$$1$$$, if the subsegment of array $$$a$$$ from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive, contains a subsequence that is a cyclic shift of $$$p$$$, and $$$0$$$ otherwise.
standard output
PASSED
bc198c29ed13772d76f87fd71e036d04
train_002.jsonl
1553965800
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation $$$p$$$ of length $$$n$$$, and Skynyrd bought an array $$$a$$$ of length $$$m$$$, consisting of integers from $$$1$$$ to $$$n$$$. Lynyrd and Skynyrd became bored, so they asked you $$$q$$$ queries, each of which has the following form: "does the subsegment of $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, have a subsequence that is a cyclic shift of $$$p$$$?" Please answer the queries.A permutation of length $$$n$$$ is a sequence of $$$n$$$ integers such that each integer from $$$1$$$ to $$$n$$$ appears exactly once in it.A cyclic shift of a permutation $$$(p_1, p_2, \ldots, p_n)$$$ is a permutation $$$(p_i, p_{i + 1}, \ldots, p_{n}, p_1, p_2, \ldots, p_{i - 1})$$$ for some $$$i$$$ from $$$1$$$ to $$$n$$$. For example, a permutation $$$(2, 1, 3)$$$ has three distinct cyclic shifts: $$$(2, 1, 3)$$$, $$$(1, 3, 2)$$$, $$$(3, 2, 1)$$$.A subsequence of a subsegment of array $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, is a sequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ for some $$$i_1, i_2, \ldots, i_k$$$ such that $$$l \leq i_1 &lt; i_2 &lt; \ldots &lt; i_k \leq r$$$.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.lang.reflect.Array; import java.util.*; import java.io.BufferedWriter; import java.io.IOException; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); int n = in.readInt(); int m = in.readInt(); int q = in.readInt(); int[] reor = new int[n+1]; for (int i = 0; i < n; i++) reor[in.readInt()] = i; int[] A = new int[m]; for (int i = 0; i < m; i++) A[i] = reor[in.readInt()]; LinkedList<Integer>[] vd = new LinkedList[n]; int[] R = new int[m]; Arrays.fill(R, 0x3f3f3f3f); for (int i = 0; i < m; i++) { int a = A[i]; int last = a-1; if(last < 0) last+=n; LinkedList<Integer> cur; if (vd[last] == null) cur = new LinkedList(); else { cur = vd[last]; vd[last] = null; } cur.addLast(i); if(vd[a] == null || vd[a].size() < cur.size()) { vd[a] = cur; } else { for (int j = 0; j < cur.size(); j++) vd[a].removeLast(); for (Integer j : cur) vd[a].addLast(j); } if (vd[a].size() == n) { int f = vd[a].pollFirst(); R[f]=i; } } for (int i = m-2; i>=0; i--) R[i] = Math.min(R[i+1], R[i]); StringBuilder sb = new StringBuilder(); for (int i = 0; i < q; i++) { int l = in.readInt(); int r = in.readInt(); l--; r--; if (R[l] <= r) sb.append('1'); else sb.append('0'); } out.print(sb); out.close(); } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int[] readIntArray(int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = readInt(); } return array; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(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(); } } }
Java
["3 6 3\n2 1 3\n1 2 3 1 2 3\n1 5\n2 6\n3 5", "2 4 3\n2 1\n1 1 2 2\n1 2\n2 3\n3 4"]
2 seconds
["110", "010"]
NoteIn the first example the segment from the $$$1$$$-st to the $$$5$$$-th positions is $$$1, 2, 3, 1, 2$$$. There is a subsequence $$$1, 3, 2$$$ that is a cyclic shift of the permutation. The subsegment from the $$$2$$$-nd to the $$$6$$$-th positions also contains a subsequence $$$2, 1, 3$$$ that is equal to the permutation. The subsegment from the $$$3$$$-rd to the $$$5$$$-th positions is $$$3, 1, 2$$$, there is only one subsequence of length $$$3$$$ ($$$3, 1, 2$$$), but it is not a cyclic shift of the permutation.In the second example the possible cyclic shifts are $$$1, 2$$$ and $$$2, 1$$$. The subsegment from the $$$1$$$-st to the $$$2$$$-nd positions is $$$1, 1$$$, its subsequences are not cyclic shifts of the permutation. The subsegment from the $$$2$$$-nd to the $$$3$$$-rd positions is $$$1, 2$$$, it coincides with the permutation. The subsegment from the $$$3$$$ to the $$$4$$$ positions is $$$2, 2$$$, its subsequences are not cyclic shifts of the permutation.
Java 8
standard input
[ "dp", "math", "data structures", "dfs and similar", "trees" ]
4aaeff1b38d501daf9a877667e075d49
The first line contains three integers $$$n$$$, $$$m$$$, $$$q$$$ ($$$1 \le n, m, q \le 2 \cdot 10^5$$$) — the length of the permutation $$$p$$$, the length of the array $$$a$$$ and the number of queries. The next line contains $$$n$$$ integers from $$$1$$$ to $$$n$$$, where the $$$i$$$-th of them is the $$$i$$$-th element of the permutation. Each integer from $$$1$$$ to $$$n$$$ appears exactly once. The next line contains $$$m$$$ integers from $$$1$$$ to $$$n$$$, the $$$i$$$-th of them is the $$$i$$$-th element of the array $$$a$$$. The next $$$q$$$ lines describe queries. The $$$i$$$-th of these lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le m$$$), meaning that the $$$i$$$-th query is about the subsegment of the array from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive.
2,000
Print a single string of length $$$q$$$, consisting of $$$0$$$ and $$$1$$$, the digit on the $$$i$$$-th positions should be $$$1$$$, if the subsegment of array $$$a$$$ from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive, contains a subsequence that is a cyclic shift of $$$p$$$, and $$$0$$$ otherwise.
standard output
PASSED
0360cf5c42bbe8c4fa871e9bf4f9cc44
train_002.jsonl
1553965800
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation $$$p$$$ of length $$$n$$$, and Skynyrd bought an array $$$a$$$ of length $$$m$$$, consisting of integers from $$$1$$$ to $$$n$$$. Lynyrd and Skynyrd became bored, so they asked you $$$q$$$ queries, each of which has the following form: "does the subsegment of $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, have a subsequence that is a cyclic shift of $$$p$$$?" Please answer the queries.A permutation of length $$$n$$$ is a sequence of $$$n$$$ integers such that each integer from $$$1$$$ to $$$n$$$ appears exactly once in it.A cyclic shift of a permutation $$$(p_1, p_2, \ldots, p_n)$$$ is a permutation $$$(p_i, p_{i + 1}, \ldots, p_{n}, p_1, p_2, \ldots, p_{i - 1})$$$ for some $$$i$$$ from $$$1$$$ to $$$n$$$. For example, a permutation $$$(2, 1, 3)$$$ has three distinct cyclic shifts: $$$(2, 1, 3)$$$, $$$(1, 3, 2)$$$, $$$(3, 2, 1)$$$.A subsequence of a subsegment of array $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, is a sequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ for some $$$i_1, i_2, \ldots, i_k$$$ such that $$$l \leq i_1 &lt; i_2 &lt; \ldots &lt; i_k \leq r$$$.
256 megabytes
import java.io.*; import java.util.*; import java.io.*; import java.util.*; public class D { public static int up[][]; public static int maxe; public static void main(String[] args) throws Exception { FastScanner sc = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int N = sc.nextInt(); int M = sc.nextInt(); int Q = sc.nextInt(); int[] perm = sc.nextInts(N); int[] arr = sc.nextInts(M); Map<Integer, Integer> pos = new HashMap<Integer, Integer>(); for(int i = 0; i < N; i++){ pos.put(perm[i], i); } maxe = (int)(Math.log(M)/Math.log(2)) + 1; up = new int[M][maxe]; for(int i = 0; i < M; i++){ Arrays.fill(up[i], -1); } Stack<Integer> stack[] = new Stack[N+1]; for(int i = 0; i < N+1; i++){ stack[i] = new Stack<Integer>(); } for(int i = 0; i < M; i++){ int prevc = perm[(pos.get(arr[i])+N-1)%N]; if(!stack[prevc].isEmpty()){ up[i][0] = stack[prevc].peek(); } stack[arr[i]].push(i); } for(int l = 1; l < maxe; l++){ for(int j = 0; j < M; j++){ if(up[j][l-1] != -1) up[j][l] = up[up[j][l-1]][l-1]; } } int[] ans = new int[M]; int lastpos = -1; for(int i = 0; i < M; i++){ lastpos = Math.max(lastpos, lift(i, N-1)); ans[i] = lastpos; } for(int q = 0; q < Q; q++){ int l = sc.nextInt()-1; int r = sc.nextInt()-1; if(ans[r] >= l){ out.print(1); } else{ out.print(0); } } out.close(); } public static int lift(int node, int k){ for(int l = 0; l < maxe; l++){ if(node != -1){ if((k & (1 << l)) != 0){ node = up[node][l]; } } } return node; } static class FastScanner { private int BS = 1 << 16; private char NC = (char) 0; private byte[] buf = new byte[BS]; private int bId = 0, size = 0; private char c = NC; private double cnt = 1; private BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } private char getChar() { while (bId == size) { try { size = in.read(buf); } catch (Exception e) { return NC; } if (size == -1) return NC; bId = 0; } return (char) buf[bId++]; } public int nextInt() { return (int) nextLong(); } public int[] nextInts(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) nextLong(); } return res; } public long[] nextLongs(int N) { long[] res = new long[N]; for (int i = 0; i < N; i++) { res[i] = nextLong(); } return res; } public long nextLong() { cnt = 1; boolean neg = false; if (c == NC) c = getChar(); for (; (c < '0' || c > '9'); c = getChar()) { if (c == '-') neg = true; } long res = 0; for (; c >= '0' && c <= '9'; c = getChar()) { res = (res << 3) + (res << 1) + c - '0'; cnt *= 10; } return neg ? -res : res; } public double nextDouble() { double cur = nextLong(); return c != '.' ? cur : cur + nextLong() / cnt; } public double[] nextDoubles(int N) { double[] res = new double[N]; for (int i = 0; i < N; i++) { res[i] = nextDouble(); } return res; } public String next() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c > 32) { res.append(c); c = getChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c != '\n') { res.append(c); c = getChar(); } return res.toString(); } public boolean hasNext() { if (c > 32) return true; while (true) { c = getChar(); if (c == NC) return false; else if (c > 32) return true; } } } static void ASSERT(boolean assertion, String message) { if (!assertion) throw new AssertionError(message); } }
Java
["3 6 3\n2 1 3\n1 2 3 1 2 3\n1 5\n2 6\n3 5", "2 4 3\n2 1\n1 1 2 2\n1 2\n2 3\n3 4"]
2 seconds
["110", "010"]
NoteIn the first example the segment from the $$$1$$$-st to the $$$5$$$-th positions is $$$1, 2, 3, 1, 2$$$. There is a subsequence $$$1, 3, 2$$$ that is a cyclic shift of the permutation. The subsegment from the $$$2$$$-nd to the $$$6$$$-th positions also contains a subsequence $$$2, 1, 3$$$ that is equal to the permutation. The subsegment from the $$$3$$$-rd to the $$$5$$$-th positions is $$$3, 1, 2$$$, there is only one subsequence of length $$$3$$$ ($$$3, 1, 2$$$), but it is not a cyclic shift of the permutation.In the second example the possible cyclic shifts are $$$1, 2$$$ and $$$2, 1$$$. The subsegment from the $$$1$$$-st to the $$$2$$$-nd positions is $$$1, 1$$$, its subsequences are not cyclic shifts of the permutation. The subsegment from the $$$2$$$-nd to the $$$3$$$-rd positions is $$$1, 2$$$, it coincides with the permutation. The subsegment from the $$$3$$$ to the $$$4$$$ positions is $$$2, 2$$$, its subsequences are not cyclic shifts of the permutation.
Java 8
standard input
[ "dp", "math", "data structures", "dfs and similar", "trees" ]
4aaeff1b38d501daf9a877667e075d49
The first line contains three integers $$$n$$$, $$$m$$$, $$$q$$$ ($$$1 \le n, m, q \le 2 \cdot 10^5$$$) — the length of the permutation $$$p$$$, the length of the array $$$a$$$ and the number of queries. The next line contains $$$n$$$ integers from $$$1$$$ to $$$n$$$, where the $$$i$$$-th of them is the $$$i$$$-th element of the permutation. Each integer from $$$1$$$ to $$$n$$$ appears exactly once. The next line contains $$$m$$$ integers from $$$1$$$ to $$$n$$$, the $$$i$$$-th of them is the $$$i$$$-th element of the array $$$a$$$. The next $$$q$$$ lines describe queries. The $$$i$$$-th of these lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le m$$$), meaning that the $$$i$$$-th query is about the subsegment of the array from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive.
2,000
Print a single string of length $$$q$$$, consisting of $$$0$$$ and $$$1$$$, the digit on the $$$i$$$-th positions should be $$$1$$$, if the subsegment of array $$$a$$$ from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive, contains a subsequence that is a cyclic shift of $$$p$$$, and $$$0$$$ otherwise.
standard output
PASSED
4994af2d8278e1936cb06b96a8e451d4
train_002.jsonl
1553965800
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation $$$p$$$ of length $$$n$$$, and Skynyrd bought an array $$$a$$$ of length $$$m$$$, consisting of integers from $$$1$$$ to $$$n$$$. Lynyrd and Skynyrd became bored, so they asked you $$$q$$$ queries, each of which has the following form: "does the subsegment of $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, have a subsequence that is a cyclic shift of $$$p$$$?" Please answer the queries.A permutation of length $$$n$$$ is a sequence of $$$n$$$ integers such that each integer from $$$1$$$ to $$$n$$$ appears exactly once in it.A cyclic shift of a permutation $$$(p_1, p_2, \ldots, p_n)$$$ is a permutation $$$(p_i, p_{i + 1}, \ldots, p_{n}, p_1, p_2, \ldots, p_{i - 1})$$$ for some $$$i$$$ from $$$1$$$ to $$$n$$$. For example, a permutation $$$(2, 1, 3)$$$ has three distinct cyclic shifts: $$$(2, 1, 3)$$$, $$$(1, 3, 2)$$$, $$$(3, 2, 1)$$$.A subsequence of a subsegment of array $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, is a sequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ for some $$$i_1, i_2, \ldots, i_k$$$ such that $$$l \leq i_1 &lt; i_2 &lt; \ldots &lt; i_k \leq r$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author ilyakor */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int m = in.nextInt(); int q = in.nextInt(); int[] p = new int[n]; for (int i = 0; i < n; ++i) p[in.nextInt() - 1] = i; int[] a = new int[m]; for (int i = 0; i < m; ++i) a[i] = p[in.nextInt() - 1]; int[][] next = new int[20][m]; { int[] nx = new int[n]; Arrays.fill(nx, m); for (int i = m - 1; i >= 0; --i) { int x = a[i]; nx[x] = i; next[0][i] = nx[(x + 1) % n]; } } for (int i = 1; i < next.length; ++i) { for (int j = 0; j < m; ++j) { int t = next[i - 1][j]; if (t < m) t = next[i - 1][t]; next[i][j] = t; } } int[] d = new int[m]; for (int i = 0; i < m; ++i) { int t = i; for (int j = next.length - 1; j >= 0; --j) { if (t >= m) break; if (((n - 1) >> j) % 2 == 1) t = next[j][t]; } d[i] = t; } SegmentTreeFastAddMax tree = new SegmentTreeFastAddMax(m + 2); for (int i = 0; i < m; ++i) tree.set(i + 1, -d[i]); for (int i = 0; i < q; ++i) { int l = in.nextInt(); int r = in.nextInt(); long val = -tree.max(l, r); if (val + 1 <= r) out.print('1'); else out.print('0'); } out.printLine(); } } static class SegmentTreeFastAddMax { final int n; final long[] t; public SegmentTreeFastAddMax(int n) { int h = 1; while (h <= n) h *= 2; n = h; this.n = n; t = new long[n + n]; } public void set(int i, long value) { add(i, value - t[i + n]); } public void add(int i, long value) { i += n; t[i] += value; for (; i > 1; i >>= 1) t[i >> 1] = Math.max(t[i], t[i ^ 1]); } public long max(int a, int b) { long res = Long.MIN_VALUE; for (a += n, b += n; a <= b; a = (a + 1) >> 1, b = (b - 1) >> 1) { res = Math.max(res, t[a]); res = Math.max(res, t[b]); } return res; } } 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(); } } static class InputReader { private InputStream stream; private byte[] buffer = new byte[10000]; private int cur; private int count; public InputReader(InputStream stream) { this.stream = stream; } public static boolean isSpace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int read() { if (count == -1) { throw new InputMismatchException(); } try { if (cur >= count) { cur = 0; count = stream.read(buffer); if (count <= 0) return -1; } } catch (IOException e) { throw new InputMismatchException(); } return buffer[cur++]; } public int readSkipSpace() { int c; do { c = read(); } while (isSpace(c)); return c; } public int nextInt() { int sgn = 1; int c = readSkipSpace(); if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res = res * 10 + c - '0'; c = read(); } while (!isSpace(c)); res *= sgn; return res; } } }
Java
["3 6 3\n2 1 3\n1 2 3 1 2 3\n1 5\n2 6\n3 5", "2 4 3\n2 1\n1 1 2 2\n1 2\n2 3\n3 4"]
2 seconds
["110", "010"]
NoteIn the first example the segment from the $$$1$$$-st to the $$$5$$$-th positions is $$$1, 2, 3, 1, 2$$$. There is a subsequence $$$1, 3, 2$$$ that is a cyclic shift of the permutation. The subsegment from the $$$2$$$-nd to the $$$6$$$-th positions also contains a subsequence $$$2, 1, 3$$$ that is equal to the permutation. The subsegment from the $$$3$$$-rd to the $$$5$$$-th positions is $$$3, 1, 2$$$, there is only one subsequence of length $$$3$$$ ($$$3, 1, 2$$$), but it is not a cyclic shift of the permutation.In the second example the possible cyclic shifts are $$$1, 2$$$ and $$$2, 1$$$. The subsegment from the $$$1$$$-st to the $$$2$$$-nd positions is $$$1, 1$$$, its subsequences are not cyclic shifts of the permutation. The subsegment from the $$$2$$$-nd to the $$$3$$$-rd positions is $$$1, 2$$$, it coincides with the permutation. The subsegment from the $$$3$$$ to the $$$4$$$ positions is $$$2, 2$$$, its subsequences are not cyclic shifts of the permutation.
Java 8
standard input
[ "dp", "math", "data structures", "dfs and similar", "trees" ]
4aaeff1b38d501daf9a877667e075d49
The first line contains three integers $$$n$$$, $$$m$$$, $$$q$$$ ($$$1 \le n, m, q \le 2 \cdot 10^5$$$) — the length of the permutation $$$p$$$, the length of the array $$$a$$$ and the number of queries. The next line contains $$$n$$$ integers from $$$1$$$ to $$$n$$$, where the $$$i$$$-th of them is the $$$i$$$-th element of the permutation. Each integer from $$$1$$$ to $$$n$$$ appears exactly once. The next line contains $$$m$$$ integers from $$$1$$$ to $$$n$$$, the $$$i$$$-th of them is the $$$i$$$-th element of the array $$$a$$$. The next $$$q$$$ lines describe queries. The $$$i$$$-th of these lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le m$$$), meaning that the $$$i$$$-th query is about the subsegment of the array from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive.
2,000
Print a single string of length $$$q$$$, consisting of $$$0$$$ and $$$1$$$, the digit on the $$$i$$$-th positions should be $$$1$$$, if the subsegment of array $$$a$$$ from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive, contains a subsequence that is a cyclic shift of $$$p$$$, and $$$0$$$ otherwise.
standard output
PASSED
fd4e4d4b81d3a6eec22dc2e40e8ab3ea
train_002.jsonl
1553965800
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation $$$p$$$ of length $$$n$$$, and Skynyrd bought an array $$$a$$$ of length $$$m$$$, consisting of integers from $$$1$$$ to $$$n$$$. Lynyrd and Skynyrd became bored, so they asked you $$$q$$$ queries, each of which has the following form: "does the subsegment of $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, have a subsequence that is a cyclic shift of $$$p$$$?" Please answer the queries.A permutation of length $$$n$$$ is a sequence of $$$n$$$ integers such that each integer from $$$1$$$ to $$$n$$$ appears exactly once in it.A cyclic shift of a permutation $$$(p_1, p_2, \ldots, p_n)$$$ is a permutation $$$(p_i, p_{i + 1}, \ldots, p_{n}, p_1, p_2, \ldots, p_{i - 1})$$$ for some $$$i$$$ from $$$1$$$ to $$$n$$$. For example, a permutation $$$(2, 1, 3)$$$ has three distinct cyclic shifts: $$$(2, 1, 3)$$$, $$$(1, 3, 2)$$$, $$$(3, 2, 1)$$$.A subsequence of a subsegment of array $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, is a sequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ for some $$$i_1, i_2, \ldots, i_k$$$ such that $$$l \leq i_1 &lt; i_2 &lt; \ldots &lt; i_k \leq r$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import java.io.IOException; import java.io.UncheckedIOException; import java.io.Closeable; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27); thread.start(); thread.join(); } static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastInput in = new FastInput(inputStream); FastOutput out = new FastOutput(outputStream); BLynyrdSkynyrd solver = new BLynyrdSkynyrd(); solver.solve(1, in, out); out.close(); } } static class BLynyrdSkynyrd { int[][] jump; int m; public void solve(int testNumber, FastInput in, FastOutput out) { int n = in.readInt(); m = in.readInt(); int q = in.readInt(); int[] a = new int[n]; int[] invA = new int[n + 1]; for (int i = 0; i < n; i++) { a[i] = in.readInt(); invA[a[i]] = i; } int[] b = new int[m]; for (int i = 0; i < m; i++) { b[i] = invA[in.readInt()]; } jump = new int[m][20]; SequenceUtils.deepFill(jump, m); int[] registry = new int[n]; SequenceUtils.deepFill(registry, m); for (int i = m - 1; i >= 0; i--) { int next = (b[i] + 1) % n; jump[i][0] = registry[next]; registry[b[i]] = i; for (int j = 0; jump[i][j] != m; j++) { jump[i][j + 1] = jump[jump[i][j]][j]; } } int[] right = new int[m]; for (int i = 0; i < m; i++) { right[i] = jump(i, n - 1); } IntegerSparseTable st = new IntegerSparseTable(right, m, (x, y) -> Math.min(x, y)); for (int i = 0; i < q; i++) { int l = in.readInt() - 1; int r = in.readInt() - 1; int min = st.query(l, r); out.append(min <= r ? '1' : '0'); } } public int jump(int i, int k) { if (i == m) { return i; } if (k == 0) { return i; } int log = CachedLog2.floorLog(k); return jump(jump[i][log], k - (1 << log)); } } static class SequenceUtils { public static void deepFill(Object array, int val) { if (!array.getClass().isArray()) { throw new IllegalArgumentException(); } if (array instanceof int[]) { int[] intArray = (int[]) array; Arrays.fill(intArray, val); } else { Object[] objArray = (Object[]) array; for (Object obj : objArray) { deepFill(obj, val); } } } } static class CachedLog2 { private static final int BITS = 16; private static final int LIMIT = 1 << BITS; private static final byte[] CACHE = new byte[LIMIT]; static { int b = 0; for (int i = 0; i < LIMIT; i++) { while ((1 << (b + 1)) <= i) { b++; } CACHE[i] = (byte) b; } } public static int floorLog(int x) { return x < LIMIT ? CACHE[x] : (BITS + CACHE[x >>> BITS]); } } static class FastInput { private final InputStream is; private byte[] buf = new byte[1 << 20]; private int bufLen; private int bufOffset; private int next; public FastInput(InputStream is) { this.is = is; } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { bufLen = -1; } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public int readInt() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } int val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } } static class IntegerSparseTable { private int[][] st; private IntegerBinaryFunction merger; public IntegerSparseTable(int[] data, int length, IntegerBinaryFunction merger) { int m = CachedLog2.floorLog(length); st = new int[m + 1][length]; this.merger = merger; for (int i = 0; i < length; i++) { st[0][i] = data[i]; } for (int i = 0; i < m; i++) { int interval = 1 << i; for (int j = 0; j < length; j++) { if (j + interval < length) { st[i + 1][j] = merge(st[i][j], st[i][j + interval]); } else { st[i + 1][j] = st[i][j]; } } } } private int merge(int a, int b) { return merger.apply(a, b); } public int query(int left, int right) { int queryLen = right - left + 1; int bit = CachedLog2.floorLog(queryLen); // x + 2^bit == right + 1 // So x should be right + 1 - 2^bit - left=queryLen - 2^bit return merge(st[bit][left], st[bit][right + 1 - (1 << bit)]); } public String toString() { return Arrays.toString(st[0]); } } static class FastOutput implements AutoCloseable, Closeable, Appendable { private StringBuilder cache = new StringBuilder(10 << 20); private final Writer os; public FastOutput append(CharSequence csq) { cache.append(csq); return this; } public FastOutput append(CharSequence csq, int start, int end) { cache.append(csq, start, end); return this; } public FastOutput(Writer os) { this.os = os; } public FastOutput(OutputStream os) { this(new OutputStreamWriter(os)); } public FastOutput append(char c) { cache.append(c); return this; } public FastOutput flush() { try { os.append(cache); os.flush(); cache.setLength(0); } catch (IOException e) { throw new UncheckedIOException(e); } return this; } public void close() { flush(); try { os.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } public String toString() { return cache.toString(); } } static interface IntegerBinaryFunction { int apply(int a, int b); } }
Java
["3 6 3\n2 1 3\n1 2 3 1 2 3\n1 5\n2 6\n3 5", "2 4 3\n2 1\n1 1 2 2\n1 2\n2 3\n3 4"]
2 seconds
["110", "010"]
NoteIn the first example the segment from the $$$1$$$-st to the $$$5$$$-th positions is $$$1, 2, 3, 1, 2$$$. There is a subsequence $$$1, 3, 2$$$ that is a cyclic shift of the permutation. The subsegment from the $$$2$$$-nd to the $$$6$$$-th positions also contains a subsequence $$$2, 1, 3$$$ that is equal to the permutation. The subsegment from the $$$3$$$-rd to the $$$5$$$-th positions is $$$3, 1, 2$$$, there is only one subsequence of length $$$3$$$ ($$$3, 1, 2$$$), but it is not a cyclic shift of the permutation.In the second example the possible cyclic shifts are $$$1, 2$$$ and $$$2, 1$$$. The subsegment from the $$$1$$$-st to the $$$2$$$-nd positions is $$$1, 1$$$, its subsequences are not cyclic shifts of the permutation. The subsegment from the $$$2$$$-nd to the $$$3$$$-rd positions is $$$1, 2$$$, it coincides with the permutation. The subsegment from the $$$3$$$ to the $$$4$$$ positions is $$$2, 2$$$, its subsequences are not cyclic shifts of the permutation.
Java 8
standard input
[ "dp", "math", "data structures", "dfs and similar", "trees" ]
4aaeff1b38d501daf9a877667e075d49
The first line contains three integers $$$n$$$, $$$m$$$, $$$q$$$ ($$$1 \le n, m, q \le 2 \cdot 10^5$$$) — the length of the permutation $$$p$$$, the length of the array $$$a$$$ and the number of queries. The next line contains $$$n$$$ integers from $$$1$$$ to $$$n$$$, where the $$$i$$$-th of them is the $$$i$$$-th element of the permutation. Each integer from $$$1$$$ to $$$n$$$ appears exactly once. The next line contains $$$m$$$ integers from $$$1$$$ to $$$n$$$, the $$$i$$$-th of them is the $$$i$$$-th element of the array $$$a$$$. The next $$$q$$$ lines describe queries. The $$$i$$$-th of these lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le m$$$), meaning that the $$$i$$$-th query is about the subsegment of the array from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive.
2,000
Print a single string of length $$$q$$$, consisting of $$$0$$$ and $$$1$$$, the digit on the $$$i$$$-th positions should be $$$1$$$, if the subsegment of array $$$a$$$ from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive, contains a subsequence that is a cyclic shift of $$$p$$$, and $$$0$$$ otherwise.
standard output
PASSED
fb6acc07a873a751e91063765551c6e6
train_002.jsonl
1553965800
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation $$$p$$$ of length $$$n$$$, and Skynyrd bought an array $$$a$$$ of length $$$m$$$, consisting of integers from $$$1$$$ to $$$n$$$. Lynyrd and Skynyrd became bored, so they asked you $$$q$$$ queries, each of which has the following form: "does the subsegment of $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, have a subsequence that is a cyclic shift of $$$p$$$?" Please answer the queries.A permutation of length $$$n$$$ is a sequence of $$$n$$$ integers such that each integer from $$$1$$$ to $$$n$$$ appears exactly once in it.A cyclic shift of a permutation $$$(p_1, p_2, \ldots, p_n)$$$ is a permutation $$$(p_i, p_{i + 1}, \ldots, p_{n}, p_1, p_2, \ldots, p_{i - 1})$$$ for some $$$i$$$ from $$$1$$$ to $$$n$$$. For example, a permutation $$$(2, 1, 3)$$$ has three distinct cyclic shifts: $$$(2, 1, 3)$$$, $$$(1, 3, 2)$$$, $$$(3, 2, 1)$$$.A subsequence of a subsegment of array $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, is a sequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ for some $$$i_1, i_2, \ldots, i_k$$$ such that $$$l \leq i_1 &lt; i_2 &lt; \ldots &lt; i_k \leq r$$$.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class B { static byte[] buf = new byte[1<<26]; static int bp = -1; public static void main(String[] args) throws IOException { /**/ DataInputStream in = new DataInputStream(System.in); /*/ DataInputStream in = new DataInputStream(new FileInputStream("src/b.in")); /**/ in.read(buf, 0, 1<<26); int n = nni(); int m = nni(); int q = nni(); int[] p = new int[n]; int[] a = new int[m]; for (int i = 0; i < n; i++) p[i] = nni(); for (int i = 0; i < m; i++) a[i] = nni(); int[] np = new int[n+1]; np[p[n-1]] = p[0]; for (int i = 0; i < n-1; i++) np[p[i]] = p[i+1]; HashMap<Integer, TreeSet<Integer>> tm = new HashMap<>(); for (int i = 0; i <= n; i++) { tm.put(i, new TreeSet<>()); } for (int i = 0; i < m; i++) { if (!tm.containsKey(a[i])) tm.put(a[i], new TreeSet<>()); tm.get(a[i]).add(i); } for (int key : tm.keySet()) { tm.get(key).add(m); } int[] next = new int[m+1]; for (int i = 0; i < m; i++) { next[i] = tm.get(np[a[i]]).higher(i); } next[m] = m; int[][] pn = new int[20][m+1]; for (int i = 0; i <= m; i++) pn[0][i] = next[i]; for (int i = 1; i < 20; i++) { for (int j = 0; j <= m; ++j) pn[i][j] = pn[i-1][pn[i-1][j]]; } int[] ce = new int[m]; int jumps = n-1; for (int i = 0; i < m; i++) { int curr = i; for (int j = 19; j >= 0; --j) { if ((jumps&(1<<j))>0) { curr = pn[j][curr]; if (curr==m) break; } } ce[i] = curr; } int[] cem = new int[m]; cem[m-1] = ce[m-1]; for (int i = m-2; i >= 0; --i) { cem[i] = Math.min(cem[i+1], ce[i]); } StringBuilder ans = new StringBuilder(); for (int i = 0; i < q; i++) { int l = nni()-1; int r = nni()-1; if (cem[l] <= r) ans.append("1"); else ans.append("0"); } System.out.println(ans); } public static int nni() { int ret = 0; byte b = buf[++bp]; while (true) { ret = ret*10+b-'0'; b = buf[++bp]; if (b<'0'||b>'9') { while (buf[bp+1]=='\r'||buf[bp+1]=='\n'||buf[bp+1]==' ') {++bp;} break; } } return ret; } }
Java
["3 6 3\n2 1 3\n1 2 3 1 2 3\n1 5\n2 6\n3 5", "2 4 3\n2 1\n1 1 2 2\n1 2\n2 3\n3 4"]
2 seconds
["110", "010"]
NoteIn the first example the segment from the $$$1$$$-st to the $$$5$$$-th positions is $$$1, 2, 3, 1, 2$$$. There is a subsequence $$$1, 3, 2$$$ that is a cyclic shift of the permutation. The subsegment from the $$$2$$$-nd to the $$$6$$$-th positions also contains a subsequence $$$2, 1, 3$$$ that is equal to the permutation. The subsegment from the $$$3$$$-rd to the $$$5$$$-th positions is $$$3, 1, 2$$$, there is only one subsequence of length $$$3$$$ ($$$3, 1, 2$$$), but it is not a cyclic shift of the permutation.In the second example the possible cyclic shifts are $$$1, 2$$$ and $$$2, 1$$$. The subsegment from the $$$1$$$-st to the $$$2$$$-nd positions is $$$1, 1$$$, its subsequences are not cyclic shifts of the permutation. The subsegment from the $$$2$$$-nd to the $$$3$$$-rd positions is $$$1, 2$$$, it coincides with the permutation. The subsegment from the $$$3$$$ to the $$$4$$$ positions is $$$2, 2$$$, its subsequences are not cyclic shifts of the permutation.
Java 8
standard input
[ "dp", "math", "data structures", "dfs and similar", "trees" ]
4aaeff1b38d501daf9a877667e075d49
The first line contains three integers $$$n$$$, $$$m$$$, $$$q$$$ ($$$1 \le n, m, q \le 2 \cdot 10^5$$$) — the length of the permutation $$$p$$$, the length of the array $$$a$$$ and the number of queries. The next line contains $$$n$$$ integers from $$$1$$$ to $$$n$$$, where the $$$i$$$-th of them is the $$$i$$$-th element of the permutation. Each integer from $$$1$$$ to $$$n$$$ appears exactly once. The next line contains $$$m$$$ integers from $$$1$$$ to $$$n$$$, the $$$i$$$-th of them is the $$$i$$$-th element of the array $$$a$$$. The next $$$q$$$ lines describe queries. The $$$i$$$-th of these lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le m$$$), meaning that the $$$i$$$-th query is about the subsegment of the array from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive.
2,000
Print a single string of length $$$q$$$, consisting of $$$0$$$ and $$$1$$$, the digit on the $$$i$$$-th positions should be $$$1$$$, if the subsegment of array $$$a$$$ from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive, contains a subsequence that is a cyclic shift of $$$p$$$, and $$$0$$$ otherwise.
standard output
PASSED
af765343ef30964d76d2262bd75c5a47
train_002.jsonl
1553965800
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation $$$p$$$ of length $$$n$$$, and Skynyrd bought an array $$$a$$$ of length $$$m$$$, consisting of integers from $$$1$$$ to $$$n$$$. Lynyrd and Skynyrd became bored, so they asked you $$$q$$$ queries, each of which has the following form: "does the subsegment of $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, have a subsequence that is a cyclic shift of $$$p$$$?" Please answer the queries.A permutation of length $$$n$$$ is a sequence of $$$n$$$ integers such that each integer from $$$1$$$ to $$$n$$$ appears exactly once in it.A cyclic shift of a permutation $$$(p_1, p_2, \ldots, p_n)$$$ is a permutation $$$(p_i, p_{i + 1}, \ldots, p_{n}, p_1, p_2, \ldots, p_{i - 1})$$$ for some $$$i$$$ from $$$1$$$ to $$$n$$$. For example, a permutation $$$(2, 1, 3)$$$ has three distinct cyclic shifts: $$$(2, 1, 3)$$$, $$$(1, 3, 2)$$$, $$$(3, 2, 1)$$$.A subsequence of a subsegment of array $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, is a sequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ for some $$$i_1, i_2, \ldots, i_k$$$ such that $$$l \leq i_1 &lt; i_2 &lt; \ldots &lt; i_k \leq r$$$.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class B { static int N,M,Q; static int[] perm, ar, answers; static ArrayList<Query> qsHere[]; static int[][] lift; static int[] prevPerm; public static void main(String[] args) { FS in = new FS(); PrintWriter out = new PrintWriter(System.out); N = in.nextInt(); M = in.nextInt(); Q = in.nextInt(); perm = new int[N]; for(int i = 0; i < N; i++) perm[i] = in.nextInt()-1; ar = new int[M]; for(int i = 0; i < M; i++) ar[i] = in.nextInt()-1; prevPerm = new int[N]; for(int i = 0; i < N; i++) { prevPerm[perm[i]] = perm[(i-1+N)%N]; } qsHere = new ArrayList[M]; for(int i = 0; i < M; i++) qsHere[i] = new ArrayList<Query>(); for(int i = 0; i < Q; i++) { Query q = new Query(in.nextInt()-1, in.nextInt()-1, i); qsHere[q.r].add(q); } int log = Integer.numberOfTrailingZeros(Integer.highestOneBit(M))+2; lift = new int[M+1][log]; for(int a[] : lift) Arrays.fill(a, -1); int lastOcc[] = new int[N]; Arrays.fill(lastOcc, -1); for(int i = 0; i < M; i++) { lift[i][0] = lastOcc[prevPerm[ar[i]]]; int cur = lift[i][0]; for(int j = 1; j < log; j++) { if(cur == -1) break; lift[i][j] = lift[cur][j-1]; cur = lift[i][j]; } lastOcc[ar[i]] = i; } answers = new int[Q]; int furthestRight = -1; for(int i = 0; i < M; i++) { // Process this index int left = N-1; int cur = i; for(int j = log-1; j >= 0; j--) { if(cur == -1) break; if((1<<j) > left) continue; cur = lift[cur][j]; left -= (1<<j); } furthestRight = Math.max(furthestRight, cur); // answer queries here for(Query q : qsHere[i]) { if(furthestRight >= q.l) answers[q.id] = 1; else answers[q.id] = 0; } } for(int ii : answers) out.print(ii); out.println(); out.close(); } static class Query { int l, r, id; public Query(int ll, int rr, int ii) { l=ll; r=rr; id=ii; } } static class FS { BufferedReader br; StringTokenizer st; public FS() { br = new BufferedReader(new InputStreamReader(System.in));} String next() { while(st == null || !st.hasMoreElements()) { try {st = new StringTokenizer(br.readLine());} catch(Exception e) { throw null;} } return st.nextToken(); } int nextInt() { return Integer.parseInt(next());} } }
Java
["3 6 3\n2 1 3\n1 2 3 1 2 3\n1 5\n2 6\n3 5", "2 4 3\n2 1\n1 1 2 2\n1 2\n2 3\n3 4"]
2 seconds
["110", "010"]
NoteIn the first example the segment from the $$$1$$$-st to the $$$5$$$-th positions is $$$1, 2, 3, 1, 2$$$. There is a subsequence $$$1, 3, 2$$$ that is a cyclic shift of the permutation. The subsegment from the $$$2$$$-nd to the $$$6$$$-th positions also contains a subsequence $$$2, 1, 3$$$ that is equal to the permutation. The subsegment from the $$$3$$$-rd to the $$$5$$$-th positions is $$$3, 1, 2$$$, there is only one subsequence of length $$$3$$$ ($$$3, 1, 2$$$), but it is not a cyclic shift of the permutation.In the second example the possible cyclic shifts are $$$1, 2$$$ and $$$2, 1$$$. The subsegment from the $$$1$$$-st to the $$$2$$$-nd positions is $$$1, 1$$$, its subsequences are not cyclic shifts of the permutation. The subsegment from the $$$2$$$-nd to the $$$3$$$-rd positions is $$$1, 2$$$, it coincides with the permutation. The subsegment from the $$$3$$$ to the $$$4$$$ positions is $$$2, 2$$$, its subsequences are not cyclic shifts of the permutation.
Java 8
standard input
[ "dp", "math", "data structures", "dfs and similar", "trees" ]
4aaeff1b38d501daf9a877667e075d49
The first line contains three integers $$$n$$$, $$$m$$$, $$$q$$$ ($$$1 \le n, m, q \le 2 \cdot 10^5$$$) — the length of the permutation $$$p$$$, the length of the array $$$a$$$ and the number of queries. The next line contains $$$n$$$ integers from $$$1$$$ to $$$n$$$, where the $$$i$$$-th of them is the $$$i$$$-th element of the permutation. Each integer from $$$1$$$ to $$$n$$$ appears exactly once. The next line contains $$$m$$$ integers from $$$1$$$ to $$$n$$$, the $$$i$$$-th of them is the $$$i$$$-th element of the array $$$a$$$. The next $$$q$$$ lines describe queries. The $$$i$$$-th of these lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le m$$$), meaning that the $$$i$$$-th query is about the subsegment of the array from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive.
2,000
Print a single string of length $$$q$$$, consisting of $$$0$$$ and $$$1$$$, the digit on the $$$i$$$-th positions should be $$$1$$$, if the subsegment of array $$$a$$$ from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive, contains a subsequence that is a cyclic shift of $$$p$$$, and $$$0$$$ otherwise.
standard output
PASSED
1b5ebe144ec22520dc15beb432a34e3b
train_002.jsonl
1553965800
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation $$$p$$$ of length $$$n$$$, and Skynyrd bought an array $$$a$$$ of length $$$m$$$, consisting of integers from $$$1$$$ to $$$n$$$. Lynyrd and Skynyrd became bored, so they asked you $$$q$$$ queries, each of which has the following form: "does the subsegment of $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, have a subsequence that is a cyclic shift of $$$p$$$?" Please answer the queries.A permutation of length $$$n$$$ is a sequence of $$$n$$$ integers such that each integer from $$$1$$$ to $$$n$$$ appears exactly once in it.A cyclic shift of a permutation $$$(p_1, p_2, \ldots, p_n)$$$ is a permutation $$$(p_i, p_{i + 1}, \ldots, p_{n}, p_1, p_2, \ldots, p_{i - 1})$$$ for some $$$i$$$ from $$$1$$$ to $$$n$$$. For example, a permutation $$$(2, 1, 3)$$$ has three distinct cyclic shifts: $$$(2, 1, 3)$$$, $$$(1, 3, 2)$$$, $$$(3, 2, 1)$$$.A subsequence of a subsegment of array $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, is a sequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ for some $$$i_1, i_2, \ldots, i_k$$$ such that $$$l \leq i_1 &lt; i_2 &lt; \ldots &lt; i_k \leq r$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.Iterator; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.NoSuchElementException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Egor Kulikov (egor@egork.net) */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); BLynyrdSkynyrd solver = new BLynyrdSkynyrd(); solver.solve(1, in, out); out.close(); } static class BLynyrdSkynyrd { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); int m = in.readInt(); int q = in.readInt(); int[] p = in.readIntArray(n); int[] a = in.readIntArray(m); MiscUtils.decreaseByOne(p, a); int[] rev = ArrayUtils.reversePermutation(p); int[] next = ArrayUtils.createArray(n, m); int[] where = new int[m + 1]; where[m] = m; for (int i = m - 1; i >= 0; i--) { int pos = rev[a[i]]; if (pos == n - 1) { pos = 0; } else { pos++; } where[i] = next[p[pos]]; next[a[i]] = i; } int[] ends = ArrayUtils.createOrder(m); for (int i = 0; (1 << i) < n; i++) { if (((n - 1) >> i & 1) == 1) { for (int j = 0; j < m; j++) { ends[j] = where[ends[j]]; } } for (int j = 0; j <= m; j++) { where[j] = where[where[j]]; } } for (int i = m - 2; i >= 0; i--) { ends[i] = Math.min(ends[i], ends[i + 1]); } StringBuilder answer = new StringBuilder(q); for (int i = 0; i < q; i++) { int l = in.readInt() - 1; int r = in.readInt() - 1; answer.append(ends[l] <= r ? 1 : 0); } out.printLine(answer); } } static interface IntStream extends Iterable<Integer>, Comparable<IntStream> { public IntIterator intIterator(); default public Iterator<Integer> iterator() { return new Iterator<Integer>() { private IntIterator it = intIterator(); public boolean hasNext() { return it.isValid(); } public Integer next() { int result = it.value(); it.advance(); return result; } }; } default public int compareTo(IntStream c) { IntIterator it = intIterator(); IntIterator jt = c.intIterator(); while (it.isValid() && jt.isValid()) { int i = it.value(); int j = jt.value(); if (i < j) { return -1; } else if (i > j) { return 1; } it.advance(); jt.advance(); } if (it.isValid()) { return 1; } if (jt.isValid()) { return -1; } return 0; } } static class IntArray extends IntAbstractStream implements IntList { private int[] data; public IntArray(int[] arr) { data = arr; } public int size() { return data.length; } public int get(int at) { return data[at]; } public void removeAt(int index) { throw new UnsupportedOperationException(); } } static class ArrayUtils { public static int[] range(int from, int to) { return Range.range(from, to).toArray(); } public static int[] createOrder(int size) { return range(0, size); } public static int[] reversePermutation(int[] permutation) { int[] result = new int[permutation.length]; for (int i = 0; i < permutation.length; i++) { result[permutation[i]] = i; } return result; } public static int[] createArray(int count, int value) { int[] array = new int[count]; Arrays.fill(array, value); return array; } } static class Range { public static IntList range(int from, int to) { int[] result = new int[Math.abs(from - to)]; int current = from; if (from <= to) { for (int i = 0; i < result.length; i++) { result[i] = current++; } } else { for (int i = 0; i < result.length; i++) { result[i] = current--; } } return new IntArray(result); } } static interface IntIterator { public int value() throws NoSuchElementException; public boolean advance(); public boolean isValid(); } static interface IntCollection extends IntStream { public int size(); default public int[] toArray() { int size = size(); int[] array = new int[size]; int i = 0; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { array[i++] = it.value(); } return array; } } static interface IntReversableCollection extends IntCollection { } static abstract class IntAbstractStream implements IntStream { public String toString() { StringBuilder builder = new StringBuilder(); boolean first = true; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { if (first) { first = false; } else { builder.append(' '); } builder.append(it.value()); } return builder.toString(); } public boolean equals(Object o) { if (!(o instanceof IntStream)) { return false; } IntStream c = (IntStream) o; IntIterator it = intIterator(); IntIterator jt = c.intIterator(); while (it.isValid() && jt.isValid()) { if (it.value() != jt.value()) { return false; } it.advance(); jt.advance(); } return !it.isValid() && !jt.isValid(); } public int hashCode() { int result = 0; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { result *= 31; result += it.value(); } return result; } } static class MiscUtils { public static void decreaseByOne(int[]... arrays) { for (int[] array : arrays) { for (int i = 0; i < array.length; i++) { array[i]--; } } } } static interface IntList extends IntReversableCollection { public abstract int get(int index); public abstract void removeAt(int index); default public IntIterator intIterator() { return new IntIterator() { private int at; private boolean removed; public int value() { if (removed) { throw new IllegalStateException(); } return get(at); } public boolean advance() { at++; removed = false; return isValid(); } public boolean isValid() { return !removed && at < size(); } public void remove() { removeAt(at); at--; removed = true; } }; } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int[] readIntArray(int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = readInt(); } return array; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(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(); } } }
Java
["3 6 3\n2 1 3\n1 2 3 1 2 3\n1 5\n2 6\n3 5", "2 4 3\n2 1\n1 1 2 2\n1 2\n2 3\n3 4"]
2 seconds
["110", "010"]
NoteIn the first example the segment from the $$$1$$$-st to the $$$5$$$-th positions is $$$1, 2, 3, 1, 2$$$. There is a subsequence $$$1, 3, 2$$$ that is a cyclic shift of the permutation. The subsegment from the $$$2$$$-nd to the $$$6$$$-th positions also contains a subsequence $$$2, 1, 3$$$ that is equal to the permutation. The subsegment from the $$$3$$$-rd to the $$$5$$$-th positions is $$$3, 1, 2$$$, there is only one subsequence of length $$$3$$$ ($$$3, 1, 2$$$), but it is not a cyclic shift of the permutation.In the second example the possible cyclic shifts are $$$1, 2$$$ and $$$2, 1$$$. The subsegment from the $$$1$$$-st to the $$$2$$$-nd positions is $$$1, 1$$$, its subsequences are not cyclic shifts of the permutation. The subsegment from the $$$2$$$-nd to the $$$3$$$-rd positions is $$$1, 2$$$, it coincides with the permutation. The subsegment from the $$$3$$$ to the $$$4$$$ positions is $$$2, 2$$$, its subsequences are not cyclic shifts of the permutation.
Java 8
standard input
[ "dp", "math", "data structures", "dfs and similar", "trees" ]
4aaeff1b38d501daf9a877667e075d49
The first line contains three integers $$$n$$$, $$$m$$$, $$$q$$$ ($$$1 \le n, m, q \le 2 \cdot 10^5$$$) — the length of the permutation $$$p$$$, the length of the array $$$a$$$ and the number of queries. The next line contains $$$n$$$ integers from $$$1$$$ to $$$n$$$, where the $$$i$$$-th of them is the $$$i$$$-th element of the permutation. Each integer from $$$1$$$ to $$$n$$$ appears exactly once. The next line contains $$$m$$$ integers from $$$1$$$ to $$$n$$$, the $$$i$$$-th of them is the $$$i$$$-th element of the array $$$a$$$. The next $$$q$$$ lines describe queries. The $$$i$$$-th of these lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le m$$$), meaning that the $$$i$$$-th query is about the subsegment of the array from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive.
2,000
Print a single string of length $$$q$$$, consisting of $$$0$$$ and $$$1$$$, the digit on the $$$i$$$-th positions should be $$$1$$$, if the subsegment of array $$$a$$$ from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive, contains a subsequence that is a cyclic shift of $$$p$$$, and $$$0$$$ otherwise.
standard output
PASSED
665fd957268f846acf7bf2c98726e315
train_002.jsonl
1553965800
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation $$$p$$$ of length $$$n$$$, and Skynyrd bought an array $$$a$$$ of length $$$m$$$, consisting of integers from $$$1$$$ to $$$n$$$. Lynyrd and Skynyrd became bored, so they asked you $$$q$$$ queries, each of which has the following form: "does the subsegment of $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, have a subsequence that is a cyclic shift of $$$p$$$?" Please answer the queries.A permutation of length $$$n$$$ is a sequence of $$$n$$$ integers such that each integer from $$$1$$$ to $$$n$$$ appears exactly once in it.A cyclic shift of a permutation $$$(p_1, p_2, \ldots, p_n)$$$ is a permutation $$$(p_i, p_{i + 1}, \ldots, p_{n}, p_1, p_2, \ldots, p_{i - 1})$$$ for some $$$i$$$ from $$$1$$$ to $$$n$$$. For example, a permutation $$$(2, 1, 3)$$$ has three distinct cyclic shifts: $$$(2, 1, 3)$$$, $$$(1, 3, 2)$$$, $$$(3, 2, 1)$$$.A subsequence of a subsegment of array $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, is a sequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ for some $$$i_1, i_2, \ldots, i_k$$$ such that $$$l \leq i_1 &lt; i_2 &lt; \ldots &lt; i_k \leq r$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); BLynyrdSkynyrd solver = new BLynyrdSkynyrd(); solver.solve(1, in, out); out.close(); } static class BLynyrdSkynyrd { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); int q = in.nextInt(); int[] p = new int[n]; int[] a = new int[m]; for (int i = 0; i < n; i++) { p[i] = in.nextInt() - 1; } int[] mp = new int[n]; for (int i = 0; i < n - 1; i++) { mp[p[i]] = p[i + 1]; } mp[p[n - 1]] = p[0]; for (int i = 0; i < m; i++) { a[i] = in.nextInt() - 1; } int[] last = new int[n]; Arrays.fill(last, -1); BinaryLifting.Vertex[] vs = BinaryLifting.Vertex.emptyGraph(m + 1); for (int i = m - 1; i >= 0; i--) { int next = mp[a[i]]; if (last[next] != -1) { vs[last[next]].adj.add(vs[i]); } else { vs[m].adj.add(vs[i]); } last[a[i]] = i; } BinaryLifting binLift = new BinaryLifting(vs, vs[m]); int[] min = new int[m]; for (int i = m - 1; i >= 0; i--) { BinaryLifting.Vertex parent = binLift.ithParent(vs[i], n - 1); if (i == m - 1) { min[i] = parent.idx; } else { min[i] = Math.min(parent.idx, min[i + 1]); } } for (int i = 0; i < q; i++) { int l = in.nextInt() - 1; int r = in.nextInt() - 1; if (min[l] <= r) { out.print('1'); } else { out.print('0'); } } } } 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()); } } static class BinaryLifting { BinaryLifting.Vertex[] vs; int timer; public BinaryLifting(BinaryLifting.Vertex[] vs, BinaryLifting.Vertex head) { this.vs = vs; this.timer = 1; dfs(head, head); } public void dfs(BinaryLifting.Vertex v, BinaryLifting.Vertex p) { v.tin = ++timer; v.up[0] = p; for (int i = 1; i < v.up.length; ++i) { v.up[i] = v.up[i - 1].up[i - 1]; } for (BinaryLifting.Vertex to : v.adj) { //noinspection ObjectEquality if (to != p) { dfs(to, v); } } v.tout = ++timer; } public BinaryLifting.Vertex ithParent(BinaryLifting.Vertex a, int i) { while (i != 0) { int pow = a.up.length - 1; while ((1 << pow) > i) { pow--; } a = a.up[pow]; i -= (1 << pow); } return a; } public static class Vertex { int idx; int tin; int tout; List<BinaryLifting.Vertex> adj = new ArrayList<>(); BinaryLifting.Vertex[] up; public static BinaryLifting.Vertex[] emptyGraph(int n) { int l = 1; while ((1 << l) <= n) { ++l; } BinaryLifting.Vertex[] vs = new BinaryLifting.Vertex[n]; for (int i = 0; i < n; i++) { vs[i] = new BinaryLifting.Vertex(); vs[i].idx = i; vs[i].up = new BinaryLifting.Vertex[l + 1]; } return vs; } } } }
Java
["3 6 3\n2 1 3\n1 2 3 1 2 3\n1 5\n2 6\n3 5", "2 4 3\n2 1\n1 1 2 2\n1 2\n2 3\n3 4"]
2 seconds
["110", "010"]
NoteIn the first example the segment from the $$$1$$$-st to the $$$5$$$-th positions is $$$1, 2, 3, 1, 2$$$. There is a subsequence $$$1, 3, 2$$$ that is a cyclic shift of the permutation. The subsegment from the $$$2$$$-nd to the $$$6$$$-th positions also contains a subsequence $$$2, 1, 3$$$ that is equal to the permutation. The subsegment from the $$$3$$$-rd to the $$$5$$$-th positions is $$$3, 1, 2$$$, there is only one subsequence of length $$$3$$$ ($$$3, 1, 2$$$), but it is not a cyclic shift of the permutation.In the second example the possible cyclic shifts are $$$1, 2$$$ and $$$2, 1$$$. The subsegment from the $$$1$$$-st to the $$$2$$$-nd positions is $$$1, 1$$$, its subsequences are not cyclic shifts of the permutation. The subsegment from the $$$2$$$-nd to the $$$3$$$-rd positions is $$$1, 2$$$, it coincides with the permutation. The subsegment from the $$$3$$$ to the $$$4$$$ positions is $$$2, 2$$$, its subsequences are not cyclic shifts of the permutation.
Java 8
standard input
[ "dp", "math", "data structures", "dfs and similar", "trees" ]
4aaeff1b38d501daf9a877667e075d49
The first line contains three integers $$$n$$$, $$$m$$$, $$$q$$$ ($$$1 \le n, m, q \le 2 \cdot 10^5$$$) — the length of the permutation $$$p$$$, the length of the array $$$a$$$ and the number of queries. The next line contains $$$n$$$ integers from $$$1$$$ to $$$n$$$, where the $$$i$$$-th of them is the $$$i$$$-th element of the permutation. Each integer from $$$1$$$ to $$$n$$$ appears exactly once. The next line contains $$$m$$$ integers from $$$1$$$ to $$$n$$$, the $$$i$$$-th of them is the $$$i$$$-th element of the array $$$a$$$. The next $$$q$$$ lines describe queries. The $$$i$$$-th of these lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le m$$$), meaning that the $$$i$$$-th query is about the subsegment of the array from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive.
2,000
Print a single string of length $$$q$$$, consisting of $$$0$$$ and $$$1$$$, the digit on the $$$i$$$-th positions should be $$$1$$$, if the subsegment of array $$$a$$$ from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive, contains a subsequence that is a cyclic shift of $$$p$$$, and $$$0$$$ otherwise.
standard output
PASSED
d320906b00ced37bb99ec8e7d92747c7
train_002.jsonl
1553965800
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation $$$p$$$ of length $$$n$$$, and Skynyrd bought an array $$$a$$$ of length $$$m$$$, consisting of integers from $$$1$$$ to $$$n$$$. Lynyrd and Skynyrd became bored, so they asked you $$$q$$$ queries, each of which has the following form: "does the subsegment of $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, have a subsequence that is a cyclic shift of $$$p$$$?" Please answer the queries.A permutation of length $$$n$$$ is a sequence of $$$n$$$ integers such that each integer from $$$1$$$ to $$$n$$$ appears exactly once in it.A cyclic shift of a permutation $$$(p_1, p_2, \ldots, p_n)$$$ is a permutation $$$(p_i, p_{i + 1}, \ldots, p_{n}, p_1, p_2, \ldots, p_{i - 1})$$$ for some $$$i$$$ from $$$1$$$ to $$$n$$$. For example, a permutation $$$(2, 1, 3)$$$ has three distinct cyclic shifts: $$$(2, 1, 3)$$$, $$$(1, 3, 2)$$$, $$$(3, 2, 1)$$$.A subsequence of a subsegment of array $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, is a sequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ for some $$$i_1, i_2, \ldots, i_k$$$ such that $$$l \leq i_1 &lt; i_2 &lt; \ldots &lt; i_k \leq r$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import java.util.function.LongBinaryOperator; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.io.UncheckedIOException; import java.util.List; import java.nio.charset.Charset; import java.util.StringTokenizer; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author mikit */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; LightScanner in = new LightScanner(inputStream); LightWriter out = new LightWriter(outputStream); BLynyrdSkynyrd solver = new BLynyrdSkynyrd(); solver.solve(1, in, out); out.close(); } static class BLynyrdSkynyrd { public void solve(int testNumber, LightScanner in, LightWriter out) { // out.setBoolLabel(LightWriter.BoolLabel.YES_NO_FIRST_UP); int n = in.ints(), m = in.ints(), q = in.ints(); int[] p = new int[n], pr = new int[n], a = new int[m]; for (int i = 0; i < n; i++) { p[i] = in.ints() - 1; pr[p[i]] = i; } for (int i = 0; i < m; i++) a[i] = in.ints() - 1; List<List<Integer>> loop = new ArrayList<>(); for (int i = 0; i < n; i++) loop.add(new ArrayList<>()); for (int i = 0; i < m; i++) { loop.get(a[i]).add(i); } int[][] next = new int[20][m]; for (int i = 0; i < m; i++) { int v = p[(pr[a[i]] + 1) % n]; List<Integer> indices = loop.get(v); if (indices.isEmpty()) { next[0][i] = -1; continue; } int min = 0, max = indices.size(); while (max - min > 0) { int mid = (min + max) / 2; if (indices.get(mid) <= i) { min = mid + 1; } else { max = mid; } } if (min == indices.size()) { next[0][i] = -1; } else { next[0][i] = indices.get(min); } } for (int i = 1; i < 20; i++) { for (int j = 0; j < m; j++) { if (next[i - 1][j] == -1) { next[i][j] = -1; } else { next[i][j] = next[i - 1][next[i - 1][j]]; } } } long[] nlate = new long[m]; outer: for (int i = 0; i < m; i++) { int cur = i; for (int j = 19; j >= 0; j--) { if (((n - 1) & (1 << j)) == 0) { continue; } cur = next[j][cur]; if (cur == -1) { nlate[i] = Long.MAX_VALUE; continue outer; } } nlate[i] = cur; } IntSegmentTree st = new IntSegmentTree(nlate, Math::min, Long.MAX_VALUE, (x, u) -> 0); for (int i = 0; i < q; i++) { int l = in.ints() - 1, r = in.ints(); if (st.query(l, r) < r) { out.print('1'); } else { out.print('0'); } } out.ln(); //System.out.println(Arrays.toString(nlate)); } } static class LightWriter implements AutoCloseable { private final Writer out; private boolean autoflush = false; private boolean breaked = true; public LightWriter(Writer out) { this.out = out; } public LightWriter(OutputStream out) { this(new BufferedWriter(new OutputStreamWriter(out, Charset.defaultCharset()))); } public LightWriter print(char c) { try { out.write(c); breaked = false; } catch (IOException ex) { throw new UncheckedIOException(ex); } return this; } public LightWriter print(String s) { try { out.write(s, 0, s.length()); breaked = false; } catch (IOException ex) { throw new UncheckedIOException(ex); } return this; } public LightWriter ln() { print(System.lineSeparator()); breaked = true; if (autoflush) { try { out.flush(); } catch (IOException ex) { throw new UncheckedIOException(ex); } } return this; } public void close() { try { out.close(); } catch (IOException ex) { throw new UncheckedIOException(ex); } } } static class LightScanner { private BufferedReader reader = null; private StringTokenizer tokenizer = null; public LightScanner(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); } public String string() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new UncheckedIOException(e); } } return tokenizer.nextToken(); } public int ints() { return Integer.parseInt(string()); } } static final class BitMath { private BitMath() { } public static int extractMsb(int v) { v = (v & 0xFFFF0000) > 0 ? v & 0xFFFF0000 : v; v = (v & 0xFF00FF00) > 0 ? v & 0xFF00FF00 : v; v = (v & 0xF0F0F0F0) > 0 ? v & 0xF0F0F0F0 : v; v = (v & 0xCCCCCCCC) > 0 ? v & 0xCCCCCCCC : v; v = (v & 0xAAAAAAAA) > 0 ? v & 0xAAAAAAAA : v; return v; } } static class IntSegmentTree { private final int n; private final int m; private final long[] tree; private final LongBinaryOperator op; private final LongBinaryOperator up; private final long zero; public IntSegmentTree(long[] array, LongBinaryOperator op, long zero, LongBinaryOperator up) { this.n = array.length; int msb = BitMath.extractMsb(n); this.m = n == msb ? msb : (msb << 1); this.tree = new long[m * 2 - 1]; this.op = op; this.up = up; this.zero = zero; Arrays.fill(tree, zero); System.arraycopy(array, 0, this.tree, m - 1, array.length); for (int i = m - 2; i >= 0; i--) { tree[i] = op.applyAsLong(tree[2 * i + 1], tree[2 * i + 2]); } } public long query(int l, int r) { long left = zero, right = zero; l += m - 1; r += m - 1; while (l < r) { if ((l & 1) == 0) { left = op.applyAsLong(left, tree[l]); } if ((r & 1) == 0) { right = op.applyAsLong(tree[r - 1], right); } l = l / 2; r = (r - 1) / 2; } return op.applyAsLong(left, right); } } }
Java
["3 6 3\n2 1 3\n1 2 3 1 2 3\n1 5\n2 6\n3 5", "2 4 3\n2 1\n1 1 2 2\n1 2\n2 3\n3 4"]
2 seconds
["110", "010"]
NoteIn the first example the segment from the $$$1$$$-st to the $$$5$$$-th positions is $$$1, 2, 3, 1, 2$$$. There is a subsequence $$$1, 3, 2$$$ that is a cyclic shift of the permutation. The subsegment from the $$$2$$$-nd to the $$$6$$$-th positions also contains a subsequence $$$2, 1, 3$$$ that is equal to the permutation. The subsegment from the $$$3$$$-rd to the $$$5$$$-th positions is $$$3, 1, 2$$$, there is only one subsequence of length $$$3$$$ ($$$3, 1, 2$$$), but it is not a cyclic shift of the permutation.In the second example the possible cyclic shifts are $$$1, 2$$$ and $$$2, 1$$$. The subsegment from the $$$1$$$-st to the $$$2$$$-nd positions is $$$1, 1$$$, its subsequences are not cyclic shifts of the permutation. The subsegment from the $$$2$$$-nd to the $$$3$$$-rd positions is $$$1, 2$$$, it coincides with the permutation. The subsegment from the $$$3$$$ to the $$$4$$$ positions is $$$2, 2$$$, its subsequences are not cyclic shifts of the permutation.
Java 8
standard input
[ "dp", "math", "data structures", "dfs and similar", "trees" ]
4aaeff1b38d501daf9a877667e075d49
The first line contains three integers $$$n$$$, $$$m$$$, $$$q$$$ ($$$1 \le n, m, q \le 2 \cdot 10^5$$$) — the length of the permutation $$$p$$$, the length of the array $$$a$$$ and the number of queries. The next line contains $$$n$$$ integers from $$$1$$$ to $$$n$$$, where the $$$i$$$-th of them is the $$$i$$$-th element of the permutation. Each integer from $$$1$$$ to $$$n$$$ appears exactly once. The next line contains $$$m$$$ integers from $$$1$$$ to $$$n$$$, the $$$i$$$-th of them is the $$$i$$$-th element of the array $$$a$$$. The next $$$q$$$ lines describe queries. The $$$i$$$-th of these lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le m$$$), meaning that the $$$i$$$-th query is about the subsegment of the array from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive.
2,000
Print a single string of length $$$q$$$, consisting of $$$0$$$ and $$$1$$$, the digit on the $$$i$$$-th positions should be $$$1$$$, if the subsegment of array $$$a$$$ from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive, contains a subsequence that is a cyclic shift of $$$p$$$, and $$$0$$$ otherwise.
standard output
PASSED
c24e4f78ee37179bb2f85e731cc48bea
train_002.jsonl
1553965800
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation $$$p$$$ of length $$$n$$$, and Skynyrd bought an array $$$a$$$ of length $$$m$$$, consisting of integers from $$$1$$$ to $$$n$$$. Lynyrd and Skynyrd became bored, so they asked you $$$q$$$ queries, each of which has the following form: "does the subsegment of $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, have a subsequence that is a cyclic shift of $$$p$$$?" Please answer the queries.A permutation of length $$$n$$$ is a sequence of $$$n$$$ integers such that each integer from $$$1$$$ to $$$n$$$ appears exactly once in it.A cyclic shift of a permutation $$$(p_1, p_2, \ldots, p_n)$$$ is a permutation $$$(p_i, p_{i + 1}, \ldots, p_{n}, p_1, p_2, \ldots, p_{i - 1})$$$ for some $$$i$$$ from $$$1$$$ to $$$n$$$. For example, a permutation $$$(2, 1, 3)$$$ has three distinct cyclic shifts: $$$(2, 1, 3)$$$, $$$(1, 3, 2)$$$, $$$(3, 2, 1)$$$.A subsequence of a subsegment of array $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, is a sequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ for some $$$i_1, i_2, \ldots, i_k$$$ such that $$$l \leq i_1 &lt; i_2 &lt; \ldots &lt; i_k \leq r$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String... args) { new Main().work(); } void work() { WORK(); out.close(); } class InputReader { BufferedReader br; StringTokenizer st; InputReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); st = null; } String next() { while(st==null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch(IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } } InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); final int N = (int)(2e5+10), MOD = (int)(1e9+7); int a[] = new int[N], b[] = new int[N], now[] = new int[N], dp[][] = new int[N][30]; int Log[] = new int[N], p[][] = new int[N][30]; void WORK() { int n = in.nextInt(), m = in.nextInt(), q = in.nextInt(); for(int i = 1; i <= n; i++) a[in.nextInt()] = i; Log[0] = -1; for(int i = 1; i <= m; i++) { b[i] = in.nextInt(); Log[i] = Log[i>>1]+1; } for(int i = m; i >= 1; i--) { now[a[b[i]]] = i; int t = a[b[i]]==n?1:a[b[i]]+1; if(now[t] != 0) p[i][0] = now[t]; } for(int i = 1; i <= 20; i++) for(int j = 1; j <= m; j++) p[j][i] = p[p[j][i-1]][i-1]; for(int i = 1; i <= m; i++) { // out.println("! = " + p[i][0]); dp[i][0] = i; int z = n-1; for(int j = 20; j >= 0; j--) if(z >= (1<<j)) { z -= (1<<j); dp[i][0] = p[dp[i][0]][j]; } if(dp[i][0] == 0) dp[i][0] = m+1; // out.println("? = " + dp[i][0]); } for(int j = 1; j <= 20; j++) { for(int i = 1; i+(1<<j)-1 <= m; i++) { dp[i][j] = Math.min(dp[i][j-1], dp[i+(1<<(j-1))][j-1]); } } while(q-- > 0) { int l = in.nextInt(), r = in.nextInt(); int k = Log[r-l+1]; int t = Math.min(dp[l][k], dp[r-(1<<k)+1][k]); // out.println("t = " + dp[l][k] + "k = " + dp[r-(1<<k)+1][k]); if(Math.min(dp[l][k], dp[r-(1<<k)+1][k]) <= r) out.print(1); else out.print(0); } } } /* 10 100 1 4 7 1 2 3 8 6 9 10 5 7 6 4 9 3 10 2 8 5 4 7 5 9 1 5 10 10 2 4 6 8 4 6 4 7 5 7 7 6 5 10 7 8 8 10 5 7 3 10 9 5 2 3 9 6 4 4 5 6 1 6 1 9 10 2 9 2 8 4 10 4 8 9 4 6 2 9 10 9 1 6 10 1 9 1 4 9 5 5 10 4 5 3 1 8 7 7 2 1 7 5 5 10 7 5 9 9 2 8 3 27 76 */
Java
["3 6 3\n2 1 3\n1 2 3 1 2 3\n1 5\n2 6\n3 5", "2 4 3\n2 1\n1 1 2 2\n1 2\n2 3\n3 4"]
2 seconds
["110", "010"]
NoteIn the first example the segment from the $$$1$$$-st to the $$$5$$$-th positions is $$$1, 2, 3, 1, 2$$$. There is a subsequence $$$1, 3, 2$$$ that is a cyclic shift of the permutation. The subsegment from the $$$2$$$-nd to the $$$6$$$-th positions also contains a subsequence $$$2, 1, 3$$$ that is equal to the permutation. The subsegment from the $$$3$$$-rd to the $$$5$$$-th positions is $$$3, 1, 2$$$, there is only one subsequence of length $$$3$$$ ($$$3, 1, 2$$$), but it is not a cyclic shift of the permutation.In the second example the possible cyclic shifts are $$$1, 2$$$ and $$$2, 1$$$. The subsegment from the $$$1$$$-st to the $$$2$$$-nd positions is $$$1, 1$$$, its subsequences are not cyclic shifts of the permutation. The subsegment from the $$$2$$$-nd to the $$$3$$$-rd positions is $$$1, 2$$$, it coincides with the permutation. The subsegment from the $$$3$$$ to the $$$4$$$ positions is $$$2, 2$$$, its subsequences are not cyclic shifts of the permutation.
Java 8
standard input
[ "dp", "math", "data structures", "dfs and similar", "trees" ]
4aaeff1b38d501daf9a877667e075d49
The first line contains three integers $$$n$$$, $$$m$$$, $$$q$$$ ($$$1 \le n, m, q \le 2 \cdot 10^5$$$) — the length of the permutation $$$p$$$, the length of the array $$$a$$$ and the number of queries. The next line contains $$$n$$$ integers from $$$1$$$ to $$$n$$$, where the $$$i$$$-th of them is the $$$i$$$-th element of the permutation. Each integer from $$$1$$$ to $$$n$$$ appears exactly once. The next line contains $$$m$$$ integers from $$$1$$$ to $$$n$$$, the $$$i$$$-th of them is the $$$i$$$-th element of the array $$$a$$$. The next $$$q$$$ lines describe queries. The $$$i$$$-th of these lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le m$$$), meaning that the $$$i$$$-th query is about the subsegment of the array from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive.
2,000
Print a single string of length $$$q$$$, consisting of $$$0$$$ and $$$1$$$, the digit on the $$$i$$$-th positions should be $$$1$$$, if the subsegment of array $$$a$$$ from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive, contains a subsequence that is a cyclic shift of $$$p$$$, and $$$0$$$ otherwise.
standard output
PASSED
b3e40cd343028d0d4ae7d670a03c685c
train_002.jsonl
1553965800
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation $$$p$$$ of length $$$n$$$, and Skynyrd bought an array $$$a$$$ of length $$$m$$$, consisting of integers from $$$1$$$ to $$$n$$$. Lynyrd and Skynyrd became bored, so they asked you $$$q$$$ queries, each of which has the following form: "does the subsegment of $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, have a subsequence that is a cyclic shift of $$$p$$$?" Please answer the queries.A permutation of length $$$n$$$ is a sequence of $$$n$$$ integers such that each integer from $$$1$$$ to $$$n$$$ appears exactly once in it.A cyclic shift of a permutation $$$(p_1, p_2, \ldots, p_n)$$$ is a permutation $$$(p_i, p_{i + 1}, \ldots, p_{n}, p_1, p_2, \ldots, p_{i - 1})$$$ for some $$$i$$$ from $$$1$$$ to $$$n$$$. For example, a permutation $$$(2, 1, 3)$$$ has three distinct cyclic shifts: $$$(2, 1, 3)$$$, $$$(1, 3, 2)$$$, $$$(3, 2, 1)$$$.A subsequence of a subsegment of array $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, is a sequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ for some $$$i_1, i_2, \ldots, i_k$$$ such that $$$l \leq i_1 &lt; i_2 &lt; \ldots &lt; i_k \leq r$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String... args) { new Main().work(); } void work() { WORK(); out.close(); } class InputReader { BufferedReader br; StringTokenizer st; InputReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); st = null; } String next() { while(st==null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch(IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } } InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); final int N = (int)(2e5+10), MOD = (int)(1e9+7); int a[] = new int[N], b[] = new int[N], now[] = new int[N], dp[][] = new int[N][30]; int Log[] = new int[N], p[][] = new int[N][30]; void WORK() { int n = in.nextInt(), m = in.nextInt(), q = in.nextInt(); for(int i = 1; i <= n; i++) a[in.nextInt()] = i; Log[0] = -1; for(int i = 1; i <= m; i++) { b[i] = in.nextInt(); Log[i] = Log[i>>1]+1; dp[i][0] = i; } for(int i = m; i >= 1; i--) { now[a[b[i]]] = i; int t = a[b[i]]==n?1:a[b[i]]+1; if(now[t] != 0) p[i][0] = now[t]; } for(int i = 1; i <= 20; i++) for(int j = 1; j <= m; j++) p[j][i] = p[p[j][i-1]][i-1]; for(int j = n-1; j > 0; j -= 1<<Log[j]) for(int i = 1; i <= m; i++) dp[i][0] = p[dp[i][0]][Log[j]]; for(int i = 1; i <= m; i++) if(dp[i][0] == 0) dp[i][0] = m+1; for(int j = 1; j <= 20; j++) for(int i = 1; i+(1<<j)-1 <= m; i++) dp[i][j] = Math.min(dp[i][j-1], dp[i+(1<<j-1)][j-1]); while(q-- > 0) { int l = in.nextInt(), r = in.nextInt(); int k = Log[r-l+1]; if(Math.min(dp[l][k], dp[r-(1<<k)+1][k]) <= r) out.print(1); else out.print(0); } } }
Java
["3 6 3\n2 1 3\n1 2 3 1 2 3\n1 5\n2 6\n3 5", "2 4 3\n2 1\n1 1 2 2\n1 2\n2 3\n3 4"]
2 seconds
["110", "010"]
NoteIn the first example the segment from the $$$1$$$-st to the $$$5$$$-th positions is $$$1, 2, 3, 1, 2$$$. There is a subsequence $$$1, 3, 2$$$ that is a cyclic shift of the permutation. The subsegment from the $$$2$$$-nd to the $$$6$$$-th positions also contains a subsequence $$$2, 1, 3$$$ that is equal to the permutation. The subsegment from the $$$3$$$-rd to the $$$5$$$-th positions is $$$3, 1, 2$$$, there is only one subsequence of length $$$3$$$ ($$$3, 1, 2$$$), but it is not a cyclic shift of the permutation.In the second example the possible cyclic shifts are $$$1, 2$$$ and $$$2, 1$$$. The subsegment from the $$$1$$$-st to the $$$2$$$-nd positions is $$$1, 1$$$, its subsequences are not cyclic shifts of the permutation. The subsegment from the $$$2$$$-nd to the $$$3$$$-rd positions is $$$1, 2$$$, it coincides with the permutation. The subsegment from the $$$3$$$ to the $$$4$$$ positions is $$$2, 2$$$, its subsequences are not cyclic shifts of the permutation.
Java 8
standard input
[ "dp", "math", "data structures", "dfs and similar", "trees" ]
4aaeff1b38d501daf9a877667e075d49
The first line contains three integers $$$n$$$, $$$m$$$, $$$q$$$ ($$$1 \le n, m, q \le 2 \cdot 10^5$$$) — the length of the permutation $$$p$$$, the length of the array $$$a$$$ and the number of queries. The next line contains $$$n$$$ integers from $$$1$$$ to $$$n$$$, where the $$$i$$$-th of them is the $$$i$$$-th element of the permutation. Each integer from $$$1$$$ to $$$n$$$ appears exactly once. The next line contains $$$m$$$ integers from $$$1$$$ to $$$n$$$, the $$$i$$$-th of them is the $$$i$$$-th element of the array $$$a$$$. The next $$$q$$$ lines describe queries. The $$$i$$$-th of these lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le m$$$), meaning that the $$$i$$$-th query is about the subsegment of the array from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive.
2,000
Print a single string of length $$$q$$$, consisting of $$$0$$$ and $$$1$$$, the digit on the $$$i$$$-th positions should be $$$1$$$, if the subsegment of array $$$a$$$ from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive, contains a subsequence that is a cyclic shift of $$$p$$$, and $$$0$$$ otherwise.
standard output
PASSED
cb31a5833f4aeefbbb7c8e13fbb28ec4
train_002.jsonl
1553965800
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation $$$p$$$ of length $$$n$$$, and Skynyrd bought an array $$$a$$$ of length $$$m$$$, consisting of integers from $$$1$$$ to $$$n$$$. Lynyrd and Skynyrd became bored, so they asked you $$$q$$$ queries, each of which has the following form: "does the subsegment of $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, have a subsequence that is a cyclic shift of $$$p$$$?" Please answer the queries.A permutation of length $$$n$$$ is a sequence of $$$n$$$ integers such that each integer from $$$1$$$ to $$$n$$$ appears exactly once in it.A cyclic shift of a permutation $$$(p_1, p_2, \ldots, p_n)$$$ is a permutation $$$(p_i, p_{i + 1}, \ldots, p_{n}, p_1, p_2, \ldots, p_{i - 1})$$$ for some $$$i$$$ from $$$1$$$ to $$$n$$$. For example, a permutation $$$(2, 1, 3)$$$ has three distinct cyclic shifts: $$$(2, 1, 3)$$$, $$$(1, 3, 2)$$$, $$$(3, 2, 1)$$$.A subsequence of a subsegment of array $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, is a sequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ for some $$$i_1, i_2, \ldots, i_k$$$ such that $$$l \leq i_1 &lt; i_2 &lt; \ldots &lt; i_k \leq r$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String... args) { new Main().work(); } void work() { WORK(); out.close(); } class InputReader { BufferedReader br; StringTokenizer st; InputReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); st = null; } String next() { while(st==null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch(IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } } InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); final int N = (int)(2e5+10), MOD = (int)(1e9+7); int a[] = new int[N], b[] = new int[N], now[] = new int[N], dp[][] = new int[N][30]; int Log[] = new int[N], p[][] = new int[N][30]; void WORK() { int n = in.nextInt(), m = in.nextInt(), q = in.nextInt(); for(int i = 1; i <= n; i++) a[in.nextInt()] = i; Log[0] = -1; for(int i = 1; i <= m; i++) { b[i] = in.nextInt(); Log[i] = Log[i>>1]+1; } for(int i = m; i >= 1; i--) { now[a[b[i]]] = i; int t = a[b[i]]==n?1:a[b[i]]+1; if(now[t] != 0) p[i][0] = now[t]; } for(int i = 1; i <= 20; i++) for(int j = 1; j <= m; j++) p[j][i] = p[p[j][i-1]][i-1]; for(int i = 1; i <= m; i++) { dp[i][0] = i; for(int j = n-1; j > 0; j -= 1<<Log[j]) dp[i][0] = p[dp[i][0]][Log[j]]; if(dp[i][0] == 0) dp[i][0] = m+1; } for(int j = 1; j <= 20; j++) for(int i = 1; i+(1<<j)-1 <= m; i++) dp[i][j] = Math.min(dp[i][j-1], dp[i+(1<<j-1)][j-1]); while(q-- > 0) { int l = in.nextInt(), r = in.nextInt(); int k = Log[r-l+1]; if(Math.min(dp[l][k], dp[r-(1<<k)+1][k]) <= r) out.print(1); else out.print(0); } } }
Java
["3 6 3\n2 1 3\n1 2 3 1 2 3\n1 5\n2 6\n3 5", "2 4 3\n2 1\n1 1 2 2\n1 2\n2 3\n3 4"]
2 seconds
["110", "010"]
NoteIn the first example the segment from the $$$1$$$-st to the $$$5$$$-th positions is $$$1, 2, 3, 1, 2$$$. There is a subsequence $$$1, 3, 2$$$ that is a cyclic shift of the permutation. The subsegment from the $$$2$$$-nd to the $$$6$$$-th positions also contains a subsequence $$$2, 1, 3$$$ that is equal to the permutation. The subsegment from the $$$3$$$-rd to the $$$5$$$-th positions is $$$3, 1, 2$$$, there is only one subsequence of length $$$3$$$ ($$$3, 1, 2$$$), but it is not a cyclic shift of the permutation.In the second example the possible cyclic shifts are $$$1, 2$$$ and $$$2, 1$$$. The subsegment from the $$$1$$$-st to the $$$2$$$-nd positions is $$$1, 1$$$, its subsequences are not cyclic shifts of the permutation. The subsegment from the $$$2$$$-nd to the $$$3$$$-rd positions is $$$1, 2$$$, it coincides with the permutation. The subsegment from the $$$3$$$ to the $$$4$$$ positions is $$$2, 2$$$, its subsequences are not cyclic shifts of the permutation.
Java 8
standard input
[ "dp", "math", "data structures", "dfs and similar", "trees" ]
4aaeff1b38d501daf9a877667e075d49
The first line contains three integers $$$n$$$, $$$m$$$, $$$q$$$ ($$$1 \le n, m, q \le 2 \cdot 10^5$$$) — the length of the permutation $$$p$$$, the length of the array $$$a$$$ and the number of queries. The next line contains $$$n$$$ integers from $$$1$$$ to $$$n$$$, where the $$$i$$$-th of them is the $$$i$$$-th element of the permutation. Each integer from $$$1$$$ to $$$n$$$ appears exactly once. The next line contains $$$m$$$ integers from $$$1$$$ to $$$n$$$, the $$$i$$$-th of them is the $$$i$$$-th element of the array $$$a$$$. The next $$$q$$$ lines describe queries. The $$$i$$$-th of these lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le m$$$), meaning that the $$$i$$$-th query is about the subsegment of the array from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive.
2,000
Print a single string of length $$$q$$$, consisting of $$$0$$$ and $$$1$$$, the digit on the $$$i$$$-th positions should be $$$1$$$, if the subsegment of array $$$a$$$ from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive, contains a subsequence that is a cyclic shift of $$$p$$$, and $$$0$$$ otherwise.
standard output
PASSED
620d736436d235b5a2b281f857765ae4
train_002.jsonl
1553965800
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation $$$p$$$ of length $$$n$$$, and Skynyrd bought an array $$$a$$$ of length $$$m$$$, consisting of integers from $$$1$$$ to $$$n$$$. Lynyrd and Skynyrd became bored, so they asked you $$$q$$$ queries, each of which has the following form: "does the subsegment of $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, have a subsequence that is a cyclic shift of $$$p$$$?" Please answer the queries.A permutation of length $$$n$$$ is a sequence of $$$n$$$ integers such that each integer from $$$1$$$ to $$$n$$$ appears exactly once in it.A cyclic shift of a permutation $$$(p_1, p_2, \ldots, p_n)$$$ is a permutation $$$(p_i, p_{i + 1}, \ldots, p_{n}, p_1, p_2, \ldots, p_{i - 1})$$$ for some $$$i$$$ from $$$1$$$ to $$$n$$$. For example, a permutation $$$(2, 1, 3)$$$ has three distinct cyclic shifts: $$$(2, 1, 3)$$$, $$$(1, 3, 2)$$$, $$$(3, 2, 1)$$$.A subsequence of a subsegment of array $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, is a sequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ for some $$$i_1, i_2, \ldots, i_k$$$ such that $$$l \leq i_1 &lt; i_2 &lt; \ldots &lt; i_k \leq r$$$.
256 megabytes
import java.util.*; import java.io.*; public class answer{ static class SparseTree{ int n; int root; int[][] dp; int[] depth; SparseTree(int n,int m,LinkedList<Integer>[] al){ this.n = n; root = m; dp = new int[20][n]; depth = new int[n]; for(int i=0;i<20;i++){ Arrays.fill(dp[i],-1); } dfs(root,-1,al); depthDfs(root,-1,al); } void dfs(int m,int p,LinkedList<Integer>[] al){ dp[0][m] = p; for(int i=1;i<20;i++){ if(dp[i-1][m]!=-1) dp[i][m] = dp[i-1][dp[i-1][m]]; } for(int u:al[m]) if(u!=p) dfs(u,m,al); } void depthDfs(int cur,int prev,LinkedList<Integer>[] al){ if(prev==-1) depth[cur] = 0; else depth[cur] = depth[prev] + 1; for(int u:al[cur]) if(u!=prev) depthDfs(u,cur,al); } int getDepth(int i){ return depth[i]; } int getParent(int node,int np){ if(np==0) return node; if(np>depth[node]) return -1; for(int i=0;i<20;i++){ if(((np>>i)&1)==1) node = dp[i][node]; } return node; } } static Node[] luckup; static class Node{ int id; int next; LinkedList<Integer> children = new LinkedList<Integer>(); Node(int id){ this.id = id; next = 0; } } public static Node getNode(int id){ return luckup[id]; } static int[] next; static void build(int[] a,int m,int n){ LinkedList<Integer>[] l = new LinkedList[n+1]; for(int i=1;i<n+1;i++){ l[i] = new LinkedList<Integer>(); } Node node; for(int i=1;i<=m;i++){ luckup[i] = new Node(i); while(!l[a[i]].isEmpty()){ node = getNode(l[a[i]].poll()); node.next = i; getNode(i).children.add(node.id); } l[next[a[i]]].add(i); } } static int[] remplir(int m,int n){ int[] s = new int[m+1]; Arrays.fill(s,-1); LinkedList<Integer>[] al = new LinkedList[m+1]; Node node; for(int i=1;i<=m;i++){ al[i-1] = new LinkedList<Integer>(); node = getNode(i); for(int u:node.children){ al[i-1].add(u-1); } } al[m] = new LinkedList<Integer>(); for(int i=1;i<=m;i++){ node = getNode(i); if(node.next==0){ al[m].add(i-1); } } SparseTree st = new SparseTree(m+1,m,al); int id; for(int i=0;i<m;i++){ id = st.getParent(i,n-1); if(id==-1 || id==m) continue; node = getNode(id); s[i+1] = id+1; } int min = -1; for(int i=m;i>=1;i--){ if(min==-1 && s[i]==-1) continue; if(min==-1){ min = s[i]; continue; } if(s[i]==-1) s[i] = min; else s[i] = Math.min(min,s[i]); min = Math.min(min,s[i]); } return s; } public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int q = Integer.parseInt(st.nextToken()); int[] p = new int[n]; int[] a = new int[m+1]; int l,r; luckup = new Node[m+1]; st = new StringTokenizer(br.readLine()); for(int i=0;i<n;i++) p[i] = Integer.parseInt(st.nextToken()); st = new StringTokenizer(br.readLine()); for(int i=1;i<=m;i++) a[i] = Integer.parseInt(st.nextToken()); next = new int[n+1]; for(int i=0;i<n;i++){ next[p[i]] = p[(i+1)%n]; } int[] s; if(n==1){ s = new int[m+1]; for(int i=1;i<=m;i++) s[i] = i; }else{ build(a,m,n); s = remplir(m,n); } for(int i=0;i<q;i++){ st = new StringTokenizer(br.readLine()); l = Integer.parseInt(st.nextToken()); r = Integer.parseInt(st.nextToken()); if(s[l]==-1) out.print("0"); else if(s[l]<=r) out.print("1"); else out.print("0"); } out.println(""); out.flush(); } }
Java
["3 6 3\n2 1 3\n1 2 3 1 2 3\n1 5\n2 6\n3 5", "2 4 3\n2 1\n1 1 2 2\n1 2\n2 3\n3 4"]
2 seconds
["110", "010"]
NoteIn the first example the segment from the $$$1$$$-st to the $$$5$$$-th positions is $$$1, 2, 3, 1, 2$$$. There is a subsequence $$$1, 3, 2$$$ that is a cyclic shift of the permutation. The subsegment from the $$$2$$$-nd to the $$$6$$$-th positions also contains a subsequence $$$2, 1, 3$$$ that is equal to the permutation. The subsegment from the $$$3$$$-rd to the $$$5$$$-th positions is $$$3, 1, 2$$$, there is only one subsequence of length $$$3$$$ ($$$3, 1, 2$$$), but it is not a cyclic shift of the permutation.In the second example the possible cyclic shifts are $$$1, 2$$$ and $$$2, 1$$$. The subsegment from the $$$1$$$-st to the $$$2$$$-nd positions is $$$1, 1$$$, its subsequences are not cyclic shifts of the permutation. The subsegment from the $$$2$$$-nd to the $$$3$$$-rd positions is $$$1, 2$$$, it coincides with the permutation. The subsegment from the $$$3$$$ to the $$$4$$$ positions is $$$2, 2$$$, its subsequences are not cyclic shifts of the permutation.
Java 8
standard input
[ "dp", "math", "data structures", "dfs and similar", "trees" ]
4aaeff1b38d501daf9a877667e075d49
The first line contains three integers $$$n$$$, $$$m$$$, $$$q$$$ ($$$1 \le n, m, q \le 2 \cdot 10^5$$$) — the length of the permutation $$$p$$$, the length of the array $$$a$$$ and the number of queries. The next line contains $$$n$$$ integers from $$$1$$$ to $$$n$$$, where the $$$i$$$-th of them is the $$$i$$$-th element of the permutation. Each integer from $$$1$$$ to $$$n$$$ appears exactly once. The next line contains $$$m$$$ integers from $$$1$$$ to $$$n$$$, the $$$i$$$-th of them is the $$$i$$$-th element of the array $$$a$$$. The next $$$q$$$ lines describe queries. The $$$i$$$-th of these lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le m$$$), meaning that the $$$i$$$-th query is about the subsegment of the array from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive.
2,000
Print a single string of length $$$q$$$, consisting of $$$0$$$ and $$$1$$$, the digit on the $$$i$$$-th positions should be $$$1$$$, if the subsegment of array $$$a$$$ from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive, contains a subsequence that is a cyclic shift of $$$p$$$, and $$$0$$$ otherwise.
standard output
PASSED
b7ae2081fbe5504a7aa1fd8e0a1127b5
train_002.jsonl
1553965800
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation $$$p$$$ of length $$$n$$$, and Skynyrd bought an array $$$a$$$ of length $$$m$$$, consisting of integers from $$$1$$$ to $$$n$$$. Lynyrd and Skynyrd became bored, so they asked you $$$q$$$ queries, each of which has the following form: "does the subsegment of $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, have a subsequence that is a cyclic shift of $$$p$$$?" Please answer the queries.A permutation of length $$$n$$$ is a sequence of $$$n$$$ integers such that each integer from $$$1$$$ to $$$n$$$ appears exactly once in it.A cyclic shift of a permutation $$$(p_1, p_2, \ldots, p_n)$$$ is a permutation $$$(p_i, p_{i + 1}, \ldots, p_{n}, p_1, p_2, \ldots, p_{i - 1})$$$ for some $$$i$$$ from $$$1$$$ to $$$n$$$. For example, a permutation $$$(2, 1, 3)$$$ has three distinct cyclic shifts: $$$(2, 1, 3)$$$, $$$(1, 3, 2)$$$, $$$(3, 2, 1)$$$.A subsequence of a subsegment of array $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, is a sequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ for some $$$i_1, i_2, \ldots, i_k$$$ such that $$$l \leq i_1 &lt; i_2 &lt; \ldots &lt; i_k \leq r$$$.
256 megabytes
import java.util.*; import java.io.*; public class issam{ public static int n,m,q; public static int[] a,b; public static int[] dp; public static int[] aft; public static LinkedList<Integer>[] al; public static class SparseTree{ int n; int root; int[][] dp; int[] depth; SparseTree(int n,int m,LinkedList<Integer>[] al){ this.n = n; root = m; dp = new int[20][n]; depth = new int[n]; for(int i=0;i<20;i++) Arrays.fill(dp[i],-1); dfs(root,-1,al); depthDfs(root,-1,al); } void dfs(int m,int p,LinkedList<Integer>[] al){ dp[0][m] = p; for(int i=1;i<20;i++){ if(dp[i-1][m]!=-1) dp[i][m] = dp[i-1][dp[i-1][m]]; } for(int u:al[m]){ if(u!=p) dfs(u,m,al); } } void depthDfs(int cur, int prev,LinkedList<Integer>[] al){ if(prev==-1) depth[cur] = 0; else depth[cur] = depth[prev] + 1; for(int u:al[cur]){ if(u != prev) depthDfs(u,cur,al); } } int getDepth(int i){ return depth[i]; } int getParent(int node,int np){ if(np==0) return node; if(np>depth[node]) return -1; for (int i=0; i<20; i++) if (((np>>i)&1)==1) node = dp[i][node]; return node; } int getSameLevelTo(int u,int v){ if(u==v||depth[u]==depth[v]) return u; if(depth[u]<depth[v]) return -1; int diff = depth[u] - depth[v]; u = getParent(u,diff); return u; } int lca(int u, int v) { int k = getSameLevelTo(u,v); if(k==-1) v = getSameLevelTo(v,u); else u = k; if (u == v) return u; for (int i=19; i>=0; i--) if (dp[i][u] != dp[i][v]){ u = dp[i][u]; v = dp[i][v]; } return dp[0][u]; } } public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); PrintWriter out = new PrintWriter(System.out); n = Integer.parseInt(st.nextToken()); m = Integer.parseInt(st.nextToken()); q = Integer.parseInt(st.nextToken()); al = new LinkedList[m+1]; boolean[] ok = new boolean[m]; Arrays.fill(ok,true); for(int i=0;i<=m;i++) al[i] = new LinkedList<Integer>(); a = new int[n]; b = new int[m]; aft = new int[n]; st = new StringTokenizer(br.readLine()); for(int i=0;i<n;i++){ int v = Integer.parseInt(st.nextToken())-1; a[i] = v; } for(int i=0;i<n-1;i++){ aft[a[i]] = a[i+1]; } aft[a[n-1]] = a[0]; st = new StringTokenizer(br.readLine()); dp = new int[m]; Arrays.fill(dp,-1); for(int i=0;i<m;i++){ int v = Integer.parseInt(st.nextToken())-1; b[i] = v; } int[] tab = new int[n]; Arrays.fill(tab,-1); for(int i=m-1;i>=0;i--){ int k = b[i]; int p = aft[k]; if(tab[p]!=-1) { al[tab[p]].add(i); ok[i] = false; } tab[k] = i; } for(int i=0;i<m;i++){ if(ok[i]) al[m].add(i); } SparseTree sp = new SparseTree(m+1,m,al); for(int i=0;i<m;i++){ dp[i] = sp.getParent(i,n-1); if(dp[i]==m) dp[i] = -1; } for(int i=m-2;i>=0;i--){ if(dp[i]==-1) dp[i] = dp[i+1]; else if(dp[i+1]==-1) continue; else dp[i] = Math.min(dp[i],dp[i+1]); } for(int i=0;i<q;i++){ st = new StringTokenizer(br.readLine()); int l = Integer.parseInt(st.nextToken())-1; int r = Integer.parseInt(st.nextToken())-1; if(dp[l]==-1||dp[l]>r) out.print("0"); else out.print("1"); } out.println(""); out.flush(); } }
Java
["3 6 3\n2 1 3\n1 2 3 1 2 3\n1 5\n2 6\n3 5", "2 4 3\n2 1\n1 1 2 2\n1 2\n2 3\n3 4"]
2 seconds
["110", "010"]
NoteIn the first example the segment from the $$$1$$$-st to the $$$5$$$-th positions is $$$1, 2, 3, 1, 2$$$. There is a subsequence $$$1, 3, 2$$$ that is a cyclic shift of the permutation. The subsegment from the $$$2$$$-nd to the $$$6$$$-th positions also contains a subsequence $$$2, 1, 3$$$ that is equal to the permutation. The subsegment from the $$$3$$$-rd to the $$$5$$$-th positions is $$$3, 1, 2$$$, there is only one subsequence of length $$$3$$$ ($$$3, 1, 2$$$), but it is not a cyclic shift of the permutation.In the second example the possible cyclic shifts are $$$1, 2$$$ and $$$2, 1$$$. The subsegment from the $$$1$$$-st to the $$$2$$$-nd positions is $$$1, 1$$$, its subsequences are not cyclic shifts of the permutation. The subsegment from the $$$2$$$-nd to the $$$3$$$-rd positions is $$$1, 2$$$, it coincides with the permutation. The subsegment from the $$$3$$$ to the $$$4$$$ positions is $$$2, 2$$$, its subsequences are not cyclic shifts of the permutation.
Java 8
standard input
[ "dp", "math", "data structures", "dfs and similar", "trees" ]
4aaeff1b38d501daf9a877667e075d49
The first line contains three integers $$$n$$$, $$$m$$$, $$$q$$$ ($$$1 \le n, m, q \le 2 \cdot 10^5$$$) — the length of the permutation $$$p$$$, the length of the array $$$a$$$ and the number of queries. The next line contains $$$n$$$ integers from $$$1$$$ to $$$n$$$, where the $$$i$$$-th of them is the $$$i$$$-th element of the permutation. Each integer from $$$1$$$ to $$$n$$$ appears exactly once. The next line contains $$$m$$$ integers from $$$1$$$ to $$$n$$$, the $$$i$$$-th of them is the $$$i$$$-th element of the array $$$a$$$. The next $$$q$$$ lines describe queries. The $$$i$$$-th of these lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le m$$$), meaning that the $$$i$$$-th query is about the subsegment of the array from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive.
2,000
Print a single string of length $$$q$$$, consisting of $$$0$$$ and $$$1$$$, the digit on the $$$i$$$-th positions should be $$$1$$$, if the subsegment of array $$$a$$$ from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive, contains a subsequence that is a cyclic shift of $$$p$$$, and $$$0$$$ otherwise.
standard output
PASSED
f3dc385efc3972fbc18a2575bcbcaa04
train_002.jsonl
1553965800
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation $$$p$$$ of length $$$n$$$, and Skynyrd bought an array $$$a$$$ of length $$$m$$$, consisting of integers from $$$1$$$ to $$$n$$$. Lynyrd and Skynyrd became bored, so they asked you $$$q$$$ queries, each of which has the following form: "does the subsegment of $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, have a subsequence that is a cyclic shift of $$$p$$$?" Please answer the queries.A permutation of length $$$n$$$ is a sequence of $$$n$$$ integers such that each integer from $$$1$$$ to $$$n$$$ appears exactly once in it.A cyclic shift of a permutation $$$(p_1, p_2, \ldots, p_n)$$$ is a permutation $$$(p_i, p_{i + 1}, \ldots, p_{n}, p_1, p_2, \ldots, p_{i - 1})$$$ for some $$$i$$$ from $$$1$$$ to $$$n$$$. For example, a permutation $$$(2, 1, 3)$$$ has three distinct cyclic shifts: $$$(2, 1, 3)$$$, $$$(1, 3, 2)$$$, $$$(3, 2, 1)$$$.A subsequence of a subsegment of array $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, is a sequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ for some $$$i_1, i_2, \ldots, i_k$$$ such that $$$l \leq i_1 &lt; i_2 &lt; \ldots &lt; i_k \leq r$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class B { public static void main(String[] args) { FastScanner fs=new FastScanner(); int permLen=fs.nextInt(), arrLen=fs.nextInt(), nQueries=fs.nextInt(); int[] perm=new int[permLen]; for (int i=0; i<permLen; i++) perm[i]=fs.nextInt()-1; int[] indexInPerm=new int[permLen]; for (int i=0; i<permLen; i++) indexInPerm[perm[i]]=i; int[] next=new int[permLen]; for (int i=0; i<permLen; i++) next[i]=perm[(1+indexInPerm[i])%permLen]; int[] arr=new int[arrLen]; for (int i=0; i<arrLen; i++) arr[i]=fs.nextInt()-1; int[][] lift=new int[arrLen][20]; int[] nextInd=new int[permLen]; Arrays.fill(nextInd, -1); for (int i=arrLen-1; i>=0; i--) { lift[i][0]=nextInd[next[arr[i]]]; nextInd[arr[i]]=i; } for (int e=1; e<20; e++) for (int i=0; i<arrLen; i++) if (lift[i][e-1]==-1) lift[i][e]=-1; else lift[i][e]=lift[lift[i][e-1]][e-1]; Query[] queries=new Query[nQueries]; Query[] sorted=new Query[nQueries]; for (int i=0; i<nQueries; i++) sorted[i]=queries[i]=new Query(fs.nextInt()-1, fs.nextInt()-1); Arrays.sort(sorted); int firstEnd=arrLen+1; int l=arrLen; for (Query q:sorted) { while (l>q.l) { l--; int end=forwardN(l, lift, permLen-1); if (end==-1) continue; else { firstEnd=Math.min(firstEnd, end); } } q.ans=firstEnd<=q.r; } PrintWriter out=new PrintWriter(System.out); for (Query q:queries) { out.print(q.ans?'1':'0'); } out.println(); out.close(); } static int forwardN(int from, int[][] lift, int toMove) { if (from==-1) return -1; if (toMove==0) return from; int trailing=Integer.numberOfTrailingZeros(toMove); return forwardN(lift[from][trailing], lift, toMove-(1<<trailing)); } static class Query implements Comparable<Query> { int l, r; boolean ans; public Query(int l, int r) { this.l=l; this.r=r; } public int compareTo(Query o) { return -Integer.compare(l, o.l); } } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); public String next() { while (!st.hasMoreElements()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) { a[i]=nextInt(); } return a; } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["3 6 3\n2 1 3\n1 2 3 1 2 3\n1 5\n2 6\n3 5", "2 4 3\n2 1\n1 1 2 2\n1 2\n2 3\n3 4"]
2 seconds
["110", "010"]
NoteIn the first example the segment from the $$$1$$$-st to the $$$5$$$-th positions is $$$1, 2, 3, 1, 2$$$. There is a subsequence $$$1, 3, 2$$$ that is a cyclic shift of the permutation. The subsegment from the $$$2$$$-nd to the $$$6$$$-th positions also contains a subsequence $$$2, 1, 3$$$ that is equal to the permutation. The subsegment from the $$$3$$$-rd to the $$$5$$$-th positions is $$$3, 1, 2$$$, there is only one subsequence of length $$$3$$$ ($$$3, 1, 2$$$), but it is not a cyclic shift of the permutation.In the second example the possible cyclic shifts are $$$1, 2$$$ and $$$2, 1$$$. The subsegment from the $$$1$$$-st to the $$$2$$$-nd positions is $$$1, 1$$$, its subsequences are not cyclic shifts of the permutation. The subsegment from the $$$2$$$-nd to the $$$3$$$-rd positions is $$$1, 2$$$, it coincides with the permutation. The subsegment from the $$$3$$$ to the $$$4$$$ positions is $$$2, 2$$$, its subsequences are not cyclic shifts of the permutation.
Java 8
standard input
[ "dp", "math", "data structures", "dfs and similar", "trees" ]
4aaeff1b38d501daf9a877667e075d49
The first line contains three integers $$$n$$$, $$$m$$$, $$$q$$$ ($$$1 \le n, m, q \le 2 \cdot 10^5$$$) — the length of the permutation $$$p$$$, the length of the array $$$a$$$ and the number of queries. The next line contains $$$n$$$ integers from $$$1$$$ to $$$n$$$, where the $$$i$$$-th of them is the $$$i$$$-th element of the permutation. Each integer from $$$1$$$ to $$$n$$$ appears exactly once. The next line contains $$$m$$$ integers from $$$1$$$ to $$$n$$$, the $$$i$$$-th of them is the $$$i$$$-th element of the array $$$a$$$. The next $$$q$$$ lines describe queries. The $$$i$$$-th of these lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le m$$$), meaning that the $$$i$$$-th query is about the subsegment of the array from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive.
2,000
Print a single string of length $$$q$$$, consisting of $$$0$$$ and $$$1$$$, the digit on the $$$i$$$-th positions should be $$$1$$$, if the subsegment of array $$$a$$$ from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive, contains a subsequence that is a cyclic shift of $$$p$$$, and $$$0$$$ otherwise.
standard output
PASSED
210eca437f06225004bdc6dc57bea994
train_002.jsonl
1553965800
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation $$$p$$$ of length $$$n$$$, and Skynyrd bought an array $$$a$$$ of length $$$m$$$, consisting of integers from $$$1$$$ to $$$n$$$. Lynyrd and Skynyrd became bored, so they asked you $$$q$$$ queries, each of which has the following form: "does the subsegment of $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, have a subsequence that is a cyclic shift of $$$p$$$?" Please answer the queries.A permutation of length $$$n$$$ is a sequence of $$$n$$$ integers such that each integer from $$$1$$$ to $$$n$$$ appears exactly once in it.A cyclic shift of a permutation $$$(p_1, p_2, \ldots, p_n)$$$ is a permutation $$$(p_i, p_{i + 1}, \ldots, p_{n}, p_1, p_2, \ldots, p_{i - 1})$$$ for some $$$i$$$ from $$$1$$$ to $$$n$$$. For example, a permutation $$$(2, 1, 3)$$$ has three distinct cyclic shifts: $$$(2, 1, 3)$$$, $$$(1, 3, 2)$$$, $$$(3, 2, 1)$$$.A subsequence of a subsegment of array $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, is a sequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ for some $$$i_1, i_2, \ldots, i_k$$$ such that $$$l \leq i_1 &lt; i_2 &lt; \ldots &lt; i_k \leq r$$$.
256 megabytes
/* ID: tommatt1 LANG: JAVA TASK: */ import java.util.*; import java.io.*; public class cf1142b{ public static void main(String[] args)throws IOException { BufferedReader bf=new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); //BufferedReader bf=new BufferedReader(new FileReader("cf1142b.in")); //PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("cf1142b.out"))); StringTokenizer st=new StringTokenizer(bf.readLine()); int n=Integer.parseInt(st.nextToken()); int m=Integer.parseInt(st.nextToken()); int q=Integer.parseInt(st.nextToken()); int[] p=new int[n+1]; int[] a=new int[m+1]; int[] min=new int[m+1]; int[] lst=new int[n+1]; int[] prev=new int[n+1]; int[][] par=new int[m+1][18]; st=new StringTokenizer(bf.readLine()); for(int i=1;i<=n;i++) { p[i]=Integer.parseInt(st.nextToken()); prev[p[i]]=p[i-1]; } prev[p[1]]=p[n]; st=new StringTokenizer(bf.readLine()); for(int i=1;i<=m;i++) { a[i]=Integer.parseInt(st.nextToken()); lst[a[i]]=i; par[i][0]=lst[prev[a[i]]]; min[i]=(int)2e5+5; for(int j=1;j<=17;j++) { par[i][j]=par[par[i][j-1]][j-1]; } int z=i; for(int j=0;j<=17;j++) { if((n-1>>j&1)>0) z=par[z][j]; } min[z]=Math.min(min[z], i); } for(int i=m-1;i>=1;i--) { min[i]=Math.min(min[i], min[i+1]); } for(int i=0;i<q;i++) { st=new StringTokenizer(bf.readLine()); int a1=Integer.parseInt(st.nextToken()); int a2=Integer.parseInt(st.nextToken()); if(min[a1]<=a2) out.print(1); else out.print(0); } out.println(""); out.close(); } }
Java
["3 6 3\n2 1 3\n1 2 3 1 2 3\n1 5\n2 6\n3 5", "2 4 3\n2 1\n1 1 2 2\n1 2\n2 3\n3 4"]
2 seconds
["110", "010"]
NoteIn the first example the segment from the $$$1$$$-st to the $$$5$$$-th positions is $$$1, 2, 3, 1, 2$$$. There is a subsequence $$$1, 3, 2$$$ that is a cyclic shift of the permutation. The subsegment from the $$$2$$$-nd to the $$$6$$$-th positions also contains a subsequence $$$2, 1, 3$$$ that is equal to the permutation. The subsegment from the $$$3$$$-rd to the $$$5$$$-th positions is $$$3, 1, 2$$$, there is only one subsequence of length $$$3$$$ ($$$3, 1, 2$$$), but it is not a cyclic shift of the permutation.In the second example the possible cyclic shifts are $$$1, 2$$$ and $$$2, 1$$$. The subsegment from the $$$1$$$-st to the $$$2$$$-nd positions is $$$1, 1$$$, its subsequences are not cyclic shifts of the permutation. The subsegment from the $$$2$$$-nd to the $$$3$$$-rd positions is $$$1, 2$$$, it coincides with the permutation. The subsegment from the $$$3$$$ to the $$$4$$$ positions is $$$2, 2$$$, its subsequences are not cyclic shifts of the permutation.
Java 8
standard input
[ "dp", "math", "data structures", "dfs and similar", "trees" ]
4aaeff1b38d501daf9a877667e075d49
The first line contains three integers $$$n$$$, $$$m$$$, $$$q$$$ ($$$1 \le n, m, q \le 2 \cdot 10^5$$$) — the length of the permutation $$$p$$$, the length of the array $$$a$$$ and the number of queries. The next line contains $$$n$$$ integers from $$$1$$$ to $$$n$$$, where the $$$i$$$-th of them is the $$$i$$$-th element of the permutation. Each integer from $$$1$$$ to $$$n$$$ appears exactly once. The next line contains $$$m$$$ integers from $$$1$$$ to $$$n$$$, the $$$i$$$-th of them is the $$$i$$$-th element of the array $$$a$$$. The next $$$q$$$ lines describe queries. The $$$i$$$-th of these lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le m$$$), meaning that the $$$i$$$-th query is about the subsegment of the array from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive.
2,000
Print a single string of length $$$q$$$, consisting of $$$0$$$ and $$$1$$$, the digit on the $$$i$$$-th positions should be $$$1$$$, if the subsegment of array $$$a$$$ from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive, contains a subsequence that is a cyclic shift of $$$p$$$, and $$$0$$$ otherwise.
standard output
PASSED
58e23371f9cebacb81c59c42cbc3afff
train_002.jsonl
1553965800
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation $$$p$$$ of length $$$n$$$, and Skynyrd bought an array $$$a$$$ of length $$$m$$$, consisting of integers from $$$1$$$ to $$$n$$$. Lynyrd and Skynyrd became bored, so they asked you $$$q$$$ queries, each of which has the following form: "does the subsegment of $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, have a subsequence that is a cyclic shift of $$$p$$$?" Please answer the queries.A permutation of length $$$n$$$ is a sequence of $$$n$$$ integers such that each integer from $$$1$$$ to $$$n$$$ appears exactly once in it.A cyclic shift of a permutation $$$(p_1, p_2, \ldots, p_n)$$$ is a permutation $$$(p_i, p_{i + 1}, \ldots, p_{n}, p_1, p_2, \ldots, p_{i - 1})$$$ for some $$$i$$$ from $$$1$$$ to $$$n$$$. For example, a permutation $$$(2, 1, 3)$$$ has three distinct cyclic shifts: $$$(2, 1, 3)$$$, $$$(1, 3, 2)$$$, $$$(3, 2, 1)$$$.A subsequence of a subsegment of array $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, is a sequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ for some $$$i_1, i_2, \ldots, i_k$$$ such that $$$l \leq i_1 &lt; i_2 &lt; \ldots &lt; i_k \leq r$$$.
256 megabytes
//package com.company; // Always comment out package when submitting. import java.io.*; import java.util.*; public class Main { public static class Task { public void solve(Scanner sc, PrintWriter pw) throws IOException { int n = sc.nextInt(); int m = sc.nextInt(); int q = sc.nextInt(); int[] p = new int[n]; for (int i = 0; i < n; i++) { p[i] = sc.nextInt() - 1; } int[] a = new int[m]; for (int i = 0; i < m; i++) { a[i] = sc.nextInt() - 1; } int[] next = new int[m]; Arrays.fill(next, -1); List<Integer>[] vals = new List[n]; for (int i = 0; i < n; i++) { vals[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { vals[a[i]].add(i); } for (int i = 0; i < n; i++) { int cur = p[i]; int nex = p[(i + 1) % n]; List<Integer> i1 = vals[cur]; List<Integer> i2 = vals[nex]; int idx1 = 0, idx2 = 0; while (idx1 < i1.size() && idx2 < i2.size()) { if (i1.get(idx1) < i2.get(idx2)) { next[i1.get(idx1)] = i2.get(idx2); idx1++; } else { idx2++; } } } int[][] jumpTable = new int[m][20]; for (int i = 0; i < m; i++) { jumpTable[i][0] = next[i]; } for (int i = 1; i < 20; i++) { for (int j = 0; j < m; j++) { if (jumpTable[j][i - 1] == -1) { jumpTable[j][i] = -1; } else { jumpTable[j][i] = jumpTable[jumpTable[j][i - 1]][i - 1]; } } } StringBuilder sb = new StringBuilder(); int[] reach = new int[m]; for (int i = 0; i < m; i++) { int mv = i; int count = 0; for (int j = 19; j >= 0; j--) { if ((1 << j) + count <= n - 1) { mv = jumpTable[mv][j]; if (mv == -1) { break; } count += 1 << j; } } reach[i] = mv; if (reach[i] == -1) reach[i] = m; } int[][] rangeMin = new int[m][20]; for (int i = 0; i < m; i++) { rangeMin[i][0] = reach[i]; } for (int i = 1; i < 20; i++) { for (int j = 0; j + (1 << (i - 1)) < m; j++) { rangeMin[j][i] = Math.min(rangeMin[j][i - 1], rangeMin[j + (1 << (i - 1))][i - 1]); } } for (int i = 0; i < q; i++) { int l = sc.nextInt() - 1; int r = sc.nextInt(); int count = m; int mv = l; for (int j = 19; j >= 0; j--) { if (mv + (1 << j) <= r) { count = Math.min(count, rangeMin[mv][j]); mv += 1 << j; } } if (count < r) { sb.append(1); } else { sb.append(0); } } pw.println(sb.toString()); } } // template, actual code is in class Task. static long TIME_START, TIME_END; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); // Scanner sc = new Scanner(new FileInputStream("Test.in")); PrintWriter pw = new PrintWriter(new BufferedOutputStream(System.out)); // PrintWriter pw = new PrintWriter(new FileOutputStream("Test.out")); Runtime runtime = Runtime.getRuntime(); long usedMemoryBefore = runtime.totalMemory() - runtime.freeMemory(); TIME_START = System.currentTimeMillis(); Task t = new Task(); t.solve(sc, pw); TIME_END = System.currentTimeMillis(); long usedMemoryAfter = runtime.totalMemory() - runtime.freeMemory(); pw.close(); // System.err.println("Memory increased: " + (usedMemoryAfter - usedMemoryBefore) / 1000000); // System.err.println("Time used: " + (TIME_END - TIME_START) + "."); } // Faster IO with BufferedReader wrapped with Scanner static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader s) throws FileNotFoundException { br = new BufferedReader(s); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["3 6 3\n2 1 3\n1 2 3 1 2 3\n1 5\n2 6\n3 5", "2 4 3\n2 1\n1 1 2 2\n1 2\n2 3\n3 4"]
2 seconds
["110", "010"]
NoteIn the first example the segment from the $$$1$$$-st to the $$$5$$$-th positions is $$$1, 2, 3, 1, 2$$$. There is a subsequence $$$1, 3, 2$$$ that is a cyclic shift of the permutation. The subsegment from the $$$2$$$-nd to the $$$6$$$-th positions also contains a subsequence $$$2, 1, 3$$$ that is equal to the permutation. The subsegment from the $$$3$$$-rd to the $$$5$$$-th positions is $$$3, 1, 2$$$, there is only one subsequence of length $$$3$$$ ($$$3, 1, 2$$$), but it is not a cyclic shift of the permutation.In the second example the possible cyclic shifts are $$$1, 2$$$ and $$$2, 1$$$. The subsegment from the $$$1$$$-st to the $$$2$$$-nd positions is $$$1, 1$$$, its subsequences are not cyclic shifts of the permutation. The subsegment from the $$$2$$$-nd to the $$$3$$$-rd positions is $$$1, 2$$$, it coincides with the permutation. The subsegment from the $$$3$$$ to the $$$4$$$ positions is $$$2, 2$$$, its subsequences are not cyclic shifts of the permutation.
Java 8
standard input
[ "dp", "math", "data structures", "dfs and similar", "trees" ]
4aaeff1b38d501daf9a877667e075d49
The first line contains three integers $$$n$$$, $$$m$$$, $$$q$$$ ($$$1 \le n, m, q \le 2 \cdot 10^5$$$) — the length of the permutation $$$p$$$, the length of the array $$$a$$$ and the number of queries. The next line contains $$$n$$$ integers from $$$1$$$ to $$$n$$$, where the $$$i$$$-th of them is the $$$i$$$-th element of the permutation. Each integer from $$$1$$$ to $$$n$$$ appears exactly once. The next line contains $$$m$$$ integers from $$$1$$$ to $$$n$$$, the $$$i$$$-th of them is the $$$i$$$-th element of the array $$$a$$$. The next $$$q$$$ lines describe queries. The $$$i$$$-th of these lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le m$$$), meaning that the $$$i$$$-th query is about the subsegment of the array from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive.
2,000
Print a single string of length $$$q$$$, consisting of $$$0$$$ and $$$1$$$, the digit on the $$$i$$$-th positions should be $$$1$$$, if the subsegment of array $$$a$$$ from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive, contains a subsequence that is a cyclic shift of $$$p$$$, and $$$0$$$ otherwise.
standard output
PASSED
c2fcb5db4416f8ae99669659ac73079a
train_002.jsonl
1553965800
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation $$$p$$$ of length $$$n$$$, and Skynyrd bought an array $$$a$$$ of length $$$m$$$, consisting of integers from $$$1$$$ to $$$n$$$. Lynyrd and Skynyrd became bored, so they asked you $$$q$$$ queries, each of which has the following form: "does the subsegment of $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, have a subsequence that is a cyclic shift of $$$p$$$?" Please answer the queries.A permutation of length $$$n$$$ is a sequence of $$$n$$$ integers such that each integer from $$$1$$$ to $$$n$$$ appears exactly once in it.A cyclic shift of a permutation $$$(p_1, p_2, \ldots, p_n)$$$ is a permutation $$$(p_i, p_{i + 1}, \ldots, p_{n}, p_1, p_2, \ldots, p_{i - 1})$$$ for some $$$i$$$ from $$$1$$$ to $$$n$$$. For example, a permutation $$$(2, 1, 3)$$$ has three distinct cyclic shifts: $$$(2, 1, 3)$$$, $$$(1, 3, 2)$$$, $$$(3, 2, 1)$$$.A subsequence of a subsegment of array $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, is a sequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ for some $$$i_1, i_2, \ldots, i_k$$$ such that $$$l \leq i_1 &lt; i_2 &lt; \ldots &lt; i_k \leq r$$$.
256 megabytes
/*Author: Satyajeet Singh, Delhi Technological University*/ import java.io.*; import java.util.*; import java.text.*; import java.lang.*; import java.math.*; public class Main{ /*********************************************Constants******************************************/ static PrintWriter out=new PrintWriter(new OutputStreamWriter(System.out)); static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static long mod=(long)1e9+7; static long mod1=998244353; static boolean sieve[]; static ArrayList<Integer> primes; static long factorial[],invFactorial[]; static ArrayList<Pair> graph[]; static int pptr=0; static String st[]; /****************************************Solutions Begins***************************************/ public static void main(String[] args) throws Exception{ nl(); int n=pi(); int m=pi(); int q=pi(); int P[]=new int[n]; nl(); for(int i=0;i<n;i++){ P[i]=pi(); } int prev[]=new int[n+1]; for(int i=n-1;i>=1;i--){ prev[P[i]]=P[i-1]; } prev[P[0]]=P[n-1]; int A[]=new int[m]; nl(); for(int i=0;i<m;i++){ A[i]=pi(); } int ans[]=new int[m+1]; String str=Integer.toBinaryString(n-1); int lt=str.length(); //debug(str); int L[][]=new int[m+1][20]; int previ[]=new int[n+1]; for(int i=0;i<m;i++){ L[i+1][0]=previ[prev[A[i]]]; previ[A[i]]=i+1; for(int j=1;j<20;j++){ L[i+1][j]=L[L[i+1][j-1]][j-1]; } int cur=i+1; for(int j=0;j<lt;j++){ int id=lt-j-1; if(str.charAt(j)=='1'){ cur=L[cur][id]; } } ans[i+1]=Math.max(cur,ans[i]); } // debug(prev); // debug(L); // debug(ans); while(q-->0){ nl(); int l=pi(); int r=pi(); if(ans[r]<l)out.print(0); else out.print(1); } /****************************************Solutions Ends**************************************************/ out.flush(); out.close(); } /****************************************Template Begins************************************************/ static void nl() throws Exception{ pptr=0; st=br.readLine().split(" "); } static void nls() throws Exception{ pptr=0; st=br.readLine().split(""); } static int pi(){ return Integer.parseInt(st[pptr++]); } static long pl(){ return Long.parseLong(st[pptr++]); } static double pd(){ return Double.parseDouble(st[pptr++]); } static String ps(){ return st[pptr++]; } /***************************************Precision Printing**********************************************/ static void printPrecision(double d){ DecimalFormat ft = new DecimalFormat("0.000000000000000000000"); out.print(ft.format(d)); } /**************************************Bit Manipulation**************************************************/ static void printMask(long mask){ System.out.println(Long.toBinaryString(mask)); } static int countBit(long mask){ int ans=0; while(mask!=0){ mask&=(mask-1); ans++; } return ans; } /******************************************Graph*********************************************************/ static void Makegraph(int n){ graph=new ArrayList[n]; for(int i=0;i<n;i++){ graph[i]=new ArrayList<>(); } } static void addEdge(int a,int b){ graph[a].add(new Pair(b,1)); } static void addEdge(int a,int b,int c){ graph[a].add(new Pair(b,c)); } /*********************************************PAIR********************************************************/ static class Pair implements Comparable<Pair> { int u; int v; int index=-1; public Pair(int u, int v) { this.u = u; this.v = v; } public int hashCode() { int hu = (int) (u ^ (u >>> 32)); int hv = (int) (v ^ (v >>> 32)); return 31 * hu + hv; } public boolean equals(Object o) { Pair other = (Pair) o; return u == other.u && v == other.v; } public int compareTo(Pair other) { if(index!=other.index) return Long.compare(index, other.index); return Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u); } public String toString() { return "[u=" + u + ", v=" + v + "]"; } } /******************************************Long Pair*******************************************************/ static class Pairl implements Comparable<Pairl> { long u; long v; int index=-1; public Pairl(long u, long v) { this.u = u; this.v = v; } public int hashCode() { int hu = (int) (u ^ (u >>> 32)); int hv = (int) (v ^ (v >>> 32)); return 31 * hu + hv; } public boolean equals(Object o) { Pairl other = (Pairl) o; return u == other.u && v == other.v; } public int compareTo(Pairl other) { if(index!=other.index) return Long.compare(index, other.index); return Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u); } public String toString() { return "[u=" + u + ", v=" + v + "]"; } } /*****************************************DEBUG***********************************************************/ public static void debug(Object... o){ System.out.println(Arrays.deepToString(o)); } /************************************MODULAR EXPONENTIATION***********************************************/ static long modulo(long a,long b,long c){ long x=1; long y=a%c; while(b > 0){ if(b%2 == 1){ x=(x*y)%c; } y = (y*y)%c; // squaring the base b /= 2; } return x%c; } /********************************************GCD**********************************************************/ static long gcd(long x, long y){ if(x==0) return y; if(y==0) return x; long r=0, a, b; a = (x > y) ? x : y; // a is greater number b = (x < y) ? x : y; // b is smaller number r = b; while(a % b != 0){ r = a % b; a = b; b = r; } return r; } /******************************************SIEVE**********************************************************/ static void sieveMake(int n){ sieve=new boolean[n]; Arrays.fill(sieve,true); sieve[0]=false; sieve[1]=false; for(int i=2;i*i<n;i++){ if(sieve[i]){ for(int j=i*i;j<n;j+=i){ sieve[j]=false; } } } primes=new ArrayList<Integer>(); for(int i=0;i<n;i++){ if(sieve[i]){ primes.add(i); } } } /********************************************End***********************************************************/ }
Java
["3 6 3\n2 1 3\n1 2 3 1 2 3\n1 5\n2 6\n3 5", "2 4 3\n2 1\n1 1 2 2\n1 2\n2 3\n3 4"]
2 seconds
["110", "010"]
NoteIn the first example the segment from the $$$1$$$-st to the $$$5$$$-th positions is $$$1, 2, 3, 1, 2$$$. There is a subsequence $$$1, 3, 2$$$ that is a cyclic shift of the permutation. The subsegment from the $$$2$$$-nd to the $$$6$$$-th positions also contains a subsequence $$$2, 1, 3$$$ that is equal to the permutation. The subsegment from the $$$3$$$-rd to the $$$5$$$-th positions is $$$3, 1, 2$$$, there is only one subsequence of length $$$3$$$ ($$$3, 1, 2$$$), but it is not a cyclic shift of the permutation.In the second example the possible cyclic shifts are $$$1, 2$$$ and $$$2, 1$$$. The subsegment from the $$$1$$$-st to the $$$2$$$-nd positions is $$$1, 1$$$, its subsequences are not cyclic shifts of the permutation. The subsegment from the $$$2$$$-nd to the $$$3$$$-rd positions is $$$1, 2$$$, it coincides with the permutation. The subsegment from the $$$3$$$ to the $$$4$$$ positions is $$$2, 2$$$, its subsequences are not cyclic shifts of the permutation.
Java 8
standard input
[ "dp", "math", "data structures", "dfs and similar", "trees" ]
4aaeff1b38d501daf9a877667e075d49
The first line contains three integers $$$n$$$, $$$m$$$, $$$q$$$ ($$$1 \le n, m, q \le 2 \cdot 10^5$$$) — the length of the permutation $$$p$$$, the length of the array $$$a$$$ and the number of queries. The next line contains $$$n$$$ integers from $$$1$$$ to $$$n$$$, where the $$$i$$$-th of them is the $$$i$$$-th element of the permutation. Each integer from $$$1$$$ to $$$n$$$ appears exactly once. The next line contains $$$m$$$ integers from $$$1$$$ to $$$n$$$, the $$$i$$$-th of them is the $$$i$$$-th element of the array $$$a$$$. The next $$$q$$$ lines describe queries. The $$$i$$$-th of these lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le m$$$), meaning that the $$$i$$$-th query is about the subsegment of the array from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive.
2,000
Print a single string of length $$$q$$$, consisting of $$$0$$$ and $$$1$$$, the digit on the $$$i$$$-th positions should be $$$1$$$, if the subsegment of array $$$a$$$ from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive, contains a subsequence that is a cyclic shift of $$$p$$$, and $$$0$$$ otherwise.
standard output
PASSED
2c8fb4b1a4d3dc605b21b07d68f25ce3
train_002.jsonl
1553965800
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation $$$p$$$ of length $$$n$$$, and Skynyrd bought an array $$$a$$$ of length $$$m$$$, consisting of integers from $$$1$$$ to $$$n$$$. Lynyrd and Skynyrd became bored, so they asked you $$$q$$$ queries, each of which has the following form: "does the subsegment of $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, have a subsequence that is a cyclic shift of $$$p$$$?" Please answer the queries.A permutation of length $$$n$$$ is a sequence of $$$n$$$ integers such that each integer from $$$1$$$ to $$$n$$$ appears exactly once in it.A cyclic shift of a permutation $$$(p_1, p_2, \ldots, p_n)$$$ is a permutation $$$(p_i, p_{i + 1}, \ldots, p_{n}, p_1, p_2, \ldots, p_{i - 1})$$$ for some $$$i$$$ from $$$1$$$ to $$$n$$$. For example, a permutation $$$(2, 1, 3)$$$ has three distinct cyclic shifts: $$$(2, 1, 3)$$$, $$$(1, 3, 2)$$$, $$$(3, 2, 1)$$$.A subsequence of a subsegment of array $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, is a sequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ for some $$$i_1, i_2, \ldots, i_k$$$ such that $$$l \leq i_1 &lt; i_2 &lt; \ldots &lt; i_k \leq r$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { public void solve(int testNumber, FastScanner in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); int numQueries = in.nextInt(); int[] p = new int[n]; for (int i = 0; i < n; i++) { p[i] = in.nextInt() - 1; } int[] a = new int[m]; for (int i = 0; i < m; i++) { a[i] = in.nextInt() - 1; } int[] nextP = new int[n]; for (int i = 0; i < n; i++) { int j = i + 1; if (j == n) { j = 0; } nextP[p[i]] = p[j]; } int log = 22; int[][] next = new int[log][m + 1]; int[] latest = new int[n + 1]; Arrays.fill(latest, m); for (int[] arr : next) { Arrays.fill(arr, m); } for (int i = m - 1; i >= 0; i--) { next[0][i] = latest[nextP[a[i]]]; latest[a[i]] = i; } for (int level = 1; level < log; level++) { for (int i = 0; i <= m; i++) { next[level][i] = next[level - 1][next[level - 1][i]]; } } MinTree tree = new MinTree(m); for (int i = 0; i < m; i++) { int need = n - 1; int j = i; for (int level = log - 1; level >= 0; level--) { if (need >= (1 << level)) { j = next[level][j]; need -= 1 << level; } } tree.set(i, j); } char[] ans = new char[numQueries]; for (int queryId = 0; queryId < numQueries; queryId++) { int l = in.nextInt() - 1; int r = in.nextInt() - 1; ans[queryId] = tree.getMin(l, r) <= r ? '1' : '0'; } out.println(new String(ans)); } class MinTree { int[] a; int n; MinTree(int size) { n = 1; while (n < size) { n *= 2; } a = new int[2 * n]; Arrays.fill(a, Integer.MAX_VALUE); } void set(int pos, int val) { pos += n; a[pos] = val; while (pos > 1) { pos /= 2; a[pos] = Math.min(a[2 * pos], a[2 * pos + 1]); } } int getMin(int l, int r) { if (l > r) { return 0; } l += n; r += n; if (l == r) { return a[l]; } int lm = a[l]; int rm = a[r]; while (r - l > 1) { if (l % 2 == 0) { lm = Math.min(lm, a[l + 1]); } if (r % 2 == 1) { rm = Math.min(rm, a[r - 1]); } l /= 2; r /= 2; } return Math.min(lm, rm); } } } static class FastScanner { private BufferedReader in; private StringTokenizer st; public FastScanner(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { String rl = in.readLine(); if (rl == null) { return null; } st = new StringTokenizer(rl); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["3 6 3\n2 1 3\n1 2 3 1 2 3\n1 5\n2 6\n3 5", "2 4 3\n2 1\n1 1 2 2\n1 2\n2 3\n3 4"]
2 seconds
["110", "010"]
NoteIn the first example the segment from the $$$1$$$-st to the $$$5$$$-th positions is $$$1, 2, 3, 1, 2$$$. There is a subsequence $$$1, 3, 2$$$ that is a cyclic shift of the permutation. The subsegment from the $$$2$$$-nd to the $$$6$$$-th positions also contains a subsequence $$$2, 1, 3$$$ that is equal to the permutation. The subsegment from the $$$3$$$-rd to the $$$5$$$-th positions is $$$3, 1, 2$$$, there is only one subsequence of length $$$3$$$ ($$$3, 1, 2$$$), but it is not a cyclic shift of the permutation.In the second example the possible cyclic shifts are $$$1, 2$$$ and $$$2, 1$$$. The subsegment from the $$$1$$$-st to the $$$2$$$-nd positions is $$$1, 1$$$, its subsequences are not cyclic shifts of the permutation. The subsegment from the $$$2$$$-nd to the $$$3$$$-rd positions is $$$1, 2$$$, it coincides with the permutation. The subsegment from the $$$3$$$ to the $$$4$$$ positions is $$$2, 2$$$, its subsequences are not cyclic shifts of the permutation.
Java 8
standard input
[ "dp", "math", "data structures", "dfs and similar", "trees" ]
4aaeff1b38d501daf9a877667e075d49
The first line contains three integers $$$n$$$, $$$m$$$, $$$q$$$ ($$$1 \le n, m, q \le 2 \cdot 10^5$$$) — the length of the permutation $$$p$$$, the length of the array $$$a$$$ and the number of queries. The next line contains $$$n$$$ integers from $$$1$$$ to $$$n$$$, where the $$$i$$$-th of them is the $$$i$$$-th element of the permutation. Each integer from $$$1$$$ to $$$n$$$ appears exactly once. The next line contains $$$m$$$ integers from $$$1$$$ to $$$n$$$, the $$$i$$$-th of them is the $$$i$$$-th element of the array $$$a$$$. The next $$$q$$$ lines describe queries. The $$$i$$$-th of these lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le m$$$), meaning that the $$$i$$$-th query is about the subsegment of the array from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive.
2,000
Print a single string of length $$$q$$$, consisting of $$$0$$$ and $$$1$$$, the digit on the $$$i$$$-th positions should be $$$1$$$, if the subsegment of array $$$a$$$ from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive, contains a subsequence that is a cyclic shift of $$$p$$$, and $$$0$$$ otherwise.
standard output
PASSED
6810d4376185c0e97f5ef58973386bf2
train_002.jsonl
1553965800
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation $$$p$$$ of length $$$n$$$, and Skynyrd bought an array $$$a$$$ of length $$$m$$$, consisting of integers from $$$1$$$ to $$$n$$$. Lynyrd and Skynyrd became bored, so they asked you $$$q$$$ queries, each of which has the following form: "does the subsegment of $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, have a subsequence that is a cyclic shift of $$$p$$$?" Please answer the queries.A permutation of length $$$n$$$ is a sequence of $$$n$$$ integers such that each integer from $$$1$$$ to $$$n$$$ appears exactly once in it.A cyclic shift of a permutation $$$(p_1, p_2, \ldots, p_n)$$$ is a permutation $$$(p_i, p_{i + 1}, \ldots, p_{n}, p_1, p_2, \ldots, p_{i - 1})$$$ for some $$$i$$$ from $$$1$$$ to $$$n$$$. For example, a permutation $$$(2, 1, 3)$$$ has three distinct cyclic shifts: $$$(2, 1, 3)$$$, $$$(1, 3, 2)$$$, $$$(3, 2, 1)$$$.A subsequence of a subsegment of array $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, is a sequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ for some $$$i_1, i_2, \ldots, i_k$$$ such that $$$l \leq i_1 &lt; i_2 &lt; \ldots &lt; i_k \leq r$$$.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.lang.*; import static java.lang.Math.*; 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(); } int querySegTree(int low, int high, int pos, int l, int r) { if(low > r || high < l) return -1; if(low >= l && high <= r) return segTree[pos]; int mid = (low + high) >> 1; int val1 = querySegTree(low, mid, 2 * pos + 1, l ,r); int val2 = querySegTree(mid + 1, high, 2 * pos + 2, l, r); return max(val1, val2); } void updateSegTree(int low, int high, int pos, int ind, int val) { if(low > ind || high < ind) return; if(low == high) { segTree[pos] = val; return; } int mid = (low + high) >> 1; updateSegTree(low, mid, 2 * pos + 1, ind, val); updateSegTree(mid + 1, high, 2 * pos + 2, ind, val); segTree[pos] = max(segTree[2 * pos + 1], segTree[2 * pos + 2]); } int segTree[]; public void run() { InputReader sc = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int n = sc.nextInt(); int m = sc.nextInt(); int q = sc.nextInt(); int permute[] = new int[n]; int needed[] = new int[n + 1]; for(int i = 0; i < n; ++i) { permute[i] = sc.nextInt(); if(i != 0) needed[permute[i]] = permute[i - 1]; } needed[permute[0]] = permute[n - 1]; int a[] = new int[m]; int par[][] = new int[m][18]; segTree = new int[4 * m]; Arrays.fill(segTree, -1); int ind[] = new int[n + 1]; Arrays.fill(ind, -1); for(int i = 0; i < m; ++i) { for(int j = 0; j < 18; ++j) par[i][j] = -1; } for(int i = 0; i < m; ++i) { a[i] = sc.nextInt(); if(ind[needed[a[i]]] != -1) { par[i][0] = ind[needed[a[i]]]; } else par[i][0] = -1; for(int j = 1; j < 18; ++j) { if(par[i][j - 1] != -1) { par[i][j] = par[par[i][j - 1]][j - 1]; } } int dist = n - 1; int curNode = i; for(int j = 17; j >= 0; --j) { int curDist = 1 << j; if(curDist <= dist) { if(par[curNode][j] == -1) break; dist -= curDist; curNode = par[curNode][j]; } } if(dist == 0) updateSegTree(0, m - 1, 0, i, curNode); ind[a[i]] = i; } for(int i = 0; i < q; ++i) { int l = sc.nextInt() - 1; int r = sc.nextInt() - 1; int cans = querySegTree(0, m - 1, 0, l, r); if(cans >= l) w.print("1"); else w.print("0"); } w.close(); } }
Java
["3 6 3\n2 1 3\n1 2 3 1 2 3\n1 5\n2 6\n3 5", "2 4 3\n2 1\n1 1 2 2\n1 2\n2 3\n3 4"]
2 seconds
["110", "010"]
NoteIn the first example the segment from the $$$1$$$-st to the $$$5$$$-th positions is $$$1, 2, 3, 1, 2$$$. There is a subsequence $$$1, 3, 2$$$ that is a cyclic shift of the permutation. The subsegment from the $$$2$$$-nd to the $$$6$$$-th positions also contains a subsequence $$$2, 1, 3$$$ that is equal to the permutation. The subsegment from the $$$3$$$-rd to the $$$5$$$-th positions is $$$3, 1, 2$$$, there is only one subsequence of length $$$3$$$ ($$$3, 1, 2$$$), but it is not a cyclic shift of the permutation.In the second example the possible cyclic shifts are $$$1, 2$$$ and $$$2, 1$$$. The subsegment from the $$$1$$$-st to the $$$2$$$-nd positions is $$$1, 1$$$, its subsequences are not cyclic shifts of the permutation. The subsegment from the $$$2$$$-nd to the $$$3$$$-rd positions is $$$1, 2$$$, it coincides with the permutation. The subsegment from the $$$3$$$ to the $$$4$$$ positions is $$$2, 2$$$, its subsequences are not cyclic shifts of the permutation.
Java 8
standard input
[ "dp", "math", "data structures", "dfs and similar", "trees" ]
4aaeff1b38d501daf9a877667e075d49
The first line contains three integers $$$n$$$, $$$m$$$, $$$q$$$ ($$$1 \le n, m, q \le 2 \cdot 10^5$$$) — the length of the permutation $$$p$$$, the length of the array $$$a$$$ and the number of queries. The next line contains $$$n$$$ integers from $$$1$$$ to $$$n$$$, where the $$$i$$$-th of them is the $$$i$$$-th element of the permutation. Each integer from $$$1$$$ to $$$n$$$ appears exactly once. The next line contains $$$m$$$ integers from $$$1$$$ to $$$n$$$, the $$$i$$$-th of them is the $$$i$$$-th element of the array $$$a$$$. The next $$$q$$$ lines describe queries. The $$$i$$$-th of these lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le m$$$), meaning that the $$$i$$$-th query is about the subsegment of the array from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive.
2,000
Print a single string of length $$$q$$$, consisting of $$$0$$$ and $$$1$$$, the digit on the $$$i$$$-th positions should be $$$1$$$, if the subsegment of array $$$a$$$ from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive, contains a subsequence that is a cyclic shift of $$$p$$$, and $$$0$$$ otherwise.
standard output
PASSED
54ff9ed7a09a0f4401c18e7e74480430
train_002.jsonl
1553965800
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation $$$p$$$ of length $$$n$$$, and Skynyrd bought an array $$$a$$$ of length $$$m$$$, consisting of integers from $$$1$$$ to $$$n$$$. Lynyrd and Skynyrd became bored, so they asked you $$$q$$$ queries, each of which has the following form: "does the subsegment of $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, have a subsequence that is a cyclic shift of $$$p$$$?" Please answer the queries.A permutation of length $$$n$$$ is a sequence of $$$n$$$ integers such that each integer from $$$1$$$ to $$$n$$$ appears exactly once in it.A cyclic shift of a permutation $$$(p_1, p_2, \ldots, p_n)$$$ is a permutation $$$(p_i, p_{i + 1}, \ldots, p_{n}, p_1, p_2, \ldots, p_{i - 1})$$$ for some $$$i$$$ from $$$1$$$ to $$$n$$$. For example, a permutation $$$(2, 1, 3)$$$ has three distinct cyclic shifts: $$$(2, 1, 3)$$$, $$$(1, 3, 2)$$$, $$$(3, 2, 1)$$$.A subsequence of a subsegment of array $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, is a sequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ for some $$$i_1, i_2, \ldots, i_k$$$ such that $$$l \leq i_1 &lt; i_2 &lt; \ldots &lt; i_k \leq r$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws Exception { new Main().go(); } PrintWriter out; Reader in; BufferedReader br; Main() throws IOException { try { //br = new BufferedReader( new FileReader("input.txt") ); //in = new Reader("input.txt"); in = new Reader("input.txt"); out = new PrintWriter( new BufferedWriter(new FileWriter("output.txt")) ); } catch (Exception e) { //br = new BufferedReader( new InputStreamReader( System.in ) ); in = new Reader(); out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out)) ); } } void go() throws Exception { //int t = in.nextInt(); int cs = 1; int t = 1; while (t > 0) { //out.print("Case #" + cs + ": "); solve(); t--; cs++; } out.flush(); out.close(); } int inf = 2000000000; int mod = 1000000007; double eps = 0.000000001; int n; int m; ArrayList<Integer>[] g; int[] a; void solve() throws IOException { int n = in.nextInt(); int m = in.nextInt(); int q = in.nextInt(); int[] p = new int[n]; int[] pos = new int[n]; int[] a = new int[m]; int[] next = new int[m]; int[] last = new int[n]; Arrays.fill(last, m); for (int i = 0; i < n; i++) { int x = in.nextInt() - 1; p[i] = x; pos[x] = i; } for (int i = 0; i < m; i++) a[i] = in.nextInt() - 1; int LOG = 20; int[][] d = new int[LOG][m + 1]; for (int i = 0; i < LOG; i++) Arrays.fill(d[i], m); for (int i = m - 1; i >= 0; i--) { int cur = a[i]; int nxtPos = (pos[cur] + 1) % n; int nxtElem = p[nxtPos]; next[i] = last[nxtElem]; last[cur] = i; d[0][i] = next[i]; } for (int i = m - 1; i >= 0; i--) { for (int j = 1; j < LOG; j++) d[j][i] = d[j - 1][d[j - 1][i]]; } int[] best = new int[m + 1]; Arrays.fill(best, inf); for (int i = m - 1; i >= 0; i--) { best[i] = best[i + 1]; int cnt = n - 1; int cur = i; for (int j = LOG - 1; j >= 0; j--) { if ((cnt & (1 << j)) > 0) cur = d[j][cur]; } best[i] = Math.min(best[i], cur); } // for (int i = 0; i < m; i++) // System.out.println(best[i]); for (int i = 0; i < q; i++) { int l = in.nextInt() - 1; int r = in.nextInt() - 1; out.print(best[l] <= r ? 1 : 0); } } long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } class Pair implements Comparable<Pair> { long a; int b; Pair(long a, int b) { this.a = a; this.b = b; } public int compareTo(Pair p) { if (a != p.a) return Long.compare(a, p.a); else return Integer.compare(b, p.b); } } class Item { int a; int b; int c; Item(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } } class Reader { BufferedReader br; StringTokenizer tok; Reader(String file) throws IOException { br = new BufferedReader( new FileReader(file) ); } Reader() throws IOException { br = new BufferedReader( new InputStreamReader(System.in) ); } String next() throws IOException { while (tok == null || !tok.hasMoreElements()) tok = new StringTokenizer(br.readLine()); return tok.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.valueOf(next()); } long nextLong() throws NumberFormatException, IOException { return Long.valueOf(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.valueOf(next()); } String nextLine() throws IOException { return br.readLine(); } } static class InputReader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public InputReader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public InputReader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } }
Java
["3 6 3\n2 1 3\n1 2 3 1 2 3\n1 5\n2 6\n3 5", "2 4 3\n2 1\n1 1 2 2\n1 2\n2 3\n3 4"]
2 seconds
["110", "010"]
NoteIn the first example the segment from the $$$1$$$-st to the $$$5$$$-th positions is $$$1, 2, 3, 1, 2$$$. There is a subsequence $$$1, 3, 2$$$ that is a cyclic shift of the permutation. The subsegment from the $$$2$$$-nd to the $$$6$$$-th positions also contains a subsequence $$$2, 1, 3$$$ that is equal to the permutation. The subsegment from the $$$3$$$-rd to the $$$5$$$-th positions is $$$3, 1, 2$$$, there is only one subsequence of length $$$3$$$ ($$$3, 1, 2$$$), but it is not a cyclic shift of the permutation.In the second example the possible cyclic shifts are $$$1, 2$$$ and $$$2, 1$$$. The subsegment from the $$$1$$$-st to the $$$2$$$-nd positions is $$$1, 1$$$, its subsequences are not cyclic shifts of the permutation. The subsegment from the $$$2$$$-nd to the $$$3$$$-rd positions is $$$1, 2$$$, it coincides with the permutation. The subsegment from the $$$3$$$ to the $$$4$$$ positions is $$$2, 2$$$, its subsequences are not cyclic shifts of the permutation.
Java 8
standard input
[ "dp", "math", "data structures", "dfs and similar", "trees" ]
4aaeff1b38d501daf9a877667e075d49
The first line contains three integers $$$n$$$, $$$m$$$, $$$q$$$ ($$$1 \le n, m, q \le 2 \cdot 10^5$$$) — the length of the permutation $$$p$$$, the length of the array $$$a$$$ and the number of queries. The next line contains $$$n$$$ integers from $$$1$$$ to $$$n$$$, where the $$$i$$$-th of them is the $$$i$$$-th element of the permutation. Each integer from $$$1$$$ to $$$n$$$ appears exactly once. The next line contains $$$m$$$ integers from $$$1$$$ to $$$n$$$, the $$$i$$$-th of them is the $$$i$$$-th element of the array $$$a$$$. The next $$$q$$$ lines describe queries. The $$$i$$$-th of these lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le m$$$), meaning that the $$$i$$$-th query is about the subsegment of the array from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive.
2,000
Print a single string of length $$$q$$$, consisting of $$$0$$$ and $$$1$$$, the digit on the $$$i$$$-th positions should be $$$1$$$, if the subsegment of array $$$a$$$ from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive, contains a subsequence that is a cyclic shift of $$$p$$$, and $$$0$$$ otherwise.
standard output
PASSED
626fc5725f5aec1fec1b4f666322304f
train_002.jsonl
1553965800
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation $$$p$$$ of length $$$n$$$, and Skynyrd bought an array $$$a$$$ of length $$$m$$$, consisting of integers from $$$1$$$ to $$$n$$$. Lynyrd and Skynyrd became bored, so they asked you $$$q$$$ queries, each of which has the following form: "does the subsegment of $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, have a subsequence that is a cyclic shift of $$$p$$$?" Please answer the queries.A permutation of length $$$n$$$ is a sequence of $$$n$$$ integers such that each integer from $$$1$$$ to $$$n$$$ appears exactly once in it.A cyclic shift of a permutation $$$(p_1, p_2, \ldots, p_n)$$$ is a permutation $$$(p_i, p_{i + 1}, \ldots, p_{n}, p_1, p_2, \ldots, p_{i - 1})$$$ for some $$$i$$$ from $$$1$$$ to $$$n$$$. For example, a permutation $$$(2, 1, 3)$$$ has three distinct cyclic shifts: $$$(2, 1, 3)$$$, $$$(1, 3, 2)$$$, $$$(3, 2, 1)$$$.A subsequence of a subsegment of array $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, is a sequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ for some $$$i_1, i_2, \ldots, i_k$$$ such that $$$l \leq i_1 &lt; i_2 &lt; \ldots &lt; i_k \leq r$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; // import java.util.StringTokenizer; import java.util.*; public class Starter { public void Run() throws IOException { int n = in.nextInt(); int m = in.nextInt(); int q = in.nextInt(); int[] reor = new int[n+1]; for (int i = 0; i < n; i++) reor[in.nextInt()] = i; int[] A = new int[m]; for (int i = 0; i < m; i++) A[i] = reor[in.nextInt()]; ArrayDeque<Integer>[] vd = new ArrayDeque[n]; int[] R = new int[m]; Arrays.fill(R, 0x3f3f3f3f); for (int i = 0; i < m; i++) { int a = A[i]; int last = a-1; if(last < 0) last+=n; ArrayDeque<Integer> cur; if (vd[last] == null) cur = new ArrayDeque<Integer>(); else { cur = vd[last]; vd[last] = null; } cur.addLast(i); if(vd[a] == null || vd[a].size() < cur.size()) { vd[a] = cur; } else { for (int j = 0; j < cur.size(); j++) vd[a].removeLast(); for (Integer j : cur) vd[a].addLast(j); } if (vd[a].size() == n) { int f = vd[a].pollFirst(); R[f]=i; } } for (int i = m-2; i>=0; i--) R[i] = Math.min(R[i+1], R[i]); for (int i = 0; i < q; i++) { int l = in.nextInt(); int r = in.nextInt(); l--; r--; if (R[l] <= r) out.print(1); else out.print(0); } } static FastReader in; static PrintWriter out; static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } } public static void main(String[] args) { try { in = new FastReader(); out = new PrintWriter(System.out); (new Starter()).Run(); in.br.close(); out.close(); } catch (Throwable e) { e.printStackTrace(); System.exit(1); } } }
Java
["3 6 3\n2 1 3\n1 2 3 1 2 3\n1 5\n2 6\n3 5", "2 4 3\n2 1\n1 1 2 2\n1 2\n2 3\n3 4"]
2 seconds
["110", "010"]
NoteIn the first example the segment from the $$$1$$$-st to the $$$5$$$-th positions is $$$1, 2, 3, 1, 2$$$. There is a subsequence $$$1, 3, 2$$$ that is a cyclic shift of the permutation. The subsegment from the $$$2$$$-nd to the $$$6$$$-th positions also contains a subsequence $$$2, 1, 3$$$ that is equal to the permutation. The subsegment from the $$$3$$$-rd to the $$$5$$$-th positions is $$$3, 1, 2$$$, there is only one subsequence of length $$$3$$$ ($$$3, 1, 2$$$), but it is not a cyclic shift of the permutation.In the second example the possible cyclic shifts are $$$1, 2$$$ and $$$2, 1$$$. The subsegment from the $$$1$$$-st to the $$$2$$$-nd positions is $$$1, 1$$$, its subsequences are not cyclic shifts of the permutation. The subsegment from the $$$2$$$-nd to the $$$3$$$-rd positions is $$$1, 2$$$, it coincides with the permutation. The subsegment from the $$$3$$$ to the $$$4$$$ positions is $$$2, 2$$$, its subsequences are not cyclic shifts of the permutation.
Java 8
standard input
[ "dp", "math", "data structures", "dfs and similar", "trees" ]
4aaeff1b38d501daf9a877667e075d49
The first line contains three integers $$$n$$$, $$$m$$$, $$$q$$$ ($$$1 \le n, m, q \le 2 \cdot 10^5$$$) — the length of the permutation $$$p$$$, the length of the array $$$a$$$ and the number of queries. The next line contains $$$n$$$ integers from $$$1$$$ to $$$n$$$, where the $$$i$$$-th of them is the $$$i$$$-th element of the permutation. Each integer from $$$1$$$ to $$$n$$$ appears exactly once. The next line contains $$$m$$$ integers from $$$1$$$ to $$$n$$$, the $$$i$$$-th of them is the $$$i$$$-th element of the array $$$a$$$. The next $$$q$$$ lines describe queries. The $$$i$$$-th of these lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le m$$$), meaning that the $$$i$$$-th query is about the subsegment of the array from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive.
2,000
Print a single string of length $$$q$$$, consisting of $$$0$$$ and $$$1$$$, the digit on the $$$i$$$-th positions should be $$$1$$$, if the subsegment of array $$$a$$$ from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive, contains a subsequence that is a cyclic shift of $$$p$$$, and $$$0$$$ otherwise.
standard output
PASSED
c471e886233a33d7a30126092a89463f
train_002.jsonl
1553965800
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation $$$p$$$ of length $$$n$$$, and Skynyrd bought an array $$$a$$$ of length $$$m$$$, consisting of integers from $$$1$$$ to $$$n$$$. Lynyrd and Skynyrd became bored, so they asked you $$$q$$$ queries, each of which has the following form: "does the subsegment of $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, have a subsequence that is a cyclic shift of $$$p$$$?" Please answer the queries.A permutation of length $$$n$$$ is a sequence of $$$n$$$ integers such that each integer from $$$1$$$ to $$$n$$$ appears exactly once in it.A cyclic shift of a permutation $$$(p_1, p_2, \ldots, p_n)$$$ is a permutation $$$(p_i, p_{i + 1}, \ldots, p_{n}, p_1, p_2, \ldots, p_{i - 1})$$$ for some $$$i$$$ from $$$1$$$ to $$$n$$$. For example, a permutation $$$(2, 1, 3)$$$ has three distinct cyclic shifts: $$$(2, 1, 3)$$$, $$$(1, 3, 2)$$$, $$$(3, 2, 1)$$$.A subsequence of a subsegment of array $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, is a sequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ for some $$$i_1, i_2, \ldots, i_k$$$ such that $$$l \leq i_1 &lt; i_2 &lt; \ldots &lt; i_k \leq r$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author lewin */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); BLynyrdSkynyrd solver = new BLynyrdSkynyrd(); solver.solve(1, in, out); out.close(); } static class BLynyrdSkynyrd { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(), m = in.nextInt(), q = in.nextInt(); int[] p = in.readIntArrayAndDecrementOne(n); int[] arr = in.readIntArrayAndDecrementOne(m); int[] prev = new int[n]; prev[p[0]] = p[n - 1]; for (int i = 1; i < n; i++) { prev[p[i]] = p[i - 1]; } int[][] ap = new int[20][m]; int[] last = new int[n]; Arrays.fill(last, -1); for (int i = 0; i < m; i++) { ap[0][i] = last[prev[arr[i]]]; last[arr[i]] = i; } for (int level = 1; level < ap.length; level++) { for (int j = 0; j < m; j++) { ap[level][j] = ap[level - 1][j] == -1 ? -1 : ap[level - 1][ap[level - 1][j]]; } } int[] pn = new int[m]; for (int i = 0; i < m; i++) { pn[i] = i; for (int k = 0; k < ap.length; k++) { if ((((n - 1) >> k) & 1) == 1 && pn[i] != -1) { pn[i] = ap[k][pn[i]]; } } pn[i] = -pn[i]; } RmqSparseTable rmq = new RmqSparseTable(pn); char[] ret = new char[q]; for (int i = 0; i < q; i++) { int l = in.nextInt() - 1, r = in.nextInt() - 1; ret[i] = -rmq.min(l, r) >= l ? '1' : '0'; } out.println(new String(ret)); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } static class RmqSparseTable { int[] logTable; int[][] rmq; int[] a; public RmqSparseTable(int[] a) { this.a = a; int n = a.length; logTable = new int[n + 1]; for (int i = 2; i <= n; i++) logTable[i] = logTable[i >> 1] + 1; rmq = new int[logTable[n] + 1][n]; for (int i = 0; i < n; ++i) rmq[0][i] = i; for (int k = 1; (1 << k) < n; ++k) { for (int i = 0; i + (1 << k) <= n; i++) { int x = rmq[k - 1][i]; int y = rmq[k - 1][i + (1 << k - 1)]; rmq[k][i] = a[x] <= a[y] ? x : y; } } } public int min(int i, int j) { int k = logTable[j - i]; int x = rmq[k][i]; int y = rmq[k][j - (1 << k) + 1]; return Math.min(a[x], a[y]); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1 << 16]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int[] readIntArrayAndDecrementOne(int tokens) { int[] ret = new int[tokens]; for (int i = 0; i < tokens; i++) { ret[i] = nextInt() - 1; } return ret; } public int read() { if (this.numChars == -1) { throw new InputMismatchException(); } else { if (this.curChar >= this.numChars) { this.curChar = 0; try { this.numChars = this.stream.read(this.buf); } catch (IOException var2) { throw new InputMismatchException(); } if (this.numChars <= 0) { return -1; } } return this.buf[this.curChar++]; } } public int nextInt() { int c; for (c = this.read(); isSpaceChar(c); c = this.read()) { ; } byte sgn = 1; if (c == 45) { sgn = -1; c = this.read(); } int res = 0; while (c >= 48 && c <= 57) { res *= 10; res += c - 48; c = this.read(); if (isSpaceChar(c)) { return res * sgn; } } throw new InputMismatchException(); } public static boolean isSpaceChar(int c) { return c == 32 || c == 10 || c == 13 || c == 9 || c == -1; } } }
Java
["3 6 3\n2 1 3\n1 2 3 1 2 3\n1 5\n2 6\n3 5", "2 4 3\n2 1\n1 1 2 2\n1 2\n2 3\n3 4"]
2 seconds
["110", "010"]
NoteIn the first example the segment from the $$$1$$$-st to the $$$5$$$-th positions is $$$1, 2, 3, 1, 2$$$. There is a subsequence $$$1, 3, 2$$$ that is a cyclic shift of the permutation. The subsegment from the $$$2$$$-nd to the $$$6$$$-th positions also contains a subsequence $$$2, 1, 3$$$ that is equal to the permutation. The subsegment from the $$$3$$$-rd to the $$$5$$$-th positions is $$$3, 1, 2$$$, there is only one subsequence of length $$$3$$$ ($$$3, 1, 2$$$), but it is not a cyclic shift of the permutation.In the second example the possible cyclic shifts are $$$1, 2$$$ and $$$2, 1$$$. The subsegment from the $$$1$$$-st to the $$$2$$$-nd positions is $$$1, 1$$$, its subsequences are not cyclic shifts of the permutation. The subsegment from the $$$2$$$-nd to the $$$3$$$-rd positions is $$$1, 2$$$, it coincides with the permutation. The subsegment from the $$$3$$$ to the $$$4$$$ positions is $$$2, 2$$$, its subsequences are not cyclic shifts of the permutation.
Java 8
standard input
[ "dp", "math", "data structures", "dfs and similar", "trees" ]
4aaeff1b38d501daf9a877667e075d49
The first line contains three integers $$$n$$$, $$$m$$$, $$$q$$$ ($$$1 \le n, m, q \le 2 \cdot 10^5$$$) — the length of the permutation $$$p$$$, the length of the array $$$a$$$ and the number of queries. The next line contains $$$n$$$ integers from $$$1$$$ to $$$n$$$, where the $$$i$$$-th of them is the $$$i$$$-th element of the permutation. Each integer from $$$1$$$ to $$$n$$$ appears exactly once. The next line contains $$$m$$$ integers from $$$1$$$ to $$$n$$$, the $$$i$$$-th of them is the $$$i$$$-th element of the array $$$a$$$. The next $$$q$$$ lines describe queries. The $$$i$$$-th of these lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le m$$$), meaning that the $$$i$$$-th query is about the subsegment of the array from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive.
2,000
Print a single string of length $$$q$$$, consisting of $$$0$$$ and $$$1$$$, the digit on the $$$i$$$-th positions should be $$$1$$$, if the subsegment of array $$$a$$$ from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive, contains a subsequence that is a cyclic shift of $$$p$$$, and $$$0$$$ otherwise.
standard output
PASSED
a1dd0ec2282c63e84507f9ac1004db50
train_002.jsonl
1553965800
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation $$$p$$$ of length $$$n$$$, and Skynyrd bought an array $$$a$$$ of length $$$m$$$, consisting of integers from $$$1$$$ to $$$n$$$. Lynyrd and Skynyrd became bored, so they asked you $$$q$$$ queries, each of which has the following form: "does the subsegment of $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, have a subsequence that is a cyclic shift of $$$p$$$?" Please answer the queries.A permutation of length $$$n$$$ is a sequence of $$$n$$$ integers such that each integer from $$$1$$$ to $$$n$$$ appears exactly once in it.A cyclic shift of a permutation $$$(p_1, p_2, \ldots, p_n)$$$ is a permutation $$$(p_i, p_{i + 1}, \ldots, p_{n}, p_1, p_2, \ldots, p_{i - 1})$$$ for some $$$i$$$ from $$$1$$$ to $$$n$$$. For example, a permutation $$$(2, 1, 3)$$$ has three distinct cyclic shifts: $$$(2, 1, 3)$$$, $$$(1, 3, 2)$$$, $$$(3, 2, 1)$$$.A subsequence of a subsegment of array $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, is a sequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ for some $$$i_1, i_2, \ldots, i_k$$$ such that $$$l \leq i_1 &lt; i_2 &lt; \ldots &lt; i_k \leq r$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.FilterInputStream; import java.io.BufferedInputStream; import java.io.InputStream; /** * @author khokharnikunj8 */ public class Main { public static void main(String[] args) { new Thread(null, new Runnable() { public void run() { new Main().solve(); } }, "1", 1 << 26).start(); } void solve() { InputStream inputStream = System.in; OutputStream outputStream = System.out; ScanReader in = new ScanReader(inputStream); PrintWriter out = new PrintWriter(outputStream); BLynyrdSkynyrd solver = new BLynyrdSkynyrd(); solver.solve(1, in, out); out.close(); } static class BLynyrdSkynyrd { int[][] last; public void solve(int testNumber, ScanReader in, PrintWriter out) { int n = in.scanInt(); int m = in.scanInt(); int q = in.scanInt(); int[] permutation = new int[n]; for (int i = 0; i < n; i++) permutation[i] = in.scanInt() - 1; int[] ar = new int[m]; for (int i = 0; i < m; i++) ar[i] = in.scanInt() - 1; int[] prev = new int[n]; prev[permutation[0]] = permutation[n - 1]; for (int i = 0; i < n - 1; i++) prev[permutation[i + 1]] = permutation[i]; last = new int[m][20]; for (int i = 0; i < m; i++) Arrays.fill(last[i], -1); int pos[] = new int[n]; Arrays.fill(pos, -1); for (int i = 0; i < m; i++) { pos[ar[i]] = i; last[i][0] = pos[prev[ar[i]]]; } for (int j = 1; j < 20; j++) { for (int i = 0; i < m; i++) { if (last[i][j - 1] != -1) last[i][j] = last[last[i][j - 1]][j - 1]; } } int LOL = n - 1; int anss[] = new int[m]; for (int i = 0; i < m; i++) { int current = i; for (int j = 19; j >= 0 && current != -1; j--) { if ((LOL & (1 << j)) != 0) current = last[current][j]; } anss[i] = current; // out.println(anss[i]); } int[] temp = new int[m + 1]; for (int i = 1; i <= m; i++) temp[i] = anss[i - 1]; SegmentTreeMax seg = new SegmentTreeMax(temp, m); int queries[][] = new int[q][2]; for (int i = 0; i < q; i++) { queries[i][0] = in.scanInt(); queries[i][1] = in.scanInt(); int query = seg.query(queries[i][0], queries[i][1]); // out.print((query + 1) + " "); if (query + 1 >= queries[i][0] && query + 1 <= queries[i][1]) out.print(1); else out.print(0); // out.println(); } } } static class ScanReader { private byte[] buf = new byte[4 * 1024]; private int index; private BufferedInputStream in; private int total; public ScanReader(InputStream inputStream) { in = new BufferedInputStream(inputStream); } private int scan() { if (index >= total) { index = 0; try { total = in.read(buf); } catch (Exception e) { e.printStackTrace(); } if (total <= 0) return -1; } return buf[index++]; } public int scanInt() { int integer = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { integer *= 10; integer += n - '0'; n = scan(); } } return neg * integer; } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; else return false; } } static class SegmentTreeMax { int n; int[] t; int[] data; public SegmentTreeMax(int[] data, int n) { this.data = data; this.n = n; this.t = new int[2 * (n + 2)]; build(); } void build() { for (int i = 0; i < n; i++) t[i + n] = (data[i + 1] == 1000000001 ? -1 : data[i + 1]); for (int i = n - 1; i > 0; --i) t[i] = Math.max(t[i << 1], t[i << 1 | 1]); } public int query(int l, int r) { int res = -1; for (l += n - 1, r += n; l < r; l >>= 1, r >>= 1) { if ((l & 1) != 0) res = Math.max(res, t[l++]); if ((r & 1) != 0) res = Math.max(res, t[--r]); } return res; } } }
Java
["3 6 3\n2 1 3\n1 2 3 1 2 3\n1 5\n2 6\n3 5", "2 4 3\n2 1\n1 1 2 2\n1 2\n2 3\n3 4"]
2 seconds
["110", "010"]
NoteIn the first example the segment from the $$$1$$$-st to the $$$5$$$-th positions is $$$1, 2, 3, 1, 2$$$. There is a subsequence $$$1, 3, 2$$$ that is a cyclic shift of the permutation. The subsegment from the $$$2$$$-nd to the $$$6$$$-th positions also contains a subsequence $$$2, 1, 3$$$ that is equal to the permutation. The subsegment from the $$$3$$$-rd to the $$$5$$$-th positions is $$$3, 1, 2$$$, there is only one subsequence of length $$$3$$$ ($$$3, 1, 2$$$), but it is not a cyclic shift of the permutation.In the second example the possible cyclic shifts are $$$1, 2$$$ and $$$2, 1$$$. The subsegment from the $$$1$$$-st to the $$$2$$$-nd positions is $$$1, 1$$$, its subsequences are not cyclic shifts of the permutation. The subsegment from the $$$2$$$-nd to the $$$3$$$-rd positions is $$$1, 2$$$, it coincides with the permutation. The subsegment from the $$$3$$$ to the $$$4$$$ positions is $$$2, 2$$$, its subsequences are not cyclic shifts of the permutation.
Java 8
standard input
[ "dp", "math", "data structures", "dfs and similar", "trees" ]
4aaeff1b38d501daf9a877667e075d49
The first line contains three integers $$$n$$$, $$$m$$$, $$$q$$$ ($$$1 \le n, m, q \le 2 \cdot 10^5$$$) — the length of the permutation $$$p$$$, the length of the array $$$a$$$ and the number of queries. The next line contains $$$n$$$ integers from $$$1$$$ to $$$n$$$, where the $$$i$$$-th of them is the $$$i$$$-th element of the permutation. Each integer from $$$1$$$ to $$$n$$$ appears exactly once. The next line contains $$$m$$$ integers from $$$1$$$ to $$$n$$$, the $$$i$$$-th of them is the $$$i$$$-th element of the array $$$a$$$. The next $$$q$$$ lines describe queries. The $$$i$$$-th of these lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le m$$$), meaning that the $$$i$$$-th query is about the subsegment of the array from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive.
2,000
Print a single string of length $$$q$$$, consisting of $$$0$$$ and $$$1$$$, the digit on the $$$i$$$-th positions should be $$$1$$$, if the subsegment of array $$$a$$$ from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive, contains a subsequence that is a cyclic shift of $$$p$$$, and $$$0$$$ otherwise.
standard output
PASSED
be4d650bb2c5b6b8d90b20a0d8c0e8e6
train_002.jsonl
1553965800
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation $$$p$$$ of length $$$n$$$, and Skynyrd bought an array $$$a$$$ of length $$$m$$$, consisting of integers from $$$1$$$ to $$$n$$$. Lynyrd and Skynyrd became bored, so they asked you $$$q$$$ queries, each of which has the following form: "does the subsegment of $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, have a subsequence that is a cyclic shift of $$$p$$$?" Please answer the queries.A permutation of length $$$n$$$ is a sequence of $$$n$$$ integers such that each integer from $$$1$$$ to $$$n$$$ appears exactly once in it.A cyclic shift of a permutation $$$(p_1, p_2, \ldots, p_n)$$$ is a permutation $$$(p_i, p_{i + 1}, \ldots, p_{n}, p_1, p_2, \ldots, p_{i - 1})$$$ for some $$$i$$$ from $$$1$$$ to $$$n$$$. For example, a permutation $$$(2, 1, 3)$$$ has three distinct cyclic shifts: $$$(2, 1, 3)$$$, $$$(1, 3, 2)$$$, $$$(3, 2, 1)$$$.A subsequence of a subsegment of array $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, is a sequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ for some $$$i_1, i_2, \ldots, i_k$$$ such that $$$l \leq i_1 &lt; i_2 &lt; \ldots &lt; i_k \leq r$$$.
256 megabytes
import java.awt.*; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; import java.util.List; import static java.lang.Math.abs; import static java.lang.Math.max; import static java.lang.Math.min; public class ArchiveSolving implements Runnable{ // SOLUTION AT THE TOP OF CODE!!! // HACK ME PLEASE IF YOU CAN!!! // PLEASE!!! // PLEASE!!! // PLEASE!!! @SuppressWarnings("unused") private final static Random rnd = new Random(); private final static String fileName = ""; private static long BASE = 1000 * 1000 * 1000 + 7, PHI = BASE - 1; private static long MODULO = BASE; // THERE SOLUTION STARTS!!! private void solve() { int n = readInt(); int m = readInt(); int q = readInt(); int[] p = readIntArrayWithDecrease(n); int[] a = readIntArrayWithDecrease(m); int[] pIndexes = new int[n]; for (int i = 0; i < n; ++i) { pIndexes[p[i]] = i; } for (int j = 0; j < m; ++j){ a[j] = pIndexes[a[j]]; } Point[] queries = readPointArray(q); // String expected = getBruteAnswer(n, p, m, a, q, queries); String answers = getAnswer(n, p, m, a, q, queries); // out.println(expected); out.println(answers); } static String getAnswer( int n, int[] p, int m, int[] a, int q, Point[] queries) { int[] counts = new int[n]; for (int value : a) { counts[value]++; } int[][] indexes = new int[n][]; for (int i = 0; i < n; ++i) { indexes[i] = new int[counts[i]]; } for (int j = m - 1; j >= 0; --j) { indexes[a[j]][--counts[a[j]]] = j; } final int INF = m + 1; final int MAX_BIT = 19; int[][] table = new int[MAX_BIT][m + 2]; for (int[] row : table) { Arrays.fill(row, INF); } for (int j = 0; j < m; ++j) { int value = a[j]; if (value == n - 1) { table[0][j] = INF; } else { int[] nextIndexes = indexes[value + 1]; int index = Arrays.binarySearch(nextIndexes, j); index = ~index; if (index < nextIndexes.length) { table[0][j] = nextIndexes[index]; } else { table[0][j] = INF; } } } for (int bit = 0; bit < MAX_BIT - 1; ++bit) { for (int j = 0; j < m; ++j) { table[bit + 1][j] = table[bit][table[bit][j]]; } } int[] lastIndexes = new int[m]; Arrays.fill(lastIndexes, INF); int[] zeroIndexes = indexes[0]; for (int j = 0; j < m; ++j) { int cur = j; int value = a[j]; int delta = n - value - 1; for (int bit = MAX_BIT - 1; bit >= 0; --bit) { if (checkBit(delta, bit)) { cur = table[bit][cur]; } } if (cur == INF) continue; if (a[cur] != n - 1) continue; if (a[j] == 0) { lastIndexes[j] = cur; } else { int zero = Arrays.binarySearch(zeroIndexes, cur); if (zero < 0) { zero = ~zero; } if (zero == zeroIndexes.length) continue; cur = zeroIndexes[zero]; int need = a[j] - 1; for (int bit = MAX_BIT - 1; bit >= 0; --bit) { if (checkBit(need, bit)) { cur = table[bit][cur]; } } if (cur == INF) continue; if (a[cur] != value - 1) continue; lastIndexes[j] = cur; } } Rmq rmq = createRmq(lastIndexes); char[] answers = new char[q]; for (int i = 0; i < q; ++i) { Point query = queries[i]; int start = query.x - 1; int end = query.y - 1; int best = rmq.getMinIndex(start, end); int bestIndex = lastIndexes[best]; if (bestIndex <= end) { answers[i] = '1'; } else { answers[i] = '0'; } } return new String(answers); } interface Rmq { @SuppressWarnings("unused") int getMin(int left, int right); int getMinIndex(int left, int right); } private static class SparseTable implements Rmq { private static final int MAX_BIT = 20; int n; int[] array; SparseTable(int[] array) { this.n = array.length; this.array = array; } int[] lengthMaxBits; int[][] table; int getIndexOfLess(int leftIndex, int rightIndex) { return (array[leftIndex] <= array[rightIndex]) ? leftIndex : rightIndex; } SparseTable build() { this.lengthMaxBits = new int[n + 1]; lengthMaxBits[0] = 0; for (int i = 1; i <= n; ++i) { lengthMaxBits[i] = lengthMaxBits[i - 1]; int length = (1 << lengthMaxBits[i]); if (length + length <= i) ++lengthMaxBits[i]; } this.table = new int[MAX_BIT][n]; table[0] = castInt(order(n)); for (int bit = 0; bit < MAX_BIT - 1; ++bit) { int delta = (1 << bit); for (int i = 0, j = delta; j + delta <= n; ++i, ++j) { table[bit + 1][i] = getIndexOfLess( table[bit][i], table[bit][j] ); } } return this; } @Override public int getMinIndex(int left, int right) { int length = (right - left + 1); int bit = lengthMaxBits[length]; int segmentLength = (1 << bit); return getIndexOfLess( table[bit][left], table[bit][right - segmentLength + 1] ); } @Override public int getMin(int left, int right) { return array[getMinIndex(left, right)]; } } private static Rmq createRmq(int[] array) { return new SparseTable(array).build(); } static String getBruteAnswer(int n, int[] p, int m, int[] a, int q, Point[] queries) { char[] answers = new char[q]; for (int it = 0; it < q; ++it) { int start = queries[it].x - 1, end = queries[it].y - 1; boolean found = false; for (int j = start; j <= end; ++j) { int value = a[j]; int k = j; while (k <= end) { if (a[k] == value) { ++value; if (value == n) break; } ++k; } if (a[j] > 0) { value = 0; while (k <= end) { if (a[k] == value) { ++value; if (value == a[j]) break; } ++k; } } if (k <= end) { found = true; break; } } if (found) { answers[it] = '1'; } else { answers[it] = '0'; } } return new String(answers); } static int square(Point zero, Point a, Point b) { return abs( det(a.x - zero.x, a.y - zero.y, b.x - zero.x, b.y - zero.y) ); } static int det(int a, int b, int c, int d) { return a * d - b * c; } ///////////////////////////////////////////////////////////////////// private final static boolean MULTIPLE_TESTS = true; private final boolean ONLINE_JUDGE = !new File("input.txt").exists(); // private final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; private final static int MAX_STACK_SIZE = 128; private final static boolean OPTIMIZE_READ_NUMBERS = false; ///////////////////////////////////////////////////////////////////// @SuppressWarnings("unused") private static long inverse(long x) { return binpow(x, MODULO - 2); } private static long binpow(long base, long power) { if (power == 0) return 1; if ((power & 1) == 0) { long half = binpow(base, power >> 1); return mult(half, half); } else { long prev = binpow(base, power - 1); return mult(prev, base); } } private static long add(long a, long b) { return (a + b) % MODULO; } @SuppressWarnings("unused") private static long subtract(long a, long b) { return add(a, MODULO - b % MODULO); } private static long mult(long a, long b) { return ((a % MODULO) * (b % MODULO)) % MODULO; } ///////////////////////////////////////////////////////////////////// @SuppressWarnings("unused") void yesNo(boolean yes) { out.println(yes ? "YES" : "NO"); } ///////////////////////////////////////////////////////////////////// public void run(){ try{ timeInit(); Locale.setDefault(Locale.US); init(); if (ONLINE_JUDGE) { solve(); } else { do { try { timeInit(); solve(); time(); out.println(); out.flush(); } catch (NumberFormatException | EOFException e) { break; } } while (MULTIPLE_TESTS); } out.close(); time(); }catch (Exception e){ e.printStackTrace(System.err); System.exit(-1); } } ///////////////////////////////////////////////////////////////////// private BufferedReader in; private OutputWriter out; private StringTokenizer tok = new StringTokenizer(""); public static void main(String[] args){ new Thread(null, new ArchiveSolving(), "", MAX_STACK_SIZE * (1L << 20)).start(); } ///////////////////////////////////////////////////////////////////// private void init() throws FileNotFoundException{ Locale.setDefault(Locale.US); if (ONLINE_JUDGE){ if (fileName.isEmpty()) { in = new BufferedReader(new InputStreamReader(System.in)); out = new OutputWriter(System.out); } else { in = new BufferedReader(new FileReader(fileName + ".in")); out = new OutputWriter(fileName + ".out"); } }else{ in = new BufferedReader(new FileReader("input.txt")); out = new OutputWriter("output.txt"); } } //////////////////////////////////////////////////////////////// private long timeBegin; private void timeInit() { this.timeBegin = System.currentTimeMillis(); } private void time(){ long timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } @SuppressWarnings("unused") private void debug(Object... objects){ if (ONLINE_JUDGE){ for (Object o: objects){ System.err.println(o.toString()); } } } ///////////////////////////////////////////////////////////////////// private String delim = " "; private String readNullableLine() { try { return in.readLine(); } catch (IOException e) { throw new RuntimeIOException(e); } } private String readLine() { String line = readNullableLine(); if (null == line) throw new EOFException(); return line; } private String readString() { while(!tok.hasMoreTokens()){ tok = new StringTokenizer(readLine(), delim); } return tok.nextToken(delim); } ///////////////////////////////////////////////////////////////// private final char NOT_A_SYMBOL = '\0'; @SuppressWarnings("unused") private char readChar() { try { int intValue = in.read(); if (intValue == -1){ return NOT_A_SYMBOL; } return (char) intValue; } catch (IOException e) { throw new RuntimeIOException(e); } } private char[] readCharArray() { return readLine().toCharArray(); } @SuppressWarnings("unused") private char[][] readCharField(int rowsCount) { char[][] field = new char[rowsCount][]; for (int row = 0; row < rowsCount; ++row) { field[row] = readCharArray(); } return field; } ///////////////////////////////////////////////////////////////// private long optimizedReadLong() { int sign = 1; long result = 0; boolean started = false; while (true) { try { int j = in.read(); if (-1 == j) { if (started) return sign * result; throw new NumberFormatException(); } if (j == '-') { if (started) throw new NumberFormatException(); sign = -sign; } if ('0' <= j && j <= '9') { result = result * 10 + j - '0'; started = true; } else if (started) { return sign * result; } } catch (IOException e) { throw new RuntimeIOException(e); } } } private int readInt() { if (!OPTIMIZE_READ_NUMBERS) { return Integer.parseInt(readString()); } else { return (int) optimizedReadLong(); } } private int[] readIntArray(int size) { int[] array = new int[size]; for (int index = 0; index < size; ++index){ array[index] = readInt(); } return array; } @SuppressWarnings("unused") private int[] readSortedIntArray(int size) { Integer[] array = new Integer[size]; for (int index = 0; index < size; ++index) { array[index] = readInt(); } Arrays.sort(array); int[] sortedArray = new int[size]; for (int index = 0; index < size; ++index) { sortedArray[index] = array[index]; } return sortedArray; } private int[] readIntArrayWithDecrease(int size) { int[] array = readIntArray(size); for (int i = 0; i < size; ++i) { array[i]--; } return array; } /////////////////////////////////////////////////////////////////// @SuppressWarnings("unused") private int[][] readIntMatrix(int rowsCount, int columnsCount) { int[][] matrix = new int[rowsCount][]; for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) { matrix[rowIndex] = readIntArray(columnsCount); } return matrix; } @SuppressWarnings("unused") private int[][] readIntMatrixWithDecrease(int rowsCount, int columnsCount) { int[][] matrix = new int[rowsCount][]; for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) { matrix[rowIndex] = readIntArrayWithDecrease(columnsCount); } return matrix; } /////////////////////////////////////////////////////////////////// private long readLong() { if (!OPTIMIZE_READ_NUMBERS) { return Long.parseLong(readString()); } else { return optimizedReadLong(); } } @SuppressWarnings("unused") private long[] readLongArray(int size) { long[] array = new long[size]; for (int index = 0; index < size; ++index){ array[index] = readLong(); } return array; } //////////////////////////////////////////////////////////////////// private double readDouble() { return Double.parseDouble(readString()); } @SuppressWarnings("unused") private double[] readDoubleArray(int size) { double[] array = new double[size]; for (int index = 0; index < size; ++index){ array[index] = readDouble(); } return array; } //////////////////////////////////////////////////////////////////// @SuppressWarnings("unused") private BigInteger readBigInteger() { return new BigInteger(readString()); } @SuppressWarnings("unused") private BigDecimal readBigDecimal() { return new BigDecimal(readString()); } ///////////////////////////////////////////////////////////////////// private Point readPoint() { int x = readInt(); int y = readInt(); return new Point(x, y); } @SuppressWarnings("unused") private Point[] readPointArray(int size) { Point[] array = new Point[size]; for (int index = 0; index < size; ++index){ array[index] = readPoint(); } return array; } ///////////////////////////////////////////////////////////////////// @Deprecated @SuppressWarnings("unused") private List<Integer>[] readGraph(int vertexNumber, int edgeNumber) { @SuppressWarnings("unchecked") List<Integer>[] graph = new List[vertexNumber]; for (int index = 0; index < vertexNumber; ++index){ graph[index] = new ArrayList<>(); } while (edgeNumber-- > 0){ int from = readInt() - 1; int to = readInt() - 1; graph[from].add(to); graph[to].add(from); } return graph; } private static class GraphBuilder { final int size; final List<Integer>[] edges; static GraphBuilder createInstance(int size) { @SuppressWarnings("unchecked") List<Integer>[] edges = new List[size]; for (int v = 0; v < size; ++v) { edges[v] = new ArrayList<>(); } return new GraphBuilder(edges); } private GraphBuilder(List<Integer>[] edges) { this.size = edges.length; this.edges = edges; } public void addEdge(int from, int to) { addDirectedEdge(from, to); addDirectedEdge(to, from); } public void addDirectedEdge(int from, int to) { edges[from].add(to); } public int[][] build() { int[][] graph = new int[size][]; for (int v = 0; v < size; ++v) { List<Integer> vEdges = edges[v]; graph[v] = castInt(vEdges); } return graph; } } @SuppressWarnings("unused") private final static int ZERO_INDEXATION = 0, ONE_INDEXATION = 1; @SuppressWarnings("unused") private int[][] readUnweightedGraph(int vertexNumber, int edgesNumber) { return readUnweightedGraph(vertexNumber, edgesNumber, ONE_INDEXATION, false); } private int[][] readUnweightedGraph(int vertexNumber, int edgesNumber, int indexation, boolean directed ) { GraphBuilder graphBuilder = GraphBuilder.createInstance(vertexNumber); for (int i = 0; i < edgesNumber; ++i) { int from = readInt() - indexation; int to = readInt() - indexation; if (directed) graphBuilder.addDirectedEdge(from, to); else graphBuilder.addEdge(from, to); } return graphBuilder.build(); } private static class Edge { int to; int w; Edge(int to, int w) { this.to = to; this.w = w; } } @SuppressWarnings("unused") private Edge[][] readWeightedGraph(int vertexNumber, int edgesNumber) { return readWeightedGraph(vertexNumber, edgesNumber, ONE_INDEXATION, false); } private Edge[][] readWeightedGraph(int vertexNumber, int edgesNumber, int indexation, boolean directed) { @SuppressWarnings("unchecked") List<Edge>[] graph = new List[vertexNumber]; for (int v = 0; v < vertexNumber; ++v) { graph[v] = new ArrayList<>(); } while (edgesNumber --> 0) { int from = readInt() - indexation; int to = readInt() - indexation; int w = readInt(); graph[from].add(new Edge(to, w)); if (!directed) graph[to].add(new Edge(from, w)); } Edge[][] graphArrays = new Edge[vertexNumber][]; for (int v = 0; v < vertexNumber; ++v) { graphArrays[v] = graph[v].toArray(new Edge[0]); } return graphArrays; } ///////////////////////////////////////////////////////////////////// private static class IntIndexPair { @SuppressWarnings("unused") static Comparator<IntIndexPair> increaseComparator = new Comparator<ArchiveSolving.IntIndexPair>() { @Override public int compare(ArchiveSolving.IntIndexPair indexPair1, ArchiveSolving.IntIndexPair indexPair2) { int value1 = indexPair1.value; int value2 = indexPair2.value; if (value1 != value2) return value1 - value2; int index1 = indexPair1.index; int index2 = indexPair2.index; return index1 - index2; } }; @SuppressWarnings("unused") static Comparator<IntIndexPair> decreaseComparator = new Comparator<ArchiveSolving.IntIndexPair>() { @Override public int compare(ArchiveSolving.IntIndexPair indexPair1, ArchiveSolving.IntIndexPair indexPair2) { int value1 = indexPair1.value; int value2 = indexPair2.value; if (value1 != value2) return -(value1 - value2); int index1 = indexPair1.index; int index2 = indexPair2.index; return index1 - index2; } }; @SuppressWarnings("unused") static IntIndexPair[] from(int[] array) { IntIndexPair[] iip = new IntIndexPair[array.length]; for (int i = 0; i < array.length; ++i) { iip[i] = new IntIndexPair(array[i], i); } return iip; } int value, index; IntIndexPair(int value, int index) { super(); this.value = value; this.index = index; } @SuppressWarnings("unused") int getRealIndex() { return index + 1; } } @SuppressWarnings("unused") private IntIndexPair[] readIntIndexArray(int size) { IntIndexPair[] array = new IntIndexPair[size]; for (int index = 0; index < size; ++index) { array[index] = new IntIndexPair(readInt(), index); } return array; } ///////////////////////////////////////////////////////////////////// private static class OutputWriter extends PrintWriter { final int DEFAULT_PRECISION = 12; private int precision; private String format, formatWithSpace; { precision = DEFAULT_PRECISION; format = createFormat(precision); formatWithSpace = format + " "; } OutputWriter(OutputStream out) { super(out); } OutputWriter(String fileName) throws FileNotFoundException { super(fileName); } int getPrecision() { return precision; } void setPrecision(int precision) { precision = max(0, precision); this.precision = precision; format = createFormat(precision); formatWithSpace = format + " "; } String createFormat(int precision){ return "%." + precision + "f"; } @Override public void print(double d){ printf(format, d); } @Override public void println(double d){ print(d); println(); } void printWithSpace(double d){ printf(formatWithSpace, d); } void printAll(double...d){ for (int i = 0; i < d.length - 1; ++i){ printWithSpace(d[i]); } print(d[d.length - 1]); } @SuppressWarnings("unused") void printlnAll(double... d){ printAll(d); println(); } void printAll(int... array) { for (int value : array) { print(value + " "); } } @SuppressWarnings("unused") void printlnAll(int... array) { printAll(array); println(); } void printIndexes(int... indexes) { for (int index : indexes) { print((index + 1) + " "); } } @SuppressWarnings("unused") void printlnIndexes(int... indexes) { printIndexes(indexes); println(); } void printAll(long... array) { for (long value : array) { print(value + " "); } } @SuppressWarnings("unused") void printlnAll(long... array) { printAll(array); println(); } } ///////////////////////////////////////////////////////////////////// private static class EOFException extends RuntimeException { EOFException() { super(); } } private static class RuntimeIOException extends RuntimeException { /** * */ private static final long serialVersionUID = -6463830523020118289L; RuntimeIOException(Throwable cause) { super(cause); } } ///////////////////////////////////////////////////////////////////// //////////////// Some useful constants andTo functions //////////////// ///////////////////////////////////////////////////////////////////// private static void swap(int[] array, int i, int j) { if (i != j) { int tmp = array[i]; array[i] = array[j]; array[j] = tmp; } } private static <T> void swap(T[] array, int i, int j) { if (i != j) { T tmp = array[i]; array[i] = array[j]; array[j] = tmp; } } private static final int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; private static final int[][] steps8 = { {-1, 0}, {1, 0}, {0, -1}, {0, 1}, {-1, -1}, {1, 1}, {1, -1}, {-1, 1} }; @SuppressWarnings("unused") private static boolean checkCell(int row, int rowsCount, int column, int columnsCount) { return checkIndex(row, rowsCount) && checkIndex(column, columnsCount); } private static boolean checkIndex(int index, int lim){ return (0 <= index && index < lim); } ///////////////////////////////////////////////////////////////////// private static int getBit(long mask, int bit) { return (int)((mask >> bit) & 1); } @SuppressWarnings("unused") private static boolean checkBit(long mask, int bit){ return getBit(mask, bit) != 0; } ///////////////////////////////////////////////////////////////////// @SuppressWarnings("unused") private static long getSum(int[] array) { long sum = 0; for (int value: array) { sum += value; } return sum; } @SuppressWarnings("unused") private static Point getMinMax(int[] array) { int min = array[0]; int max = array[0]; for (int index = 0, size = array.length; index < size; ++index, ++index) { int value = array[index]; if (index == size - 1) { min = min(min, value); max = max(max, value); } else { int otherValue = array[index + 1]; if (value <= otherValue) { min = min(min, value); max = max(max, otherValue); } else { min = min(min, otherValue); max = max(max, value); } } } return new Point(min, max); } ///////////////////////////////////////////////////////////////////// @SuppressWarnings("unused") private static boolean isPrime(int x) { if (x < 2) return false; for (int d = 2; d * d <= x; ++d) { if (x % d == 0) return false; } return true; } @SuppressWarnings("unused") private static int[] getPrimes(int n) { boolean[] used = new boolean[n]; 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; } ///////////////////////////////////////////////////////////////////// @SuppressWarnings("unused") static int[] getDivisors(int value) { List<Integer> divisors = new ArrayList<>(); for (int divisor = 1; divisor * divisor <= value; ++divisor) { if (value % divisor == 0) { divisors.add(divisor); if (divisor * divisor != value) { divisors.add(value / divisor); } } } return castInt(divisors); } @SuppressWarnings("unused") static long[] getDivisors(long value) { List<Long> divisors = new ArrayList<>(); for (long divisor = 1; divisor * divisor <= value; ++divisor) { if (value % divisor == 0) { divisors.add(divisor); if (divisor * divisor != value) { divisors.add(value / divisor); } } } return castLong(divisors); } ///////////////////////////////////////////////////////////////////// @SuppressWarnings("unused") 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)); } ///////////////////////////////////////////////////////////////////// private static int[] castInt(List<Integer> list) { int[] array = new int[list.size()]; for (int i = 0; i < array.length; ++i) { array[i] = list.get(i); } return array; } @SuppressWarnings("unused") private static long[] castLong(List<Long> list) { long[] array = new long[list.size()]; for (int i = 0; i < array.length; ++i) { array[i] = list.get(i); } return array; } ///////////////////////////////////////////////////////////////////// /** * Generates list with keys 0..<n * @param n - exclusive limit of sequence */ @SuppressWarnings("unused") private static List<Integer> order(int n) { List<Integer> sequence = new ArrayList<>(); for (int i = 0; i < n; ++i) { sequence.add(i); } return sequence; } @SuppressWarnings("unused") private static List<Integer> shuffled(List<Integer> list) { Collections.shuffle(list, rnd); return list; } }
Java
["3 6 3\n2 1 3\n1 2 3 1 2 3\n1 5\n2 6\n3 5", "2 4 3\n2 1\n1 1 2 2\n1 2\n2 3\n3 4"]
2 seconds
["110", "010"]
NoteIn the first example the segment from the $$$1$$$-st to the $$$5$$$-th positions is $$$1, 2, 3, 1, 2$$$. There is a subsequence $$$1, 3, 2$$$ that is a cyclic shift of the permutation. The subsegment from the $$$2$$$-nd to the $$$6$$$-th positions also contains a subsequence $$$2, 1, 3$$$ that is equal to the permutation. The subsegment from the $$$3$$$-rd to the $$$5$$$-th positions is $$$3, 1, 2$$$, there is only one subsequence of length $$$3$$$ ($$$3, 1, 2$$$), but it is not a cyclic shift of the permutation.In the second example the possible cyclic shifts are $$$1, 2$$$ and $$$2, 1$$$. The subsegment from the $$$1$$$-st to the $$$2$$$-nd positions is $$$1, 1$$$, its subsequences are not cyclic shifts of the permutation. The subsegment from the $$$2$$$-nd to the $$$3$$$-rd positions is $$$1, 2$$$, it coincides with the permutation. The subsegment from the $$$3$$$ to the $$$4$$$ positions is $$$2, 2$$$, its subsequences are not cyclic shifts of the permutation.
Java 8
standard input
[ "dp", "math", "data structures", "dfs and similar", "trees" ]
4aaeff1b38d501daf9a877667e075d49
The first line contains three integers $$$n$$$, $$$m$$$, $$$q$$$ ($$$1 \le n, m, q \le 2 \cdot 10^5$$$) — the length of the permutation $$$p$$$, the length of the array $$$a$$$ and the number of queries. The next line contains $$$n$$$ integers from $$$1$$$ to $$$n$$$, where the $$$i$$$-th of them is the $$$i$$$-th element of the permutation. Each integer from $$$1$$$ to $$$n$$$ appears exactly once. The next line contains $$$m$$$ integers from $$$1$$$ to $$$n$$$, the $$$i$$$-th of them is the $$$i$$$-th element of the array $$$a$$$. The next $$$q$$$ lines describe queries. The $$$i$$$-th of these lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le m$$$), meaning that the $$$i$$$-th query is about the subsegment of the array from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive.
2,000
Print a single string of length $$$q$$$, consisting of $$$0$$$ and $$$1$$$, the digit on the $$$i$$$-th positions should be $$$1$$$, if the subsegment of array $$$a$$$ from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive, contains a subsequence that is a cyclic shift of $$$p$$$, and $$$0$$$ otherwise.
standard output
PASSED
876fb1949f87f3e97868645a0d4d0ec5
train_002.jsonl
1553965800
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation $$$p$$$ of length $$$n$$$, and Skynyrd bought an array $$$a$$$ of length $$$m$$$, consisting of integers from $$$1$$$ to $$$n$$$. Lynyrd and Skynyrd became bored, so they asked you $$$q$$$ queries, each of which has the following form: "does the subsegment of $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, have a subsequence that is a cyclic shift of $$$p$$$?" Please answer the queries.A permutation of length $$$n$$$ is a sequence of $$$n$$$ integers such that each integer from $$$1$$$ to $$$n$$$ appears exactly once in it.A cyclic shift of a permutation $$$(p_1, p_2, \ldots, p_n)$$$ is a permutation $$$(p_i, p_{i + 1}, \ldots, p_{n}, p_1, p_2, \ldots, p_{i - 1})$$$ for some $$$i$$$ from $$$1$$$ to $$$n$$$. For example, a permutation $$$(2, 1, 3)$$$ has three distinct cyclic shifts: $$$(2, 1, 3)$$$, $$$(1, 3, 2)$$$, $$$(3, 2, 1)$$$.A subsequence of a subsegment of array $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, is a sequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ for some $$$i_1, i_2, \ldots, i_k$$$ such that $$$l \leq i_1 &lt; i_2 &lt; \ldots &lt; i_k \leq r$$$.
256 megabytes
import java.io.FileInputStream; import java.util.*; import static java.lang.Math.max; import static java.lang.Math.min; public class TaskB { int INF = 1000100; int n, m, q; int[] ps, as; int[] dp; int[][] aft; Map<Integer, Integer> mp = new HashMap<>(); Map<Integer, ArrayList<Integer>> ids = new HashMap<>(); int get(int i, int j){ //System.out.println(i + " " + j); if(i<0 || i>=m || j>(m-i) || j<=0 ) return INF; int k=0; while((1<<k) < j){ k++; } if((1<<k) == j){ return aft[i][k]; }else{ int ii = get(i, 1<<(k-1)); return get(ii, j - (1<<(k-1)) + 1); } } int upper_bound(List<Integer> ls, int t){ int ln = ls.size(); int l = 0, r = ln-1; if(ls.get(r)<=t) return -1; if(ls.get(0)>t) return ls.get(0); while(l<=r){ int m = l + (r-l)/2; if(ls.get(m)<=t){ l = m + 1; }else{ r = m - 1; } } return ls.get(l); } int low_bound(List<Integer> ls, int t){ int ln = ls.size(); int l = 0, r = ln-1; if(ls.get(r)<t) return ls.get(r); if(ls.get(0)>=t) return -1; while(l<=r){ int m = l + (r-l)/2; if(ls.get(m)<t){ l = m + 1; }else{ r = m - 1; } } return ls.get(r); } void solve() throws Exception { Scanner sc = new Scanner(System.in); n = sc.nextInt(); m = sc.nextInt(); q = sc.nextInt(); ps = new int[n]; as = new int[m]; for (int i = 0; i < n; i++) { ps[i] = sc.nextInt(); mp.put(ps[i], i); } for (int i = 0; i < m; i++) { as[i] = sc.nextInt(); int a = as[i]; if(!ids.containsKey(a)){ ids.put(a, new ArrayList<>()); } ids.get(a).add(i); } aft = new int[m][31]; for(int i=m-1; i>=0; i--){ int a = as[i]; int api = mp.get(a); int bpi = (api + 1) % n; int b = ps[bpi]; //System.out.println(b + " " + i + " " + ids.get(b)); int bi = INF; if(ids.get(b)!=null) { bi = upper_bound(ids.get(b), i); } aft[i][0] = i; for(int j=1; j<31; j++){ aft[i][j] = get(bi, (1<<j)-1); //System.out.println(i + " " + j + " " + aft[i][j]); } } //System.out.println(get(1, 3)); dp = new int[m]; int ci = INF; for(int i=m-1; i>=0; i--){ ci = min(ci, get(i, n)); dp[i] = ci; //System.out.println(i + "=====" + dp[i]); } int[] res = new int[q]; StringBuffer sb = new StringBuffer(); for(int i=0; i<q; i++){ int l,r; l = sc.nextInt(); r= sc.nextInt(); l--; r--; int rr = dp[l]; if(rr<=r){ res[i] = 1; }else{ res[i] = 0; } if(n==1) res[i] = 1; sb.append(res[i]); //System.out.printf("%d", res[i]); } System.out.println(sb.toString()); System.out.println(""); } public static void main(String[] args) throws Exception { //System.setIn(new FileInputStream("inputs/b.in")); TaskB s = new TaskB(); s.solve(); } }
Java
["3 6 3\n2 1 3\n1 2 3 1 2 3\n1 5\n2 6\n3 5", "2 4 3\n2 1\n1 1 2 2\n1 2\n2 3\n3 4"]
2 seconds
["110", "010"]
NoteIn the first example the segment from the $$$1$$$-st to the $$$5$$$-th positions is $$$1, 2, 3, 1, 2$$$. There is a subsequence $$$1, 3, 2$$$ that is a cyclic shift of the permutation. The subsegment from the $$$2$$$-nd to the $$$6$$$-th positions also contains a subsequence $$$2, 1, 3$$$ that is equal to the permutation. The subsegment from the $$$3$$$-rd to the $$$5$$$-th positions is $$$3, 1, 2$$$, there is only one subsequence of length $$$3$$$ ($$$3, 1, 2$$$), but it is not a cyclic shift of the permutation.In the second example the possible cyclic shifts are $$$1, 2$$$ and $$$2, 1$$$. The subsegment from the $$$1$$$-st to the $$$2$$$-nd positions is $$$1, 1$$$, its subsequences are not cyclic shifts of the permutation. The subsegment from the $$$2$$$-nd to the $$$3$$$-rd positions is $$$1, 2$$$, it coincides with the permutation. The subsegment from the $$$3$$$ to the $$$4$$$ positions is $$$2, 2$$$, its subsequences are not cyclic shifts of the permutation.
Java 8
standard input
[ "dp", "math", "data structures", "dfs and similar", "trees" ]
4aaeff1b38d501daf9a877667e075d49
The first line contains three integers $$$n$$$, $$$m$$$, $$$q$$$ ($$$1 \le n, m, q \le 2 \cdot 10^5$$$) — the length of the permutation $$$p$$$, the length of the array $$$a$$$ and the number of queries. The next line contains $$$n$$$ integers from $$$1$$$ to $$$n$$$, where the $$$i$$$-th of them is the $$$i$$$-th element of the permutation. Each integer from $$$1$$$ to $$$n$$$ appears exactly once. The next line contains $$$m$$$ integers from $$$1$$$ to $$$n$$$, the $$$i$$$-th of them is the $$$i$$$-th element of the array $$$a$$$. The next $$$q$$$ lines describe queries. The $$$i$$$-th of these lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le m$$$), meaning that the $$$i$$$-th query is about the subsegment of the array from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive.
2,000
Print a single string of length $$$q$$$, consisting of $$$0$$$ and $$$1$$$, the digit on the $$$i$$$-th positions should be $$$1$$$, if the subsegment of array $$$a$$$ from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive, contains a subsequence that is a cyclic shift of $$$p$$$, and $$$0$$$ otherwise.
standard output
PASSED
e7c95e540af8000f5e6495ba878cad72
train_002.jsonl
1386493200
Berland is going through tough times — the dirt price has dropped and that is a blow to the country's economy. Everybody knows that Berland is the top world dirt exporter!The President of Berland was forced to leave only k of the currently existing n subway stations.The subway stations are located on a straight line one after another, the trains consecutively visit the stations as they move. You can assume that the stations are on the Ox axis, the i-th station is at point with coordinate xi. In such case the distance between stations i and j is calculated by a simple formula |xi - xj|.Currently, the Ministry of Transport is choosing which stations to close and which ones to leave. Obviously, the residents of the capital won't be too enthusiastic about the innovation, so it was decided to show the best side to the people. The Ministry of Transport wants to choose such k stations that minimize the average commute time in the subway!Assuming that the train speed is constant (it is a fixed value), the average commute time in the subway is calculated as the sum of pairwise distances between stations, divided by the number of pairs (that is ) and divided by the speed of the train.Help the Minister of Transport to solve this difficult problem. Write a program that, given the location of the stations selects such k stations that the average commute time in the subway is minimized.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; import java.util.TreeMap; public class E_218 { static BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st = new StringTokenizer(""); static String readString() throws Exception { while(!st.hasMoreTokens()) st = new StringTokenizer(stdin.readLine()); return st.nextToken(); } static int readInt() throws Exception { return Integer.parseInt(readString()); } public static void main(String[] args) throws Exception { int n = readInt(); int a[] = new int[n]; TreeMap<Integer, Integer> map = new TreeMap(); for(int i = 0; i <n; i++){ a[i] = readInt(); map.put(a[i], i+1); } int k = readInt(); Arrays.sort(a); int zero = a[0]-10; double sum = 0; double pnt = 0; for(int i = 1; i < k; i++){ int val = a[i]-a[i-1]; sum += val*i*(k-i); pnt += a[i]-zero; } pnt /= k-1; //System.out.println("sum from 0 to " +(k-1) + " is "+sum + " pnt="+pnt); double best = sum; int ind = 0; for(int i = k; i < n; i++){ //double newPnt = ((pnt)*(k-1)-a[i-k]+a[i])/(k-1); //System.out.println("pnt from "+(i-k+1)+" to "+(i-1)+" is "+pnt); double newSum = sum-(pnt-(a[i-k]-zero))*(k-1)+((a[i]-zero)-pnt)*(k-1); //System.out.println("sum from "+(i-k+1)+" to "+i+" is "+newSum); if(newSum < best){ best = newSum; ind = i-k+1; } pnt = ((pnt)*(k-1)-(a[i-k+1]-zero)+(a[i]-zero))/(k-1); sum = newSum; } StringBuilder ss = new StringBuilder(); for(int i = ind; i < ind+k; i++ ){ ss.append(map.get(a[i])); ss.append(' '); } System.out.println(ss.toString()); } }
Java
["3\n1 100 101\n2"]
2 seconds
["2 3"]
NoteIn the sample testcase the optimal answer is to destroy the first station (with x = 1). The average commute time will be equal to 1 in this way.
Java 7
standard input
[ "two pointers", "greedy", "math" ]
321dfe3005c81bf00458e475202a83a8
The first line of the input contains integer n (3 ≤ n ≤ 3·105) — the number of the stations before the innovation. The second line contains the coordinates of the stations x1, x2, ..., xn ( - 108 ≤ xi ≤ 108). The third line contains integer k (2 ≤ k ≤ n - 1) — the number of stations after the innovation. The station coordinates are distinct and not necessarily sorted.
2,000
Print a sequence of k distinct integers t1, t2, ..., tk (1 ≤ tj ≤ n) — the numbers of the stations that should be left after the innovation in arbitrary order. Assume that the stations are numbered 1 through n in the order they are given in the input. The number of stations you print must have the minimum possible average commute time among all possible ways to choose k stations. If there are multiple such ways, you are allowed to print any of them.
standard output
PASSED
6a9166fa796e29670b1173c0fc85d1d7
train_002.jsonl
1386493200
Berland is going through tough times — the dirt price has dropped and that is a blow to the country's economy. Everybody knows that Berland is the top world dirt exporter!The President of Berland was forced to leave only k of the currently existing n subway stations.The subway stations are located on a straight line one after another, the trains consecutively visit the stations as they move. You can assume that the stations are on the Ox axis, the i-th station is at point with coordinate xi. In such case the distance between stations i and j is calculated by a simple formula |xi - xj|.Currently, the Ministry of Transport is choosing which stations to close and which ones to leave. Obviously, the residents of the capital won't be too enthusiastic about the innovation, so it was decided to show the best side to the people. The Ministry of Transport wants to choose such k stations that minimize the average commute time in the subway!Assuming that the train speed is constant (it is a fixed value), the average commute time in the subway is calculated as the sum of pairwise distances between stations, divided by the number of pairs (that is ) and divided by the speed of the train.Help the Minister of Transport to solve this difficult problem. Write a program that, given the location of the stations selects such k stations that the average commute time in the subway is minimized.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.util.TreeMap; public class E_218 { static BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st = new StringTokenizer(""); static String readString() throws Exception { while(!st.hasMoreTokens()) st = new StringTokenizer(stdin.readLine()); return st.nextToken(); } static int readInt() throws Exception { return Integer.parseInt(readString()); } public static void main(String[] args) throws Exception { int n = readInt(); int a[] = new int[n]; TreeMap<Integer, Integer> map = new TreeMap(); for(int i = 0; i <n; i++){ a[i] = readInt(); map.put(a[i], i+1); } int k = readInt(); Arrays.sort(a); int zero = a[0]-10; double sum = 0; double pnt = 0; for(int i = 1; i < k; i++){ int val = a[i]-a[i-1]; sum += val*i*(k-i); pnt += a[i]-zero; } pnt /= k-1; //System.out.println("sum from 0 to " +(k-1) + " is "+sum + " pnt="+pnt); double best = sum; int ind = 0; for(int i = k; i < n; i++){ //double newPnt = ((pnt)*(k-1)-a[i-k]+a[i])/(k-1); //System.out.println("pnt from "+(i-k+1)+" to "+(i-1)+" is "+pnt); double newSum = sum-(pnt-(a[i-k]-zero))*(k-1)+((a[i]-zero)-pnt)*(k-1); //System.out.println("sum from "+(i-k+1)+" to "+i+" is "+newSum); if(newSum < best){ best = newSum; ind = i-k+1; } pnt = ((pnt)*(k-1)-(a[i-k+1]-zero)+ (a[i]-zero))/(k-1); sum = newSum; } PrintWriter oo = new PrintWriter (new BufferedWriter(new OutputStreamWriter(System.out)));; StringBuilder ss = new StringBuilder(); for(int i = ind; i < ind+k; i++ ){ ss.append(map.get(a[i])); ss.append(' '); } oo.write(ss.toString()); oo.flush(); } }
Java
["3\n1 100 101\n2"]
2 seconds
["2 3"]
NoteIn the sample testcase the optimal answer is to destroy the first station (with x = 1). The average commute time will be equal to 1 in this way.
Java 7
standard input
[ "two pointers", "greedy", "math" ]
321dfe3005c81bf00458e475202a83a8
The first line of the input contains integer n (3 ≤ n ≤ 3·105) — the number of the stations before the innovation. The second line contains the coordinates of the stations x1, x2, ..., xn ( - 108 ≤ xi ≤ 108). The third line contains integer k (2 ≤ k ≤ n - 1) — the number of stations after the innovation. The station coordinates are distinct and not necessarily sorted.
2,000
Print a sequence of k distinct integers t1, t2, ..., tk (1 ≤ tj ≤ n) — the numbers of the stations that should be left after the innovation in arbitrary order. Assume that the stations are numbered 1 through n in the order they are given in the input. The number of stations you print must have the minimum possible average commute time among all possible ways to choose k stations. If there are multiple such ways, you are allowed to print any of them.
standard output
PASSED
95c5ea80c115bcb3461688468eb126af
train_002.jsonl
1386493200
Berland is going through tough times — the dirt price has dropped and that is a blow to the country's economy. Everybody knows that Berland is the top world dirt exporter!The President of Berland was forced to leave only k of the currently existing n subway stations.The subway stations are located on a straight line one after another, the trains consecutively visit the stations as they move. You can assume that the stations are on the Ox axis, the i-th station is at point with coordinate xi. In such case the distance between stations i and j is calculated by a simple formula |xi - xj|.Currently, the Ministry of Transport is choosing which stations to close and which ones to leave. Obviously, the residents of the capital won't be too enthusiastic about the innovation, so it was decided to show the best side to the people. The Ministry of Transport wants to choose such k stations that minimize the average commute time in the subway!Assuming that the train speed is constant (it is a fixed value), the average commute time in the subway is calculated as the sum of pairwise distances between stations, divided by the number of pairs (that is ) and divided by the speed of the train.Help the Minister of Transport to solve this difficult problem. Write a program that, given the location of the stations selects such k stations that the average commute time in the subway is minimized.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashMap; import java.util.StringTokenizer; public class E_218 { static BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st = new StringTokenizer(""); static String readString() throws Exception { while(!st.hasMoreTokens()) st = new StringTokenizer(stdin.readLine()); return st.nextToken(); } static int readInt() throws Exception { return Integer.parseInt(readString()); } public static void main(String[] args) throws Exception { int n = readInt(); int a[] = new int[n]; HashMap<Integer, Integer> map = new HashMap(); for(int i = 0; i <n; i++){ a[i] = readInt(); map.put(a[i], i+1); } int k = readInt(); Arrays.sort(a); int zero = a[0]-10; double sum = 0; double pnt = 0; for(int i = 1; i < k; i++){ int val = a[i]-a[i-1]; sum += val*i*(k-i); pnt += a[i]-zero; } pnt /= k-1; //System.out.println("sum from 0 to " +(k-1) + " is "+sum + " pnt="+pnt); double best = sum; int ind = 0; for(int i = k; i < n; i++){ //double newPnt = ((pnt)*(k-1)-a[i-k]+a[i])/(k-1); //System.out.println("pnt from "+(i-k+1)+" to "+(i-1)+" is "+pnt); double newSum = sum-(pnt-(a[i-k]-zero))*(k-1)+((a[i]-zero)-pnt)*(k-1); //System.out.println("sum from "+(i-k+1)+" to "+i+" is "+newSum); if(newSum < best){ best = newSum; ind = i-k+1; } pnt = ((pnt)*(k-1)-(a[i-k+1]-zero)+ (a[i]-zero))/(k-1); sum = newSum; } PrintWriter oo = new PrintWriter (new BufferedWriter(new OutputStreamWriter(System.out)));; StringBuilder ss = new StringBuilder(); for(int i = ind; i < ind+k; i++ ){ ss.append(map.get(a[i])); ss.append(' '); } oo.write(ss.toString()); oo.flush(); } }
Java
["3\n1 100 101\n2"]
2 seconds
["2 3"]
NoteIn the sample testcase the optimal answer is to destroy the first station (with x = 1). The average commute time will be equal to 1 in this way.
Java 7
standard input
[ "two pointers", "greedy", "math" ]
321dfe3005c81bf00458e475202a83a8
The first line of the input contains integer n (3 ≤ n ≤ 3·105) — the number of the stations before the innovation. The second line contains the coordinates of the stations x1, x2, ..., xn ( - 108 ≤ xi ≤ 108). The third line contains integer k (2 ≤ k ≤ n - 1) — the number of stations after the innovation. The station coordinates are distinct and not necessarily sorted.
2,000
Print a sequence of k distinct integers t1, t2, ..., tk (1 ≤ tj ≤ n) — the numbers of the stations that should be left after the innovation in arbitrary order. Assume that the stations are numbered 1 through n in the order they are given in the input. The number of stations you print must have the minimum possible average commute time among all possible ways to choose k stations. If there are multiple such ways, you are allowed to print any of them.
standard output
PASSED
fef15d534bf35a56e5d28b9433651b84
train_002.jsonl
1386493200
Berland is going through tough times — the dirt price has dropped and that is a blow to the country's economy. Everybody knows that Berland is the top world dirt exporter!The President of Berland was forced to leave only k of the currently existing n subway stations.The subway stations are located on a straight line one after another, the trains consecutively visit the stations as they move. You can assume that the stations are on the Ox axis, the i-th station is at point with coordinate xi. In such case the distance between stations i and j is calculated by a simple formula |xi - xj|.Currently, the Ministry of Transport is choosing which stations to close and which ones to leave. Obviously, the residents of the capital won't be too enthusiastic about the innovation, so it was decided to show the best side to the people. The Ministry of Transport wants to choose such k stations that minimize the average commute time in the subway!Assuming that the train speed is constant (it is a fixed value), the average commute time in the subway is calculated as the sum of pairwise distances between stations, divided by the number of pairs (that is ) and divided by the speed of the train.Help the Minister of Transport to solve this difficult problem. Write a program that, given the location of the stations selects such k stations that the average commute time in the subway is minimized.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashMap; import java.util.StringTokenizer; public class E_218 { static BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st = new StringTokenizer(""); static String readString() throws Exception { while(!st.hasMoreTokens()) st = new StringTokenizer(stdin.readLine()); return st.nextToken(); } static int readInt() throws Exception { return Integer.parseInt(readString()); } public static void main(String[] args) throws Exception { int n = readInt(); int a[] = new int[n]; HashMap<Integer, Integer> map = new HashMap(); for(int i = 0; i <n; i++){ a[i] = readInt(); map.put(a[i], i+1); } int k = readInt(); Arrays.sort(a); int zero = a[0]-10; double sum = 0; double pnt = 0; for(int i = 1; i < k; i++){ int val = a[i]-a[i-1]; sum += val*i*(k-i); pnt += a[i]-zero; } pnt /= k-1; //System.out.println("sum from 0 to " +(k-1) + " is "+sum + " pnt="+pnt); double best = sum; int ind = 0; for(int i = k; i < n; i++){ //double newPnt = ((pnt)*(k-1)-a[i-k]+a[i])/(k-1); //System.out.println("pnt from "+(i-k+1)+" to "+(i-1)+" is "+pnt); double newSum = sum-(pnt-(a[i-k]-zero))*(k-1)+((a[i]-zero)-pnt)*(k-1); //System.out.println("sum from "+(i-k+1)+" to "+i+" is "+newSum); if(newSum < best){ best = newSum; ind = i-k+1; } pnt = ((pnt)*(k-1)-(a[i-k+1]-zero)+ (a[i]-zero))/(k-1); sum = newSum; } PrintWriter oo = new PrintWriter (new BufferedWriter(new OutputStreamWriter(System.out)));; StringBuilder ss = new StringBuilder(); for(int i = ind; i < ind+k; i++ ){ ss.append(map.get(a[i])); ss.append(' '); } //oo.write(ss.toString()); System.out.println(ss.toString()); } }
Java
["3\n1 100 101\n2"]
2 seconds
["2 3"]
NoteIn the sample testcase the optimal answer is to destroy the first station (with x = 1). The average commute time will be equal to 1 in this way.
Java 7
standard input
[ "two pointers", "greedy", "math" ]
321dfe3005c81bf00458e475202a83a8
The first line of the input contains integer n (3 ≤ n ≤ 3·105) — the number of the stations before the innovation. The second line contains the coordinates of the stations x1, x2, ..., xn ( - 108 ≤ xi ≤ 108). The third line contains integer k (2 ≤ k ≤ n - 1) — the number of stations after the innovation. The station coordinates are distinct and not necessarily sorted.
2,000
Print a sequence of k distinct integers t1, t2, ..., tk (1 ≤ tj ≤ n) — the numbers of the stations that should be left after the innovation in arbitrary order. Assume that the stations are numbered 1 through n in the order they are given in the input. The number of stations you print must have the minimum possible average commute time among all possible ways to choose k stations. If there are multiple such ways, you are allowed to print any of them.
standard output
PASSED
f3b355af791274bcff79c8b01efd88b1
train_002.jsonl
1386493200
Berland is going through tough times — the dirt price has dropped and that is a blow to the country's economy. Everybody knows that Berland is the top world dirt exporter!The President of Berland was forced to leave only k of the currently existing n subway stations.The subway stations are located on a straight line one after another, the trains consecutively visit the stations as they move. You can assume that the stations are on the Ox axis, the i-th station is at point with coordinate xi. In such case the distance between stations i and j is calculated by a simple formula |xi - xj|.Currently, the Ministry of Transport is choosing which stations to close and which ones to leave. Obviously, the residents of the capital won't be too enthusiastic about the innovation, so it was decided to show the best side to the people. The Ministry of Transport wants to choose such k stations that minimize the average commute time in the subway!Assuming that the train speed is constant (it is a fixed value), the average commute time in the subway is calculated as the sum of pairwise distances between stations, divided by the number of pairs (that is ) and divided by the speed of the train.Help the Minister of Transport to solve this difficult problem. Write a program that, given the location of the stations selects such k stations that the average commute time in the subway is minimized.
256 megabytes
/* CodeForces Template v0.20 by Sergey Esipenko */ import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.binarySearch; import static java.util.Arrays.fill; import static java.util.Arrays.sort; public class Main implements Runnable { /* START OF SOLUTION */ void solve() throws IOException { final int n = nextInt(); final Item[] items = new Item [n]; for (int i = 0; i < n; i++) { items[i] = new Item(i, nextInt()); } final int k = nextInt(); sort(items); final long[] xs = new long [n]; for (int i = 0; i < n; i++) { xs[i] = items[i].pos; } final long[] pSums = getPartialSums(xs); final long[] dSums = getDescSums(xs); final long[] aSums = getAscSums(xs); long bestSum = Long.MAX_VALUE; int bestStart = -1; for (int l = 0; l + k <= n; l++) { final int r = l + k - 1; final long curSum = s(aSums, l, r) - s(dSums, l, r) + (n - r - l - 1L) * s(pSums, l, r); if (bestSum > curSum) { bestSum = curSum; bestStart = l; } } for (int i = 0; i < k; i++) { if (i > 0) out.print(' '); out.print((items[bestStart + i].id + 1)); } out.println(); } static long s(long[] sums, int l, int r) { return sums[r + 1] - sums[l]; } static long[] getDescSums(long[] a) { final int n = a.length; final long[] sums = new long [n + 1]; for (int i = 0; i < n; i++) { sums[i + 1] = sums[i] + (n - i) * a[i]; } return sums; } static long[] getAscSums(long[] a) { final int n = a.length; final long[] sums = new long [n + 1]; for (int i = 0; i < n; i++) { sums[i + 1] = sums[i] + (i + 1) * a[i]; } return sums; } static class Item implements Comparable<Item> { final int id; final int pos; public Item(int id, int pos) { this.id = id; this.pos = pos; } @Override public int compareTo(Item i) { return pos - i.pos; } } /* END OF SOLUTION */ /************************************************************************** * Entry point *************************************************************************/ static final Main INSTANCE = new Main(); static final Random RND = new Random(); static final boolean WRITE_LOG = true; static final long STACK_SIZE = 1L << 24; // < 0 to default stack size static long initTime; static boolean localRun = false; @SuppressWarnings("unused") public static void main(String[] args) throws IOException { initTime = System.currentTimeMillis(); try { localRun = "true".equals(System.getProperty("LOCAL_RUN_7777")); if (localRun && new File("input.txt").exists()) System.setIn(new FileInputStream("input.txt")); } catch (SecurityException e) { // Can't get property. It seems that solution is running in secure // environment } if (STACK_SIZE < 0L) { INSTANCE.run(); } else { new Thread(null, INSTANCE, "Solver", 1L << 24).start(); } } @Override public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); in.close(); writeLog("Total time: " + (System.currentTimeMillis() - initTime) + " ms"); writeLog("Memory status: " + memoryStatus()); } catch (IOException e) { e.printStackTrace(); } } /************************************************************************** * Input *************************************************************************/ BufferedReader in; PrintWriter out; StringTokenizer st = new StringTokenizer(""); String nextToken() throws IOException { while (!st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } int[] nextIntArray(int size) throws IOException { int[] ret = new int [size]; for (int i = 0; i < size; i++) ret[i] = nextInt(); return ret; } long[] nextLongArray(int size) throws IOException { long[] ret = new long [size]; for (int i = 0; i < size; i++) ret[i] = nextLong(); return ret; } double[] nextDoubleArray(int size) throws IOException { double[] ret = new double [size]; for (int i = 0; i < size; i++) ret[i] = nextDouble(); return ret; } String nextLine() throws IOException { st = new StringTokenizer(""); return in.readLine(); } boolean isEof() throws IOException { while (!st.hasMoreTokens()) { String s = in.readLine(); if (s == null) return true; st = new StringTokenizer(s); } return false; } /************************************************************************** * Output *************************************************************************/ void printRepeat(String s, int count) { for (int i = 0; i < count; i++) out.print(s); } void printArray(int[] array) { if (array == null || array.length == 0) return; for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(long[] array) { if (array == null || array.length == 0) return; for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(double[] array) { if (array == null || array.length == 0) return; for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(double[] array, String spec) { if (array == null || array.length == 0) return; for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.printf(Locale.US, spec, array[i]); } out.println(); } void printArray(Object[] array) { if (array == null || array.length == 0) return; boolean blank = false; for (Object x : array) { if (blank) out.print(' '); else blank = true; out.print(x); } out.println(); } @SuppressWarnings("rawtypes") void printCollection(Collection collection) { if (collection == null || collection.isEmpty()) return; boolean blank = false; for (Object x : collection) { if (blank) out.print(' '); else blank = true; out.print(x); } out.println(); } /************************************************************************** * Utility *************************************************************************/ static String memoryStatus() { return (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory() >> 20) + "/" + (Runtime.getRuntime().totalMemory() >> 20) + " MB"; } static void checkMemory() { System.err.println(memoryStatus()); } static long prevTimeStamp = Long.MIN_VALUE; static void updateTimer() { prevTimeStamp = System.currentTimeMillis(); } static long elapsedTime() { return (System.currentTimeMillis() - prevTimeStamp); } static void checkTimer() { System.err.println(elapsedTime() + " ms"); } static void chk(boolean f) { if (!f) throw new RuntimeException("Assert failed"); } static void chk(boolean f, String format, Object ... args) { if (!f) throw new RuntimeException(String.format(format, args)); } static void writeLog(String format, Object... args) { if (localRun && WRITE_LOG) System.err.println(String.format(Locale.US, format, args)); } static void swap(int[] a, int i, int j) { int tmp = a[i]; a[i] = a[j]; a[j] = tmp; } static void swap(long[] a, int i, int j) { long tmp = a[i]; a[i] = a[j]; a[j] = tmp; } static void swap(double[] a, int i, int j) { double tmp = a[i]; a[i] = a[j]; a[j] = tmp; } static void shuffle(int[] a, int from, int to) { for (int i = from; i < to; i++) swap(a, i, RND.nextInt(a.length)); } static void shuffle(long[] a, int from, int to) { for (int i = from; i < to; i++) swap(a, i, RND.nextInt(a.length)); } static void shuffle(double[] a, int from, int to) { for (int i = from; i < to; i++) swap(a, i, RND.nextInt(a.length)); } static void shuffle(int[] a) { if (a == null) return; shuffle(a, 0, a.length); } static void shuffle(long[] a) { if (a == null) return; shuffle(a, 0, a.length); } static void shuffle(double[] a) { if (a == null) return; shuffle(a, 0, a.length); } static long[] getPartialSums(int[] a) { final long[] sums = new long [a.length + 1]; for (int i = 0; i < a.length; i++) sums[i + 1] = sums[i] + a[i]; return sums; } static long[] getPartialSums(long[] a) { final long[] sums = new long [a.length + 1]; for (int i = 0; i < a.length; i++) sums[i + 1] = sums[i] + a[i]; return sums; } static int[] getOrderedSet(int[] a) { final int[] set = Arrays.copyOf(a, a.length); if (a.length == 0) return set; shuffle(set); sort(set); int k = 1; int prev = set[0]; for (int i = 1; i < a.length; i++) { if (prev != set[i]) { set[k++] = prev = set[i]; } } return Arrays.copyOf(set, k); } static long[] getOrderedSet(long[] a) { final long[] set = Arrays.copyOf(a, a.length); if (a.length == 0) return set; shuffle(set); sort(set); int k = 1; long prev = set[0]; for (int i = 1; i < a.length; i++) { if (prev != set[i]) { set[k++] = prev = set[i]; } } return Arrays.copyOf(set, k); } static int gcd(int x, int y) { x = abs(x); y = abs(y); while (x > 0 && y > 0) { if (x > y) { x %= y; } else { y %= x; } } return x + y; } static long gcd(long x, long y) { x = abs(x); y = abs(y); while (x > 0 && y > 0) { if (x > y) { x %= y; } else { y %= x; } } return x + y; } }
Java
["3\n1 100 101\n2"]
2 seconds
["2 3"]
NoteIn the sample testcase the optimal answer is to destroy the first station (with x = 1). The average commute time will be equal to 1 in this way.
Java 7
standard input
[ "two pointers", "greedy", "math" ]
321dfe3005c81bf00458e475202a83a8
The first line of the input contains integer n (3 ≤ n ≤ 3·105) — the number of the stations before the innovation. The second line contains the coordinates of the stations x1, x2, ..., xn ( - 108 ≤ xi ≤ 108). The third line contains integer k (2 ≤ k ≤ n - 1) — the number of stations after the innovation. The station coordinates are distinct and not necessarily sorted.
2,000
Print a sequence of k distinct integers t1, t2, ..., tk (1 ≤ tj ≤ n) — the numbers of the stations that should be left after the innovation in arbitrary order. Assume that the stations are numbered 1 through n in the order they are given in the input. The number of stations you print must have the minimum possible average commute time among all possible ways to choose k stations. If there are multiple such ways, you are allowed to print any of them.
standard output
PASSED
3c2fab6256e6efa7997466870bf8e0c8
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
import java.io.InputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.InputMismatchException; import java.util.NoSuchElementException; import java.util.PriorityQueue; import java.math.BigInteger; public class Main{ static PrintWriter out; static InputReader ir; static final int INF=1<<29; static void solve(){ int n=ir.nextInt(); int m=ir.nextInt(); int p=0; int[][] e=new int[m][],ee=new int[n*(n-1)/2-m][]; boolean[][] rail=new boolean[n][n]; for(int i=0;i<m;i++){ int u=ir.nextInt()-1; int v=ir.nextInt()-1; if(u>v){ int temp=u; u=v; v=temp; } rail[u][v]=true; e[i]=new int[]{u,v,1}; } for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ if(!rail[i][j]){ ee[p++]=new int[]{i,j,1}; } } } int[][][] g=make_graph(n,e),gg=make_graph(n,ee); int[] dist=new int[n]; dijkstra(g,0,dist); if(dist[n-1]==INF){ out.println(-1); return; } int ans=dist[n-1]; dijkstra(gg,0,dist); if(dist[n-1]==INF){ out.println(-1); return; } out.println((int)Math.max(dist[n-1],ans)); } public static int[][][] make_graph(int n,int[][] e){ int[][][] ret=new int[n][][]; int[] cnt=new int[n]; for(int i=0;i<e.length;i++){ if(e[i]==null) break; cnt[e[i][0]]++; cnt[e[i][1]]++; } for(int i=0;i<n;i++) ret[i]=new int[cnt[i]][]; for(int i=0;i<e.length;i++){ if(e[i]==null) break; ret[e[i][0]][ret[e[i][0]].length-cnt[e[i][0]]--]=new int[]{e[i][1],e[i][2]}; ret[e[i][1]][ret[e[i][1]].length-cnt[e[i][1]]--]=new int[]{e[i][0],e[i][2]}; } return ret; } public static int[][] search_tree(int[][][] g,int v,int root){ int[] par=new int[v]; int[] dep=new int[v]; int[] size=new int[v]; Arrays.fill(par,-1); _search_tree(g,root,par,dep,size); return new int[][]{par,dep,size}; } public static int _search_tree(int[][][] g,int now,int[] par,int[] dep,int[] size){ for(int i=0;i<g[now].length;i++){ int next=g[now][i][0]; if(next==par[now]) continue; par[next]=now; dep[next]=dep[now]+1; size[now]+=_search_tree(g,next,par,dep,size); } return ++size[now]; } public static void dijkstra(int[][][] g,int s,int[] dist){ PriorityQueue<int[]> pque=new PriorityQueue<int[]>(11,new Comparator<int[]>(){ public int compare(int[] a,int[] b){ return Integer.compare(a[0],b[0]); } }); Arrays.fill(dist,INF); dist[s]=0; pque.offer(new int[]{0,s}); while(!pque.isEmpty()){ int[] p=pque.poll(); int v=p[1]; if(dist[v]<p[0]) continue; for(int i=0;i<g[v].length;i++){ if(dist[g[v][i][0]]>dist[v]+g[v][i][1]){ dist[g[v][i][0]]=dist[v]+g[v][i][1]; pque.offer(new int[]{dist[g[v][i][0]],g[v][i][0]}); } } } } public static void main(String[] args) throws Exception{ ir=new InputReader(System.in); out=new PrintWriter(System.out); solve(); out.flush(); } static class InputReader { private InputStream in; private byte[] buffer=new byte[1024]; private int curbuf; private int lenbuf; public InputReader(InputStream in) {this.in=in; this.curbuf=this.lenbuf=0;} public boolean hasNextByte() { if(curbuf>=lenbuf){ curbuf= 0; try{ lenbuf=in.read(buffer); }catch(IOException e) { throw new InputMismatchException(); } if(lenbuf<=0) return false; } return true; } private int readByte(){if(hasNextByte()) return buffer[curbuf++]; else return -1;} private boolean isSpaceChar(int c){return !(c>=33&&c<=126);} private void skip(){while(hasNextByte()&&isSpaceChar(buffer[curbuf])) curbuf++;} public boolean hasNext(){skip(); return hasNextByte();} public String next(){ if(!hasNext()) throw new NoSuchElementException(); StringBuilder sb=new StringBuilder(); int b=readByte(); while(!isSpaceChar(b)){ sb.appendCodePoint(b); b=readByte(); } return sb.toString(); } public int nextInt() { if(!hasNext()) throw new NoSuchElementException(); int c=readByte(); while (isSpaceChar(c)) c=readByte(); boolean minus=false; if (c=='-') { minus=true; c=readByte(); } int res=0; do{ if(c<'0'||c>'9') throw new InputMismatchException(); res=res*10+c-'0'; c=readByte(); }while(!isSpaceChar(c)); return (minus)?-res:res; } public long nextLong() { if(!hasNext()) throw new NoSuchElementException(); int c=readByte(); while (isSpaceChar(c)) c=readByte(); boolean minus=false; if (c=='-') { minus=true; c=readByte(); } long res = 0; do{ if(c<'0'||c>'9') throw new InputMismatchException(); res=res*10+c-'0'; c=readByte(); }while(!isSpaceChar(c)); return (minus)?-res:res; } public double nextDouble(){return Double.parseDouble(next());} public BigInteger nextBigInteger(){return new BigInteger(next());} 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 char[][] nextCharMap(int n,int m){ char[][] map=new char[n][m]; for(int i=0;i<n;i++) map[i]=next().toCharArray(); return map; } } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
3ff88b926638b87598a33b3d2ac64ac7
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
import java.io.*; import java.util.*; public class C { static ArrayList<Integer> g[]; static int[] vis,dist; public static void main(String[] args)throws IOException { FastReader f=new FastReader(); StringBuffer sb = new StringBuffer(); int n=f.nextInt(); int m=f.nextInt(); g=new ArrayList[n+1]; for(int i=1;i<=n;i++) g[i]=new ArrayList<>(); vis=new int[n+1]; dist=new int[n+1]; Set<String> edges=new HashSet<>(); for(int i=0;i<m;i++) { int x=f.nextInt(); int y=f.nextInt(); edges.add(x+" "+y); edges.add(y+" "+x); g[x].add(y); g[y].add(x); } // using railroads bfs(1); int d1=dist[n]-1; for(int i=1;i<=n;i++) g[i]=new ArrayList<>(); dist=new int[n+1]; vis=new int[n+1]; for(int i=1;i<=n;i++) { for(int j=i+1;j<=n;j++) { if(edges.contains(i+" "+j)) continue; g[i].add(j); g[j].add(i); } } //using roads bfs(1); int d2=dist[n]-1; int ans=(d1>0 && d2>0)?Math.max(d1, d2):-1; System.out.println(ans); } static void bfs(int n) { Queue<Integer> q = new LinkedList<>(); q.add(n); vis[n] = 1; dist[n]=1; while (!q.isEmpty()) { int par = q.poll(); for (int child : g[par]) { if (vis[child] == 0) { dist[child]=dist[par]+1; vis[child] = 1; q.add(child); } } } } 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
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
523bc7d58f5815c138bef72a3bfd94af
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; import java.util.Queue; import java.io.BufferedReader; import java.util.LinkedList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); boolean flag = false; boolean[][] mat = new boolean[n][n]; for (int i = 0; i < m; ++i) { int a = in.nextInt() - 1; int b = in.nextInt() - 1; if (Math.min(a, b) == 0 && Math.max(a, b) == n - 1) flag = true; mat[a][b] = true; mat[b][a] = true; } if (flag) { for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) mat[i][j] = !mat[i][j]; } ArrayList<ArrayList<Integer>> graph = new ArrayList<>(); for (int i = 0; i < n; ++i) graph.add(new ArrayList<Integer>()); for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) { if (mat[i][j]) graph.get(i).add(j); } int[] dist = new int[n]; Arrays.fill(dist, -1); Queue<Integer> qu = new LinkedList<Integer>(); dist[0] = 0; qu.add(0); while (!qu.isEmpty()) { int next = qu.poll(); for (int nei : graph.get(next)) { if (dist[nei] == -1) { qu.add(nei); dist[nei] = dist[next] + 1; } } } out.println(dist[n - 1]); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
ade5af2d78ba7659bf85f9efc2a71533
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
import java.util.*; import static java.util.Arrays.fill; public class Main { private static int n,m,s = 0; private static boolean[] used; private static int[] d,p; private static List<Integer>[] graphTrain; private static List<Integer>[] graphCar; private static final int INF = Integer.MAX_VALUE; private static Queue<Integer> q = new ArrayDeque<>(); public static void main(String[] args) { System.out.println(Solve()); } private static int Solve(){ Scanner in = new Scanner(System.in); n = in.nextInt(); m = in.nextInt(); graphTrain = new List[n]; Set<Integer>[] trainCity = new HashSet[n]; for (int i = 0; i < n ; i++) { graphTrain[i] = new ArrayList<>(); trainCity[i] = new HashSet<>(); } for (int i = 0; i < m; i++){ int from = in.nextInt() - 1; int to = in.nextInt() - 1; graphTrain[from].add(to); graphTrain[to].add(from); trainCity[from].add(to); trainCity[to].add(from); } for ( int to:graphTrain[0]) if (to == n-1){ // find path car graphCar = new List[n]; for (int i = 0; i < n; i++){ graphCar[i] = new ArrayList<>(); for (int j = 0; j < n; j++) if (!trainCity[i].contains(j)) graphCar[i].add(j); } return pathFind(graphCar); } // find path train return pathFind(graphTrain); } static int pathFind(List<Integer>[] graph){ used = new boolean[n]; d = new int[n]; for (int i = 0; i < n; i++) d[i] = INF; d[s] = -1; used[s] = true; int[] p = new int[n];fill(p,-1); q.add(s); while ( q.size() > 0){ int from = q.poll(); for (int to: graph[from]) if (!used[to]){ used[to] = true; q.add(to); d[to] = d[from] + 1; p[to] = from; } } int to = n-1; if (!used[to]) { return -1; } List<Integer> path = new ArrayList<>(); for (int i = to; i!=p[s];i = p[i]) path.add(i); return path.size()-1; } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
b7e5beae3324600c0b5cc7a79fa7b1f8
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayDeque; public class C { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); String[] split = br.readLine().split(" "); int n = Integer.parseInt(split[0]), m = Integer.parseInt(split[1]); boolean[][] rail = new boolean[n][n]; for(int i = 0; i < m; i++){ split = br.readLine().split(" "); rail[Integer.parseInt(split[0])-1][Integer.parseInt(split[1])-1] = true; rail[Integer.parseInt(split[1])-1][Integer.parseInt(split[0])-1] = true; } boolean t = false, c = false; int tt = 0, cc = 0; ArrayDeque<N> q = new ArrayDeque<>(); boolean[] v = new boolean[n]; v[0] = true; q.add(new N(0, 0)); while(!q.isEmpty()){ N cur = q.poll(); int x = cur.n; if(x == n-1){ t = true; tt = cur.c; break; } for(int i = 0; i < n; i++){ if(rail[x][i] && !v[i]){ v[i] = true; q.add(new N(i, cur.c+1)); } } } q.clear(); v = new boolean[n]; v[0] = true; q.add(new N(0, 0)); while(!q.isEmpty()){ N cur = q.poll(); int x = cur.n; if(x == n-1){ c = true; cc = cur.c; break; } for(int i = 0; i < n; i++){ if(!rail[x][i] && !v[i]){ v[i] = true; q.add(new N(i, cur.c+1)); } } } if(!c || !t) System.out.println(-1); else System.out.println(Math.max(tt, cc)); } static class N { int n, c; public N(int a, int d){n = a; c = d;} } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
52406cc42eb0e555bc3e3142d0b6de55
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; public class TheTwoRoutes { static ArrayList<Integer> [] adjList1; static ArrayList<Integer> [] adjList2; static boolean [][] adjMatrix1; static boolean [][] adjMatrix2; static boolean visited1[]; static boolean visited2[]; static int parent1[]; static int parent2[]; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); adjList1 = new ArrayList[n]; adjList2 = new ArrayList[n]; adjMatrix1 = new boolean[n][n]; adjMatrix2 = new boolean[n][n]; visited1 = new boolean[n]; visited2 = new boolean[n]; parent1 = new int[n]; parent2 = new int[n]; Arrays.fill(parent1, -1); Arrays.fill(parent2, -1); for(int i=0; i<n; i++){ adjList1[i] = new ArrayList<Integer>(); adjList2[i] = new ArrayList<Integer>(); } for(int i=0; i<m; i++){ int u = sc.nextInt()-1; int v = sc.nextInt()-1; adjList1[u].add(v); adjList1[v].add(u); adjMatrix1[u][v] = true; adjMatrix1[v][u] = true; } for(int i=0; i<n; i++) for(int j=i+1; j<n; j++) if(!adjMatrix1[i][j]){ adjMatrix2[i][j] = true; adjMatrix2[j][i] = true; adjList2[i].add(j); adjList2[j].add(i); } bfs1(0); bfs2(0); if(!visited1[n-1] || !visited2[n-1]){ System.out.println(-1); return; } int c1 = 0; int c2 = 0; int i = n-1; while(parent1[i]!=-1){ c1++; i = parent1[i]; } i = n-1; while(parent2[i]!=-1){ c2++; i = parent2[i]; } System.out.println(Math.max(c1, c2)); } static void bfs1(int node){ Queue<Integer> q = new LinkedList<Integer>(); q.add(node); while(!q.isEmpty()){ int n = q.remove(); visited1[n] = true; for(int ch:adjList1[n]){ if(!visited1[ch]){ parent1[ch] = n; q.add(ch); visited1[ch] = true; } } } } static void bfs2(int node){ Queue<Integer> q = new LinkedList<Integer>(); q.add(node); while(!q.isEmpty()){ int n = q.remove(); visited2[n] = true; for(int ch:adjList2[n]){ if(!visited2[ch]){ parent2[ch] = n; q.add(ch); visited2[ch] = true; } } } } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
4f43c7efc8eae7f0bceabc5bc8948b23
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
import java.io.*; import java.util.*; public class ProblemC { public static void main(String[] args) throws Exception{ BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(f.readLine()); int towns = Integer.parseInt(st.nextToken()); int rails = Integer.parseInt(st.nextToken()); ArrayList<ArrayList<Integer>> rAdj = new ArrayList<ArrayList<Integer>>(); ArrayList<ArrayList<Integer>> bAdj = new ArrayList<ArrayList<Integer>>(); for(int i = 0;i<towns+1;i++){ rAdj.add(new ArrayList<Integer>()); bAdj.add(new ArrayList<Integer>()); } boolean search = false; for(int i = 0;i<rails;i++){ st = new StringTokenizer(f.readLine()); int t1 = Integer.parseInt(st.nextToken()); int t2 = Integer.parseInt(st.nextToken()); if((t1 == 1 && t2 == towns) || (t2 == 1 && t1 == towns))search = true; rAdj.get(t1).add(t2); rAdj.get(t2).add(t1); } for(int i = 1;i<=towns-1;i++){ for(int j = 2;j<=towns;j++){ if(!rAdj.get(i).contains(j)){ bAdj.get(i).add(j); bAdj.get(j).add(i); } } } int minLength = Integer.MAX_VALUE; if(search){ Queue<Integer> q = new LinkedList<Integer>(); int[] dist = new int[towns+1]; Arrays.fill(dist, Integer.MAX_VALUE); dist[1] = 0; int current = 1; q.add(current); boolean[] visited = new boolean[towns+1]; visited[current] = true; while(!q.isEmpty()){ current = q.remove(); for(int i = 0;i<bAdj.get(current).size();i++){ if(!visited[bAdj.get(current).get(i)]){ q.add(bAdj.get(current).get(i)); visited[bAdj.get(current).get(i)] = true; dist[bAdj.get(current).get(i)] = Math.min(dist[bAdj.get(current).get(i)], dist[current] +1); } } } minLength = dist[towns]; } else{ Queue<Integer> q = new LinkedList<Integer>(); int[] dist = new int[towns+1]; Arrays.fill(dist, Integer.MAX_VALUE); dist[1] = 0; int current = 1; q.add(current); boolean[] visited = new boolean[towns+1]; visited[current] = true; while(!q.isEmpty()){ current = q.remove(); for(int i = 0;i<rAdj.get(current).size();i++){ if(!visited[rAdj.get(current).get(i)]){ q.add(rAdj.get(current).get(i)); visited[rAdj.get(current).get(i)] = true; dist[rAdj.get(current).get(i)] = Math.min(dist[rAdj.get(current).get(i)], dist[current] +1); } } } minLength = dist[towns]; } if(minLength == Integer.MAX_VALUE) System.out.println(-1); else System.out.println(minLength); } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
3d6a971d0f937d1d0b7022d59bbf9311
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; public class C { public static void main(String[] args) throws Exception { Scanner sc = System.getProperty("ONLINE_JUDGE") == null ? new Scanner( new BufferedReader(new FileReader("in"))) : new Scanner( System.in); n = sc.nextInt(); int m = sc.nextInt(); for (int i = 0; i < m; i++) { int u = sc.nextInt(); int v = sc.nextInt(); rail[u][v] = true; rail[v][u] = true; } sc.close(); for (int u = 1; u <= n; u++) for (int v = 1; v <= n; v++) if (u != v) { if (rail[u][v]) { adj1[u][d1[u]] = v; d1[u]++; } else { adj2[u][d2[u]] = v; d2[u]++; } } int ans = -1; ArrayList<Integer> prail = path(adj1, d1, new ArrayList<Integer>()); ArrayList<Integer> proad = path(adj2, d2, prail); if (prail.size() > 0 && proad.size() > 0) ans = Math.max(prail.size(), proad.size()); proad = path(adj2, d2, new ArrayList<Integer>()); prail = path(adj1, d1, proad); if (prail.size() > 0 && proad.size() > 0) ans = Math.min(ans, Math.max(prail.size(), proad.size())); System.out.println(ans); } private static int n; private static boolean[][] rail = new boolean[401][401]; private static int[][] adj1 = new int[401][400]; private static int[] d1 = new int[401]; private static int[][] adj2 = new int[401][400]; private static int[] d2 = new int[401]; private static ArrayList<Integer> path(int[][] adj, int[] d, ArrayList<Integer> avoid) { int[] pre = new int[n + 1]; int[] t = new int[n + 1]; Arrays.fill(pre, -1); pre[1] = 0; ArrayList<Integer> queue = new ArrayList<Integer>(); queue.add(1); t[1] = 0; while (queue.size() > 0) { int u = queue.remove(0); if(u == n) break; int tv = t[u] + 1; for (int i = 0; i < d[u]; i++) { int v = adj[u][i];//System.out.println(u + " -> " + v); if (pre[v] == -1 && (tv >= avoid.size() || avoid.get(tv) != v)) { pre[v] = u; t[v] = tv; queue.add(v);//System.out.printf("pre[%d] = %d \n", v, u); } } } ArrayList<Integer> p = new ArrayList<Integer>(); int cur = pre[n]; while (cur != -1 && cur != 0) { p.add(0, cur); //System.out.print(cur + " "); cur = pre[cur]; } //System.out.println(); return p; } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
2a0ee9410332216634f7cfba4464eef5
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
import java.io.*; import java.util.*; public class P3 { public static void main (String[] args) { Scanner sc = new Scanner (System.in); PrintStream op = System.out; int n = sc.nextInt(), m = sc.nextInt(); boolean[][] g = new boolean [n][n]; for (int i = 0; i < m; i++) { int x = sc.nextInt() - 1, y = sc.nextInt() - 1; g[x][y] = g[y][x] = true; } if (g[0][n - 1]) { for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { g[i][j] = !g[i][j]; g[j][i] = !g[j][i]; } } } Deque <Integer> a = new ArrayDeque<Integer>(); a.add(0); boolean[] taken = new boolean [n]; int[] parent = new int [n]; for (int i = 0; i < n; i++) parent[i] = -1; taken[0] = true; while (!a.isEmpty()) { int ind = a.pop(); for (int i = 0; i < n; i++) { if (g[ind][i] && !taken[i]) { a.add(i); taken[i] = true; parent[i] = ind; } } } int nd = n - 1, count = 1; boolean isP = true; while (parent[nd] != 0) { if (parent[nd] == -1) { isP = false; break; } count++; nd = parent[nd]; } if (isP) op.println(count); else op.println(-1); sc.close(); op.close(); } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
82fef9465b92cde967a80c437b9e3f92
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
import java.util.*; import java.io.*; import java.lang.Math.*; public class Graph { int V;int arrival[];int dep[]; LinkedList<Integer> adj[]; int time=0; Graph(int v) { V=v; adj=new LinkedList[v]; arrival=new int[v]; dep=new int[v]; for(int i=0;i<v;i++) { adj[i]=new LinkedList(); } //System.out.println(this.V); } public void addEdge(int x,int y) { adj[x].add(y);adj[y].add(x); } public void MST() { PriorityQueue<Integer> prq =new PriorityQueue<Integer>(); } public int find(int parent[],int v) { if(parent[v]!=v) { parent[v]=find(parent,parent[v]); } return parent[v]; } public void union(int parent[],int x,int y,int rank[]) { int xroot=find(parent,x); int yroot=find(parent,y); if(rank[xroot]>rank[yroot]) { parent[yroot]=xroot; } else if(rank[xroot]<rank[yroot]) { parent[xroot]=yroot; } else { parent[yroot]=xroot; rank[xroot]++; } } public boolean isCycle_directedUtil(int visited[],int rstack[],int s) { visited[s]=1; rstack[s]=1; for(int i=0;i<adj[s].size();i++) { if(visited[adj[s].get(i)]==0) { if(isCycle_directedUtil(visited,rstack,adj[s].get(i))) { return true; } } else { if(rstack[adj[s].get(i)]==1) { return true; } } } rstack[s]=0; return false; } public boolean isCycle_directed(int s) { int visited[]=new int[V]; int rstack[]=new int[V]; for(int i=0;i<V;i++) { if(visited[i]==0) { if(isCycle_directedUtil(visited,rstack,s)) { return true; } } } return false; } public void DFS(int s ,int visited[]) { arrival[s]=time++; visited[s]=1; for(int i=0;i<adj[s].size();i++ ) { if(visited[adj[s].get(i)]==0) { DFS(adj[s].get(i),visited); } } dep[s]=time++; } int BFS(int s,int parent) { // Mark all the vertices as not visited(By default // set as false) //System.out.println(V); boolean visited[] = new boolean[V]; // Create a queue for BFS LinkedList<Pairs> queue = new LinkedList<Pairs>(); // Mark the current node as visited and enqueue it visited[s]=true; queue.add(new Pairs(s,parent)); while (queue.size() != 0) { // Dequeue a vertex from queue and print it Pairs p = queue.poll(); //System.out.println(p.x); // Get all adjacent vertices of the dequeued vertex s // If a adjacent has not been visited, then mark it // visited and enqueue it Iterator<Integer> i = adj[(int)p.x].listIterator(); while (i.hasNext()) { int n = i.next(); if (!visited[n]) { if(n==V-1)return p.y+1; visited[n] = true; queue.add(new Pairs(n,p.y+1)); } } } return -1; } public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int v=in.nextInt(); Graph g=new Graph(v); Graph r=new Graph(v); int edges=in.nextInt(); Pairs p[]=new Pairs[edges]; for(int i=0;i<edges;i++) { int x=in.nextInt()-1; int y=in.nextInt()-1; if(x>y) { int temp=x; x=y; y=temp; } p[i]=new Pairs(x,y); } int flag=0; Arrays.sort(p);int k=0; for(int i=0;i<v-1;i++) { for(int j=i+1;j<v;j++) { if(k<edges && p[k].x==0 && p[k].y==v-1)flag=1; if(k<edges && p[k].x==i && p[k].y==j) { g.addEdge(i, j); k++; } else r.addEdge(i, j); } } if(flag==1) { int x=r.BFS(0,0); out.println(x); } else { int x=g.BFS(0,0); out.println(x); } out.close(); } static class Pairs implements Comparable<Pairs> { long x; int y; Pairs(long a, int b) { x = a; y = b; } @Override public int compareTo(Pairs o) { // TODO Auto-generated method stub if (x == o.x) return Integer.compare(y, o.y); else return Long.compare(x, o.x); } } public static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public long[] nextLongArray(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
6c9366f99c59f27a0c2ca6faba90a2e6
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class R333C { static int INF = Integer.MAX_VALUE / 3; public static void main (String[] args) throws java.lang.Exception { InputReader in = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int n = in.nextInt(), m = in.nextInt(); boolean[][] graph = new boolean[n][n]; for (int i = 0; i < m; i++) { int u = in.nextInt() - 1, v = in.nextInt() - 1; graph[u][v] = graph[v][u] = true; } int mx = Math.max(bfs(graph, true), bfs(graph, false)); if (mx == INF) w.println(-1); else w.println(mx); w.close(); } static int bfs(boolean[][] mat, boolean same) { int n = mat.length; int[] dis = new int[n]; Arrays.fill(dis, INF); Deque<Integer> dq = new LinkedList<>(); dq.add(0); dis[0] = 0; while (dq.size() > 0) { int temp = dq.pop(); for (int i = 0; i < n; i++) { if (mat[temp][i] == same && i != temp && dis[temp] + 1 < dis[i]) { dis[i] = dis[temp] + 1; dq.add(i); } } } return dis[n - 1]; } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new UnknownError(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new UnknownError(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int peek() { if (numChars == -1) return -1; if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { return -1; } if (numChars <= 0) return -1; } return buf[curChar]; } public void skip(int x) { while (x-- > 0) read(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public String nextString() { return next(); } public String next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { StringBuffer buf = new StringBuffer(); int c = read(); while (c != '\n' && c != -1) { if (c != '\r') buf.appendCodePoint(c); c = read(); } return buf.toString(); } 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 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 boolean hasNext() { int value; while (isSpaceChar(value = peek()) && value != -1) read(); return value != -1; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
a4541484ce5a4e5889080bb446ac674e
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
import java.util.Arrays; import java.util.LinkedList; import java.util.Queue; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class MainClass { int [] visited ; MainClass (int v) { visited = new int[v] ; Arrays.fill(visited,0); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void addEdge (LinkedList<Integer> [] g ,int s , int d ) { g[s].addLast(d); g[d].addLast(s); } int DFS (LinkedList<Integer> [] g , int n, MainClass obj) { Queue<Integer> que = new LinkedList<>() ; que.add(0) ; this.visited[0] = 1 ; while (!que.isEmpty()) { int currNode = que.remove() ; for (int x : g[currNode]) { if (visited[x] == 0) { visited[x] = visited[currNode]+1 ; if (visited[x] != obj.visited[x]) que.add(x) ; } if (x == n-1) { return visited[x]-1 ; } } } return 0 ; } public static void main(String[] args) { FastReader in = new FastReader() ; int vertices , railways ; vertices = in.nextInt() ; railways = in.nextInt() ; if ((vertices*(vertices-1)/2) == railways) { System.out.println(-1); return; } LinkedList<Integer> [] graph = new LinkedList[vertices] ; LinkedList<Integer>[] completeGraph = new LinkedList[vertices] ; int [][] edges = new int[vertices][vertices] ; for (int i = 0 ; i < vertices ; i++) { graph[i] = new LinkedList<>() ; completeGraph[i] = new LinkedList<>() ; } for (int i = 0 ; i < railways ; i++) { int a = in.nextInt()-1 ; int b = in.nextInt()-1 ; edges[a][b] = 1 ; edges[b][a] = 1 ; } for (int i = 0 ; i < vertices ; i++) { for (int j = 0 ; j < vertices ; j++) { if (edges[i][j] == 1) addEdge(graph,i,j ); else addEdge(completeGraph,i,j); } } MainClass train = new MainClass(vertices) ; MainClass bus = new MainClass(vertices) ; int path1 = train.DFS(graph,vertices,bus) ; int path2 = bus.DFS(completeGraph,vertices,train); if (path1!= 0 && path2!=0) { System.out.println(Math.max(path1,path2)); } else System.out.println(-1); } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
0b671f297000916aab01dc1f6980fd31
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Queue; import java.util.StringTokenizer; /** * * Codeforces Round #333 (Div 2) - C. The Two Routes * * In-progress * * @author Daniel * */ public class C { static void solve() throws Exception { int n = nextInt(); int m = nextInt(); boolean[][] railway = new boolean[n][n]; for (int i=0; i<m; i++) { int u = nextInt(); int v = nextInt(); railway[u-1][v-1] = true; railway[v-1][u-1] = true; } boolean path = !railway[0][n-1]; int[] dist = new int[n]; Arrays.fill(dist, Integer.MAX_VALUE); dist[0] = 0; Queue<Integer> queue = new ArrayDeque<Integer>(n); queue.offer(0); while (!queue.isEmpty()) { int v = queue.poll(); for (int w=0; w<n; w++) if (v != w && railway[v][w] == path && dist[w] == Integer.MAX_VALUE) { dist[w] = dist[v] + 1; queue.offer(w); } } printf("%d", dist[n-1] < Integer.MAX_VALUE ? dist[n-1] : -1); } /*============================================================================= * STANDARD I/O TEMPLATE * ============================================================================ */ static BufferedReader in; static BufferedWriter out; static StringTokenizer tok; public static void main(String[] args) { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new BufferedWriter(new OutputStreamWriter(System.out)); solve(); out.flush(); out.close(); in.close(); } catch (Throwable e) { e.printStackTrace(); System.exit(1); } } static void print(CharSequence str) throws IOException { out.write(str.toString()); } static void println() throws IOException { out.write(System.lineSeparator()); } static void println(CharSequence str) throws IOException { print(str); println(); } static void printf(String format, Object... args) throws IOException { print(String.format(format, args)); } 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()); } static String next() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } static String nextLine() throws IOException { if (tok == null || !tok.hasMoreTokens()) return in.readLine(); else return tok.nextToken("\n\r"); } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
2173ddafedb026efae3b26d848c0a101
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.InputMismatchException; import java.util.LinkedList; import java.util.Queue; public class TheTwoRoutes { public static void main(String[] args) { FasterScanner sc = new FasterScanner(); int N = sc.nextInt(); int M = sc.nextInt(); Node[] rail = new Node[N + 1]; Node[] road = new Node[N + 1]; for (int i = 1; i <= N; i++) { rail[i] = new Node(i); road[i] = new Node(i); } boolean[][] hasRail = new boolean[N + 1][N + 1]; for (int i = 0; i < M; i++) { int U = sc.nextInt(); int V = sc.nextInt(); hasRail[U][V] = true; hasRail[V][U] = true; } for (int i = 1; i <= N; i++) { for (int j = 1; j <= N; j++) { if (i != j) { if (hasRail[i][j]) { rail[i].next.add(rail[j]); } else { road[i].next.add(road[j]); } } } } HashMap<Node, Integer> distRail = getDists(rail[1]); HashMap<Node, Integer> distRoad = getDists(road[1]); Integer railN = distRail.get(rail[N]); Integer roadN = distRoad.get(road[N]); if (railN == null || roadN == null) { System.out.println(-1); } else { System.out.println(Math.max(railN, roadN)); } } public static HashMap<Node, Integer> getDists(Node start) { HashMap<Node, Integer> dist = new HashMap<Node, Integer>(); Queue<Node> q = new LinkedList<Node>(); dist.put(start, 0); q.add(start); while (!q.isEmpty()) { Node curr = q.poll(); int d = dist.get(curr); for (Node n : curr.next) { if (!dist.containsKey(n)) { dist.put(n, d + 1); q.add(n); } } } return dist; } public static class Node { public HashSet<Node> next; public int idx; public Node(int i) { this.next = new HashSet<Node>(); this.idx = i; } @Override public String toString() { return "NODE " + idx; } } public static class FasterScanner { private byte[] buf = new byte[1024]; private int curChar; private int numChars; public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = System.in.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
155c2e41a4703d3122dd89945635d934
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
import java.util.*; public final class TwoRoutes { static boolean[] marked; public static void main(String[] args) { Scanner br=new Scanner(System.in); int n=br.nextInt(); int m=br.nextInt(); int[][] arr=new int[n+1][n+1]; for(int i=0;i<m;i++) { int x=br.nextInt(); int y=br.nextInt(); arr[x][y]=1; arr[y][x]=1; } marked=new boolean[n+1]; int c=bfs(arr,1,n,'b'); marked=new boolean[n+1]; int d=bfs(arr,1,n,'r'); if(c<0 || d<0) System.out.print("-1"); else System.out.print(c>=d?c:d); } public static int bfs(int[][] a,int s,int n,char t) { ArrayDeque<Integer> q=new ArrayDeque<Integer>(); marked[s]=true; q.offerLast(s); int c=1,v=0,ans=0; while(!q.isEmpty()) { int k=q.pollFirst(); c--; for(int i=1;i<=n;i++) { if( i!=k && !marked[i]) { if(t=='b' && a[k][i]==0) { q.offerLast(i); marked[i]=true; v++; } if(t=='r' && a[k][i]==1) { q.offerLast(i); marked[i]=true; v++; } } } if(c==0 && !q.isEmpty()) { ans++; if(marked[n]) return ans; c=v; v=0; } } return marked[n]==true?ans:-1; } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
f5fba5aca8adc29a081256ee2bd2a2df
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Scanner; import java.util.Set; public class TwoRoutes { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); Graph graph = Graph.readGraph(n, m, sc); int dist1 = graph.bfs(graph.getNode(0), graph.getNode(n - 1)); graph.clear(); int dist2 = graph.bfs2(graph.getNode(0), graph.getNode(n - 1)); if (dist1 == -1 || dist2 == -1) { System.out.println(-1); } else { System.out.println(Math.max(dist1, dist2)); } } } class Graph implements Iterable<GraphNode> { private int nodesCount; private int edgesCount; private GraphNode[] nodes; public Graph(int nodesCount) { this.nodesCount = nodesCount; nodes = new GraphNode[nodesCount + 1]; for (int i = 0; i < nodes.length; i++) { nodes[i] = new GraphNode(i); } } public int getNodesCount() { return nodesCount; } public int getEdgesCount() { return edgesCount; } public void addEdge(int u, int v) { addEdge(u, v, 1); } public void addEdge(int u, int v, int weight) { nodes[v].addEdge(new GraphEdge(u, weight)); nodes[u].addEdge(new GraphEdge(v, weight)); edgesCount++; } public List<GraphEdge> getNeighbours(int id) { return nodes[id].getEdges(); } public GraphNode getNode(int id) { return nodes[id]; } @Override public String toString() { return "Graph{" + "nodesCount=" + nodesCount + '}'; } public static Graph readGraph(int n, int m, Scanner sc) { Graph graph = new Graph(n); for (int i = 0; i < m; i++) { int a = sc.nextInt(); int b = sc.nextInt(); graph.addEdge(a - 1, b - 1); } return graph; } public int bfs(GraphNode start, GraphNode end) { Deque<GraphNode> queue = new ArrayDeque<>(); queue.addLast(start); start.color = 1; int maxDistance = -1; while (!queue.isEmpty()) { GraphNode graphNode = queue.pollFirst(); for (GraphEdge edge : graphNode.edges) { GraphNode next = nodes[edge.id]; if (next.color == 0) { next.color = 1; queue.addLast(next); next.distance = graphNode.distance + 1; if (next.id == end.id) { return next.distance; } } } } return maxDistance; } public int bfs2(GraphNode start, GraphNode end) { Deque<GraphNode> queue = new ArrayDeque<>(); queue.addLast(start); start.color = 1; int maxDistance = -1; while (!queue.isEmpty()) { GraphNode graphNode = queue.pollFirst(); List<GraphEdge> edges = graphNode.edges; Set<Integer> ids = new HashSet<>(); for (GraphEdge edge : edges) { ids.add(edge.id); } Set<Integer> neg = new HashSet<>(); for (int i = 0; i < nodesCount; i++) { if (!ids.contains(i)) { neg.add(i); } } for (Integer edge : neg) { GraphNode next = nodes[edge]; if (next.color == 0) { next.color = 1; queue.addLast(next); next.distance = graphNode.distance + 1; if (next.id == end.id) { return next.distance; } } } } return maxDistance; } @Override public Iterator<GraphNode> iterator() { return null; } public void clear() { for (GraphNode node : nodes) { node.color = 0; } } } class GraphNode { List<GraphEdge> edges = new ArrayList<>(); int id; int color; int component; int distance; public GraphNode(int id) { this.id = id; } public void addEdge(GraphEdge edge) { edges.add(edge); } public List<GraphEdge> getEdges() { return edges; } } class GraphEdge { int id; int weight; GraphEdge(int id, int weight) { this.id = id; this.weight = weight; } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
0bc0cafca4c54e533c857f9a6527c480
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
//package codeforces.cfr333div2; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Scanner; /** * Created by raggzy on 3/21/2016. */ public class C { private static int bfs(boolean[][] conneted, boolean value) { int[] dist = new int[conneted.length]; Arrays.fill(dist, -1); List<Integer> current = new LinkedList<>(); current.add(0); int currDist = 0; while (current.size() > 0) { currDist++; List<Integer> next = new LinkedList<>(); for (Integer i : current) { for (int j = 0; j < conneted.length; j++) { if (conneted[i][j] == value && dist[j] == -1) { dist[j] = currDist; next.add(j); } } } current = next; } return dist[conneted.length - 1]; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); boolean[][] rail = new boolean[n][n]; for (int i = 0; i < m; i++) { int u = in.nextInt() - 1; int v = in.nextInt() - 1; rail[u][v] = true; rail[v][u] = true; } if (rail[0][n - 1]) { System.out.println(bfs(rail, false)); } else { System.out.println(bfs(rail, true)); } } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
0184775f7c62ca80479664fafbf26606
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
import java.awt.*; import java.awt.geom.Line2D; import java.io.*; import java.math.*; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.attribute.BasicFileAttributeView; import java.nio.file.attribute.FileTime; import java.util.*; import java.util.List; public class Main implements Runnable { int maxn = (int)4e2+111; int mod = (int)1e9+7; int inf = (int)1e9; int n,m,k; int a[][] = new int[maxn][maxn]; boolean used[] = new boolean [maxn]; void solve() throws Exception { n = in.nextInt(); m = in.nextInt(); boolean ok = false; for (int i=1; i<=m; i++) { int from = in.nextInt(); int to = in.nextInt(); if ((to==1 && from ==n) || (to==n && from==1)) ok = true; a[from][to] = 1; a[to][from] = 1; } Deque<Pair> q = new ArrayDeque<Pair>(); q.addLast(new Pair(1,0)); used[1] = true; int val = 0; if (!ok) val = 1; int ret = -1; while (!q.isEmpty()) { Pair p = q.pop(); int v = p.x; if (v==n) { ret = p.y; break; } for (int i=1; i<=n; i++) { if (i==v) continue; if (a[v][i]==val && !used[i]) { q.addLast(new Pair(i,p.y+1)); used[i] = true; } } } out.println(ret); } class Pair implements Comparable<Pair>{ int x,y; public Pair (int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(Pair p) { if (x>p.x) return 1; else if (x==p.x) { if (y>p.y) return 1; else if (y==p.y) return 0; else return -1; } else { return -1; } } } String fileInName = "network"; boolean file = false; boolean isAcmp = true; static Throwable throwable; public static void main (String [] args) throws Throwable { Thread thread = new Thread(null, new Main(), "", (1 << 26)); thread.start(); thread.join(); thread.run(); if (throwable != null) throw throwable; } FastReader in; PrintWriter out; public void run() { String fileIn = "input.txt"; String fileOut = "output.txt"; try { if (isAcmp) { if (file) { in = new FastReader(new BufferedReader(new FileReader(fileIn))); out = new PrintWriter (fileOut); } else { in = new FastReader(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); } } else if (file) { in = new FastReader(new BufferedReader(new FileReader(fileInName+".in"))); out = new PrintWriter (fileInName + ".out"); } else { in = new FastReader(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); } solve(); } catch(Exception e) { throwable = e; } finally { out.close(); } } } class FastReader { BufferedReader bf; StringTokenizer tk = null; public FastReader(BufferedReader bf) { this.bf = bf; } public String nextToken () throws Exception { if (tk==null || !tk.hasMoreTokens()) { tk = new StringTokenizer(bf.readLine()); } if (!tk.hasMoreTokens()) return nextToken(); else return tk.nextToken(); } public int nextInt() throws Exception { return Integer.parseInt(nextToken()); } public long nextLong() throws Exception { return Long.parseLong(nextToken()); } public double nextDouble() throws Exception { return Double.parseDouble(nextToken()); } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
874e62f0e35c1a65efaa7ef7335de7e6
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Collection; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Queue; import java.util.LinkedList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { private int N; private int M; private List<Integer>[] graph; private boolean[][] road; private boolean[] visitedBus; private boolean[] visitedTrain; private int dfs() { int timeBus = 0, timeTrain = 0; Queue<Pair> qBus = new LinkedList<>(); Queue<Pair> qTrain = new LinkedList<>(); qBus.add(new Pair(0, 1)); qTrain.add(new Pair(0, 1)); while (!(qBus.isEmpty() && qTrain.isEmpty())) { Pair bus = qBus.poll(); Pair train = qTrain.poll(); if (bus != null && train != null && bus.equals(train)) continue; if (bus != null && !visitedBus[bus.v]) { visitedBus[bus.v] = true; if (bus.v == N) { timeBus = bus.time; qBus.clear(); } else { for (int w : graph[bus.v]) { if (road[bus.v][w] && !visitedBus[w]) qBus.add(new Pair(bus.time + 1, w)); } } } if (train != null && !visitedTrain[train.v]) { visitedTrain[train.v] = true; if (train.v == N) { timeTrain = train.time; qTrain.clear(); } else { for (int w : graph[train.v]) { if (!road[train.v][w] && !visitedTrain[w]) qTrain.add(new Pair(train.time + 1, w)); } } } } if (!visitedTrain[N] || !visitedBus[N]) return -1; return Math.max(timeBus, timeTrain); } public void solve(int testNumber, InputReader in, PrintWriter out) { N = in.nextInt(); M = in.nextInt(); road = new boolean[N + 1][N + 1]; visitedBus = new boolean[N + 1]; visitedTrain = new boolean[N + 1]; graph = new List[N + 1]; for (int i = 1; i <= N; i++) { graph[i] = new ArrayList<>(); for (int j = 1; j <= N; j++) { if (i != j) graph[i].add(j); road[i][j] = true; } } for (int i = 1; i <= M; i++) { int u = in.nextInt(), v = in.nextInt(); road[u][v] = road[v][u] = false; } out.println(dfs()); } class Pair { int time; int v; Pair(int time, int v) { this.time = time; this.v = v; } public boolean equals(Object o) { if (o == null) return false; if (o.getClass() != getClass()) return false; Pair p = (Pair) o; return (v != 1 && p.v != 1 && p.v == v && p.time == time); } } } static class InputReader { private int lenbuf = 0; private int ptrbuf = 0; private InputStream in; private byte[] inbuf = new byte[1024]; public InputReader(InputStream in) { this.in = in; } private int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = in.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } public int nextInt() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
0802728072c133997984f3678c508a3f
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
import java.util.*; import java.io.*; public class C { public static void solve() { Kattio in = new Kattio(System.in); int V = in.nextInt(); int E = in.nextInt(); boolean[][] adjMat = new boolean[V+1][V+1]; for(int i = 0; i < E; i++) { int u = in.nextInt(); int v = in.nextInt(); adjMat[u][v] = adjMat[v][u] = true; } boolean flag = adjMat[1][V]; boolean[] vis = new boolean[V+1]; ArrayDeque<Pair> q = new ArrayDeque<Pair>(); q.offer(new Pair(1, 0)); while(!q.isEmpty()) { Pair st = q.poll(); int u = st.f; int d = st.s; if(u == V) { System.out.println(d); return; } if(vis[u]) continue; vis[u] = true; for(int v = 1; v <= V; v++) { if(u == v) continue; if(adjMat[u][v] == flag) continue; q.offer(new Pair(v, d+1)); } } System.out.println(-1); in.flush(); in.close(); } private static class Pair { int f, s; public Pair(int f, int s) { this.f = f; this.s = s; } } public static void main(String args[] ) throws Exception { Thread t = new Thread(null, null, "~", Runtime.getRuntime().maxMemory()){ @Override public void run() { solve(); } }; t.start(); t.join(); } private static class Kattio extends PrintWriter { private BufferedReader r; private String line; private StringTokenizer st; private String token; public Kattio(InputStream i) { super(new BufferedOutputStream(System.out)); r = new BufferedReader(new InputStreamReader(i)); } public Kattio(InputStream i, OutputStream o) { super(new BufferedOutputStream(o)); r = new BufferedReader(new InputStreamReader(i)); } public boolean hasNext() { return peekToken() != null; } public int nextInt() { return Integer.parseInt(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public String next() { return nextToken(); } public String nextLine() { token = null; st = null; try { return r.readLine(); } catch (IOException e) { return null; } } private String peekToken() { if (token == null) try { while (st == null || !st.hasMoreTokens()) { line = r.readLine(); if (line == null) return null; st = new StringTokenizer(line); } token = st.nextToken(); } catch (IOException e) { } return token; } private String nextToken() { String ans = peekToken(); token = null; return ans; } } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output
PASSED
413de74b3cc0a988e872a277228ab38a
train_002.jsonl
1448382900
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
256 megabytes
//cd ~/BAU/ACM-ICPC/Teams/A++/BlackBurn95 //sudo apt-get Accepted import java.io.*; import java.util.*; import java.math.*; import static java.lang.Math.*; import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.lang.Double.parseDouble; import static java.lang.String.*; public class Main { static int n,m; static List<Integer> [] g1,g2; static int [] dist; static boolean [][] e; public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringBuilder out = new StringBuilder(); StringTokenizer tk; tk = new StringTokenizer(in.readLine()); n = parseInt(tk.nextToken()); m = parseInt(tk.nextToken()); g1 = new List[n]; g2 = new List[n]; for(int i=0; i<n; i++) { g1[i] = new ArrayList(); g2[i] = new ArrayList(); } e = new boolean[n][n]; while(m-- > 0) { tk = new StringTokenizer(in.readLine()); int a = parseInt(tk.nextToken())-1,b = parseInt(tk.nextToken())-1; g1[a].add(b); g1[b].add(a); e[a][b] = e[b][a] = true; } for(int i=0; i<n; i++) { for(int j=i+1; j<n; j++) { if(!e[i][j]) { g2[i].add(j); g2[j].add(i); } } } if(e[0][n-1]) System.out.println(bfs(2,0)); else System.out.println(bfs(1,0)); } static int bfs(int t,int u) { dist = new int[n]; Arrays.fill(dist,-1); Queue<Integer> q = new LinkedList(); q.add(0); dist[0] = 0; while(!q.isEmpty()) { u = q.remove(); if(u==n-1) return dist[u]; if(t==1) { for(int v : g1[u]) if(dist[v]==-1) { dist[v] = dist[u]+1; q.add(v); } } else { for(int v : g2[u]) if(dist[v]==-1) { dist[v] = dist[u]+1; q.add(v); } } } return -1; } }
Java
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
2 seconds
["2", "-1", "3"]
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Java 8
standard input
[ "graphs" ]
fbfc333ad4b0a750f654a00be84aea67
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
1,600
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.
standard output